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