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