]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
af_zz_imgproxy: add optional setting to proxy all remote images
[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, $attributes = "") {
671 $checked_str = $checked ? "checked" : "";
672
673 print "<input dojoType=\"dijit.form.CheckBox\" id=\"$id\" $checked_str $attributes name=\"$id\">";
674 }
675
676 function print_button($type, $value, $attributes = "") {
677 print "<p><button dojoType=\"dijit.form.Button\" $attributes type=\"$type\">$value</button>";
678 }
679
680 function print_radio($id, $default, $true_is, $values, $attributes = "") {
681 foreach ($values as $v) {
682
683 if ($v == $default)
684 $sel = "checked";
685 else
686 $sel = "";
687
688 if ($v == $true_is) {
689 $sel .= " value=\"1\"";
690 } else {
691 $sel .= " value=\"0\"";
692 }
693
694 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
695 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
696
697 }
698 }
699
700 function initialize_user_prefs($uid, $profile = false) {
701
702 $uid = db_escape_string($uid);
703
704 if (!$profile) {
705 $profile = "NULL";
706 $profile_qpart = "AND profile IS NULL";
707 } else {
708 $profile_qpart = "AND profile = '$profile'";
709 }
710
711 if (get_schema_version() < 63) $profile_qpart = "";
712
713 db_query("BEGIN");
714
715 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
716
717 $u_result = db_query("SELECT pref_name
718 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
719
720 $active_prefs = array();
721
722 while ($line = db_fetch_assoc($u_result)) {
723 array_push($active_prefs, $line["pref_name"]);
724 }
725
726 while ($line = db_fetch_assoc($result)) {
727 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
728 // print "adding " . $line["pref_name"] . "<br>";
729
730 $line["def_value"] = db_escape_string($line["def_value"]);
731 $line["pref_name"] = db_escape_string($line["pref_name"]);
732
733 if (get_schema_version() < 63) {
734 db_query("INSERT INTO ttrss_user_prefs
735 (owner_uid,pref_name,value) VALUES
736 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
737
738 } else {
739 db_query("INSERT INTO ttrss_user_prefs
740 (owner_uid,pref_name,value, profile) VALUES
741 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
742 }
743
744 }
745 }
746
747 db_query("COMMIT");
748
749 }
750
751 function get_ssl_certificate_id() {
752 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
753 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
754 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
755 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
756 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
757 }
758 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
759 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
760 $_SERVER["SSL_CLIENT_V_START"] .
761 $_SERVER["SSL_CLIENT_V_END"] .
762 $_SERVER["SSL_CLIENT_S_DN"]);
763 }
764 return "";
765 }
766
767 function authenticate_user($login, $password, $check_only = false) {
768
769 if (!SINGLE_USER_MODE) {
770 $user_id = false;
771
772 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
773
774 $user_id = (int) $plugin->authenticate($login, $password);
775
776 if ($user_id) {
777 $_SESSION["auth_module"] = strtolower(get_class($plugin));
778 break;
779 }
780 }
781
782 if ($user_id && !$check_only) {
783 @session_start();
784
785 $_SESSION["uid"] = $user_id;
786 $_SESSION["version"] = VERSION_STATIC;
787
788 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
789 WHERE id = '$user_id'");
790
791 $_SESSION["name"] = db_fetch_result($result, 0, "login");
792 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
793 $_SESSION["csrf_token"] = uniqid_short();
794
795 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
796 $_SESSION["uid"]);
797
798 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
799 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
800 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
801
802 $_SESSION["last_version_check"] = time();
803
804 initialize_user_prefs($_SESSION["uid"]);
805
806 return true;
807 }
808
809 return false;
810
811 } else {
812
813 $_SESSION["uid"] = 1;
814 $_SESSION["name"] = "admin";
815 $_SESSION["access_level"] = 10;
816
817 $_SESSION["hide_hello"] = true;
818 $_SESSION["hide_logout"] = true;
819
820 $_SESSION["auth_module"] = false;
821
822 if (!$_SESSION["csrf_token"]) {
823 $_SESSION["csrf_token"] = uniqid_short();
824 }
825
826 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
827
828 initialize_user_prefs($_SESSION["uid"]);
829
830 return true;
831 }
832 }
833
834 function make_password($length = 8) {
835
836 $password = "";
837 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
838
839 $i = 0;
840
841 while ($i < $length) {
842 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
843
844 if (!strstr($password, $char)) {
845 $password .= $char;
846 $i++;
847 }
848 }
849 return $password;
850 }
851
852 // this is called after user is created to initialize default feeds, labels
853 // or whatever else
854
855 // user preferences are checked on every login, not here
856
857 function initialize_user($uid) {
858
859 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
860 values ('$uid', 'Tiny Tiny RSS: Forum',
861 'http://tt-rss.org/forum/rss.php')");
862 }
863
864 function logout_user() {
865 session_destroy();
866 if (isset($_COOKIE[session_name()])) {
867 setcookie(session_name(), '', time()-42000, '/');
868 }
869 }
870
871 function validate_csrf($csrf_token) {
872 return $csrf_token == $_SESSION['csrf_token'];
873 }
874
875 function load_user_plugins($owner_uid, $pluginhost = false) {
876
877 if (!$pluginhost) $pluginhost = PluginHost::getInstance();
878
879 if ($owner_uid && SCHEMA_VERSION >= 100) {
880 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
881
882 $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
883
884 if (get_schema_version() > 100) {
885 $pluginhost->load_data();
886 }
887 }
888 }
889
890 function login_sequence() {
891 if (SINGLE_USER_MODE) {
892 @session_start();
893 authenticate_user("admin", null);
894 startup_gettext();
895 load_user_plugins($_SESSION["uid"]);
896 } else {
897 if (!validate_session()) $_SESSION["uid"] = false;
898
899 if (!$_SESSION["uid"]) {
900
901 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
902 $_SESSION["ref_schema_version"] = get_schema_version(true);
903 } else {
904 authenticate_user(null, null, true);
905 }
906
907 if (!$_SESSION["uid"]) {
908 @session_destroy();
909 setcookie(session_name(), '', time()-42000, '/');
910
911 render_login_form();
912 exit;
913 }
914
915 } else {
916 /* bump login timestamp */
917 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
918 $_SESSION["uid"]);
919 $_SESSION["last_login_update"] = time();
920 }
921
922 if ($_SESSION["uid"]) {
923 startup_gettext();
924 load_user_plugins($_SESSION["uid"]);
925
926 /* cleanup ccache */
927
928 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
929 $_SESSION["uid"] . " AND
930 (SELECT COUNT(id) FROM ttrss_feeds WHERE
931 ttrss_feeds.id = feed_id) = 0");
932
933 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
934 $_SESSION["uid"] . " AND
935 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
936 ttrss_feed_categories.id = feed_id) = 0");
937
938 }
939
940 }
941 }
942
943 function truncate_string($str, $max_len, $suffix = '&hellip;') {
944 if (mb_strlen($str, "utf-8") > $max_len) {
945 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
946 } else {
947 return $str;
948 }
949 }
950
951 // is not utf8 clean
952 function truncate_middle($str, $max_len, $suffix = '&hellip;') {
953 if (strlen($str) > $max_len) {
954 return substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
955 } else {
956 return $str;
957 }
958 }
959
960 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
961
962 try {
963 $source_tz = new DateTimeZone($source_tz);
964 } catch (Exception $e) {
965 $source_tz = new DateTimeZone('UTC');
966 }
967
968 try {
969 $dest_tz = new DateTimeZone($dest_tz);
970 } catch (Exception $e) {
971 $dest_tz = new DateTimeZone('UTC');
972 }
973
974 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
975 return $dt->format('U') + $dest_tz->getOffset($dt);
976 }
977
978 function make_local_datetime($timestamp, $long, $owner_uid = false,
979 $no_smart_dt = false, $eta_min = false) {
980
981 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
982 if (!$timestamp) $timestamp = '1970-01-01 0:00';
983
984 global $utc_tz;
985 global $user_tz;
986
987 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
988
989 $timestamp = substr($timestamp, 0, 19);
990
991 # We store date in UTC internally
992 $dt = new DateTime($timestamp, $utc_tz);
993
994 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
995
996 if ($user_tz_string != 'Automatic') {
997
998 try {
999 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
1000 } catch (Exception $e) {
1001 $user_tz = $utc_tz;
1002 }
1003
1004 $tz_offset = $user_tz->getOffset($dt);
1005 } else {
1006 $tz_offset = (int) -$_SESSION["clientTzOffset"];
1007 }
1008
1009 $user_timestamp = $dt->format('U') + $tz_offset;
1010
1011 if (!$no_smart_dt) {
1012 return smart_date_time($user_timestamp,
1013 $tz_offset, $owner_uid, $eta_min);
1014 } else {
1015 if ($long)
1016 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1017 else
1018 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
1019
1020 return date($format, $user_timestamp);
1021 }
1022 }
1023
1024 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
1025 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1026
1027 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
1028 return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
1029 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
1030 return date("G:i", $timestamp);
1031 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
1032 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
1033 return date($format, $timestamp);
1034 } else {
1035 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
1036 return date($format, $timestamp);
1037 }
1038 }
1039
1040 function sql_bool_to_bool($s) {
1041 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
1042 return true;
1043 } else {
1044 return false;
1045 }
1046 }
1047
1048 function bool_to_sql_bool($s) {
1049 if ($s) {
1050 return "true";
1051 } else {
1052 return "false";
1053 }
1054 }
1055
1056 // Session caching removed due to causing wrong redirects to upgrade
1057 // script when get_schema_version() is called on an obsolete session
1058 // created on a previous schema version.
1059 function get_schema_version($nocache = false) {
1060 global $schema_version;
1061
1062 if (!$schema_version && !$nocache) {
1063 $result = db_query("SELECT schema_version FROM ttrss_version");
1064 $version = db_fetch_result($result, 0, "schema_version");
1065 $schema_version = $version;
1066 return $version;
1067 } else {
1068 return $schema_version;
1069 }
1070 }
1071
1072 function sanity_check() {
1073 require_once 'errors.php';
1074 global $ERRORS;
1075
1076 $error_code = 0;
1077 $schema_version = get_schema_version(true);
1078
1079 if ($schema_version != SCHEMA_VERSION) {
1080 $error_code = 5;
1081 }
1082
1083 if (DB_TYPE == "mysql") {
1084 $result = db_query("SELECT true", false);
1085 if (db_num_rows($result) != 1) {
1086 $error_code = 10;
1087 }
1088 }
1089
1090 if (db_escape_string("testTEST") != "testTEST") {
1091 $error_code = 12;
1092 }
1093
1094 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1095 }
1096
1097 function file_is_locked($filename) {
1098 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1099 if (function_exists('flock')) {
1100 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1101 if ($fp) {
1102 if (flock($fp, LOCK_EX | LOCK_NB)) {
1103 flock($fp, LOCK_UN);
1104 fclose($fp);
1105 return false;
1106 }
1107 fclose($fp);
1108 return true;
1109 } else {
1110 return false;
1111 }
1112 }
1113 return true; // consider the file always locked and skip the test
1114 } else {
1115 return false;
1116 }
1117 }
1118
1119
1120 function make_lockfile($filename) {
1121 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1122
1123 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1124 $stat_h = fstat($fp);
1125 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1126
1127 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1128 if ($stat_h["ino"] != $stat_f["ino"] ||
1129 $stat_h["dev"] != $stat_f["dev"]) {
1130
1131 return false;
1132 }
1133 }
1134
1135 if (function_exists('posix_getpid')) {
1136 fwrite($fp, posix_getpid() . "\n");
1137 }
1138 return $fp;
1139 } else {
1140 return false;
1141 }
1142 }
1143
1144 function make_stampfile($filename) {
1145 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1146
1147 if (flock($fp, LOCK_EX | LOCK_NB)) {
1148 fwrite($fp, time() . "\n");
1149 flock($fp, LOCK_UN);
1150 fclose($fp);
1151 return true;
1152 } else {
1153 return false;
1154 }
1155 }
1156
1157 function sql_random_function() {
1158 if (DB_TYPE == "mysql") {
1159 return "RAND()";
1160 } else {
1161 return "RANDOM()";
1162 }
1163 }
1164
1165 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1166
1167 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1168
1169 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1170
1171 // Todo: all this interval stuff needs some generic generator function
1172
1173 $date_qpart = "false";
1174
1175 switch ($mode) {
1176 case "1day":
1177 if (DB_TYPE == "pgsql") {
1178 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1179 } else {
1180 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1181 }
1182 break;
1183 case "1week":
1184 if (DB_TYPE == "pgsql") {
1185 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1186 } else {
1187 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1188 }
1189 break;
1190 case "2week":
1191 if (DB_TYPE == "pgsql") {
1192 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1193 } else {
1194 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1195 }
1196 break;
1197 default:
1198 $date_qpart = "true";
1199 }
1200
1201 if (is_numeric($feed)) {
1202 if ($cat_view) {
1203
1204 if ($feed >= 0) {
1205
1206 if ($feed > 0) {
1207 $children = getChildCategories($feed, $owner_uid);
1208 array_push($children, $feed);
1209
1210 $children = join(",", $children);
1211
1212 $cat_qpart = "cat_id IN ($children)";
1213 } else {
1214 $cat_qpart = "cat_id IS NULL";
1215 }
1216
1217 db_query("UPDATE ttrss_user_entries
1218 SET unread = false, last_read = NOW() WHERE ref_id IN
1219 (SELECT id FROM
1220 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1221 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1222 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1223
1224 } else if ($feed == -2) {
1225
1226 db_query("UPDATE ttrss_user_entries
1227 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1228 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1229 AND unread = true AND owner_uid = $owner_uid");
1230 }
1231
1232 } else if ($feed > 0) {
1233
1234 db_query("UPDATE ttrss_user_entries
1235 SET unread = false, last_read = NOW() WHERE ref_id IN
1236 (SELECT id FROM
1237 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1238 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1239
1240 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1241
1242 if ($feed == -1) {
1243 db_query("UPDATE ttrss_user_entries
1244 SET unread = false, last_read = NOW() WHERE ref_id IN
1245 (SELECT id FROM
1246 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1247 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1248 }
1249
1250 if ($feed == -2) {
1251 db_query("UPDATE ttrss_user_entries
1252 SET unread = false, last_read = NOW() WHERE ref_id IN
1253 (SELECT id FROM
1254 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1255 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1256 }
1257
1258 if ($feed == -3) {
1259
1260 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1261
1262 if (DB_TYPE == "pgsql") {
1263 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1264 } else {
1265 $match_part = "date_entered > DATE_SUB(NOW(),
1266 INTERVAL $intl HOUR) ";
1267 }
1268
1269 db_query("UPDATE ttrss_user_entries
1270 SET unread = false, last_read = NOW() WHERE ref_id IN
1271 (SELECT id FROM
1272 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1273 AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1274 }
1275
1276 if ($feed == -4) {
1277 db_query("UPDATE ttrss_user_entries
1278 SET unread = false, last_read = NOW() WHERE ref_id IN
1279 (SELECT id FROM
1280 (SELECT DISTINCT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1281 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1282 }
1283
1284 } else if ($feed < LABEL_BASE_INDEX) { // label
1285
1286 $label_id = feed_to_label_id($feed);
1287
1288 db_query("UPDATE ttrss_user_entries
1289 SET unread = false, last_read = NOW() WHERE ref_id IN
1290 (SELECT id FROM
1291 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1292 AND label_id = '$label_id' AND ref_id = article_id
1293 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1294
1295 }
1296
1297 ccache_update($feed, $owner_uid, $cat_view);
1298
1299 } else { // tag
1300 db_query("UPDATE ttrss_user_entries
1301 SET unread = false, last_read = NOW() WHERE ref_id IN
1302 (SELECT id FROM
1303 (SELECT DISTINCT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1304 AND post_int_id = int_id AND tag_name = '$feed'
1305 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1306
1307 }
1308 }
1309
1310 function getAllCounters() {
1311 $data = getGlobalCounters();
1312
1313 $data = array_merge($data, getVirtCounters());
1314 $data = array_merge($data, getLabelCounters());
1315 $data = array_merge($data, getFeedCounters());
1316 $data = array_merge($data, getCategoryCounters());
1317
1318 return $data;
1319 }
1320
1321 function getCategoryTitle($cat_id) {
1322
1323 if ($cat_id == -1) {
1324 return __("Special");
1325 } else if ($cat_id == -2) {
1326 return __("Labels");
1327 } else {
1328
1329 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1330 id = '$cat_id'");
1331
1332 if (db_num_rows($result) == 1) {
1333 return db_fetch_result($result, 0, "title");
1334 } else {
1335 return __("Uncategorized");
1336 }
1337 }
1338 }
1339
1340
1341 function getCategoryCounters() {
1342 $ret_arr = array();
1343
1344 /* Labels category */
1345
1346 $cv = array("id" => -2, "kind" => "cat",
1347 "counter" => getCategoryUnread(-2));
1348
1349 array_push($ret_arr, $cv);
1350
1351 $result = db_query("SELECT id AS cat_id, value AS unread,
1352 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1353 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1354 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1355 WHERE ttrss_cat_counters_cache.feed_id = id AND
1356 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1357 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1358
1359 while ($line = db_fetch_assoc($result)) {
1360 $line["cat_id"] = (int) $line["cat_id"];
1361
1362 if ($line["num_children"] > 0) {
1363 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1364 } else {
1365 $child_counter = 0;
1366 }
1367
1368 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1369 "counter" => $line["unread"] + $child_counter);
1370
1371 array_push($ret_arr, $cv);
1372 }
1373
1374 /* Special case: NULL category doesn't actually exist in the DB */
1375
1376 $cv = array("id" => 0, "kind" => "cat",
1377 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1378
1379 array_push($ret_arr, $cv);
1380
1381 return $ret_arr;
1382 }
1383
1384 // only accepts real cats (>= 0)
1385 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1386 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1387
1388 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1389 AND owner_uid = $owner_uid");
1390
1391 $unread = 0;
1392
1393 while ($line = db_fetch_assoc($result)) {
1394 $unread += getCategoryUnread($line["id"], $owner_uid);
1395 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1396 }
1397
1398 return $unread;
1399 }
1400
1401 function getCategoryUnread($cat, $owner_uid = false) {
1402
1403 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1404
1405 if ($cat >= 0) {
1406
1407 if ($cat != 0) {
1408 $cat_query = "cat_id = '$cat'";
1409 } else {
1410 $cat_query = "cat_id IS NULL";
1411 }
1412
1413 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1414 AND owner_uid = " . $owner_uid);
1415
1416 $cat_feeds = array();
1417 while ($line = db_fetch_assoc($result)) {
1418 array_push($cat_feeds, "feed_id = " . $line["id"]);
1419 }
1420
1421 if (count($cat_feeds) == 0) return 0;
1422
1423 $match_part = implode(" OR ", $cat_feeds);
1424
1425 $result = db_query("SELECT COUNT(int_id) AS unread
1426 FROM ttrss_user_entries
1427 WHERE unread = true AND ($match_part)
1428 AND owner_uid = " . $owner_uid);
1429
1430 $unread = 0;
1431
1432 # this needs to be rewritten
1433 while ($line = db_fetch_assoc($result)) {
1434 $unread += $line["unread"];
1435 }
1436
1437 return $unread;
1438 } else if ($cat == -1) {
1439 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1440 } else if ($cat == -2) {
1441
1442 $result = db_query("
1443 SELECT COUNT(unread) AS unread FROM
1444 ttrss_user_entries, ttrss_user_labels2
1445 WHERE article_id = ref_id AND unread = true
1446 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1447
1448 $unread = db_fetch_result($result, 0, "unread");
1449
1450 return $unread;
1451
1452 }
1453 }
1454
1455 function getFeedUnread($feed, $is_cat = false) {
1456 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1457 }
1458
1459 function getLabelUnread($label_id, $owner_uid = false) {
1460 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1461
1462 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1463 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1464
1465 if (db_num_rows($result) != 0) {
1466 return db_fetch_result($result, 0, "unread");
1467 } else {
1468 return 0;
1469 }
1470 }
1471
1472 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1473 $owner_uid = false) {
1474
1475 $n_feed = (int) $feed;
1476 $need_entries = false;
1477
1478 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1479
1480 if ($unread_only) {
1481 $unread_qpart = "unread = true";
1482 } else {
1483 $unread_qpart = "true";
1484 }
1485
1486 if ($is_cat) {
1487 return getCategoryUnread($n_feed, $owner_uid);
1488 } else if ($n_feed == -6) {
1489 return 0;
1490 } else if ($feed != "0" && $n_feed == 0) {
1491
1492 $feed = db_escape_string($feed);
1493
1494 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1495 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1496 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1497 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1498 return db_fetch_result($result, 0, "count");
1499
1500 } else if ($n_feed == -1) {
1501 $match_part = "marked = true";
1502 } else if ($n_feed == -2) {
1503 $match_part = "published = true";
1504 } else if ($n_feed == -3) {
1505 $match_part = "unread = true AND score >= 0";
1506
1507 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1508
1509 if (DB_TYPE == "pgsql") {
1510 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1511 } else {
1512 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1513 }
1514
1515 $need_entries = true;
1516
1517 } else if ($n_feed == -4) {
1518 $match_part = "true";
1519 } else if ($n_feed >= 0) {
1520
1521 if ($n_feed != 0) {
1522 $match_part = "feed_id = '$n_feed'";
1523 } else {
1524 $match_part = "feed_id IS NULL";
1525 }
1526
1527 } else if ($feed < LABEL_BASE_INDEX) {
1528
1529 $label_id = feed_to_label_id($feed);
1530
1531 return getLabelUnread($label_id, $owner_uid);
1532
1533 }
1534
1535 if ($match_part) {
1536
1537 if ($need_entries) {
1538 $from_qpart = "ttrss_user_entries,ttrss_entries";
1539 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1540 } else {
1541 $from_qpart = "ttrss_user_entries";
1542 $from_where = "";
1543 }
1544
1545 $query = "SELECT count(int_id) AS unread
1546 FROM $from_qpart WHERE
1547 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1548
1549 //echo "[$feed/$query]\n";
1550
1551 $result = db_query($query);
1552
1553 } else {
1554
1555 $result = db_query("SELECT COUNT(post_int_id) AS unread
1556 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1557 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1558 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1559 }
1560
1561 $unread = db_fetch_result($result, 0, "unread");
1562
1563 return $unread;
1564 }
1565
1566 function getGlobalUnread($user_id = false) {
1567
1568 if (!$user_id) {
1569 $user_id = $_SESSION["uid"];
1570 }
1571
1572 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1573 WHERE owner_uid = '$user_id' AND feed_id > 0");
1574
1575 $c_id = db_fetch_result($result, 0, "c_id");
1576
1577 return $c_id;
1578 }
1579
1580 function getGlobalCounters($global_unread = -1) {
1581 $ret_arr = array();
1582
1583 if ($global_unread == -1) {
1584 $global_unread = getGlobalUnread();
1585 }
1586
1587 $cv = array("id" => "global-unread",
1588 "counter" => (int) $global_unread);
1589
1590 array_push($ret_arr, $cv);
1591
1592 $result = db_query("SELECT COUNT(id) AS fn FROM
1593 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1594
1595 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1596
1597 $cv = array("id" => "subscribed-feeds",
1598 "counter" => (int) $subscribed_feeds);
1599
1600 array_push($ret_arr, $cv);
1601
1602 return $ret_arr;
1603 }
1604
1605 function getVirtCounters() {
1606
1607 $ret_arr = array();
1608
1609 for ($i = 0; $i >= -4; $i--) {
1610
1611 $count = getFeedUnread($i);
1612
1613 if ($i == 0 || $i == -1 || $i == -2)
1614 $auxctr = getFeedArticles($i, false);
1615 else
1616 $auxctr = 0;
1617
1618 $cv = array("id" => $i,
1619 "counter" => (int) $count,
1620 "auxcounter" => (int) $auxctr);
1621
1622 // if (get_pref('EXTENDED_FEEDLIST'))
1623 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1624
1625 array_push($ret_arr, $cv);
1626 }
1627
1628 $feeds = PluginHost::getInstance()->get_feeds(-1);
1629
1630 if (is_array($feeds)) {
1631 foreach ($feeds as $feed) {
1632 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1633 "counter" => $feed['sender']->get_unread($feed['id']));
1634
1635 if (method_exists($feed['sender'], 'get_total'))
1636 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1637
1638 array_push($ret_arr, $cv);
1639 }
1640 }
1641
1642 return $ret_arr;
1643 }
1644
1645 function getLabelCounters($descriptions = false) {
1646
1647 $ret_arr = array();
1648
1649 $owner_uid = $_SESSION["uid"];
1650
1651 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1652 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1653 (ttrss_labels2.id = label_id)
1654 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1655 WHERE ttrss_labels2.owner_uid = $owner_uid AND u1.owner_uid = $owner_uid
1656 GROUP BY ttrss_labels2.id,
1657 ttrss_labels2.caption");
1658
1659 while ($line = db_fetch_assoc($result)) {
1660
1661 $id = label_to_feed_id($line["id"]);
1662
1663 $cv = array("id" => $id,
1664 "counter" => (int) $line["unread"],
1665 "auxcounter" => (int) $line["total"]);
1666
1667 if ($descriptions)
1668 $cv["description"] = $line["caption"];
1669
1670 array_push($ret_arr, $cv);
1671 }
1672
1673 return $ret_arr;
1674 }
1675
1676 function getFeedCounters($active_feed = false) {
1677
1678 $ret_arr = array();
1679
1680 $query = "SELECT ttrss_feeds.id,
1681 ttrss_feeds.title,
1682 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1683 last_error, value AS count
1684 FROM ttrss_feeds, ttrss_counters_cache
1685 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1686 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1687 AND ttrss_counters_cache.feed_id = id";
1688
1689 $result = db_query($query);
1690
1691 while ($line = db_fetch_assoc($result)) {
1692
1693 $id = $line["id"];
1694 $count = $line["count"];
1695 $last_error = htmlspecialchars($line["last_error"]);
1696
1697 $last_updated = make_local_datetime($line['last_updated'], false);
1698
1699 $has_img = feed_has_icon($id);
1700
1701 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1702 $last_updated = '';
1703
1704 $cv = array("id" => $id,
1705 "updated" => $last_updated,
1706 "counter" => (int) $count,
1707 "has_img" => (int) $has_img);
1708
1709 if ($last_error)
1710 $cv["error"] = $last_error;
1711
1712 // if (get_pref('EXTENDED_FEEDLIST'))
1713 // $cv["xmsg"] = getFeedArticles($id)." ".__("total");
1714
1715 if ($active_feed && $id == $active_feed)
1716 $cv["title"] = truncate_string($line["title"], 30);
1717
1718 array_push($ret_arr, $cv);
1719
1720 }
1721
1722 return $ret_arr;
1723 }
1724
1725 function get_pgsql_version() {
1726 $result = db_query("SELECT version() AS version");
1727 $version = explode(" ", db_fetch_result($result, 0, "version"));
1728 return $version[1];
1729 }
1730
1731 /**
1732 * @return array (code => Status code, message => error message if available)
1733 *
1734 * 0 - OK, Feed already exists
1735 * 1 - OK, Feed added
1736 * 2 - Invalid URL
1737 * 3 - URL content is HTML, no feeds available
1738 * 4 - URL content is HTML which contains multiple feeds.
1739 * Here you should call extractfeedurls in rpc-backend
1740 * to get all possible feeds.
1741 * 5 - Couldn't download the URL content.
1742 * 6 - Content is an invalid XML.
1743 */
1744 function subscribe_to_feed($url, $cat_id = 0,
1745 $auth_login = '', $auth_pass = '') {
1746
1747 global $fetch_last_error;
1748 global $fetch_last_error_content;
1749 global $fetch_last_error_code;
1750
1751 require_once "include/rssfuncs.php";
1752
1753 $url = fix_url($url);
1754
1755 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1756
1757 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1758
1759 if (!$contents) {
1760 if (preg_match("/cloudflare\.com/", $fetch_last_error_content)) {
1761 $fetch_last_error .= " (feed behind Cloudflare)";
1762 }
1763
1764 return array("code" => 5, "message" => $fetch_last_error);
1765 }
1766
1767 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SUBSCRIBE_FEED) as $plugin) {
1768 $contents = $plugin->hook_subscribe_feed($contents, $url, $auth_login, $auth_pass);
1769 }
1770
1771 if (is_html($contents)) {
1772 $feedUrls = get_feeds_from_html($url, $contents);
1773
1774 if (count($feedUrls) == 0) {
1775 return array("code" => 3);
1776 } else if (count($feedUrls) > 1) {
1777 return array("code" => 4, "feeds" => $feedUrls);
1778 }
1779 //use feed url as new URL
1780 $url = key($feedUrls);
1781 }
1782
1783 if ($cat_id == "0" || !$cat_id) {
1784 $cat_qpart = "NULL";
1785 } else {
1786 $cat_qpart = "'$cat_id'";
1787 }
1788
1789 $result = db_query(
1790 "SELECT id FROM ttrss_feeds
1791 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1792
1793 $auth_pass_encrypted = 'false';
1794 $auth_pass = db_escape_string($auth_pass);
1795
1796 if (db_num_rows($result) == 0) {
1797 $result = db_query(
1798 "INSERT INTO ttrss_feeds
1799 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method,auth_pass_encrypted)
1800 VALUES ('".$_SESSION["uid"]."', '$url',
1801 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0, $auth_pass_encrypted)");
1802
1803 $result = db_query(
1804 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1805 AND owner_uid = " . $_SESSION["uid"]);
1806
1807 $feed_id = db_fetch_result($result, 0, "id");
1808
1809 if ($feed_id) {
1810 set_basic_feed_info($feed_id);
1811 }
1812
1813 return array("code" => 1, "feed_id" => (int) $feed_id);
1814 } else {
1815 return array("code" => 0, "feed_id" => (int) db_fetch_result($result, 0, "id"));
1816 }
1817 }
1818
1819 function print_feed_select($id, $default_id = "",
1820 $attributes = "", $include_all_feeds = true,
1821 $root_id = false, $nest_level = 0) {
1822
1823 if (!$root_id) {
1824 print "<select id=\"$id\" name=\"$id\" $attributes>";
1825 if ($include_all_feeds) {
1826 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1827 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1828 }
1829 }
1830
1831 if (get_pref('ENABLE_FEED_CATS')) {
1832
1833 if ($root_id)
1834 $parent_qpart = "parent_cat = '$root_id'";
1835 else
1836 $parent_qpart = "parent_cat IS NULL";
1837
1838 $result = db_query("SELECT id,title,
1839 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1840 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1841 FROM ttrss_feed_categories
1842 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1843
1844 while ($line = db_fetch_assoc($result)) {
1845
1846 for ($i = 0; $i < $nest_level; $i++)
1847 $line["title"] = " - " . $line["title"];
1848
1849 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1850
1851 printf("<option $is_selected value='CAT:%d'>%s</option>",
1852 $line["id"], htmlspecialchars($line["title"]));
1853
1854 if ($line["num_children"] > 0)
1855 print_feed_select($id, $default_id, $attributes,
1856 $include_all_feeds, $line["id"], $nest_level+1);
1857
1858 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1859 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1860
1861 while ($fline = db_fetch_assoc($feed_result)) {
1862 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1863
1864 $fline["title"] = " + " . $fline["title"];
1865
1866 for ($i = 0; $i < $nest_level; $i++)
1867 $fline["title"] = " - " . $fline["title"];
1868
1869 printf("<option $is_selected value='%d'>%s</option>",
1870 $fline["id"], htmlspecialchars($fline["title"]));
1871 }
1872 }
1873
1874 if (!$root_id) {
1875 $default_is_cat = ($default_id == "CAT:0");
1876 $is_selected = $default_is_cat ? "selected=\"1\"" : "";
1877
1878 printf("<option $is_selected value='CAT:0'>%s</option>",
1879 __("Uncategorized"));
1880
1881 $feed_result = db_query("SELECT id,title FROM ttrss_feeds
1882 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1883
1884 while ($fline = db_fetch_assoc($feed_result)) {
1885 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1886
1887 $fline["title"] = " + " . $fline["title"];
1888
1889 for ($i = 0; $i < $nest_level; $i++)
1890 $fline["title"] = " - " . $fline["title"];
1891
1892 printf("<option $is_selected value='%d'>%s</option>",
1893 $fline["id"], htmlspecialchars($fline["title"]));
1894 }
1895 }
1896
1897 } else {
1898 $result = db_query("SELECT id,title FROM ttrss_feeds
1899 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1900
1901 while ($line = db_fetch_assoc($result)) {
1902
1903 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1904
1905 printf("<option $is_selected value='%d'>%s</option>",
1906 $line["id"], htmlspecialchars($line["title"]));
1907 }
1908 }
1909
1910 if (!$root_id) {
1911 print "</select>";
1912 }
1913 }
1914
1915 function print_feed_cat_select($id, $default_id,
1916 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1917
1918 if (!$root_id) {
1919 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1920 }
1921
1922 if ($root_id)
1923 $parent_qpart = "parent_cat = '$root_id'";
1924 else
1925 $parent_qpart = "parent_cat IS NULL";
1926
1927 $result = db_query("SELECT id,title,
1928 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1929 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1930 FROM ttrss_feed_categories
1931 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1932
1933 while ($line = db_fetch_assoc($result)) {
1934 if ($line["id"] == $default_id) {
1935 $is_selected = "selected=\"1\"";
1936 } else {
1937 $is_selected = "";
1938 }
1939
1940 for ($i = 0; $i < $nest_level; $i++)
1941 $line["title"] = " - " . $line["title"];
1942
1943 if ($line["title"])
1944 printf("<option $is_selected value='%d'>%s</option>",
1945 $line["id"], htmlspecialchars($line["title"]));
1946
1947 if ($line["num_children"] > 0)
1948 print_feed_cat_select($id, $default_id, $attributes,
1949 $include_all_cats, $line["id"], $nest_level+1);
1950 }
1951
1952 if (!$root_id) {
1953 if ($include_all_cats) {
1954 if (db_num_rows($result) > 0) {
1955 print "<option disabled=\"1\">--------</option>";
1956 }
1957
1958 if ($default_id == 0) {
1959 $is_selected = "selected=\"1\"";
1960 } else {
1961 $is_selected = "";
1962 }
1963
1964 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1965 }
1966 print "</select>";
1967 }
1968 }
1969
1970 function checkbox_to_sql_bool($val) {
1971 return ($val == "on") ? "true" : "false";
1972 }
1973
1974 function getFeedCatTitle($id) {
1975 if ($id == -1) {
1976 return __("Special");
1977 } else if ($id < LABEL_BASE_INDEX) {
1978 return __("Labels");
1979 } else if ($id > 0) {
1980 $result = db_query("SELECT ttrss_feed_categories.title
1981 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1982 cat_id = ttrss_feed_categories.id");
1983 if (db_num_rows($result) == 1) {
1984 return db_fetch_result($result, 0, "title");
1985 } else {
1986 return __("Uncategorized");
1987 }
1988 } else {
1989 return "getFeedCatTitle($id) failed";
1990 }
1991
1992 }
1993
1994 function getFeedIcon($id) {
1995 switch ($id) {
1996 case 0:
1997 return "images/archive.png";
1998 break;
1999 case -1:
2000 return "images/star.png";
2001 break;
2002 case -2:
2003 return "images/feed.png";
2004 break;
2005 case -3:
2006 return "images/fresh.png";
2007 break;
2008 case -4:
2009 return "images/folder.png";
2010 break;
2011 case -6:
2012 return "images/time.png";
2013 break;
2014 default:
2015 if ($id < LABEL_BASE_INDEX) {
2016 return "images/label.png";
2017 } else {
2018 if (file_exists(ICONS_DIR . "/$id.ico"))
2019 return ICONS_URL . "/$id.ico";
2020 }
2021 break;
2022 }
2023
2024 return false;
2025 }
2026
2027 function getFeedTitle($id, $cat = false) {
2028 if ($cat) {
2029 return getCategoryTitle($id);
2030 } else if ($id == -1) {
2031 return __("Starred articles");
2032 } else if ($id == -2) {
2033 return __("Published articles");
2034 } else if ($id == -3) {
2035 return __("Fresh articles");
2036 } else if ($id == -4) {
2037 return __("All articles");
2038 } else if ($id === 0 || $id === "0") {
2039 return __("Archived articles");
2040 } else if ($id == -6) {
2041 return __("Recently read");
2042 } else if ($id < LABEL_BASE_INDEX) {
2043 $label_id = feed_to_label_id($id);
2044 $result = db_query("SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2045 if (db_num_rows($result) == 1) {
2046 return db_fetch_result($result, 0, "caption");
2047 } else {
2048 return "Unknown label ($label_id)";
2049 }
2050
2051 } else if (is_numeric($id) && $id > 0) {
2052 $result = db_query("SELECT title FROM ttrss_feeds WHERE id = '$id'");
2053 if (db_num_rows($result) == 1) {
2054 return db_fetch_result($result, 0, "title");
2055 } else {
2056 return "Unknown feed ($id)";
2057 }
2058 } else {
2059 return $id;
2060 }
2061 }
2062
2063 function uniqid_short() {
2064 return uniqid(base_convert(rand(), 10, 36));
2065 }
2066
2067 // TODO: less dumb splitting
2068 require_once "functions2.php";
2069
2070 ?>