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