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