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