]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
d90855ea6bd275acd90e8a0427ece00233e2a674
[tt-rss.git] / include / functions.php
1 <?php
2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 128);
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 = "") {
584 print "<select name=\"$id\" id=\"$id\" $attributes>";
585 foreach ($values as $v) {
586 if ($v == $default)
587 $sel = "selected=\"1\"";
588 else
589 $sel = "";
590
591 $v = trim($v);
592
593 print "<option value=\"$v\" $sel>$v</option>";
594 }
595 print "</select>";
596 }
597
598 function print_select_hash($id, $default, $values, $attributes = "") {
599 print "<select name=\"$id\" id='$id' $attributes>";
600 foreach (array_keys($values) as $v) {
601 if ($v == $default)
602 $sel = 'selected="selected"';
603 else
604 $sel = "";
605
606 $v = trim($v);
607
608 print "<option $sel value=\"$v\">".$values[$v]."</option>";
609 }
610
611 print "</select>";
612 }
613
614 function print_radio($id, $default, $true_is, $values, $attributes = "") {
615 foreach ($values as $v) {
616
617 if ($v == $default)
618 $sel = "checked";
619 else
620 $sel = "";
621
622 if ($v == $true_is) {
623 $sel .= " value=\"1\"";
624 } else {
625 $sel .= " value=\"0\"";
626 }
627
628 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
629 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
630
631 }
632 }
633
634 function initialize_user_prefs($uid, $profile = false) {
635
636 $uid = db_escape_string($uid);
637
638 if (!$profile) {
639 $profile = "NULL";
640 $profile_qpart = "AND profile IS NULL";
641 } else {
642 $profile_qpart = "AND profile = '$profile'";
643 }
644
645 if (get_schema_version() < 63) $profile_qpart = "";
646
647 db_query("BEGIN");
648
649 $result = db_query("SELECT pref_name,def_value FROM ttrss_prefs");
650
651 $u_result = db_query("SELECT pref_name
652 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
653
654 $active_prefs = array();
655
656 while ($line = db_fetch_assoc($u_result)) {
657 array_push($active_prefs, $line["pref_name"]);
658 }
659
660 while ($line = db_fetch_assoc($result)) {
661 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
662 // print "adding " . $line["pref_name"] . "<br>";
663
664 $line["def_value"] = db_escape_string($line["def_value"]);
665 $line["pref_name"] = db_escape_string($line["pref_name"]);
666
667 if (get_schema_version() < 63) {
668 db_query("INSERT INTO ttrss_user_prefs
669 (owner_uid,pref_name,value) VALUES
670 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
671
672 } else {
673 db_query("INSERT INTO ttrss_user_prefs
674 (owner_uid,pref_name,value, profile) VALUES
675 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
676 }
677
678 }
679 }
680
681 db_query("COMMIT");
682
683 }
684
685 function get_ssl_certificate_id() {
686 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
687 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
688 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
689 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
690 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
691 }
692 if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
693 return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
694 $_SERVER["SSL_CLIENT_V_START"] .
695 $_SERVER["SSL_CLIENT_V_END"] .
696 $_SERVER["SSL_CLIENT_S_DN"]);
697 }
698 return "";
699 }
700
701 function authenticate_user($login, $password, $check_only = false) {
702
703 if (!SINGLE_USER_MODE) {
704 $user_id = false;
705
706 foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
707
708 $user_id = (int) $plugin->authenticate($login, $password);
709
710 if ($user_id) {
711 $_SESSION["auth_module"] = strtolower(get_class($plugin));
712 break;
713 }
714 }
715
716 if ($user_id && !$check_only) {
717 @session_start();
718
719 $_SESSION["uid"] = $user_id;
720 $_SESSION["version"] = VERSION_STATIC;
721
722 $result = db_query("SELECT login,access_level,pwd_hash FROM ttrss_users
723 WHERE id = '$user_id'");
724
725 $_SESSION["name"] = db_fetch_result($result, 0, "login");
726 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
727 $_SESSION["csrf_token"] = uniqid_short();
728
729 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
730 $_SESSION["uid"]);
731
732 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
733 $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
734 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
735
736 $_SESSION["last_version_check"] = time();
737
738 initialize_user_prefs($_SESSION["uid"]);
739
740 return true;
741 }
742
743 return false;
744
745 } else {
746
747 $_SESSION["uid"] = 1;
748 $_SESSION["name"] = "admin";
749 $_SESSION["access_level"] = 10;
750
751 $_SESSION["hide_hello"] = true;
752 $_SESSION["hide_logout"] = true;
753
754 $_SESSION["auth_module"] = false;
755
756 if (!$_SESSION["csrf_token"]) {
757 $_SESSION["csrf_token"] = uniqid_short();
758 }
759
760 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
761
762 initialize_user_prefs($_SESSION["uid"]);
763
764 return true;
765 }
766 }
767
768 function make_password($length = 8) {
769
770 $password = "";
771 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
772
773 $i = 0;
774
775 while ($i < $length) {
776 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
777
778 if (!strstr($password, $char)) {
779 $password .= $char;
780 $i++;
781 }
782 }
783 return $password;
784 }
785
786 // this is called after user is created to initialize default feeds, labels
787 // or whatever else
788
789 // user preferences are checked on every login, not here
790
791 function initialize_user($uid) {
792
793 db_query("insert into ttrss_feeds (owner_uid,title,feed_url)
794 values ('$uid', 'Tiny Tiny RSS: Forum',
795 'http://tt-rss.org/forum/rss.php')");
796 }
797
798 function logout_user() {
799 session_destroy();
800 if (isset($_COOKIE[session_name()])) {
801 setcookie(session_name(), '', time()-42000, '/');
802 }
803 }
804
805 function validate_csrf($csrf_token) {
806 return $csrf_token == $_SESSION['csrf_token'];
807 }
808
809 function load_user_plugins($owner_uid) {
810 if ($owner_uid && SCHEMA_VERSION >= 100) {
811 $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
812
813 PluginHost::getInstance()->load($plugins, PluginHost::KIND_USER, $owner_uid);
814
815 if (get_schema_version() > 100) {
816 PluginHost::getInstance()->load_data();
817 }
818 }
819 }
820
821 function login_sequence() {
822 if (SINGLE_USER_MODE) {
823 @session_start();
824 authenticate_user("admin", null);
825 startup_gettext();
826 load_user_plugins($_SESSION["uid"]);
827 } else {
828 if (!validate_session()) $_SESSION["uid"] = false;
829
830 if (!$_SESSION["uid"]) {
831
832 if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
833 $_SESSION["ref_schema_version"] = get_schema_version(true);
834 } else {
835 authenticate_user(null, null, true);
836 }
837
838 if (!$_SESSION["uid"]) {
839 @session_destroy();
840 setcookie(session_name(), '', time()-42000, '/');
841
842 render_login_form();
843 exit;
844 }
845
846 } else {
847 /* bump login timestamp */
848 db_query("UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
849 $_SESSION["uid"]);
850 $_SESSION["last_login_update"] = time();
851 }
852
853 if ($_SESSION["uid"]) {
854 startup_gettext();
855 load_user_plugins($_SESSION["uid"]);
856
857 /* cleanup ccache */
858
859 db_query("DELETE FROM ttrss_counters_cache WHERE owner_uid = ".
860 $_SESSION["uid"] . " AND
861 (SELECT COUNT(id) FROM ttrss_feeds WHERE
862 ttrss_feeds.id = feed_id) = 0");
863
864 db_query("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ".
865 $_SESSION["uid"] . " AND
866 (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
867 ttrss_feed_categories.id = feed_id) = 0");
868
869 }
870
871 }
872 }
873
874 function truncate_string($str, $max_len, $suffix = '&hellip;') {
875 if (mb_strlen($str, "utf-8") > $max_len) {
876 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
877 } else {
878 return $str;
879 }
880 }
881
882 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
883
884 try {
885 $source_tz = new DateTimeZone($source_tz);
886 } catch (Exception $e) {
887 $source_tz = new DateTimeZone('UTC');
888 }
889
890 try {
891 $dest_tz = new DateTimeZone($dest_tz);
892 } catch (Exception $e) {
893 $dest_tz = new DateTimeZone('UTC');
894 }
895
896 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
897 return $dt->format('U') + $dest_tz->getOffset($dt);
898 }
899
900 function make_local_datetime($timestamp, $long, $owner_uid = false,
901 $no_smart_dt = false, $eta_min = false) {
902
903 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
904 if (!$timestamp) $timestamp = '1970-01-01 0:00';
905
906 global $utc_tz;
907 global $user_tz;
908
909 if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
910
911 $timestamp = substr($timestamp, 0, 19);
912
913 # We store date in UTC internally
914 $dt = new DateTime($timestamp, $utc_tz);
915
916 $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
917
918 if ($user_tz_string != 'Automatic') {
919
920 try {
921 if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
922 } catch (Exception $e) {
923 $user_tz = $utc_tz;
924 }
925
926 $tz_offset = $user_tz->getOffset($dt);
927 } else {
928 $tz_offset = (int) -$_SESSION["clientTzOffset"];
929 }
930
931 $user_timestamp = $dt->format('U') + $tz_offset;
932
933 if (!$no_smart_dt) {
934 return smart_date_time($user_timestamp,
935 $tz_offset, $owner_uid, $eta_min);
936 } else {
937 if ($long)
938 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
939 else
940 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
941
942 return date($format, $user_timestamp);
943 }
944 }
945
946 function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
947 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
948
949 if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
950 return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
951 } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
952 return date("G:i", $timestamp);
953 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
954 $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
955 return date($format, $timestamp);
956 } else {
957 $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
958 return date($format, $timestamp);
959 }
960 }
961
962 function sql_bool_to_bool($s) {
963 if ($s == "t" || $s == "1" || strtolower($s) == "true") {
964 return true;
965 } else {
966 return false;
967 }
968 }
969
970 function bool_to_sql_bool($s) {
971 if ($s) {
972 return "true";
973 } else {
974 return "false";
975 }
976 }
977
978 // Session caching removed due to causing wrong redirects to upgrade
979 // script when get_schema_version() is called on an obsolete session
980 // created on a previous schema version.
981 function get_schema_version($nocache = false) {
982 global $schema_version;
983
984 if (!$schema_version && !$nocache) {
985 $result = db_query("SELECT schema_version FROM ttrss_version");
986 $version = db_fetch_result($result, 0, "schema_version");
987 $schema_version = $version;
988 return $version;
989 } else {
990 return $schema_version;
991 }
992 }
993
994 function sanity_check() {
995 require_once 'errors.php';
996 global $ERRORS;
997
998 $error_code = 0;
999 $schema_version = get_schema_version(true);
1000
1001 if ($schema_version != SCHEMA_VERSION) {
1002 $error_code = 5;
1003 }
1004
1005 if (DB_TYPE == "mysql") {
1006 $result = db_query("SELECT true", false);
1007 if (db_num_rows($result) != 1) {
1008 $error_code = 10;
1009 }
1010 }
1011
1012 if (db_escape_string("testTEST") != "testTEST") {
1013 $error_code = 12;
1014 }
1015
1016 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1017 }
1018
1019 function file_is_locked($filename) {
1020 if (file_exists(LOCK_DIRECTORY . "/$filename")) {
1021 if (function_exists('flock')) {
1022 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1023 if ($fp) {
1024 if (flock($fp, LOCK_EX | LOCK_NB)) {
1025 flock($fp, LOCK_UN);
1026 fclose($fp);
1027 return false;
1028 }
1029 fclose($fp);
1030 return true;
1031 } else {
1032 return false;
1033 }
1034 }
1035 return true; // consider the file always locked and skip the test
1036 } else {
1037 return false;
1038 }
1039 }
1040
1041
1042 function make_lockfile($filename) {
1043 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1044
1045 if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
1046 $stat_h = fstat($fp);
1047 $stat_f = stat(LOCK_DIRECTORY . "/$filename");
1048
1049 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
1050 if ($stat_h["ino"] != $stat_f["ino"] ||
1051 $stat_h["dev"] != $stat_f["dev"]) {
1052
1053 return false;
1054 }
1055 }
1056
1057 if (function_exists('posix_getpid')) {
1058 fwrite($fp, posix_getpid() . "\n");
1059 }
1060 return $fp;
1061 } else {
1062 return false;
1063 }
1064 }
1065
1066 function make_stampfile($filename) {
1067 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1068
1069 if (flock($fp, LOCK_EX | LOCK_NB)) {
1070 fwrite($fp, time() . "\n");
1071 flock($fp, LOCK_UN);
1072 fclose($fp);
1073 return true;
1074 } else {
1075 return false;
1076 }
1077 }
1078
1079 function sql_random_function() {
1080 if (DB_TYPE == "mysql") {
1081 return "RAND()";
1082 } else {
1083 return "RANDOM()";
1084 }
1085 }
1086
1087 function catchup_feed($feed, $cat_view, $owner_uid = false, $max_id = false, $mode = 'all') {
1088
1089 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1090
1091 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1092
1093 // Todo: all this interval stuff needs some generic generator function
1094
1095 $date_qpart = "false";
1096
1097 switch ($mode) {
1098 case "1day":
1099 if (DB_TYPE == "pgsql") {
1100 $date_qpart = "date_entered < NOW() - INTERVAL '1 day' ";
1101 } else {
1102 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 DAY) ";
1103 }
1104 break;
1105 case "1week":
1106 if (DB_TYPE == "pgsql") {
1107 $date_qpart = "date_entered < NOW() - INTERVAL '1 week' ";
1108 } else {
1109 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 1 WEEK) ";
1110 }
1111 break;
1112 case "2week":
1113 if (DB_TYPE == "pgsql") {
1114 $date_qpart = "date_entered < NOW() - INTERVAL '2 week' ";
1115 } else {
1116 $date_qpart = "date_entered < DATE_SUB(NOW(), INTERVAL 2 WEEK) ";
1117 }
1118 break;
1119 default:
1120 $date_qpart = "true";
1121 }
1122
1123 if (is_numeric($feed)) {
1124 if ($cat_view) {
1125
1126 if ($feed >= 0) {
1127
1128 if ($feed > 0) {
1129 $children = getChildCategories($feed, $owner_uid);
1130 array_push($children, $feed);
1131
1132 $children = join(",", $children);
1133
1134 $cat_qpart = "cat_id IN ($children)";
1135 } else {
1136 $cat_qpart = "cat_id IS NULL";
1137 }
1138
1139 db_query("UPDATE ttrss_user_entries
1140 SET unread = false, last_read = NOW() WHERE ref_id IN
1141 (SELECT id FROM
1142 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1143 AND owner_uid = $owner_uid AND unread = true AND feed_id IN
1144 (SELECT id FROM ttrss_feeds WHERE $cat_qpart) AND $date_qpart) as tmp)");
1145
1146 } else if ($feed == -2) {
1147
1148 db_query("UPDATE ttrss_user_entries
1149 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1150 FROM ttrss_user_labels2, ttrss_entries WHERE article_id = ref_id AND id = ref_id AND $date_qpart) > 0
1151 AND unread = true AND owner_uid = $owner_uid");
1152 }
1153
1154 } else if ($feed > 0) {
1155
1156 db_query("UPDATE ttrss_user_entries
1157 SET unread = false, last_read = NOW() WHERE ref_id IN
1158 (SELECT id FROM
1159 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1160 AND owner_uid = $owner_uid AND unread = true AND feed_id = $feed AND $date_qpart) as tmp)");
1161
1162 } else if ($feed < 0 && $feed > LABEL_BASE_INDEX) { // special, like starred
1163
1164 if ($feed == -1) {
1165 db_query("UPDATE ttrss_user_entries
1166 SET unread = false, last_read = NOW() WHERE ref_id IN
1167 (SELECT id FROM
1168 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1169 AND owner_uid = $owner_uid AND unread = true AND marked = true AND $date_qpart) as tmp)");
1170 }
1171
1172 if ($feed == -2) {
1173 db_query("UPDATE ttrss_user_entries
1174 SET unread = false, last_read = NOW() WHERE ref_id IN
1175 (SELECT id FROM
1176 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1177 AND owner_uid = $owner_uid AND unread = true AND published = true AND $date_qpart) as tmp)");
1178 }
1179
1180 if ($feed == -3) {
1181
1182 $intl = get_pref("FRESH_ARTICLE_MAX_AGE");
1183
1184 if (DB_TYPE == "pgsql") {
1185 $match_part = "date_entered > NOW() - INTERVAL '$intl hour' ";
1186 } else {
1187 $match_part = "date_entered > DATE_SUB(NOW(),
1188 INTERVAL $intl HOUR) ";
1189 }
1190
1191 db_query("UPDATE ttrss_user_entries
1192 SET unread = false, last_read = NOW() WHERE ref_id IN
1193 (SELECT id FROM
1194 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1195 AND owner_uid = $owner_uid AND score >= 0 AND unread = true AND $date_qpart AND $match_part) as tmp)");
1196 }
1197
1198 if ($feed == -4) {
1199 db_query("UPDATE ttrss_user_entries
1200 SET unread = false, last_read = NOW() WHERE ref_id IN
1201 (SELECT id FROM
1202 (SELECT id FROM ttrss_entries, ttrss_user_entries WHERE ref_id = id
1203 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1204 }
1205
1206 } else if ($feed < LABEL_BASE_INDEX) { // label
1207
1208 $label_id = feed_to_label_id($feed);
1209
1210 db_query("UPDATE ttrss_user_entries
1211 SET unread = false, last_read = NOW() WHERE ref_id IN
1212 (SELECT id FROM
1213 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_user_labels2 WHERE ref_id = id
1214 AND label_id = '$label_id' AND ref_id = article_id
1215 AND owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1216
1217 }
1218
1219 ccache_update($feed, $owner_uid, $cat_view);
1220
1221 } else { // tag
1222 db_query("UPDATE ttrss_user_entries
1223 SET unread = false, last_read = NOW() WHERE ref_id IN
1224 (SELECT id FROM
1225 (SELECT ttrss_entries.id FROM ttrss_entries, ttrss_user_entries, ttrss_tags WHERE ref_id = ttrss_entries.id
1226 AND post_int_id = int_id AND tag_name = '$feed'
1227 AND ttrss_user_entries.owner_uid = $owner_uid AND unread = true AND $date_qpart) as tmp)");
1228
1229 }
1230 }
1231
1232 function getAllCounters() {
1233 $data = getGlobalCounters();
1234
1235 $data = array_merge($data, getVirtCounters());
1236 $data = array_merge($data, getLabelCounters());
1237 $data = array_merge($data, getFeedCounters());
1238 $data = array_merge($data, getCategoryCounters());
1239
1240 return $data;
1241 }
1242
1243 function getCategoryTitle($cat_id) {
1244
1245 if ($cat_id == -1) {
1246 return __("Special");
1247 } else if ($cat_id == -2) {
1248 return __("Labels");
1249 } else {
1250
1251 $result = db_query("SELECT title FROM ttrss_feed_categories WHERE
1252 id = '$cat_id'");
1253
1254 if (db_num_rows($result) == 1) {
1255 return db_fetch_result($result, 0, "title");
1256 } else {
1257 return __("Uncategorized");
1258 }
1259 }
1260 }
1261
1262
1263 function getCategoryCounters() {
1264 $ret_arr = array();
1265
1266 /* Labels category */
1267
1268 $cv = array("id" => -2, "kind" => "cat",
1269 "counter" => getCategoryUnread(-2));
1270
1271 array_push($ret_arr, $cv);
1272
1273 $result = db_query("SELECT id AS cat_id, value AS unread,
1274 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1275 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1276 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1277 WHERE ttrss_cat_counters_cache.feed_id = id AND
1278 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1279 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1280
1281 while ($line = db_fetch_assoc($result)) {
1282 $line["cat_id"] = (int) $line["cat_id"];
1283
1284 if ($line["num_children"] > 0) {
1285 $child_counter = getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]);
1286 } else {
1287 $child_counter = 0;
1288 }
1289
1290 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1291 "counter" => $line["unread"] + $child_counter);
1292
1293 array_push($ret_arr, $cv);
1294 }
1295
1296 /* Special case: NULL category doesn't actually exist in the DB */
1297
1298 $cv = array("id" => 0, "kind" => "cat",
1299 "counter" => (int) ccache_find(0, $_SESSION["uid"], true));
1300
1301 array_push($ret_arr, $cv);
1302
1303 return $ret_arr;
1304 }
1305
1306 // only accepts real cats (>= 0)
1307 function getCategoryChildrenUnread($cat, $owner_uid = false) {
1308 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1309
1310 $result = db_query("SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1311 AND owner_uid = $owner_uid");
1312
1313 $unread = 0;
1314
1315 while ($line = db_fetch_assoc($result)) {
1316 $unread += getCategoryUnread($line["id"], $owner_uid);
1317 $unread += getCategoryChildrenUnread($line["id"], $owner_uid);
1318 }
1319
1320 return $unread;
1321 }
1322
1323 function getCategoryUnread($cat, $owner_uid = false) {
1324
1325 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1326
1327 if ($cat >= 0) {
1328
1329 if ($cat != 0) {
1330 $cat_query = "cat_id = '$cat'";
1331 } else {
1332 $cat_query = "cat_id IS NULL";
1333 }
1334
1335 $result = db_query("SELECT id FROM ttrss_feeds WHERE $cat_query
1336 AND owner_uid = " . $owner_uid);
1337
1338 $cat_feeds = array();
1339 while ($line = db_fetch_assoc($result)) {
1340 array_push($cat_feeds, "feed_id = " . $line["id"]);
1341 }
1342
1343 if (count($cat_feeds) == 0) return 0;
1344
1345 $match_part = implode(" OR ", $cat_feeds);
1346
1347 $result = db_query("SELECT COUNT(int_id) AS unread
1348 FROM ttrss_user_entries
1349 WHERE unread = true AND ($match_part)
1350 AND owner_uid = " . $owner_uid);
1351
1352 $unread = 0;
1353
1354 # this needs to be rewritten
1355 while ($line = db_fetch_assoc($result)) {
1356 $unread += $line["unread"];
1357 }
1358
1359 return $unread;
1360 } else if ($cat == -1) {
1361 return getFeedUnread(-1) + getFeedUnread(-2) + getFeedUnread(-3) + getFeedUnread(0);
1362 } else if ($cat == -2) {
1363
1364 $result = db_query("
1365 SELECT COUNT(unread) AS unread FROM
1366 ttrss_user_entries, ttrss_user_labels2
1367 WHERE article_id = ref_id AND unread = true
1368 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1369
1370 $unread = db_fetch_result($result, 0, "unread");
1371
1372 return $unread;
1373
1374 }
1375 }
1376
1377 function getFeedUnread($feed, $is_cat = false) {
1378 return getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
1379 }
1380
1381 function getLabelUnread($label_id, $owner_uid = false) {
1382 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1383
1384 $result = db_query("SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1385 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1386
1387 if (db_num_rows($result) != 0) {
1388 return db_fetch_result($result, 0, "unread");
1389 } else {
1390 return 0;
1391 }
1392 }
1393
1394 function getFeedArticles($feed, $is_cat = false, $unread_only = false,
1395 $owner_uid = false) {
1396
1397 $n_feed = (int) $feed;
1398 $need_entries = false;
1399
1400 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1401
1402 if ($unread_only) {
1403 $unread_qpart = "unread = true";
1404 } else {
1405 $unread_qpart = "true";
1406 }
1407
1408 if ($is_cat) {
1409 return getCategoryUnread($n_feed, $owner_uid);
1410 } else if ($n_feed == -6) {
1411 return 0;
1412 } else if ($feed != "0" && $n_feed == 0) {
1413
1414 $feed = db_escape_string($feed);
1415
1416 $result = db_query("SELECT SUM((SELECT COUNT(int_id)
1417 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1418 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1419 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1420 return db_fetch_result($result, 0, "count");
1421
1422 } else if ($n_feed == -1) {
1423 $match_part = "marked = true";
1424 } else if ($n_feed == -2) {
1425 $match_part = "published = true";
1426 } else if ($n_feed == -3) {
1427 $match_part = "unread = true AND score >= 0";
1428
1429 $intl = get_pref("FRESH_ARTICLE_MAX_AGE", $owner_uid);
1430
1431 if (DB_TYPE == "pgsql") {
1432 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' ";
1433 } else {
1434 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1435 }
1436
1437 $need_entries = true;
1438
1439 } else if ($n_feed == -4) {
1440 $match_part = "true";
1441 } else if ($n_feed >= 0) {
1442
1443 if ($n_feed != 0) {
1444 $match_part = "feed_id = '$n_feed'";
1445 } else {
1446 $match_part = "feed_id IS NULL";
1447 }
1448
1449 } else if ($feed < LABEL_BASE_INDEX) {
1450
1451 $label_id = feed_to_label_id($feed);
1452
1453 return getLabelUnread($label_id, $owner_uid);
1454
1455 }
1456
1457 if ($match_part) {
1458
1459 if ($need_entries) {
1460 $from_qpart = "ttrss_user_entries,ttrss_entries";
1461 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1462 } else {
1463 $from_qpart = "ttrss_user_entries";
1464 $from_where = "";
1465 }
1466
1467 $query = "SELECT count(int_id) AS unread
1468 FROM $from_qpart WHERE
1469 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1470
1471 //echo "[$feed/$query]\n";
1472
1473 $result = db_query($query);
1474
1475 } else {
1476
1477 $result = db_query("SELECT COUNT(post_int_id) AS unread
1478 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1479 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1480 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1481 }
1482
1483 $unread = db_fetch_result($result, 0, "unread");
1484
1485 return $unread;
1486 }
1487
1488 function getGlobalUnread($user_id = false) {
1489
1490 if (!$user_id) {
1491 $user_id = $_SESSION["uid"];
1492 }
1493
1494 $result = db_query("SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1495 WHERE owner_uid = '$user_id' AND feed_id > 0");
1496
1497 $c_id = db_fetch_result($result, 0, "c_id");
1498
1499 return $c_id;
1500 }
1501
1502 function getGlobalCounters($global_unread = -1) {
1503 $ret_arr = array();
1504
1505 if ($global_unread == -1) {
1506 $global_unread = getGlobalUnread();
1507 }
1508
1509 $cv = array("id" => "global-unread",
1510 "counter" => (int) $global_unread);
1511
1512 array_push($ret_arr, $cv);
1513
1514 $result = db_query("SELECT COUNT(id) AS fn FROM
1515 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1516
1517 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1518
1519 $cv = array("id" => "subscribed-feeds",
1520 "counter" => (int) $subscribed_feeds);
1521
1522 array_push($ret_arr, $cv);
1523
1524 return $ret_arr;
1525 }
1526
1527 function getVirtCounters() {
1528
1529 $ret_arr = array();
1530
1531 for ($i = 0; $i >= -4; $i--) {
1532
1533 $count = getFeedUnread($i);
1534
1535 if ($i == 0 || $i == -1 || $i == -2)
1536 $auxctr = getFeedArticles($i, false);
1537 else
1538 $auxctr = 0;
1539
1540 $cv = array("id" => $i,
1541 "counter" => (int) $count,
1542 "auxcounter" => $auxctr);
1543
1544 // if (get_pref('EXTENDED_FEEDLIST'))
1545 // $cv["xmsg"] = getFeedArticles($i)." ".__("total");
1546
1547 array_push($ret_arr, $cv);
1548 }
1549
1550 $feeds = PluginHost::getInstance()->get_feeds(-1);
1551
1552 if (is_array($feeds)) {
1553 foreach ($feeds as $feed) {
1554 $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']),
1555 "counter" => $feed['sender']->get_unread($feed['id']));
1556
1557 if (method_exists($feed['sender'], 'get_total'))
1558 $cv["auxcounter"] = $feed['sender']->get_total($feed['id']);
1559
1560 array_push($ret_arr, $cv);
1561 }
1562 }
1563
1564 return $ret_arr;
1565 }
1566
1567 function getLabelCounters($descriptions = false) {
1568
1569 $ret_arr = array();
1570
1571 $owner_uid = $_SESSION["uid"];
1572
1573 $result = db_query("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total
1574 FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON
1575 (ttrss_labels2.id = label_id)
1576 LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id
1577 WHERE ttrss_labels2.owner_uid = $owner_uid 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 ?>