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