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