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