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