]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
comment out subtest
[tt-rss.git] / include / functions.php
1 <?php
2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 123);
4
5 define('LABEL_BASE_INDEX', -1024);
6 define('PLUGIN_FEED_BASE_INDEX', -128);
7
8 define('COOKIE_LIFETIME_LONG', 86400*365);
9
10 $fetch_last_error = false;
11 $fetch_last_error_code = false;
12 $fetch_last_content_type = false;
13 $fetch_curl_used = false;
14 $suppress_debugging = false;
15
16 mb_internal_encoding("UTF-8");
17 date_default_timezone_set('UTC');
18 if (defined('E_DEPRECATED')) {
19 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
20 } else {
21 error_reporting(E_ALL & ~E_NOTICE);
22 }
23
24 require_once 'config.php';
25
26 /**
27 * Define a constant if not already defined
28 *
29 * @param string $name The constant name.
30 * @param mixed $value The constant value.
31 * @access public
32 * @return boolean True if defined successfully or not.
33 */
34 function define_default($name, $value) {
35 defined($name) or define($name, $value);
36 }
37
38 ///// Some defaults that you can override in config.php //////
39
40 define_default('FEED_FETCH_TIMEOUT', 45);
41 // How may seconds to wait for response when requesting feed from a site
42 define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
43 // How may seconds to wait for response when requesting feed from a
44 // site when that feed wasn't cached before
45 define_default('FILE_FETCH_TIMEOUT', 45);
46 // Default timeout when fetching files from remote sites
47 define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
48 // How many seconds to wait for initial response from website when
49 // fetching files from remote sites
50
51 if (DB_TYPE == "pgsql") {
52 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
53 } else {
54 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
55 }
56
57 /**
58 * Return available translations names.
59 *
60 * @access public
61 * @return array A array of available translations.
62 */
63 function get_translations() {
64 $tr = array(
65 "auto" => "Detect automatically",
66 "ca_CA" => "Català",
67 "cs_CZ" => "Česky",
68 "en_US" => "English",
69 "es_ES" => "Español",
70 "de_DE" => "Deutsch",
71 "fr_FR" => "Français",
72 "hu_HU" => "Magyar (Hungarian)",
73 "it_IT" => "Italiano",
74 "ja_JP" => "日本語 (Japanese)",
75 "lv_LV" => "Latviešu",
76 "nb_NO" => "Norwegian bokmål",
77 "nl_NL" => "Dutch",
78 "pl_PL" => "Polski",
79 "ru_RU" => "Русский",
80 "pt_BR" => "Portuguese/Brazil",
81 "zh_CN" => "Simplified Chinese",
82 "zh_TW" => "Traditional Chinese",
83 "sv_SE" => "Svenska",
84 "fi_FI" => "Suomi",
85 "tr_TR" => "Türkçe");
86
87 return $tr;
88 }
89
90 require_once "lib/accept-to-gettext.php";
91 require_once "lib/gettext/gettext.inc";
92
93 require_once "lib/languagedetect/LanguageDetect.php";
94
95 function startup_gettext() {
96
97 # Get locale from Accept-Language header
98 $lang = al2gt(array_keys(get_translations()), "text/html");
99
100 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
101 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
102 }
103
104 if ($_SESSION["uid"] && get_schema_version() >= 120) {
105 $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
106
107 if ($pref_lang && $pref_lang != 'auto') {
108 $lang = $pref_lang;
109 }
110 }
111
112 if ($lang) {
113 if (defined('LC_MESSAGES')) {
114 _setlocale(LC_MESSAGES, $lang);
115 } else if (defined('LC_ALL')) {
116 _setlocale(LC_ALL, $lang);
117 }
118
119 _bindtextdomain("messages", "locale");
120
121 _textdomain("messages");
122 _bind_textdomain_codeset("messages", "UTF-8");
123 }
124 }
125
126 require_once 'db-prefs.php';
127 require_once 'version.php';
128 require_once 'ccache.php';
129 require_once 'labels.php';
130
131 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
132 ini_set('user_agent', SELF_USER_AGENT);
133
134 require_once 'lib/pubsubhubbub/publisher.php';
135
136 $schema_version = false;
137
138 function _debug_suppress($suppress) {
139 global $suppress_debugging;
140
141 $suppress_debugging = $suppress;
142 }
143
144 /**
145 * Print a timestamped debug message.
146 *
147 * @param string $msg The debug message.
148 * @return void
149 */
150 function _debug($msg, $show = true) {
151 global $suppress_debugging;
152
153 //echo "[$suppress_debugging] $msg $show\n";
154
155 if ($suppress_debugging) return false;
156
157 $ts = strftime("%H:%M:%S", time());
158 if (function_exists('posix_getpid')) {
159 $ts = "$ts/" . posix_getpid();
160 }
161
162 if ($show && !(defined('QUIET') && QUIET)) {
163 print "[$ts] $msg\n";
164 }
165
166 if (defined('LOGFILE')) {
167 $fp = fopen(LOGFILE, 'a+');
168
169 if ($fp) {
170 $locked = false;
171
172 if (function_exists("flock")) {
173 $tries = 0;
174
175 // try to lock logfile for writing
176 while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
177 sleep(1);
178 ++$tries;
179 }
180
181 if (!$locked) {
182 fclose($fp);
183 return;
184 }
185 }
186
187 fputs($fp, "[$ts] $msg\n");
188
189 if (function_exists("flock")) {
190 flock($fp, LOCK_UN);
191 }
192
193 fclose($fp);
194 }
195 }
196
197 } // function _debug
198
199 /**
200 * Purge a feed old posts.
201 *
202 * @param mixed $link A database connection.
203 * @param mixed $feed_id The id of the purged feed.
204 * @param mixed $purge_interval Olderness of purged posts.
205 * @param boolean $debug Set to True to enable the debug. False by default.
206 * @access public
207 * @return void
208 */
209 function purge_feed($feed_id, $purge_interval, $debug = false) {
210
211 if (!$purge_interval) $purge_interval = feed_purge_interval($feed_id);
212
213 $rows = -1;
214
215 $result = db_query(
216 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
217
218 $owner_uid = false;
219
220 if (db_num_rows($result) == 1) {
221 $owner_uid = db_fetch_result($result, 0, "owner_uid");
222 }
223
224 if ($purge_interval == -1 || !$purge_interval) {
225 if ($owner_uid) {
226 ccache_update($feed_id, $owner_uid);
227 }
228 return;
229 }
230
231 if (!$owner_uid) return;
232
233 if (FORCE_ARTICLE_PURGE == 0) {
234 $purge_unread = get_pref("PURGE_UNREAD_ARTICLES",
235 $owner_uid, false);
236 } else {
237 $purge_unread = true;
238 $purge_interval = FORCE_ARTICLE_PURGE;
239 }
240
241 if (!$purge_unread) $query_limit = " unread = false AND ";
242
243 if (DB_TYPE == "pgsql") {
244 $pg_version = get_pgsql_version();
245
246 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
247
248 $result = db_query("DELETE FROM ttrss_user_entries WHERE
249 ttrss_entries.id = ref_id AND
250 marked = false AND
251 feed_id = '$feed_id' AND
252 $query_limit
253 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
254
255 } else {
256
257 $result = db_query("DELETE FROM ttrss_user_entries
258 USING ttrss_entries
259 WHERE ttrss_entries.id = ref_id AND
260 marked = false AND
261 feed_id = '$feed_id' AND
262 $query_limit
263 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
264 }
265
266 } else {
267
268 /* $result = db_query("DELETE FROM ttrss_user_entries WHERE
269 marked = false AND feed_id = '$feed_id' AND
270 (SELECT date_updated FROM ttrss_entries WHERE
271 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
272
273 $result = db_query("DELETE FROM ttrss_user_entries
274 USING ttrss_user_entries, ttrss_entries
275 WHERE ttrss_entries.id = ref_id AND
276 marked = false AND
277 feed_id = '$feed_id' AND
278 $query_limit
279 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
280 }
281
282 $rows = db_affected_rows($result);
283
284 ccache_update($feed_id, $owner_uid);
285
286 if ($debug) {
287 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
288 }
289
290 return $rows;
291 } // function purge_feed
292
293 function feed_purge_interval($feed_id) {
294
295 $result = db_query("SELECT purge_interval, owner_uid FROM ttrss_feeds
296 WHERE id = '$feed_id'");
297
298 if (db_num_rows($result) == 1) {
299 $purge_interval = db_fetch_result($result, 0, "purge_interval");
300 $owner_uid = db_fetch_result($result, 0, "owner_uid");
301
302 if ($purge_interval == 0) $purge_interval = get_pref(
303 'PURGE_OLD_DAYS', $owner_uid);
304
305 return $purge_interval;
306
307 } else {
308 return -1;
309 }
310 }
311
312 function purge_orphans($do_output = false) {
313
314 // purge orphaned posts in main content table
315 $result = db_query("DELETE FROM ttrss_entries WHERE
316 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
317
318 if ($do_output) {
319 $rows = db_affected_rows($result);
320 _debug("Purged $rows orphaned posts.");
321 }
322 }
323
324 function get_feed_update_interval($feed_id) {
325 $result = db_query("SELECT owner_uid, update_interval FROM
326 ttrss_feeds WHERE id = '$feed_id'");
327
328 if (db_num_rows($result) == 1) {
329 $update_interval = db_fetch_result($result, 0, "update_interval");
330 $owner_uid = db_fetch_result($result, 0, "owner_uid");
331
332 if ($update_interval != 0) {
333 return $update_interval;
334 } else {
335 return get_pref('DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
336 }
337
338 } else {
339 return -1;
340 }
341 }
342
343 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false, $timeout = false, $timestamp = 0, $useragent = false) {
344
345 global $fetch_last_error;
346 global $fetch_last_error_code;
347 global $fetch_last_content_type;
348 global $fetch_curl_used;
349
350 $url = str_replace(' ', '%20', $url);
351
352 if (!defined('NO_CURL') && function_exists('curl_init')) {
353
354 $fetch_curl_used = true;
355
356 if (ini_get("safe_mode") || ini_get("open_basedir")) {
357 $new_url = geturl($url);
358 if (!$new_url) {
359 // geturl has already populated $fetch_last_error
360 return false;
361 }
362 $ch = curl_init($new_url);
363 } else {
364 $ch = curl_init($url);
365 }
366
367 if ($timestamp && !$post_query) {
368 curl_setopt($ch, CURLOPT_HTTPHEADER,
369 array("If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T', $timestamp)));
370 }
371
372 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
373 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
374 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("safe_mode") && !ini_get("open_basedir"));
375 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
376 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
377 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
378 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
379 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
380 curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
381 SELF_USER_AGENT);
382 curl_setopt($ch, CURLOPT_ENCODING, "");
383 curl_setopt($ch, CURLOPT_REFERER, $url);
384
385 if (!ini_get("safe_mode") && !ini_get("open_basedir")) {
386 curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
387 }
388
389 if (defined('_CURL_HTTP_PROXY')) {
390 curl_setopt($ch, CURLOPT_PROXY, _CURL_HTTP_PROXY);
391 }
392
393 if ($post_query) {
394 curl_setopt($ch, CURLOPT_POST, true);
395 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
396 }
397
398 if ((OPENSSL_VERSION_NUMBER >= 0x0090808f) && (OPENSSL_VERSION_NUMBER < 0x10000000)) {
399 curl_setopt($ch, CURLOPT_SSLVERSION, 3);
400 }
401
402 if ($login && $pass)
403 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
404
405 $contents = @curl_exec($ch);
406
407 if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
408 curl_setopt($ch, CURLOPT_ENCODING, 'none');
409 $contents = @curl_exec($ch);
410 }
411
412 if ($contents === false) {
413 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
414 curl_close($ch);
415 return false;
416 }
417
418 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
419 $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
420
421 $fetch_last_error_code = $http_code;
422
423 if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
424 if (curl_errno($ch) != 0) {
425 $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
426 } else {
427 $fetch_last_error = "HTTP Code: $http_code";
428 }
429 curl_close($ch);
430 return false;
431 }
432
433 curl_close($ch);
434
435 return $contents;
436 } else {
437
438 $fetch_curl_used = false;
439
440 if ($login && $pass){
441 $url_parts = array();
442
443 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
444
445 $pass = urlencode($pass);
446
447 if ($url_parts[1] && $url_parts[2]) {
448 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
449 }
450 }
451
452 if (!$post_query && $timestamp) {
453 $context = stream_context_create(array(
454 'http' => array(
455 'method' => 'GET',
456 'header' => "If-Modified-Since: ".gmdate("D, d M Y H:i:s \\G\\M\\T\r\n", $timestamp)
457 )));
458 } else {
459 $context = NULL;
460 }
461
462 $old_error = error_get_last();
463
464 $data = @file_get_contents($url, false, $context);
465
466 $fetch_last_content_type = false; // reset if no type was sent from server
467 if (isset($http_response_header) && is_array($http_response_header)) {
468 foreach ($http_response_header as $h) {
469 if (substr(strtolower($h), 0, 13) == 'content-type:') {
470 $fetch_last_content_type = substr($h, 14);
471 // don't abort here b/c there might be more than one
472 // e.g. if we were being redirected -- last one is the right one
473 }
474
475 if (substr(strtolower($h), 0, 7) == 'http/1.') {
476 $fetch_last_error_code = (int) substr($h, 9, 3);
477 }
478 }
479 }
480
481 if (!$data) {
482 $error = error_get_last();
483
484 if ($error['message'] != $old_error['message']) {
485 $fetch_last_error = $error["message"];
486 } else {
487 $fetch_last_error = "HTTP Code: $fetch_last_error_code";
488 }
489 }
490 return $data;
491 }
492
493 }
494
495 /**
496 * Try to determine the favicon URL for a feed.
497 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
498 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
499 *
500 * @param string $url A feed or page URL
501 * @access public
502 * @return mixed The favicon URL, or false if none was found.
503 */
504 function get_favicon_url($url) {
505
506 $favicon_url = false;
507
508 if ($html = @fetch_file_contents($url)) {
509
510 libxml_use_internal_errors(true);
511
512 $doc = new DOMDocument();
513 $doc->loadHTML($html);
514 $xpath = new DOMXPath($doc);
515
516 $base = $xpath->query('/html/head/base');
517 foreach ($base as $b) {
518 $url = $b->getAttribute("href");
519 break;
520 }
521
522 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
523 if (count($entries) > 0) {
524 foreach ($entries as $entry) {
525 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
526 break;
527 }
528 }
529 }
530
531 if (!$favicon_url)
532 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
533
534 return $favicon_url;
535 } // function get_favicon_url
536
537 function check_feed_favicon($site_url, $feed) {
538 # print "FAVICON [$site_url]: $favicon_url\n";
539
540 $icon_file = ICONS_DIR . "/$feed.ico";
541
542 if (!file_exists($icon_file)) {
543 $favicon_url = get_favicon_url($site_url);
544
545 if ($favicon_url) {
546 // Limiting to "image" type misses those served with text/plain
547 $contents = fetch_file_contents($favicon_url); // , "image");
548
549 if ($contents) {
550 // Crude image type matching.
551 // Patterns gleaned from the file(1) source code.
552 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
553 // 0 string \000\000\001\000 MS Windows icon resource
554 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
555 }
556 elseif (preg_match('/^GIF8/', $contents)) {
557 // 0 string GIF8 GIF image data
558 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
559 }
560 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
561 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
562 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
563 }
564 elseif (preg_match('/^\xff\xd8/', $contents)) {
565 // 0 beshort 0xffd8 JPEG image data
566 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
567 }
568 else {
569 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
570 $contents = "";
571 }
572 }
573
574 if ($contents) {
575 $fp = @fopen($icon_file, "w");
576
577 if ($fp) {
578 fwrite($fp, $contents);
579 fclose($fp);
580 chmod($icon_file, 0644);
581 }
582 }
583 }
584 return $icon_file;
585 }
586 }
587
588 function print_select($id, $default, $values, $attributes = "") {
589 print "<select name=\"$id\" id=\"$id\" $attributes>";
590 foreach ($values as $v) {
591 if ($v == $default)
592 $sel = "selected=\"1\"";
593 else
594 $sel = "";
595
596 $v = trim($v);
597
598 print "<option value=\"$v\" $sel>$v</option>";
599 }
600 print "</select>";
601 }
602
603 function print_select_hash($id, $default, $values, $attributes = "") {
604 print "<select name=\"$id\" id='$id' $attributes>";
605 foreach (array_keys($values) as $v) {
606 if ($v == $default)
607 $sel = 'selected="selected"';
608 else
609 $sel = "";
610
611 $v = trim($v);
612
613 print "<option $sel value=\"$v\">".$values[$v]."</option>";
614 }
615
616 print "</select>";
617 }
618
619 function print_radio($id, $default, $true_is, $values, $attributes = "") {
620 foreach ($values as $v) {
621
622 if ($v == $default)
623 $sel = "checked";
624 else
625 $sel = "";
626
627 if ($v == $true_is) {
628 $sel .= " value=\"1\"";
629 } else {
630 $sel .= " value=\"0\"";
631 }
632
633 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
634 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
635
636 }
637 }
638
639 function initialize_user_prefs($uid, $profile = false) {
640
641 $uid = db_escape_string($uid);
642
643 if (!$profile) {
644 $profile = "NULL";
645 $profile_qpart = "AND profile IS NULL";
646 } else {
647 $profile_qpart = "AND profile = '$profile'";
648 }
649
650 if (get_schema_version() < 63) $profile_qpart = "";
651
652 db_query("BEGIN");
653
654 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
655
656 $u_result = db_query("SELECT pref_name
657 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
658
659 $active_prefs = array();
660
661 while ($line = db_fetch_assoc($u_result)) {
662 array_push($active_prefs, $line["pref_name"]);
663 }
664
665 while ($line = db_fetch_assoc($result)) {
666 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
667 // print "adding " . $line["pref_name"] . "<br>";
668
669 $line["def_value"] = db_escape_string($line["def_value"]);
670 $line["pref_name"] = db_escape_string($line["pref_name"]);
671
672 if (get_schema_version() < 63) {
673 db_query("INSERT INTO ttrss_user_prefs
674 (owner_uid,pref_name,value) VALUES
675 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
676
677 } else {
678 db_query("INSERT INTO ttrss_user_prefs
679 (owner_uid,pref_name,value, profile) VALUES
680 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
681 }
682
683 }
684 }
685
686 db_query("COMMIT");
687
688 }
689
690 function get_ssl_certificate_id() {
691 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
692 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
693 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
694 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
695 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
696 }
697 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
698 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
699 $_SERVER["SSL_CLIENT_V_START"] .
700 $_SERVER["SSL_CLIENT_V_END"] .
701 $_SERVER["SSL_CLIENT_S_DN"]);
702 }
703 return "";
704 }
705
706 function authenticate_user($login, $password, $check_only = false) {
707
708 if (!SINGLE_USER_MODE) {
709 $user_id = false;
710
711 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
712
713 $user_id = (int) $plugin->authenticate($login, $password);
714
715 if ($user_id) {
716 $_SESSION["auth_module"] = strtolower(get_class($plugin));
717 break;
718 }
719 }
720
721 if ($user_id && !$check_only) {
722 @session_start();
723
724 $_SESSION["uid"] = $user_id;
725 $_SESSION["version"] = VERSION_STATIC;
726
727 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
728 WHERE id = '$user_id'");
729
730 $_SESSION["name"] = db_fetch_result($result, 0, "login");
731 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
732 $_SESSION["csrf_token"] = uniqid(rand(), true);
733
734 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
735 $_SESSION["uid"]);
736
737 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
738 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
739 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
740
741 $_SESSION["last_version_check"] = time();
742
743 initialize_user_prefs($_SESSION["uid"]);
744
745 return true;
746 }
747
748 return false;
749
750 } else {
751
752 $_SESSION["uid"] = 1;
753 $_SESSION["name"] = "admin";
754 $_SESSION["access_level"] = 10;
755
756 $_SESSION["hide_hello"] = true;
757 $_SESSION["hide_logout"] = true;
758
759 $_SESSION["auth_module"] = false;
760
761 if (!$_SESSION["csrf_token"]) {
762 $_SESSION["csrf_token"] = uniqid(rand(), true);
763 }
764
765 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
766
767 initialize_user_prefs($_SESSION["uid"]);
768
769 return true;
770 }
771 }
772
773 function make_password($length = 8) {
774
775 $password = "";
776 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
777
778 $i = 0;
779
780 while ($i < $length) {
781 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
782
783 if (!strstr($password, $char)) {
784 $password .= $char;
785 $i++;
786 }
787 }
788 return $password;
789 }
790
791 // this is called after user is created to initialize default feeds, labels
792 // or whatever else
793
794 // user preferences are checked on every login, not here
795
796 function initialize_user($uid) {
797
798 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
799 values ('$uid', 'Tiny Tiny RSS: New Releases',
800 'http://tt-rss.org/releases.rss')");
801
802 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
803 values ('$uid', 'Tiny Tiny RSS: Forum',
804 'http://tt-rss.org/forum/rss.php')");
805 }
806
807 function logout_user() {
808 session_destroy();
809 if (isset($_COOKIE[session_name()])) {
810 setcookie(session_name(), '', time()-42000, '/');
811 }
812 }
813
814 function validate_csrf($csrf_token) {
815 return $csrf_token == $_SESSION['csrf_token'];
816 }
817
818 function load_user_plugins($owner_uid) {
819 if ($owner_uid && SCHEMA_VERSION >= 100) {
820 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
821
822 PluginHost::getInstance()->load($plugins, PluginHost::KIND_USER, $owner_uid);
823
824 if (get_schema_version() > 100) {
825 PluginHost::getInstance()->load_data();
826 }
827 }
828 }
829
830 function login_sequence() {
831 if (SINGLE_USER_MODE) {
832 @session_start();
833 authenticate_user("admin", null);
834 startup_gettext();
835 load_user_plugins($_SESSION["uid"]);
836 } else {
837 if (!validate_session()) $_SESSION["uid"] = false;
838
839 if (!$_SESSION["uid"]) {
840
841 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
842 $_SESSION["ref_schema_version"] = get_schema_version(true);
843 } else {
844 authenticate_user(null, null, true);
845 }
846
847 if (!$_SESSION["uid"]) {
848 @session_destroy();
849 setcookie(session_name(), '', time()-42000, '/');
850
851 render_login_form();
852 exit;
853 }
854
855 } else {
856 /* bump login timestamp */
857 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
858 $_SESSION["uid"]);
859 $_SESSION["last_login_update"] = time();
860 }
861
862 if ($_SESSION["uid"]) {
863 startup_gettext();
864 load_user_plugins($_SESSION["uid"]);
865
866 /* cleanup ccache */
867
868 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
869 $_SESSION["uid"] . " AND
870 (SELECT COUNT(id) FROM ttrss_feeds WHERE
871 ttrss_feeds.id = feed_id) = 0");
872
873 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
874 $_SESSION["uid"] . " AND
875 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
876 ttrss_feed_categories.id = feed_id) = 0");
877
878 }
879
880 }
881 }
882
883 function truncate_string($str, $max_len, $suffix = '&hellip;') {
884 if (mb_strlen($str, "utf-8") > $max_len) {
885 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
886 } else {
887 return $str;
888 }
889 }
890
891 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
892
893 try {
894 $source_tz = new DateTimeZone($source_tz);
895 } catch (Exception $e) {
896 $source_tz = new DateTimeZone('UTC');
897 }
898
899 try {
900 $dest_tz = new DateTimeZone($dest_tz);
901 } catch (Exception $e) {
902 $dest_tz = new DateTimeZone('UTC');
903 }
904
905 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
906 return $dt->format('U') + $dest_tz->getOffset($dt);
907 }
908
909 function make_local_datetime($timestamp, $long, $owner_uid = false,
910 $no_smart_dt = false) {
911
912 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
913 if (!$timestamp) $timestamp = '1970-01-01 0:00';
914
915 global $utc_tz;
916 global $user_tz;
917
918 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
919
920 $timestamp = substr($timestamp, 0, 19);
921
922 # We store date in UTC internally
923 $dt = new DateTime($timestamp, $utc_tz);
924
925 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
926
927 if ($user_tz_string != 'Automatic') {
928
929 try {
930 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
931 } catch (Exception $e) {
932 $user_tz = $utc_tz;
933 }
934
935 $tz_offset = $user_tz->getOffset($dt);
936 } else {
937 $tz_offset = (int) -$_SESSION["clientTzOffset"];
938 }
939
940 $user_timestamp = $dt->format('U') + $tz_offset;
941
942 if (!$no_smart_dt) {
943 return smart_date_time($user_timestamp,
944 $tz_offset, $owner_uid);
945 } else {
946 if ($long)
947 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
948 else
949 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
950
951 return date($format, $user_timestamp);
952 }
953 }
954
955 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false) {
956 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
957
958 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
959 return date("G:i", $timestamp);
960 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
961 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
962 return date($format, $timestamp);
963 } else {
964 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
965 return date($format, $timestamp);
966 }
967 }
968
969 function sql_bool_to_bool($s) {
970 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
971 return true;
972 } else {
973 return false;
974 }
975 }
976
977 function bool_to_sql_bool($s) {
978 if ($s) {
979 return "true";
980 } else {
981 return "false";
982 }
983 }
984
985 // Session caching removed due to causing wrong redirects to upgrade
986 // script when get_schema_version() is called on an obsolete session
987 // created on a previous schema version.
988 function get_schema_version($nocache = false) {
989 global $schema_version;
990
991 if (!$schema_version && !$nocache) {
992 $result = db_query("SELECT schema_version FROM ttrss_version");
993 $version = db_fetch_result($result, 0, "schema_version");
994 $schema_version = $version;
995 return $version;
996 } else {
997 return $schema_version;
998 }
999 }
1000
1001 function sanity_check() {
1002 require_once 'errors.php';
1003
1004 $error_code = 0;
1005 $schema_version = get_schema_version(true);
1006
1007 if ($schema_version != SCHEMA_VERSION) {
1008 $error_code = 5;
1009 }
1010
1011 if (DB_TYPE == "mysql") {
1012 $result = db_query("SELECT true", false);
1013 if (db_num_rows($result) != 1) {
1014 $error_code = 10;
1015 }
1016 }
1017
1018 if (db_escape_string("testTEST") != "testTEST") {
1019 $error_code = 12;
1020 }
1021
1022 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1023 }
1024
1025 function file_is_locked($filename) {
1026 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1027 if (function_exists('flock')) {
1028 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1029 if ($fp) {
1030 if (flock($fp, LOCK_EX | LOCK_NB)) {
1031 flock($fp, LOCK_UN);
1032 fclose($fp);
1033 return false;
1034 }
1035 fclose($fp);
1036 return true;
1037 } else {
1038 return false;
1039 }
1040 }
1041 return true; // consider the file always locked and skip the test
1042 } else {
1043 return false;
1044 }
1045 }
1046
1047
1048 function make_lockfile($filename) {
1049 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1050
1051 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1052 $stat_h = fstat($fp);
1053 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1054
1055 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1056 if ($stat_h["ino"] != $stat_f["ino"] ||
1057 $stat_h["dev"] != $stat_f["dev"]) {
1058
1059 return false;
1060 }
1061 }
1062
1063 if (function_exists('posix_getpid')) {
1064 fwrite($fp, posix_getpid() . "\n");
1065 }
1066 return $fp;
1067 } else {
1068 return false;
1069 }
1070 }
1071
1072 function make_stampfile($filename) {
1073 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1074
1075 if (flock($fp, LOCK_EX | LOCK_NB)) {
1076 fwrite($fp, time() . "\n");
1077 flock($fp, LOCK_UN);
1078 fclose($fp);
1079 return true;
1080 } else {
1081 return false;
1082 }
1083 }
1084
1085 function sql_random_function() {
1086 if (DB_TYPE == "mysql") {
1087 return "RAND()";
1088 } else {
1089 return "RANDOM()";
1090 }
1091 }
1092
1093 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1094
1095 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1096
1097 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1098
1099 // Todo: all this interval stuff needs some generic generator function
1100
1101 $date_qpart = "false";
1102
1103 switch ($mode) {
1104 case "1day":
1105 if (DB_TYPE == "pgsql") {
1106 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1107 } else {
1108 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1109 }
1110 break;
1111 case "1week":
1112 if (DB_TYPE == "pgsql") {
1113 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1114 } else {
1115 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1116 }
1117 break;
1118 case "2week":
1119 if (DB_TYPE == "pgsql") {
1120 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1121 } else {
1122 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1123 }
1124 break;
1125 default:
1126 $date_qpart = "true";
1127 }
1128
1129 if (is_numeric($feed)) {
1130 if ($cat_view) {
1131
1132 if ($feed >= 0) {
1133
1134 if ($feed > 0) {
1135 $children = getChildCategories($feed, $owner_uid);
1136 array_push($children, $feed);
1137
1138 $children = join(",", $children);
1139
1140 $cat_qpart = "cat_id IN ($children)";
1141 } else {
1142 $cat_qpart = "cat_id IS NULL";
1143 }
1144
1145 db_query("UPDATE ttrss_user_entries
1146 SET unread = false, last_read = NOW() WHERE ref_id IN
1147 (SELECT id FROM
1148 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1149 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1150 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1151
1152 } else if ($feed == -2) {
1153
1154 db_query("UPDATE ttrss_user_entries
1155 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1156 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1157 AND unread = true AND owner_uid = $owner_uid");
1158 }
1159
1160 } else if ($feed > 0) {
1161
1162 db_query("UPDATE ttrss_user_entries
1163 SET unread = false, last_read = NOW() WHERE ref_id IN
1164 (SELECT id FROM
1165 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1166 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1167
1168 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1169
1170 if ($feed == -1) {
1171 db_query("UPDATE ttrss_user_entries
1172 SET unread = false, last_read = NOW() WHERE ref_id IN
1173 (SELECT id FROM
1174 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1175 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1176 }
1177
1178 if ($feed == -2) {
1179 db_query("UPDATE ttrss_user_entries
1180 SET unread = false, last_read = NOW() WHERE ref_id IN
1181 (SELECT id FROM
1182 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1183 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1184 }
1185
1186 if ($feed == -3) {
1187
1188 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1189
1190 if (DB_TYPE == "pgsql") {
1191 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1192 } else {
1193 $match_part = "date_entered > DATE_SUB(NOW(),
1194 INTERVAL $intl HOUR) ";
1195 }
1196
1197 db_query("UPDATE ttrss_user_entries
1198 SET unread = false, last_read = NOW() WHERE ref_id IN
1199 (SELECT id FROM
1200 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1201 AND owner_uid = $owner_uid AND unread = true AND $date_qpart AND $match_part) as tmp)");
1202 }
1203
1204 if ($feed == -4) {
1205 db_query("UPDATE ttrss_user_entries
1206 SET unread = false, last_read = NOW() WHERE ref_id IN
1207 (SELECT id FROM
1208 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1209 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1210 }
1211
1212 } else if ($feed < LABEL_BASE_INDEX) { // label
1213
1214 $label_id = feed_to_label_id($feed);
1215
1216 db_query("UPDATE ttrss_user_entries
1217 SET unread = false, last_read = NOW() WHERE ref_id IN
1218 (SELECT id FROM
1219 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1220 AND label_id = '$label_id' AND ref_id = article_id
1221 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1222
1223 }
1224
1225 ccache_update($feed, $owner_uid, $cat_view);
1226
1227 } else { // tag
1228 db_query("UPDATE ttrss_user_entries
1229 SET unread = false, last_read = NOW() WHERE ref_id IN
1230 (SELECT id FROM
1231 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1232 AND post_int_id = int_id AND tag_name = '$feed'
1233 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1234
1235 }
1236 }
1237
1238 function getAllCounters() {
1239 $data = getGlobalCounters();
1240
1241 $data = array_merge($data, getVirtCounters());
1242 $data = array_merge($data, getLabelCounters());
1243 $data = array_merge($data, getFeedCounters());
1244 $data = array_merge($data, getCategoryCounters());
1245
1246 return $data;
1247 }
1248
1249 function getCategoryTitle($cat_id) {
1250
1251 if ($cat_id == -1) {
1252 return __("Special");
1253 } else if ($cat_id == -2) {
1254 return __("Labels");
1255 } else {
1256
1257 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1258 id = '$cat_id'");
1259
1260 if (db_num_rows($result) == 1) {
1261 return db_fetch_result($result, 0, "title");
1262 } else {
1263 return __("Uncategorized");
1264 }
1265 }
1266 }
1267
1268
1269 function getCategoryCounters() {
1270 $ret_arr = array();
1271
1272 /* Labels category */
1273
1274 $cv = array("id" => -2, "kind" => "cat",
1275 "counter" => getCategoryUnread(-2));
1276
1277 array_push($ret_arr, $cv);
1278
1279 $result = db_query("SELECT id AS cat_id, value AS unread,
1280 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1281 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1282 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1283 WHERE ttrss_cat_counters_cache.feed_id = id AND
1284 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1285 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1286
1287 while ($line = db_fetch_assoc($result)) {
1288 $line["cat_id"] = (int) $line["cat_id"];
1289
1290 if ($line["num_children"] > 0) {
1291 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1292 } else {
1293 $child_counter = 0;
1294 }
1295
1296 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1297 "counter" => $line["unread"] + $child_counter);
1298
1299 array_push($ret_arr, $cv);
1300 }
1301
1302 /* Special case: NULL category doesn't actually exist in the DB */
1303
1304 $cv = array("id" => 0, "kind" => "cat",
1305 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1306
1307 array_push($ret_arr, $cv);
1308
1309 return $ret_arr;
1310 }
1311
1312 // only accepts real cats (>= 0)
1313 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1314 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1315
1316 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1317 AND owner_uid = $owner_uid");
1318
1319 $unread = 0;
1320
1321 while ($line = db_fetch_assoc($result)) {
1322 $unread += getCategoryUnread($line["id"], $owner_uid);
1323 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1324 }
1325
1326 return $unread;
1327 }
1328
1329 function getCategoryUnread($cat, $owner_uid = false) {
1330
1331 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1332
1333 if ($cat >= 0) {
1334
1335 if ($cat != 0) {
1336 $cat_query = "cat_id = '$cat'";
1337 } else {
1338 $cat_query = "cat_id IS NULL";
1339 }
1340
1341 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1342 AND owner_uid = " . $owner_uid);
1343
1344 $cat_feeds = array();
1345 while ($line = db_fetch_assoc($result)) {
1346 array_push($cat_feeds, "feed_id = " . $line["id"]);
1347 }
1348
1349 if (count($cat_feeds) == 0) return 0;
1350
1351 $match_part = implode(" OR ", $cat_feeds);
1352
1353 $result = db_query("SELECT COUNT(int_id) AS unread
1354 FROM ttrss_user_entries
1355 WHERE unread = true AND ($match_part)
1356 AND owner_uid = " . $owner_uid);
1357
1358 $unread = 0;
1359
1360 # this needs to be rewritten
1361 while ($line = db_fetch_assoc($result)) {
1362 $unread += $line["unread"];
1363 }
1364
1365 return $unread;
1366 } else if ($cat == -1) {
1367 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1368 } else if ($cat == -2) {
1369
1370 $result = db_query("
1371 SELECT COUNT(unread) AS unread FROM
1372 ttrss_user_entries, ttrss_user_labels2
1373 WHERE article_id = ref_id AND unread = true
1374 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1375
1376 $unread = db_fetch_result($result, 0, "unread");
1377
1378 return $unread;
1379
1380 }
1381 }
1382
1383 function getFeedUnread($feed, $is_cat = false) {
1384 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1385 }
1386
1387 function getLabelUnread($label_id, $owner_uid = false) {
1388 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1389
1390 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1391 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1392
1393 if (db_num_rows($result) != 0) {
1394 return db_fetch_result($result, 0, "unread");
1395 } else {
1396 return 0;
1397 }
1398 }
1399
1400 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1401 $owner_uid = false) {
1402
1403 $n_feed = (int) $feed;
1404 $need_entries = false;
1405
1406 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1407
1408 if ($unread_only) {
1409 $unread_qpart = "unread = true";
1410 } else {
1411 $unread_qpart = "true";
1412 }
1413
1414 if ($is_cat) {
1415 return getCategoryUnread($n_feed, $owner_uid);
1416 } else if ($n_feed == -6) {
1417 return 0;
1418 } else if ($feed != "0" && $n_feed == 0) {
1419
1420 $feed = db_escape_string($feed);
1421
1422 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1423 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1424 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1425 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1426 return db_fetch_result($result, 0, "count");
1427
1428 } else if ($n_feed == -1) {
1429 $match_part = "marked = true";
1430 } else if ($n_feed == -2) {
1431 $match_part = "published = true";
1432 } else if ($n_feed == -3) {
1433 $match_part = "unread = true AND score >= 0";
1434
1435 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1436
1437 if (DB_TYPE == "pgsql") {
1438 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1439 } else {
1440 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1441 }
1442
1443 $need_entries = true;
1444
1445 } else if ($n_feed == -4) {
1446 $match_part = "true";
1447 } else if ($n_feed >= 0) {
1448
1449 if ($n_feed != 0) {
1450 $match_part = "feed_id = '$n_feed'";
1451 } else {
1452 $match_part = "feed_id IS NULL";
1453 }
1454
1455 } else if ($feed < LABEL_BASE_INDEX) {
1456
1457 $label_id = feed_to_label_id($feed);
1458
1459 return getLabelUnread($label_id, $owner_uid);
1460
1461 }
1462
1463 if ($match_part) {
1464
1465 if ($need_entries) {
1466 $from_qpart = "ttrss_user_entries,ttrss_entries";
1467 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1468 } else {
1469 $from_qpart = "ttrss_user_entries";
1470 $from_where = "";
1471 }
1472
1473 $query = "SELECT count(int_id) AS unread
1474 FROM $from_qpart WHERE
1475 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1476
1477 //echo "[$feed/$query]\n";
1478
1479 $result = db_query($query);
1480
1481 } else {
1482
1483 $result = db_query("SELECT COUNT(post_int_id) AS unread
1484 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1485 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1486 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1487 }
1488
1489 $unread = db_fetch_result($result, 0, "unread");
1490
1491 return $unread;
1492 }
1493
1494 function getGlobalUnread($user_id = false) {
1495
1496 if (!$user_id) {
1497 $user_id = $_SESSION["uid"];
1498 }
1499
1500 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1501 WHERE owner_uid = '$user_id' AND feed_id > 0");
1502
1503 $c_id = db_fetch_result($result, 0, "c_id");
1504
1505 return $c_id;
1506 }
1507
1508 function getGlobalCounters($global_unread = -1) {
1509 $ret_arr = array();
1510
1511 if ($global_unread == -1) {
1512 $global_unread = getGlobalUnread();
1513 }
1514
1515 $cv = array("id" => "global-unread",
1516 "counter" => (int) $global_unread);
1517
1518 array_push($ret_arr, $cv);
1519
1520 $result = db_query("SELECT COUNT(id) AS fn FROM
1521 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1522
1523 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1524
1525 $cv = array("id" => "subscribed-feeds",
1526 "counter" => (int) $subscribed_feeds);
1527
1528 array_push($ret_arr, $cv);
1529
1530 return $ret_arr;
1531 }
1532
1533 function getVirtCounters() {
1534
1535 $ret_arr = array();
1536
1537 for ($i = 0; $i >= -4; $i--) {
1538
1539 $count = getFeedUnread($i);
1540
1541 if ($i == 0 || $i == -1 || $i == -2)
1542 $auxctr = getFeedArticles($i, false);
1543 else
1544 $auxctr = 0;
1545
1546 $cv = array("id" => $i,
1547 "counter" => (int) $count,
1548 "auxcounter" => $auxctr);
1549
1550 // if (get_pref('EXTENDED_FEEDLIST'))
1551 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1552
1553 array_push($ret_arr, $cv);
1554 }
1555
1556 $feeds = PluginHost::getInstance()->get_feeds(-1);
1557
1558 if (is_array($feeds)) {
1559 foreach ($feeds as $feed) {
1560 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1561 "counter" => $feed['sender']->get_unread($feed['id']));
1562
1563 if (method_exists($feed['sender'], 'get_total'))
1564 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1565
1566 array_push($ret_arr, $cv);
1567 }
1568 }
1569
1570 return $ret_arr;
1571 }
1572
1573 function getLabelCounters($descriptions = false) {
1574
1575 $ret_arr = array();
1576
1577 $owner_uid = $_SESSION["uid"];
1578
1579 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1580 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1581 (ttrss_labels2.id = label_id)
1582 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1583 WHERE ttrss_labels2.owner_uid = $owner_uid GROUP BY ttrss_labels2.id,
1584 ttrss_labels2.caption");
1585
1586 while ($line = db_fetch_assoc($result)) {
1587
1588 $id = label_to_feed_id($line["id"]);
1589
1590 $cv = array("id" => $id,
1591 "counter" => (int) $line["unread"],
1592 "auxcounter" => (int) $line["total"]);
1593
1594 if ($descriptions)
1595 $cv["description"] = $line["caption"];
1596
1597 array_push($ret_arr, $cv);
1598 }
1599
1600 return $ret_arr;
1601 }
1602
1603 function getFeedCounters($active_feed = false) {
1604
1605 $ret_arr = array();
1606
1607 $query = "SELECT ttrss_feeds.id,
1608 ttrss_feeds.title,
1609 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1610 last_error, value AS count
1611 FROM ttrss_feeds, ttrss_counters_cache
1612 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1613 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1614 AND ttrss_counters_cache.feed_id = id";
1615
1616 $result = db_query($query);
1617
1618 while ($line = db_fetch_assoc($result)) {
1619
1620 $id = $line["id"];
1621 $count = $line["count"];
1622 $last_error = htmlspecialchars($line["last_error"]);
1623
1624 $last_updated = make_local_datetime($line['last_updated'], false);
1625
1626 $has_img = feed_has_icon($id);
1627
1628 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1629 $last_updated = '';
1630
1631 $cv = array("id" => $id,
1632 "updated" => $last_updated,
1633 "counter" => (int) $count,
1634 "has_img" => (int) $has_img);
1635
1636 if ($last_error)
1637 $cv["error"] = $last_error;
1638
1639 // if (get_pref('EXTENDED_FEEDLIST'))
1640 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1641
1642 if ($active_feed && $id == $active_feed)
1643 $cv["title"] = truncate_string($line["title"], 30);
1644
1645 array_push($ret_arr, $cv);
1646
1647 }
1648
1649 return $ret_arr;
1650 }
1651
1652 function get_pgsql_version() {
1653 $result = db_query("SELECT version() AS version");
1654 $version = explode(" ", db_fetch_result($result, 0, "version"));
1655 return $version[1];
1656 }
1657
1658 /**
1659 * @return array (code => Status code, message => error message if available)
1660 *
1661 * 0 - OK, Feed already exists
1662 * 1 - OK, Feed added
1663 * 2 - Invalid URL
1664 * 3 - URL content is HTML, no feeds available
1665 * 4 - URL content is HTML which contains multiple feeds.
1666 * Here you should call extractfeedurls in rpc-backend
1667 * to get all possible feeds.
1668 * 5 - Couldn't download the URL content.
1669 * 6 - Content is an invalid XML.
1670 */
1671 function subscribe_to_feed($url, $cat_id = 0,
1672 $auth_login = '', $auth_pass = '') {
1673
1674 global $fetch_last_error;
1675
1676 require_once "include/rssfuncs.php";
1677
1678 $url = fix_url($url);
1679
1680 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1681
1682 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1683
1684 if (!$contents) {
1685 return array("code" => 5, "message" => $fetch_last_error);
1686 }
1687
1688 if (is_html($contents)) {
1689 $feedUrls = get_feeds_from_html($url, $contents);
1690
1691 if (count($feedUrls) == 0) {
1692 return array("code" => 3);
1693 } else if (count($feedUrls) > 1) {
1694 return array("code" => 4, "feeds" => $feedUrls);
1695 }
1696 //use feed url as new URL
1697 $url = key($feedUrls);
1698 }
1699
1700 /* libxml_use_internal_errors(true);
1701 $doc = new DOMDocument();
1702 $doc->loadXML($contents);
1703 $error = libxml_get_last_error();
1704 libxml_clear_errors();
1705
1706 if ($error) {
1707 $error_message = format_libxml_error($error);
1708
1709 return array("code" => 6, "message" => $error_message);
1710 } */
1711
1712 if ($cat_id == "0" || !$cat_id) {
1713 $cat_qpart = "NULL";
1714 } else {
1715 $cat_qpart = "'$cat_id'";
1716 }
1717
1718 $result = db_query(
1719 "SELECT id FROM ttrss_feeds
1720 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1721
1722 if (strlen(FEED_CRYPT_KEY) > 0) {
1723 require_once "crypt.php";
1724 $auth_pass = substr(encrypt_string($auth_pass), 0, 250);
1725 $auth_pass_encrypted = 'true';
1726 } else {
1727 $auth_pass_encrypted = 'false';
1728 }
1729
1730 $auth_pass = db_escape_string($auth_pass);
1731
1732 if (db_num_rows($result) == 0) {
1733 $result = db_query(
1734 "INSERT INTO ttrss_feeds
1735 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1736 VALUES ('".$_SESSION["uid"]."', '$url',
1737 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1738
1739 $result = db_query(
1740 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1741 AND owner_uid = " . $_SESSION["uid"]);
1742
1743 $feed_id = db_fetch_result($result, 0, "id");
1744
1745 if ($feed_id) {
1746 update_rss_feed($feed_id, true);
1747 }
1748
1749 return array("code" => 1);
1750 } else {
1751 return array("code" => 0);
1752 }
1753 }
1754
1755 function print_feed_select($id, $default_id = "",
1756 $attributes = "", $include_all_feeds = true,
1757 $root_id = false, $nest_level = 0) {
1758
1759 if (!$root_id) {
1760 print "<select id=\"$id\" name=\"$id\" $attributes>";
1761 if ($include_all_feeds) {
1762 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1763 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1764 }
1765 }
1766
1767 if (get_pref('ENABLE_FEED_CATS')) {
1768
1769 if ($root_id)
1770 $parent_qpart = "parent_cat = '$root_id'";
1771 else
1772 $parent_qpart = "parent_cat IS NULL";
1773
1774 $result = db_query("SELECT id,title,
1775 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1776 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1777 FROM ttrss_feed_categories
1778 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1779
1780 while ($line = db_fetch_assoc($result)) {
1781
1782 for ($i = 0; $i < $nest_level; $i++)
1783 $line["title"] = " - " . $line["title"];
1784
1785 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1786
1787 printf("<option $is_selected value='CAT:%d'>%s</option>",
1788 $line["id"], htmlspecialchars($line["title"]));
1789
1790 if ($line["num_children"] > 0)
1791 print_feed_select($id, $default_id, $attributes,
1792 $include_all_feeds, $line["id"], $nest_level+1);
1793
1794 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1795 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1796
1797 while ($fline = db_fetch_assoc($feed_result)) {
1798 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1799
1800 $fline["title"] = " + " . $fline["title"];
1801
1802 for ($i = 0; $i < $nest_level; $i++)
1803 $fline["title"] = " - " . $fline["title"];
1804
1805 printf("<option $is_selected value='%d'>%s</option>",
1806 $fline["id"], htmlspecialchars($fline["title"]));
1807 }
1808 }
1809
1810 if (!$root_id) {
1811 $default_is_cat = ($default_id == "CAT:0");
1812 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1813
1814 printf("<option $is_selected value='CAT:0'>%s</option>",
1815 __("Uncategorized"));
1816
1817 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1818 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1819
1820 while ($fline = db_fetch_assoc($feed_result)) {
1821 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1822
1823 $fline["title"] = " + " . $fline["title"];
1824
1825 for ($i = 0; $i < $nest_level; $i++)
1826 $fline["title"] = " - " . $fline["title"];
1827
1828 printf("<option $is_selected value='%d'>%s</option>",
1829 $fline["id"], htmlspecialchars($fline["title"]));
1830 }
1831 }
1832
1833 } else {
1834 $result = db_query("SELECT id,title FROM ttrss_feeds
1835 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1836
1837 while ($line = db_fetch_assoc($result)) {
1838
1839 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1840
1841 printf("<option $is_selected value='%d'>%s</option>",
1842 $line["id"], htmlspecialchars($line["title"]));
1843 }
1844 }
1845
1846 if (!$root_id) {
1847 print "</select>";
1848 }
1849 }
1850
1851 function print_feed_cat_select($id, $default_id,
1852 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1853
1854 if (!$root_id) {
1855 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1856 }
1857
1858 if ($root_id)
1859 $parent_qpart = "parent_cat = '$root_id'";
1860 else
1861 $parent_qpart = "parent_cat IS NULL";
1862
1863 $result = db_query("SELECT id,title,
1864 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1865 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1866 FROM ttrss_feed_categories
1867 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1868
1869 while ($line = db_fetch_assoc($result)) {
1870 if ($line["id"] == $default_id) {
1871 $is_selected = "selected=\"1\"";
1872 } else {
1873 $is_selected = "";
1874 }
1875
1876 for ($i = 0; $i < $nest_level; $i++)
1877 $line["title"] = " - " . $line["title"];
1878
1879 if ($line["title"])
1880 printf("<option $is_selected value='%d'>%s</option>",
1881 $line["id"], htmlspecialchars($line["title"]));
1882
1883 if ($line["num_children"] > 0)
1884 print_feed_cat_select($id, $default_id, $attributes,
1885 $include_all_cats, $line["id"], $nest_level+1);
1886 }
1887
1888 if (!$root_id) {
1889 if ($include_all_cats) {
1890 if (db_num_rows($result) > 0) {
1891 print "<option disabled=\"1\">--------</option>";
1892 }
1893
1894 if ($default_id == 0) {
1895 $is_selected = "selected=\"1\"";
1896 } else {
1897 $is_selected = "";
1898 }
1899
1900 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1901 }
1902 print "</select>";
1903 }
1904 }
1905
1906 function checkbox_to_sql_bool($val) {
1907 return ($val == "on") ? "true" : "false";
1908 }
1909
1910 function getFeedCatTitle($id) {
1911 if ($id == -1) {
1912 return __("Special");
1913 } else if ($id < LABEL_BASE_INDEX) {
1914 return __("Labels");
1915 } else if ($id > 0) {
1916 $result = db_query("SELECT ttrss_feed_categories.title
1917 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1918 cat_id = ttrss_feed_categories.id");
1919 if (db_num_rows($result) == 1) {
1920 return db_fetch_result($result, 0, "title");
1921 } else {
1922 return __("Uncategorized");
1923 }
1924 } else {
1925 return "getFeedCatTitle($id) failed";
1926 }
1927
1928 }
1929
1930 function getFeedIcon($id) {
1931 switch ($id) {
1932 case 0:
1933 return "images/archive.png";
1934 break;
1935 case -1:
1936 return "images/star.png";
1937 break;
1938 case -2:
1939 return "images/feed.png";
1940 break;
1941 case -3:
1942 return "images/fresh.png";
1943 break;
1944 case -4:
1945 return "images/folder.png";
1946 break;
1947 case -6:
1948 return "images/time.png";
1949 break;
1950 default:
1951 if ($id < LABEL_BASE_INDEX) {
1952 return "images/label.png";
1953 } else {
1954 if (file_exists(ICONS_DIR . "/$id.ico"))
1955 return ICONS_URL . "/$id.ico";
1956 }
1957 break;
1958 }
1959
1960 return false;
1961 }
1962
1963 function getFeedTitle($id, $cat = false) {
1964 if ($cat) {
1965 return getCategoryTitle($id);
1966 } else if ($id == -1) {
1967 return __("Starred articles");
1968 } else if ($id == -2) {
1969 return __("Published articles");
1970 } else if ($id == -3) {
1971 return __("Fresh articles");
1972 } else if ($id == -4) {
1973 return __("All articles");
1974 } else if ($id === 0 || $id === "0") {
1975 return __("Archived articles");
1976 } else if ($id == -6) {
1977 return __("Recently read");
1978 } else if ($id < LABEL_BASE_INDEX) {
1979 $label_id = feed_to_label_id($id);
1980 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1981 if (db_num_rows($result) == 1) {
1982 return db_fetch_result($result, 0, "caption");
1983 } else {
1984 return "Unknown label ($label_id)";
1985 }
1986
1987 } else if (is_numeric($id) && $id > 0) {
1988 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
1989 if (db_num_rows($result) == 1) {
1990 return db_fetch_result($result, 0, "title");
1991 } else {
1992 return "Unknown feed ($id)";
1993 }
1994 } else {
1995 return $id;
1996 }
1997 }
1998
1999 // TODO: less dumb splitting
2000 require_once "functions2.php";
2001
2002 ?>