]> git.wh0rd.org - tt-rss.git/blob - include/functions.php
029b3248fa3c29c81d1abb8c6969a0b986c25fac
[tt-rss.git] / include / functions.php
1 <?php
2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 102);
4
5 $fetch_last_error = false;
6 $pluginhost = false;
7
8 function __autoload($class) {
9 $class_file = str_replace("_", "/", strtolower(basename($class)));
10
11 $file = dirname(__FILE__)."/../classes/$class_file.php";
12
13 if (file_exists($file)) {
14 require $file;
15 }
16
17 }
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 if (DB_TYPE == "pgsql") {
30 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
31 } else {
32 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
33 }
34
35 define('THEME_VERSION_REQUIRED', 1.1);
36
37 /**
38 * Return available translations names.
39 *
40 * @access public
41 * @return array A array of available translations.
42 */
43 function get_translations() {
44 $tr = array(
45 "auto" => "Detect automatically",
46 "ca_CA" => "Català",
47 "en_US" => "English",
48 "es_ES" => "Español",
49 "de_DE" => "Deutsch",
50 "fr_FR" => "Français",
51 "hu_HU" => "Magyar (Hungarian)",
52 "it_IT" => "Italiano",
53 "ja_JP" => "日本語 (Japanese)",
54 "nb_NO" => "Norwegian bokmål",
55 "pl_PL" => "Polski",
56 "ru_RU" => "Русский",
57 "pt_BR" => "Portuguese/Brazil",
58 "zh_CN" => "Simplified Chinese");
59
60 return $tr;
61 }
62
63 require_once "lib/accept-to-gettext.php";
64 require_once "lib/gettext/gettext.inc";
65
66
67 function startup_gettext() {
68
69 # Get locale from Accept-Language header
70 $lang = al2gt(array_keys(get_translations()), "text/html");
71
72 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
73 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
74 }
75
76 /* In login action of mobile version */
77 if ($_POST["language"] && defined('MOBILE_VERSION')) {
78 $lang = $_POST["language"];
79 } else {
80 $lang = $_SESSION["language"];
81 }
82
83 if ($lang) {
84 if (defined('LC_MESSAGES')) {
85 _setlocale(LC_MESSAGES, $lang);
86 } else if (defined('LC_ALL')) {
87 _setlocale(LC_ALL, $lang);
88 }
89
90 if (defined('MOBILE_VERSION')) {
91 _bindtextdomain("messages", "../locale");
92 } else {
93 _bindtextdomain("messages", "locale");
94 }
95
96 _textdomain("messages");
97 _bind_textdomain_codeset("messages", "UTF-8");
98 }
99 }
100
101 startup_gettext();
102
103 require_once 'db-prefs.php';
104 require_once 'version.php';
105 require_once 'ccache.php';
106 require_once 'labels.php';
107
108 ini_set('user_agent', SELF_USER_AGENT);
109
110 require_once 'lib/pubsubhubbub/publisher.php';
111 require_once 'lib/htmLawed.php';
112
113 $tz_offset = -1;
114 $utc_tz = new DateTimeZone('UTC');
115 $schema_version = false;
116
117 /**
118 * Print a timestamped debug message.
119 *
120 * @param string $msg The debug message.
121 * @return void
122 */
123 function _debug($msg) {
124 if (defined('QUIET') && QUIET) {
125 return;
126 }
127 $ts = strftime("%H:%M:%S", time());
128 if (function_exists('posix_getpid')) {
129 $ts = "$ts/" . posix_getpid();
130 }
131 print "[$ts] $msg\n";
132 } // function _debug
133
134 /**
135 * Purge a feed old posts.
136 *
137 * @param mixed $link A database connection.
138 * @param mixed $feed_id The id of the purged feed.
139 * @param mixed $purge_interval Olderness of purged posts.
140 * @param boolean $debug Set to True to enable the debug. False by default.
141 * @access public
142 * @return void
143 */
144 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
145
146 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
147
148 $rows = -1;
149
150 $result = db_query($link,
151 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
152
153 $owner_uid = false;
154
155 if (db_num_rows($result) == 1) {
156 $owner_uid = db_fetch_result($result, 0, "owner_uid");
157 }
158
159 if ($purge_interval == -1 || !$purge_interval) {
160 if ($owner_uid) {
161 ccache_update($link, $feed_id, $owner_uid);
162 }
163 return;
164 }
165
166 if (!$owner_uid) return;
167
168 if (FORCE_ARTICLE_PURGE == 0) {
169 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
170 $owner_uid, false);
171 } else {
172 $purge_unread = true;
173 $purge_interval = FORCE_ARTICLE_PURGE;
174 }
175
176 if (!$purge_unread) $query_limit = " unread = false AND ";
177
178 if (DB_TYPE == "pgsql") {
179 $pg_version = get_pgsql_version($link);
180
181 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
182
183 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
184 ttrss_entries.id = ref_id AND
185 marked = false AND
186 feed_id = '$feed_id' AND
187 $query_limit
188 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
189
190 } else {
191
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
193 USING ttrss_entries
194 WHERE ttrss_entries.id = ref_id AND
195 marked = false AND
196 feed_id = '$feed_id' AND
197 $query_limit
198 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
199 }
200
201 $rows = pg_affected_rows($result);
202
203 } else {
204
205 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
206 marked = false AND feed_id = '$feed_id' AND
207 (SELECT date_updated FROM ttrss_entries WHERE
208 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
209
210 $result = db_query($link, "DELETE FROM ttrss_user_entries
211 USING ttrss_user_entries, ttrss_entries
212 WHERE ttrss_entries.id = ref_id AND
213 marked = false AND
214 feed_id = '$feed_id' AND
215 $query_limit
216 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
217
218 $rows = mysql_affected_rows($link);
219
220 }
221
222 ccache_update($link, $feed_id, $owner_uid);
223
224 if ($debug) {
225 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
226 }
227 } // function purge_feed
228
229 function feed_purge_interval($link, $feed_id) {
230
231 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
232 WHERE id = '$feed_id'");
233
234 if (db_num_rows($result) == 1) {
235 $purge_interval = db_fetch_result($result, 0, "purge_interval");
236 $owner_uid = db_fetch_result($result, 0, "owner_uid");
237
238 if ($purge_interval == 0) $purge_interval = get_pref($link,
239 'PURGE_OLD_DAYS', $owner_uid);
240
241 return $purge_interval;
242
243 } else {
244 return -1;
245 }
246 }
247
248 function purge_orphans($link, $do_output = false) {
249
250 // purge orphaned posts in main content table
251 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
252 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
253
254 if ($do_output) {
255 $rows = db_affected_rows($link, $result);
256 _debug("Purged $rows orphaned posts.");
257 }
258 }
259
260 function get_feed_update_interval($link, $feed_id) {
261 $result = db_query($link, "SELECT owner_uid, update_interval FROM
262 ttrss_feeds WHERE id = '$feed_id'");
263
264 if (db_num_rows($result) == 1) {
265 $update_interval = db_fetch_result($result, 0, "update_interval");
266 $owner_uid = db_fetch_result($result, 0, "owner_uid");
267
268 if ($update_interval != 0) {
269 return $update_interval;
270 } else {
271 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
272 }
273
274 } else {
275 return -1;
276 }
277 }
278
279 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
280 $login = urlencode($login);
281 $pass = urlencode($pass);
282
283 global $fetch_last_error;
284
285 if (function_exists('curl_init') && !ini_get("open_basedir")) {
286 $ch = curl_init($url);
287
288 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
289 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
290 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
291 curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
292 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
293 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
294 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
295 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
296 curl_setopt($ch, CURLOPT_USERAGENT, SELF_USER_AGENT);
297 curl_setopt($ch, CURLOPT_ENCODING , "gzip");
298
299 if ($post_query) {
300 curl_setopt($ch, CURLOPT_POST, true);
301 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
302 }
303
304 if ($login && $pass)
305 curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
306
307 $contents = @curl_exec($ch);
308
309 if ($contents === false) {
310 $fetch_last_error = curl_error($ch);
311 curl_close($ch);
312 return false;
313 }
314
315 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
316 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
317 curl_close($ch);
318
319 if ($http_code != 200 || $type && strpos($content_type, "$type") === false) {
320 return false;
321 }
322
323 return $contents;
324 } else {
325 if ($login && $pass ){
326 $url_parts = array();
327
328 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
329
330 if ($url_parts[1] && $url_parts[2]) {
331 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
332 }
333 }
334
335 $data = @file_get_contents($url);
336
337 if (!$data && function_exists('error_get_last')) {
338 $error = error_get_last();
339 $fetch_last_error = $error["message"];
340 }
341 return $data;
342 }
343
344 }
345
346 /**
347 * Try to determine the favicon URL for a feed.
348 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
349 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
350 *
351 * @param string $url A feed or page URL
352 * @access public
353 * @return mixed The favicon URL, or false if none was found.
354 */
355 function get_favicon_url($url) {
356
357 $favicon_url = false;
358
359 if ($html = @fetch_file_contents($url)) {
360
361 libxml_use_internal_errors(true);
362
363 $doc = new DOMDocument();
364 $doc->loadHTML($html);
365 $xpath = new DOMXPath($doc);
366
367 $base = $xpath->query('/html/head/base');
368 foreach ($base as $b) {
369 $url = $b->getAttribute("href");
370 break;
371 }
372
373 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
374 if (count($entries) > 0) {
375 foreach ($entries as $entry) {
376 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
377 break;
378 }
379 }
380 }
381
382 if (!$favicon_url)
383 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
384
385 return $favicon_url;
386 } // function get_favicon_url
387
388 function check_feed_favicon($site_url, $feed, $link) {
389 # print "FAVICON [$site_url]: $favicon_url\n";
390
391 $icon_file = ICONS_DIR . "/$feed.ico";
392
393 if (!file_exists($icon_file)) {
394 $favicon_url = get_favicon_url($site_url);
395
396 if ($favicon_url) {
397 // Limiting to "image" type misses those served with text/plain
398 $contents = fetch_file_contents($favicon_url); // , "image");
399
400 if ($contents) {
401 // Crude image type matching.
402 // Patterns gleaned from the file(1) source code.
403 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
404 // 0 string \000\000\001\000 MS Windows icon resource
405 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
406 }
407 elseif (preg_match('/^GIF8/', $contents)) {
408 // 0 string GIF8 GIF image data
409 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
410 }
411 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
412 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
413 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
414 }
415 elseif (preg_match('/^\xff\xd8/', $contents)) {
416 // 0 beshort 0xffd8 JPEG image data
417 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
418 }
419 else {
420 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
421 $contents = "";
422 }
423 }
424
425 if ($contents) {
426 $fp = @fopen($icon_file, "w");
427
428 if ($fp) {
429 fwrite($fp, $contents);
430 fclose($fp);
431 chmod($icon_file, 0644);
432 }
433 }
434 }
435 }
436 }
437
438 function print_select($id, $default, $values, $attributes = "") {
439 print "<select name=\"$id\" id=\"$id\" $attributes>";
440 foreach ($values as $v) {
441 if ($v == $default)
442 $sel = "selected=\"1\"";
443 else
444 $sel = "";
445
446 print "<option value=\"$v\" $sel>$v</option>";
447 }
448 print "</select>";
449 }
450
451 function print_select_hash($id, $default, $values, $attributes = "") {
452 print "<select name=\"$id\" id='$id' $attributes>";
453 foreach (array_keys($values) as $v) {
454 if ($v == $default)
455 $sel = 'selected="selected"';
456 else
457 $sel = "";
458
459 print "<option $sel value=\"$v\">".$values[$v]."</option>";
460 }
461
462 print "</select>";
463 }
464
465 function getmicrotime() {
466 list($usec, $sec) = explode(" ",microtime());
467 return ((float)$usec + (float)$sec);
468 }
469
470 function print_radio($id, $default, $true_is, $values, $attributes = "") {
471 foreach ($values as $v) {
472
473 if ($v == $default)
474 $sel = "checked";
475 else
476 $sel = "";
477
478 if ($v == $true_is) {
479 $sel .= " value=\"1\"";
480 } else {
481 $sel .= " value=\"0\"";
482 }
483
484 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
485 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
486
487 }
488 }
489
490 function initialize_user_prefs($link, $uid, $profile = false) {
491
492 $uid = db_escape_string($uid);
493
494 if (!$profile) {
495 $profile = "NULL";
496 $profile_qpart = "AND profile IS NULL";
497 } else {
498 $profile_qpart = "AND profile = '$profile'";
499 }
500
501 if (get_schema_version($link) < 63) $profile_qpart = "";
502
503 db_query($link, "BEGIN");
504
505 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
506
507 $u_result = db_query($link, "SELECT pref_name
508 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
509
510 $active_prefs = array();
511
512 while ($line = db_fetch_assoc($u_result)) {
513 array_push($active_prefs, $line["pref_name"]);
514 }
515
516 while ($line = db_fetch_assoc($result)) {
517 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
518 // print "adding " . $line["pref_name"] . "<br>";
519
520 if (get_schema_version($link) < 63) {
521 db_query($link, "INSERT INTO ttrss_user_prefs
522 (owner_uid,pref_name,value) VALUES
523 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
524
525 } else {
526 db_query($link, "INSERT INTO ttrss_user_prefs
527 (owner_uid,pref_name,value, profile) VALUES
528 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
529 }
530
531 }
532 }
533
534 db_query($link, "COMMIT");
535
536 }
537
538 function get_ssl_certificate_id() {
539 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
540 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
541 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
542 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
543 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
544 }
545 return "";
546 }
547
548 function authenticate_user($link, $login, $password, $check_only = false) {
549
550 if (!SINGLE_USER_MODE) {
551
552 $user_id = false;
553
554 global $pluginhost;
555 foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER) as $plugin) {
556
557 $user_id = (int) $plugin->authenticate($login, $password);
558
559 if ($user_id) {
560 $_SESSION["auth_module"] = strtolower(get_class($plugin));
561 break;
562 }
563 }
564
565 if ($user_id && !$check_only) {
566 $_SESSION["uid"] = $user_id;
567
568 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
569 WHERE id = '$user_id'");
570
571 $_SESSION["name"] = db_fetch_result($result, 0, "login");
572 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
573 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
574
575 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
576 $_SESSION["uid"]);
577
578 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
579 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
580
581 $_SESSION["last_version_check"] = time();
582
583 initialize_user_prefs($link, $_SESSION["uid"]);
584
585 return true;
586 }
587
588 return false;
589
590 } else {
591
592 $_SESSION["uid"] = 1;
593 $_SESSION["name"] = "admin";
594 $_SESSION["access_level"] = 10;
595
596 $_SESSION["hide_hello"] = true;
597 $_SESSION["hide_logout"] = true;
598
599 $_SESSION["auth_module"] = false;
600
601 if (!$_SESSION["csrf_token"]) {
602 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
603 }
604
605 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
606
607 initialize_user_prefs($link, $_SESSION["uid"]);
608
609 return true;
610 }
611 }
612
613 function make_password($length = 8) {
614
615 $password = "";
616 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
617
618 $i = 0;
619
620 while ($i < $length) {
621 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
622
623 if (!strstr($password, $char)) {
624 $password .= $char;
625 $i++;
626 }
627 }
628 return $password;
629 }
630
631 // this is called after user is created to initialize default feeds, labels
632 // or whatever else
633
634 // user preferences are checked on every login, not here
635
636 function initialize_user($link, $uid) {
637
638 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
639 values ('$uid', 'Tiny Tiny RSS: New Releases',
640 'http://tt-rss.org/releases.rss')");
641
642 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
643 values ('$uid', 'Tiny Tiny RSS: Forum',
644 'http://tt-rss.org/forum/rss.php')");
645 }
646
647 function logout_user() {
648 session_destroy();
649 if (isset($_COOKIE[session_name()])) {
650 setcookie(session_name(), '', time()-42000, '/');
651 }
652 }
653
654 function validate_csrf($csrf_token) {
655 return $csrf_token == $_SESSION['csrf_token'];
656 }
657
658 function validate_session($link) {
659 if (SINGLE_USER_MODE) return true;
660
661 $check_ip = $_SESSION['ip_address'];
662
663 switch (SESSION_CHECK_ADDRESS) {
664 case 0:
665 $check_ip = '';
666 break;
667 case 1:
668 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
669 break;
670 case 2:
671 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
672 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
673 break;
674 };
675
676 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
677 $_SESSION["login_error_msg"] =
678 __("Session failed to validate (incorrect IP)");
679 return false;
680 }
681
682 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
683 return false;
684
685 if ($_SESSION["uid"]) {
686
687 $result = db_query($link,
688 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
689
690 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
691
692 if ($pwd_hash != $_SESSION["pwd_hash"]) {
693 return false;
694 }
695 }
696
697 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
698
699 //print_r($_SESSION);
700
701 if (time() > $_SESSION["cookie_lifetime"]) {
702 return false;
703 }
704 } */
705
706 return true;
707 }
708
709 function load_user_plugins($link, $owner_uid) {
710 if ($owner_uid) {
711 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
712
713 global $pluginhost;
714 $pluginhost->load($plugins, $pluginhost::KIND_USER, $owner_uid);
715
716 if (get_schema_version($link) > 100) {
717 $pluginhost->load_data();
718 }
719 }
720 }
721
722 function login_sequence($link, $login_form = 0) {
723 if (SINGLE_USER_MODE) {
724 authenticate_user($link, "admin", null);
725 load_user_plugins($link, $_SESSION["uid"]);
726 } else {
727 if (!$_SESSION["uid"] || !validate_session($link)) {
728
729 if (AUTH_AUTO_LOGIN && authenticate_user($link, null, null)) {
730 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
731 } else {
732 authenticate_user($link, null, null, true);
733 }
734
735 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
736
737 } else {
738 /* bump login timestamp */
739 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
740 $_SESSION["uid"]);
741 }
742
743 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
744 setcookie("ttrss_lang", $_SESSION["language"],
745 time() + SESSION_COOKIE_LIFETIME);
746 }
747
748 if ($_SESSION["uid"]) {
749 load_user_plugins($link, $_SESSION["uid"]);
750 }
751 }
752 }
753
754 function truncate_string($str, $max_len, $suffix = '&hellip;') {
755 if (mb_strlen($str, "utf-8") > $max_len - 3) {
756 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
757 } else {
758 return $str;
759 }
760 }
761
762 function theme_image($link, $filename) {
763 if ($link) {
764 $theme_path = get_user_theme_path($link);
765
766 if ($theme_path && is_file($theme_path.$filename)) {
767 return $theme_path.$filename;
768 } else {
769 return $filename;
770 }
771 } else {
772 return $filename;
773 }
774 }
775
776 function get_user_theme($link) {
777
778 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
779 $theme_name = get_pref($link, "_THEME_ID");
780 if (is_dir("themes/$theme_name")) {
781 return $theme_name;
782 } else {
783 return '';
784 }
785 } else {
786 return '';
787 }
788
789 }
790
791 function get_user_theme_path($link) {
792 $theme_path = '';
793
794 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
795 $theme_name = get_pref($link, "_THEME_ID");
796
797 if ($theme_name && is_dir("themes/$theme_name")) {
798 $theme_path = "themes/$theme_name/";
799 } else {
800 $theme_name = '';
801 }
802 } else {
803 $theme_path = '';
804 }
805
806 if ($theme_path) {
807 if (is_file("$theme_path/theme.ini")) {
808 $ini = parse_ini_file("$theme_path/theme.ini", true);
809 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
810 return $theme_path;
811 }
812 }
813 }
814 return '';
815 }
816
817 function get_user_theme_options($link) {
818 $t = get_user_theme_path($link);
819
820 if ($t) {
821 if (is_file("$t/theme.ini")) {
822 $ini = parse_ini_file("$t/theme.ini", true);
823 if ($ini['theme']['version']) {
824 return $ini['theme']['options'];
825 }
826 }
827 }
828 return '';
829 }
830
831 function print_theme_includes($link) {
832
833 $t = get_user_theme_path($link);
834 $time = time();
835
836 if ($t) {
837 print "<link rel=\"stylesheet\" type=\"text/css\"
838 href=\"$t/theme.css?$time \">";
839 if (file_exists("$t/theme.js")) {
840 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
841 </script>";
842 }
843 }
844 }
845
846 function get_all_themes() {
847 $themes = glob("themes/*");
848
849 asort($themes);
850
851 $rv = array();
852
853 foreach ($themes as $t) {
854 if (is_file("$t/theme.ini")) {
855 $ini = parse_ini_file("$t/theme.ini", true);
856 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
857 !$ini['theme']['disabled']) {
858 $entry = array();
859 $entry["path"] = $t;
860 $entry["base"] = basename($t);
861 $entry["name"] = $ini['theme']['name'];
862 $entry["version"] = $ini['theme']['version'];
863 $entry["author"] = $ini['theme']['author'];
864 $entry["options"] = $ini['theme']['options'];
865 array_push($rv, $entry);
866 }
867 }
868 }
869
870 return $rv;
871 }
872
873 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
874
875 try {
876 $source_tz = new DateTimeZone($source_tz);
877 } catch (Exception $e) {
878 $source_tz = new DateTimeZone('UTC');
879 }
880
881 try {
882 $dest_tz = new DateTimeZone($dest_tz);
883 } catch (Exception $e) {
884 $dest_tz = new DateTimeZone('UTC');
885 }
886
887 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
888 return $dt->format('U') + $dest_tz->getOffset($dt);
889 }
890
891 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
892 $no_smart_dt = false) {
893
894 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
895 if (!$timestamp) $timestamp = '1970-01-01 0:00';
896
897 global $utc_tz;
898 global $tz_offset;
899
900 # We store date in UTC internally
901 $dt = new DateTime($timestamp, $utc_tz);
902
903 if ($tz_offset == -1) {
904
905 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
906
907 try {
908 $user_tz = new DateTimeZone($user_tz_string);
909 } catch (Exception $e) {
910 $user_tz = $utc_tz;
911 }
912
913 $tz_offset = $user_tz->getOffset($dt);
914 }
915
916 $user_timestamp = $dt->format('U') + $tz_offset;
917
918 if (!$no_smart_dt) {
919 return smart_date_time($link, $user_timestamp,
920 $tz_offset, $owner_uid);
921 } else {
922 if ($long)
923 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
924 else
925 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
926
927 return date($format, $user_timestamp);
928 }
929 }
930
931 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
932 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
933
934 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
935 return date("G:i", $timestamp);
936 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
937 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
938 return date($format, $timestamp);
939 } else {
940 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
941 return date($format, $timestamp);
942 }
943 }
944
945 function sql_bool_to_bool($s) {
946 if ($s == "t" || $s == "1" || $s == "true") {
947 return true;
948 } else {
949 return false;
950 }
951 }
952
953 function bool_to_sql_bool($s) {
954 if ($s) {
955 return "true";
956 } else {
957 return "false";
958 }
959 }
960
961 // Session caching removed due to causing wrong redirects to upgrade
962 // script when get_schema_version() is called on an obsolete session
963 // created on a previous schema version.
964 function get_schema_version($link, $nocache = false) {
965 global $schema_version;
966
967 if (!$schema_version) {
968 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
969 $version = db_fetch_result($result, 0, "schema_version");
970 $schema_version = $version;
971 return $version;
972 } else {
973 return $schema_version;
974 }
975 }
976
977 function sanity_check($link) {
978 require_once 'errors.php';
979
980 $error_code = 0;
981 $schema_version = get_schema_version($link, true);
982
983 if ($schema_version != SCHEMA_VERSION) {
984 $error_code = 5;
985 }
986
987 if (DB_TYPE == "mysql") {
988 $result = db_query($link, "SELECT true", false);
989 if (db_num_rows($result) != 1) {
990 $error_code = 10;
991 }
992 }
993
994 if (db_escape_string("testTEST") != "testTEST") {
995 $error_code = 12;
996 }
997
998 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
999 }
1000
1001 function file_is_locked($filename) {
1002 if (function_exists('flock')) {
1003 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
1004 if ($fp) {
1005 if (flock($fp, LOCK_EX | LOCK_NB)) {
1006 flock($fp, LOCK_UN);
1007 fclose($fp);
1008 return false;
1009 }
1010 fclose($fp);
1011 return true;
1012 } else {
1013 return false;
1014 }
1015 }
1016 return true; // consider the file always locked and skip the test
1017 }
1018
1019 function make_lockfile($filename) {
1020 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1021
1022 if (flock($fp, LOCK_EX | LOCK_NB)) {
1023 if (function_exists('posix_getpid')) {
1024 fwrite($fp, posix_getpid() . "\n");
1025 }
1026 return $fp;
1027 } else {
1028 return false;
1029 }
1030 }
1031
1032 function make_stampfile($filename) {
1033 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1034
1035 if (flock($fp, LOCK_EX | LOCK_NB)) {
1036 fwrite($fp, time() . "\n");
1037 flock($fp, LOCK_UN);
1038 fclose($fp);
1039 return true;
1040 } else {
1041 return false;
1042 }
1043 }
1044
1045 function sql_random_function() {
1046 if (DB_TYPE == "mysql") {
1047 return "RAND()";
1048 } else {
1049 return "RANDOM()";
1050 }
1051 }
1052
1053 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
1054
1055 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1056
1057 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1058
1059 $ref_check_qpart = ($max_id &&
1060 !get_pref($link, 'REVERSE_HEADLINES')) ? "ref_id <= '$max_id'" : "true";
1061
1062 if (is_numeric($feed)) {
1063 if ($cat_view) {
1064
1065 if ($feed >= 0) {
1066
1067 if ($feed > 0) {
1068 $children = getChildCategories($link, $feed, $owner_uid);
1069 array_push($children, $feed);
1070
1071 $children = join(",", $children);
1072
1073 $cat_qpart = "cat_id IN ($children)";
1074 } else {
1075 $cat_qpart = "cat_id IS NULL";
1076 }
1077
1078 db_query($link, "UPDATE ttrss_user_entries
1079 SET unread = false,last_read = NOW()
1080 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
1081 AND $ref_check_qpart
1082 AND owner_uid = $owner_uid");
1083
1084 } else if ($feed == -2) {
1085
1086 db_query($link, "UPDATE ttrss_user_entries
1087 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1088 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1089 AND $ref_check_qpart
1090 AND unread = true AND owner_uid = $owner_uid");
1091 }
1092
1093 } else if ($feed > 0) {
1094
1095 db_query($link, "UPDATE ttrss_user_entries
1096 SET unread = false,last_read = NOW()
1097 WHERE feed_id = '$feed'
1098 AND $ref_check_qpart
1099 AND owner_uid = $owner_uid");
1100
1101 } else if ($feed < 0 && $feed > -10) { // special, like starred
1102
1103 if ($feed == -1) {
1104 db_query($link, "UPDATE ttrss_user_entries
1105 SET unread = false,last_read = NOW()
1106 WHERE marked = true
1107 AND $ref_check_qpart
1108 AND owner_uid = $owner_uid");
1109 }
1110
1111 if ($feed == -2) {
1112 db_query($link, "UPDATE ttrss_user_entries
1113 SET unread = false,last_read = NOW()
1114 WHERE published = true
1115 AND $ref_check_qpart
1116 AND owner_uid = $owner_uid");
1117 }
1118
1119 if ($feed == -3) {
1120
1121 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1122
1123 if (DB_TYPE == "pgsql") {
1124 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1125 } else {
1126 $match_part = "updated > DATE_SUB(NOW(),
1127 INTERVAL $intl HOUR) ";
1128 }
1129
1130 $result = db_query($link, "SELECT id FROM ttrss_entries,
1131 ttrss_user_entries WHERE $match_part AND
1132 unread = true AND
1133 ttrss_user_entries.ref_id = ttrss_entries.id AND
1134 owner_uid = $owner_uid");
1135
1136 $affected_ids = array();
1137
1138 while ($line = db_fetch_assoc($result)) {
1139 array_push($affected_ids, $line["id"]);
1140 }
1141
1142 catchupArticlesById($link, $affected_ids, 0);
1143 }
1144
1145 if ($feed == -4) {
1146 db_query($link, "UPDATE ttrss_user_entries
1147 SET unread = false,last_read = NOW()
1148 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1149 }
1150
1151 } else if ($feed < -10) { // label
1152
1153 $label_id = -$feed - 11;
1154
1155 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1156 SET unread = false, last_read = NOW()
1157 WHERE label_id = '$label_id' AND unread = true
1158 AND $ref_check_qpart
1159 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1160
1161 }
1162
1163 ccache_update($link, $feed, $owner_uid, $cat_view);
1164
1165 } else { // tag
1166 db_query($link, "BEGIN");
1167
1168 $tag_name = db_escape_string($feed);
1169
1170 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1171 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1172
1173 while ($line = db_fetch_assoc($result)) {
1174 db_query($link, "UPDATE ttrss_user_entries SET
1175 unread = false, last_read = NOW()
1176 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1177 }
1178 db_query($link, "COMMIT");
1179 }
1180 }
1181
1182 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1183
1184 if (!$omode) $omode = "flc";
1185
1186 $data = getGlobalCounters($link);
1187
1188 $data = array_merge($data, getVirtCounters($link));
1189
1190 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1191 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1192 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1193 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1194
1195 return $data;
1196 }
1197
1198 function getCategoryTitle($link, $cat_id) {
1199
1200 if ($cat_id == -1) {
1201 return __("Special");
1202 } else if ($cat_id == -2) {
1203 return __("Labels");
1204 } else {
1205
1206 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1207 id = '$cat_id'");
1208
1209 if (db_num_rows($result) == 1) {
1210 return db_fetch_result($result, 0, "title");
1211 } else {
1212 return __("Uncategorized");
1213 }
1214 }
1215 }
1216
1217
1218 function getCategoryCounters($link) {
1219 $ret_arr = array();
1220
1221 /* Labels category */
1222
1223 $cv = array("id" => -2, "kind" => "cat",
1224 "counter" => getCategoryUnread($link, -2));
1225
1226 array_push($ret_arr, $cv);
1227
1228 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1229 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1230 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1231 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1232 WHERE ttrss_cat_counters_cache.feed_id = id AND
1233 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1234 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1235
1236 while ($line = db_fetch_assoc($result)) {
1237 $line["cat_id"] = (int) $line["cat_id"];
1238
1239 if ($line["num_children"] > 0) {
1240 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1241 } else {
1242 $child_counter = 0;
1243 }
1244
1245 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1246 "counter" => $line["unread"] + $child_counter);
1247
1248 array_push($ret_arr, $cv);
1249 }
1250
1251 /* Special case: NULL category doesn't actually exist in the DB */
1252
1253 $cv = array("id" => 0, "kind" => "cat",
1254 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1255
1256 array_push($ret_arr, $cv);
1257
1258 return $ret_arr;
1259 }
1260
1261 // only accepts real cats (>= 0)
1262 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1263 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1264
1265 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1266 AND owner_uid = $owner_uid");
1267
1268 $unread = 0;
1269
1270 while ($line = db_fetch_assoc($result)) {
1271 $unread += getCategoryUnread($link, $line["id"], $owner_uid);
1272 $unread += getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1273 }
1274
1275 return $unread;
1276 }
1277
1278 function getCategoryUnread($link, $cat, $owner_uid = false) {
1279
1280 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1281
1282 if ($cat >= 0) {
1283
1284 if ($cat != 0) {
1285 $cat_query = "cat_id = '$cat'";
1286 } else {
1287 $cat_query = "cat_id IS NULL";
1288 }
1289
1290 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1291 AND owner_uid = " . $owner_uid);
1292
1293 $cat_feeds = array();
1294 while ($line = db_fetch_assoc($result)) {
1295 array_push($cat_feeds, "feed_id = " . $line["id"]);
1296 }
1297
1298 if (count($cat_feeds) == 0) return 0;
1299
1300 $match_part = implode(" OR ", $cat_feeds);
1301
1302 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1303 FROM ttrss_user_entries
1304 WHERE unread = true AND ($match_part)
1305 AND owner_uid = " . $owner_uid);
1306
1307 $unread = 0;
1308
1309 # this needs to be rewritten
1310 while ($line = db_fetch_assoc($result)) {
1311 $unread += $line["unread"];
1312 }
1313
1314 return $unread;
1315 } else if ($cat == -1) {
1316 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
1317 } else if ($cat == -2) {
1318
1319 $result = db_query($link, "
1320 SELECT COUNT(unread) AS unread FROM
1321 ttrss_user_entries, ttrss_user_labels2
1322 WHERE article_id = ref_id AND unread = true
1323 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1324
1325 $unread = db_fetch_result($result, 0, "unread");
1326
1327 return $unread;
1328
1329 }
1330 }
1331
1332 function getFeedUnread($link, $feed, $is_cat = false) {
1333 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1334 }
1335
1336 function getLabelUnread($link, $label_id, $owner_uid = false) {
1337 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1338
1339 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1340 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1341
1342 if (db_num_rows($result) != 0) {
1343 return db_fetch_result($result, 0, "unread");
1344 } else {
1345 return 0;
1346 }
1347 }
1348
1349 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1350 $owner_uid = false) {
1351
1352 $n_feed = (int) $feed;
1353 $need_entries = false;
1354
1355 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1356
1357 if ($unread_only) {
1358 $unread_qpart = "unread = true";
1359 } else {
1360 $unread_qpart = "true";
1361 }
1362
1363 if ($is_cat) {
1364 return getCategoryUnread($link, $n_feed, $owner_uid);
1365 } else if ($n_feed == -6) {
1366 return 0;
1367 } else if ($feed != "0" && $n_feed == 0) {
1368
1369 $feed = db_escape_string($feed);
1370
1371 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1372 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1373 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1374 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1375 return db_fetch_result($result, 0, "count");
1376
1377 } else if ($n_feed == -1) {
1378 $match_part = "marked = true";
1379 } else if ($n_feed == -2) {
1380 $match_part = "published = true";
1381 } else if ($n_feed == -3) {
1382 $match_part = "unread = true AND score >= 0";
1383
1384 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1385
1386 if (DB_TYPE == "pgsql") {
1387 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1388 } else {
1389 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1390 }
1391
1392 $need_entries = true;
1393
1394 } else if ($n_feed == -4) {
1395 $match_part = "true";
1396 } else if ($n_feed >= 0) {
1397
1398 if ($n_feed != 0) {
1399 $match_part = "feed_id = '$n_feed'";
1400 } else {
1401 $match_part = "feed_id IS NULL";
1402 }
1403
1404 } else if ($feed < -10) {
1405
1406 $label_id = -$feed - 11;
1407
1408 return getLabelUnread($link, $label_id, $owner_uid);
1409
1410 }
1411
1412 if ($match_part) {
1413
1414 if ($need_entries) {
1415 $from_qpart = "ttrss_user_entries,ttrss_entries";
1416 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1417 } else {
1418 $from_qpart = "ttrss_user_entries";
1419 }
1420
1421 $query = "SELECT count(int_id) AS unread
1422 FROM $from_qpart WHERE
1423 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1424
1425 //echo "[$feed/$query]\n";
1426
1427 $result = db_query($link, $query);
1428
1429 } else {
1430
1431 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1432 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1433 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1434 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1435 }
1436
1437 $unread = db_fetch_result($result, 0, "unread");
1438
1439 return $unread;
1440 }
1441
1442 function getGlobalUnread($link, $user_id = false) {
1443
1444 if (!$user_id) {
1445 $user_id = $_SESSION["uid"];
1446 }
1447
1448 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1449 WHERE owner_uid = '$user_id' AND feed_id > 0");
1450
1451 $c_id = db_fetch_result($result, 0, "c_id");
1452
1453 return $c_id;
1454 }
1455
1456 function getGlobalCounters($link, $global_unread = -1) {
1457 $ret_arr = array();
1458
1459 if ($global_unread == -1) {
1460 $global_unread = getGlobalUnread($link);
1461 }
1462
1463 $cv = array("id" => "global-unread",
1464 "counter" => (int) $global_unread);
1465
1466 array_push($ret_arr, $cv);
1467
1468 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1469 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1470
1471 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1472
1473 $cv = array("id" => "subscribed-feeds",
1474 "counter" => (int) $subscribed_feeds);
1475
1476 array_push($ret_arr, $cv);
1477
1478 return $ret_arr;
1479 }
1480
1481 function getTagCounters($link) {
1482
1483 $ret_arr = array();
1484
1485 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1486 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1487 AND ref_id = id AND unread = true)) AS count FROM ttrss_tags
1488 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1489 ORDER BY count DESC LIMIT 55");
1490
1491 $tags = array();
1492
1493 while ($line = db_fetch_assoc($result)) {
1494 $tags[$line["tag_name"]] += $line["count"];
1495 }
1496
1497 foreach (array_keys($tags) as $tag) {
1498 $unread = $tags[$tag];
1499 $tag = htmlspecialchars($tag);
1500
1501 $cv = array("id" => $tag,
1502 "kind" => "tag",
1503 "counter" => $unread);
1504
1505 array_push($ret_arr, $cv);
1506 }
1507
1508 return $ret_arr;
1509 }
1510
1511 function getVirtCounters($link) {
1512
1513 $ret_arr = array();
1514
1515 for ($i = 0; $i >= -4; $i--) {
1516
1517 $count = getFeedUnread($link, $i);
1518
1519 $cv = array("id" => $i,
1520 "counter" => (int) $count);
1521
1522 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1523 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1524
1525 array_push($ret_arr, $cv);
1526 }
1527
1528 return $ret_arr;
1529 }
1530
1531 function getLabelCounters($link, $descriptions = false) {
1532
1533 $ret_arr = array();
1534
1535 $owner_uid = $_SESSION["uid"];
1536
1537 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1538 WHERE owner_uid = '$owner_uid'");
1539
1540 while ($line = db_fetch_assoc($result)) {
1541
1542 $id = -$line["id"] - 11;
1543
1544 $label_name = $line["caption"];
1545 $count = getFeedUnread($link, $id);
1546
1547 $cv = array("id" => $id,
1548 "counter" => (int) $count);
1549
1550 if ($descriptions)
1551 $cv["description"] = $label_name;
1552
1553 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1554 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1555
1556 array_push($ret_arr, $cv);
1557 }
1558
1559 return $ret_arr;
1560 }
1561
1562 function getFeedCounters($link, $active_feed = false) {
1563
1564 $ret_arr = array();
1565
1566 $query = "SELECT ttrss_feeds.id,
1567 ttrss_feeds.title,
1568 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
1569 last_error, value AS count
1570 FROM ttrss_feeds, ttrss_counters_cache
1571 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1572 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1573 AND ttrss_counters_cache.feed_id = id";
1574
1575 $result = db_query($link, $query);
1576 $fctrs_modified = false;
1577
1578 while ($line = db_fetch_assoc($result)) {
1579
1580 $id = $line["id"];
1581 $count = $line["count"];
1582 $last_error = htmlspecialchars($line["last_error"]);
1583
1584 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1585
1586 $has_img = feed_has_icon($id);
1587
1588 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1589 $last_updated = '';
1590
1591 $cv = array("id" => $id,
1592 "updated" => $last_updated,
1593 "counter" => (int) $count,
1594 "has_img" => (int) $has_img);
1595
1596 if ($last_error)
1597 $cv["error"] = $last_error;
1598
1599 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1600 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1601
1602 if ($active_feed && $id == $active_feed)
1603 $cv["title"] = truncate_string($line["title"], 30);
1604
1605 array_push($ret_arr, $cv);
1606
1607 }
1608
1609 return $ret_arr;
1610 }
1611
1612 function get_pgsql_version($link) {
1613 $result = db_query($link, "SELECT version() AS version");
1614 $version = explode(" ", db_fetch_result($result, 0, "version"));
1615 return $version[1];
1616 }
1617
1618 /**
1619 * @return array (code => Status code, message => error message if available)
1620 *
1621 * 0 - OK, Feed already exists
1622 * 1 - OK, Feed added
1623 * 2 - Invalid URL
1624 * 3 - URL content is HTML, no feeds available
1625 * 4 - URL content is HTML which contains multiple feeds.
1626 * Here you should call extractfeedurls in rpc-backend
1627 * to get all possible feeds.
1628 * 5 - Couldn't download the URL content.
1629 */
1630 function subscribe_to_feed($link, $url, $cat_id = 0,
1631 $auth_login = '', $auth_pass = '', $need_auth = false) {
1632
1633 global $fetch_last_error;
1634
1635 require_once "include/rssfuncs.php";
1636
1637 $url = fix_url($url);
1638
1639 if (!$url || !validate_feed_url($url)) return array("code" => 2);
1640
1641 $contents = @fetch_file_contents($url, false, $auth_login, $auth_pass);
1642
1643 if (!$contents) {
1644 return array("code" => 5, "message" => $fetch_last_error);
1645 }
1646
1647 if (is_html($contents)) {
1648 $feedUrls = get_feeds_from_html($url, $contents);
1649
1650 if (count($feedUrls) == 0) {
1651 return array("code" => 3);
1652 } else if (count($feedUrls) > 1) {
1653 return array("code" => 4, "feeds" => $feedUrls);
1654 }
1655 //use feed url as new URL
1656 $url = key($feedUrls);
1657 }
1658
1659 if ($cat_id == "0" || !$cat_id) {
1660 $cat_qpart = "NULL";
1661 } else {
1662 $cat_qpart = "'$cat_id'";
1663 }
1664
1665 $result = db_query($link,
1666 "SELECT id FROM ttrss_feeds
1667 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1668
1669 if (db_num_rows($result) == 0) {
1670 $result = db_query($link,
1671 "INSERT INTO ttrss_feeds
1672 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1673 VALUES ('".$_SESSION["uid"]."', '$url',
1674 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1675
1676 $result = db_query($link,
1677 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1678 AND owner_uid = " . $_SESSION["uid"]);
1679
1680 $feed_id = db_fetch_result($result, 0, "id");
1681
1682 if ($feed_id) {
1683 update_rss_feed($link, $feed_id, true);
1684 }
1685
1686 return array("code" => 1);
1687 } else {
1688 return array("code" => 0);
1689 }
1690 }
1691
1692 function print_feed_select($link, $id, $default_id = "",
1693 $attributes = "", $include_all_feeds = true,
1694 $root_id = false, $nest_level = 0) {
1695
1696 if (!$root_id) {
1697 print "<select id=\"$id\" name=\"$id\" $attributes>";
1698 if ($include_all_feeds) {
1699 $is_selected = ("0" == $default_id) ? "selected=\"1\"" : "";
1700 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1701 }
1702 }
1703
1704 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1705
1706 if ($root_id)
1707 $parent_qpart = "parent_cat = '$root_id'";
1708 else
1709 $parent_qpart = "parent_cat IS NULL";
1710
1711 $result = db_query($link, "SELECT id,title,
1712 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1713 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1714 FROM ttrss_feed_categories
1715 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1716
1717 while ($line = db_fetch_assoc($result)) {
1718
1719 for ($i = 0; $i < $nest_level; $i++)
1720 $line["title"] = " - " . $line["title"];
1721
1722 $is_selected = ("CAT:".$line["id"] == $default_id) ? "selected=\"1\"" : "";
1723
1724 printf("<option $is_selected value='CAT:%d'>%s</option>",
1725 $line["id"], htmlspecialchars($line["title"]));
1726
1727 if ($line["num_children"] > 0)
1728 print_feed_select($link, $id, $default_id, $attributes,
1729 $include_all_feeds, $line["id"], $nest_level+1);
1730
1731 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1732 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1733
1734 while ($fline = db_fetch_assoc($feed_result)) {
1735 $is_selected = ($fline["id"] == $default_id) ? "selected=\"1\"" : "";
1736
1737 $fline["title"] = " + " . $fline["title"];
1738
1739 for ($i = 0; $i < $nest_level; $i++)
1740 $fline["title"] = " - " . $fline["title"];
1741
1742 printf("<option $is_selected value='%d'>%s</option>",
1743 $fline["id"], htmlspecialchars($fline["title"]));
1744 }
1745 }
1746
1747 if (!$root_id) {
1748 $is_selected = ($default_id == "CAT:0") ? "selected=\"1\"" : "";
1749
1750 printf("<option $is_selected value='CAT:0'>%s</option>",
1751 __("Uncategorized"));
1752
1753 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1754 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1755
1756 while ($fline = db_fetch_assoc($feed_result)) {
1757 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ? "selected=\"1\"" : "";
1758
1759 $fline["title"] = " + " . $fline["title"];
1760
1761 for ($i = 0; $i < $nest_level; $i++)
1762 $fline["title"] = " - " . $fline["title"];
1763
1764 printf("<option $is_selected value='%d'>%s</option>",
1765 $fline["id"], htmlspecialchars($fline["title"]));
1766 }
1767 }
1768
1769 } else {
1770 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1771 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1772
1773 while ($line = db_fetch_assoc($result)) {
1774
1775 $is_selected = ($line["id"] == $default_id) ? "selected=\"1\"" : "";
1776
1777 printf("<option $is_selected value='%d'>%s</option>",
1778 $line["id"], htmlspecialchars($line["title"]));
1779 }
1780 }
1781
1782 if (!$root_id) {
1783 print "</select>";
1784 }
1785 }
1786
1787 function print_feed_cat_select($link, $id, $default_id,
1788 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1789
1790 if (!$root_id) {
1791 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1792 }
1793
1794 if ($root_id)
1795 $parent_qpart = "parent_cat = '$root_id'";
1796 else
1797 $parent_qpart = "parent_cat IS NULL";
1798
1799 $result = db_query($link, "SELECT id,title,
1800 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1801 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1802 FROM ttrss_feed_categories
1803 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1804
1805 while ($line = db_fetch_assoc($result)) {
1806 if ($line["id"] == $default_id) {
1807 $is_selected = "selected=\"1\"";
1808 } else {
1809 $is_selected = "";
1810 }
1811
1812 for ($i = 0; $i < $nest_level; $i++)
1813 $line["title"] = " - " . $line["title"];
1814
1815 if ($line["title"])
1816 printf("<option $is_selected value='%d'>%s</option>",
1817 $line["id"], htmlspecialchars($line["title"]));
1818
1819 if ($line["num_children"] > 0)
1820 print_feed_cat_select($link, $id, $default_id, $attributes,
1821 $include_all_cats, $line["id"], $nest_level+1);
1822 }
1823
1824 if (!$root_id) {
1825 if ($include_all_cats) {
1826 if (db_num_rows($result) > 0) {
1827 print "<option disabled=\"1\">--------</option>";
1828 }
1829
1830 if ($default_id == 0) {
1831 $is_selected = "selected=\"1\"";
1832 } else {
1833 $is_selected = "";
1834 }
1835
1836 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1837 }
1838 print "</select>";
1839 }
1840 }
1841
1842 function checkbox_to_sql_bool($val) {
1843 return ($val == "on") ? "true" : "false";
1844 }
1845
1846 function getFeedCatTitle($link, $id) {
1847 if ($id == -1) {
1848 return __("Special");
1849 } else if ($id < -10) {
1850 return __("Labels");
1851 } else if ($id > 0) {
1852 $result = db_query($link, "SELECT ttrss_feed_categories.title
1853 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1854 cat_id = ttrss_feed_categories.id");
1855 if (db_num_rows($result) == 1) {
1856 return db_fetch_result($result, 0, "title");
1857 } else {
1858 return __("Uncategorized");
1859 }
1860 } else {
1861 return "getFeedCatTitle($id) failed";
1862 }
1863
1864 }
1865
1866 function getFeedIcon($id) {
1867 switch ($id) {
1868 case 0:
1869 return "images/archive.png";
1870 break;
1871 case -1:
1872 return "images/mark_set.svg";
1873 break;
1874 case -2:
1875 return "images/pub_set.svg";
1876 break;
1877 case -3:
1878 return "images/fresh.png";
1879 break;
1880 case -4:
1881 return "images/tag.png";
1882 break;
1883 case -6:
1884 return "images/recently_read.png";
1885 break;
1886 default:
1887 if ($id < -10) {
1888 return "images/label.png";
1889 } else {
1890 if (file_exists(ICONS_DIR . "/$id.ico"))
1891 return ICONS_URL . "/$id.ico";
1892 }
1893 break;
1894 }
1895 }
1896
1897 function getFeedTitle($link, $id, $cat = false) {
1898 if ($cat) {
1899 return getCategoryTitle($link, $id);
1900 } else if ($id == -1) {
1901 return __("Starred articles");
1902 } else if ($id == -2) {
1903 return __("Published articles");
1904 } else if ($id == -3) {
1905 return __("Fresh articles");
1906 } else if ($id == -4) {
1907 return __("All articles");
1908 } else if ($id === 0 || $id === "0") {
1909 return __("Archived articles");
1910 } else if ($id == -6) {
1911 return __("Recently read");
1912 } else if ($id < -10) {
1913 $label_id = -$id - 11;
1914 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1915 if (db_num_rows($result) == 1) {
1916 return db_fetch_result($result, 0, "caption");
1917 } else {
1918 return "Unknown label ($label_id)";
1919 }
1920
1921 } else if (is_numeric($id) && $id > 0) {
1922 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1923 if (db_num_rows($result) == 1) {
1924 return db_fetch_result($result, 0, "title");
1925 } else {
1926 return "Unknown feed ($id)";
1927 }
1928 } else {
1929 return $id;
1930 }
1931 }
1932
1933 function make_init_params($link) {
1934 $params = array();
1935
1936 $params["theme"] = get_user_theme($link);
1937 $params["theme_options"] = get_user_theme_options($link);
1938
1939 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1940 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1941 $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
1942 $params["sign_info"] = theme_image($link, "images/sign_info.svg");
1943
1944 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1945 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1946 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1947 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1948
1949 $params[strtolower($param)] = (int) get_pref($link, $param);
1950 }
1951
1952 $params["icons_url"] = ICONS_URL;
1953 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
1954 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1955 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1956 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1957 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1958
1959 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1960 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1961
1962 $max_feed_id = db_fetch_result($result, 0, "mid");
1963 $num_feeds = db_fetch_result($result, 0, "nf");
1964
1965 $params["max_feed_id"] = (int) $max_feed_id;
1966 $params["num_feeds"] = (int) $num_feeds;
1967
1968 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1969 $params["hotkeys"] = get_hotkeys_map($link);
1970
1971 $params["csrf_token"] = $_SESSION["csrf_token"];
1972 $params["widescreen"] = (int) $_SESSION["widescreen"];
1973
1974 $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
1975
1976 return $params;
1977 }
1978
1979 function get_hotkeys_info($link) {
1980 $hotkeys = array(
1981 __("Navigation") => array(
1982 "next_feed" => __("Open next feed"),
1983 "prev_feed" => __("Open previous feed"),
1984 "next_article" => __("Open next article"),
1985 "prev_article" => __("Open previous article"),
1986 "search_dialog" => __("Show search dialog")),
1987 __("Article") => array(
1988 "toggle_mark" => __("Toggle starred"),
1989 "toggle_publ" => __("Toggle published"),
1990 "toggle_unread" => __("Toggle unread"),
1991 "edit_tags" => __("Edit tags"),
1992 "dismiss_selected" => __("Dismiss selected"),
1993 "dismiss_read" => __("Dismiss read"),
1994 "open_in_new_window" => __("Open in new window"),
1995 "catchup_below" => __("Mark below as read"),
1996 "catchup_above" => __("Mark above as read"),
1997 "article_scroll_down" => __("Scroll down"),
1998 "article_scroll_up" => __("Scroll up"),
1999 "select_article_cursor" => __("Select article under cursor"),
2000 "email_article" => __("Email article"),
2001 "close_article" => __("Close article"),
2002 "toggle_widescreen" => __("Toggle widescreen mode")),
2003 __("Article selection") => array(
2004 "select_all" => __("Select all articles"),
2005 "select_unread" => __("Select unread"),
2006 "select_marked" => __("Select starred"),
2007 "select_published" => __("Select published"),
2008 "select_invert" => __("Invert selection"),
2009 "select_none" => __("Deselect everything")),
2010 __("Feed") => array(
2011 "feed_refresh" => __("Refresh current feed"),
2012 "feed_unhide_read" => __("Un/hide read feeds"),
2013 "feed_subscribe" => __("Subscribe to feed"),
2014 "feed_edit" => __("Edit feed"),
2015 "feed_catchup" => __("Mark as read"),
2016 "feed_reverse" => __("Reverse headlines"),
2017 "feed_debug_update" => __("Debug feed update"),
2018 "catchup_all" => __("Mark all feeds as read"),
2019 "cat_toggle_collapse" => __("Un/collapse current category")),
2020 __("Go to") => array(
2021 "goto_all" => __("All articles"),
2022 "goto_fresh" => __("Fresh"),
2023 "goto_marked" => __("Starred"),
2024 "goto_published" => __("Published"),
2025 "goto_tagcloud" => __("Tag cloud"),
2026 "goto_prefs" => __("Preferences")),
2027 __("Other") => array(
2028 "create_label" => __("Create label"),
2029 "create_filter" => __("Create filter"),
2030 "collapse_sidebar" => __("Un/collapse sidebar"),
2031 "help_dialog" => __("Show help dialog"))
2032 );
2033
2034 return $hotkeys;
2035 }
2036
2037 function get_hotkeys_map($link) {
2038 $hotkeys = array(
2039 // "navigation" => array(
2040 "k" => "next_feed",
2041 "j" => "prev_feed",
2042 "n" => "next_article",
2043 "p" => "prev_article",
2044 "(38)|up" => "prev_article",
2045 "(40)|down" => "next_article",
2046 "(191)|/" => "search_dialog",
2047 // "article" => array(
2048 "s" => "toggle_mark",
2049 "S" => "toggle_publ",
2050 "u" => "toggle_unread",
2051 "T" => "edit_tags",
2052 "D" => "dismiss_selected",
2053 "X" => "dismiss_read",
2054 "o" => "open_in_new_window",
2055 "c p" => "catchup_below",
2056 "c n" => "catchup_above",
2057 "N" => "article_scroll_down",
2058 "P" => "article_scroll_up",
2059 "a W" => "toggle_widescreen",
2060 "e" => "email_article",
2061 "a q" => "close_article",
2062 // "article_selection" => array(
2063 "a a" => "select_all",
2064 "a u" => "select_unread",
2065 "a U" => "select_marked",
2066 "a p" => "select_published",
2067 "a i" => "select_invert",
2068 "a n" => "select_none",
2069 // "feed" => array(
2070 "f r" => "feed_refresh",
2071 "f a" => "feed_unhide_read",
2072 "f s" => "feed_subscribe",
2073 "f e" => "feed_edit",
2074 "f q" => "feed_catchup",
2075 "f x" => "feed_reverse",
2076 "f D" => "feed_debug_update",
2077 "Q" => "catchup_all",
2078 "x" => "cat_toggle_collapse",
2079 // "goto" => array(
2080 "g a" => "goto_all",
2081 "g f" => "goto_fresh",
2082 "g s" => "goto_marked",
2083 "g p" => "goto_published",
2084 "g t" => "goto_tagcloud",
2085 "g P" => "goto_prefs",
2086 // "other" => array(
2087 "(9)|Tab" => "select_article_cursor", // tab
2088 "c l" => "create_label",
2089 "c f" => "create_filter",
2090 "c s" => "collapse_sidebar",
2091 "^(191)|Ctrl+/" => "help_dialog",
2092 );
2093
2094 global $pluginhost;
2095 foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP) as $plugin) {
2096 $hotkeys = $plugin->hook_hotkey_map($hotkeys);
2097 }
2098
2099 $prefixes = array();
2100
2101 foreach (array_keys($hotkeys) as $hotkey) {
2102 $pair = explode(" ", $hotkey, 2);
2103
2104 if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
2105 array_push($prefixes, $pair[0]);
2106 }
2107 }
2108
2109 return array($prefixes, $hotkeys);
2110 }
2111
2112 function make_runtime_info($link) {
2113 $data = array();
2114
2115 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2116 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2117
2118 $max_feed_id = db_fetch_result($result, 0, "mid");
2119 $num_feeds = db_fetch_result($result, 0, "nf");
2120
2121 $data["max_feed_id"] = (int) $max_feed_id;
2122 $data["num_feeds"] = (int) $num_feeds;
2123
2124 $data['last_article_id'] = getLastArticleId($link);
2125 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2126
2127 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
2128
2129 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2130
2131 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2132
2133 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
2134
2135 if ($stamp) {
2136 $stamp_delta = time() - $stamp;
2137
2138 if ($stamp_delta > 1800) {
2139 $stamp_check = 0;
2140 } else {
2141 $stamp_check = 1;
2142 $_SESSION["daemon_stamp_check"] = time();
2143 }
2144
2145 $data['daemon_stamp_ok'] = $stamp_check;
2146
2147 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2148
2149 $data['daemon_stamp'] = $stamp_fmt;
2150 }
2151 }
2152 }
2153
2154 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
2155 $new_version_details = @check_for_update($link);
2156
2157 $data['new_version_available'] = (int) ($new_version_details != false);
2158
2159 $_SESSION["last_version_check"] = time();
2160 $_SESSION["version_data"] = $new_version_details;
2161 }
2162
2163 return $data;
2164 }
2165
2166 function search_to_sql($link, $search, $match_on) {
2167
2168 $search_query_part = "";
2169
2170 $keywords = explode(" ", $search);
2171 $query_keywords = array();
2172
2173 foreach ($keywords as $k) {
2174 if (strpos($k, "-") === 0) {
2175 $k = substr($k, 1);
2176 $not = "NOT";
2177 } else {
2178 $not = "";
2179 }
2180
2181 $commandpair = explode(":", mb_strtolower($k), 2);
2182
2183 if ($commandpair[0] == "note" && $commandpair[1]) {
2184
2185 if ($commandpair[1] == "true")
2186 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2187 else
2188 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2189
2190 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2191
2192 if ($commandpair[1] == "true")
2193 array_push($query_keywords, "($not (marked = true))");
2194 else
2195 array_push($query_keywords, "($not (marked = false))");
2196
2197 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2198
2199 if ($commandpair[1] == "true")
2200 array_push($query_keywords, "($not (published = true))");
2201 else
2202 array_push($query_keywords, "($not (published = false))");
2203
2204 } else if (strpos($k, "@") === 0) {
2205
2206 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2207 $orig_ts = strtotime(substr($k, 1));
2208 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2209
2210 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2211
2212 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
2213 } else if ($match_on == "both") {
2214 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2215 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2216 } else if ($match_on == "title") {
2217 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2218 } else if ($match_on == "content") {
2219 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2220 }
2221 }
2222
2223 $search_query_part = implode("AND", $query_keywords);
2224
2225 return $search_query_part;
2226 }
2227
2228 function getParentCategories($link, $cat, $owner_uid) {
2229 $rv = array();
2230
2231 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2232 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2233
2234 while ($line = db_fetch_assoc($result)) {
2235 array_push($rv, $line["parent_cat"]);
2236 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2237 }
2238
2239 return $rv;
2240 }
2241
2242 function getChildCategories($link, $cat, $owner_uid) {
2243 $rv = array();
2244
2245 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2246 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2247
2248 while ($line = db_fetch_assoc($result)) {
2249 array_push($rv, $line["id"]);
2250 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2251 }
2252
2253 return $rv;
2254 }
2255
2256 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0, $include_children = false) {
2257
2258 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2259
2260 $ext_tables_part = "";
2261
2262 if ($search) {
2263
2264 if (SPHINX_ENABLED) {
2265 $ids = join(",", @sphinx_search($search, 0, 500));
2266
2267 if ($ids)
2268 $search_query_part = "ref_id IN ($ids) AND ";
2269 else
2270 $search_query_part = "ref_id = -1 AND ";
2271
2272 } else {
2273 $search_query_part = search_to_sql($link, $search, $match_on);
2274 $search_query_part .= " AND ";
2275 }
2276
2277 } else {
2278 $search_query_part = "";
2279 }
2280
2281 if ($filter) {
2282
2283 if (DB_TYPE == "pgsql") {
2284 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2285 } else {
2286 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2287 }
2288
2289 $override_order = "updated DESC";
2290
2291 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2292
2293 // Try to check if SQL regexp implementation chokes on a valid regexp
2294 $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
2295 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2296 WHERE $filter_query_part LIMIT 1", false);
2297
2298 $test = db_fetch_result($result, 0, "true_val");
2299
2300 if (!$test) {
2301 $filter_query_part = "false AND";
2302 } else {
2303 $filter_query_part .= " AND";
2304 }
2305
2306 } else {
2307 $filter_query_part = "";
2308 }
2309
2310 if ($since_id) {
2311 $since_id_part = "ttrss_entries.id > $since_id AND ";
2312 } else {
2313 $since_id_part = "";
2314 }
2315
2316 $view_query_part = "";
2317
2318 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
2319 if ($search) {
2320 $view_query_part = " ";
2321 } else if ($feed != -1) {
2322 $unread = getFeedUnread($link, $feed, $cat_view);
2323
2324 if ($cat_view && $feed > 0 && $include_children)
2325 $unread += getCategoryChildrenUnread($link, $feed);
2326
2327 if ($unread > 0) {
2328 $view_query_part = " unread = true AND ";
2329 }
2330 }
2331 }
2332
2333 if ($view_mode == "marked") {
2334 $view_query_part = " marked = true AND ";
2335 }
2336
2337 if ($view_mode == "published") {
2338 $view_query_part = " published = true AND ";
2339 }
2340
2341 if ($view_mode == "unread") {
2342 $view_query_part = " unread = true AND ";
2343 }
2344
2345 if ($view_mode == "updated") {
2346 $view_query_part = " (last_read is null and unread = false) AND ";
2347 }
2348
2349 if ($limit > 0) {
2350 $limit_query_part = "LIMIT " . $limit;
2351 }
2352
2353 $allow_archived = false;
2354
2355 $vfeed_query_part = "";
2356
2357 // override query strategy and enable feed display when searching globally
2358 if ($search && $search_mode == "all_feeds") {
2359 $query_strategy_part = "true";
2360 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2361 /* tags */
2362 } else if (!is_numeric($feed)) {
2363 $query_strategy_part = "true";
2364 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2365 id = feed_id) as feed_title,";
2366 } else if ($search && $search_mode == "this_cat") {
2367 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2368
2369 if ($feed > 0) {
2370 if ($include_children) {
2371 $subcats = getChildCategories($link, $feed, $owner_uid);
2372 array_push($subcats, $feed);
2373 $cats_qpart = join(",", $subcats);
2374 } else {
2375 $cats_qpart = $feed;
2376 }
2377
2378 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2379
2380 } else {
2381 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2382 }
2383
2384 } else if ($feed > 0) {
2385
2386 if ($cat_view) {
2387
2388 if ($feed > 0) {
2389 if ($include_children) {
2390 # sub-cats
2391 $subcats = getChildCategories($link, $feed, $owner_uid);
2392
2393 array_push($subcats, $feed);
2394 $query_strategy_part = "cat_id IN (".
2395 implode(",", $subcats).")";
2396
2397 } else {
2398 $query_strategy_part = "cat_id = '$feed'";
2399 }
2400
2401 } else {
2402 $query_strategy_part = "cat_id IS NULL";
2403 }
2404
2405 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2406
2407 } else {
2408 $query_strategy_part = "feed_id = '$feed'";
2409 }
2410 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2411 $query_strategy_part = "feed_id IS NULL";
2412 $allow_archived = true;
2413 } else if ($feed == 0 && $cat_view) { // uncategorized
2414 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2415 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2416 } else if ($feed == -1) { // starred virtual feed
2417 $query_strategy_part = "marked = true";
2418 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2419 $allow_archived = true;
2420
2421 } else if ($feed == -2) { // published virtual feed OR labels category
2422
2423 if (!$cat_view) {
2424 $query_strategy_part = "published = true";
2425 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2426 $allow_archived = true;
2427
2428 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2429 } else {
2430 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2431
2432 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2433
2434 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2435 ttrss_user_labels2.article_id = ref_id";
2436
2437 }
2438 } else if ($feed == -6) { // recently read
2439 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2440 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2441 $allow_archived = true;
2442
2443 if (!$override_order) $override_order = "last_read DESC";
2444 } else if ($feed == -3) { // fresh virtual feed
2445 $query_strategy_part = "unread = true AND score >= 0";
2446
2447 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2448
2449 if (DB_TYPE == "pgsql") {
2450 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2451 } else {
2452 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2453 }
2454
2455 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2456 } else if ($feed == -4) { // all articles virtual feed
2457 $query_strategy_part = "true";
2458 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2459 } else if ($feed <= -10) { // labels
2460 $label_id = -$feed - 11;
2461
2462 $query_strategy_part = "label_id = '$label_id' AND
2463 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2464 ttrss_user_labels2.article_id = ref_id";
2465
2466 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2467 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2468 $allow_archived = true;
2469
2470 } else {
2471 $query_strategy_part = "true";
2472 }
2473
2474 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2475 $date_sort_field = "updated";
2476 } else {
2477 $date_sort_field = "date_entered";
2478 }
2479
2480 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2481 $order_by = "$date_sort_field";
2482 } else {
2483 $order_by = "$date_sort_field DESC";
2484 }
2485
2486 if ($view_mode != "noscores") {
2487 $order_by = "score DESC, $order_by";
2488 }
2489
2490 if ($override_order) {
2491 $order_by = $override_order;
2492 }
2493
2494 $feed_title = "";
2495
2496 if ($search) {
2497 $feed_title = T_sprintf("Search results: %s", $search);
2498 } else {
2499 if ($cat_view) {
2500 $feed_title = getCategoryTitle($link, $feed);
2501 } else {
2502 if (is_numeric($feed) && $feed > 0) {
2503 $result = db_query($link, "SELECT title,site_url,last_error
2504 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2505
2506 $feed_title = db_fetch_result($result, 0, "title");
2507 $feed_site_url = db_fetch_result($result, 0, "site_url");
2508 $last_error = db_fetch_result($result, 0, "last_error");
2509 } else {
2510 $feed_title = getFeedTitle($link, $feed);
2511 }
2512 }
2513 }
2514
2515 $content_query_part = "content as content_preview, cached_content, ";
2516
2517 if (is_numeric($feed)) {
2518
2519 if ($feed >= 0) {
2520 $feed_kind = "Feeds";
2521 } else {
2522 $feed_kind = "Labels";
2523 }
2524
2525 if ($limit_query_part) {
2526 $offset_query_part = "OFFSET $offset";
2527 }
2528
2529 // proper override_order applied above
2530 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2531 if (!$override_order) {
2532 $order_by = "ttrss_feeds.title, $order_by";
2533 } else {
2534 $order_by = "ttrss_feeds.title, $override_order";
2535 }
2536 }
2537
2538 if (!$allow_archived) {
2539 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2540 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2541
2542 } else {
2543 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2544 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2545 }
2546
2547 $query = "SELECT DISTINCT
2548 date_entered,
2549 guid,
2550 ttrss_entries.id,ttrss_entries.title,
2551 updated,
2552 label_cache,
2553 tag_cache,
2554 always_display_enclosures,
2555 site_url,
2556 note,
2557 num_comments,
2558 comments,
2559 int_id,
2560 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2561 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
2562 $vfeed_query_part
2563 $content_query_part
2564 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
2565 author,score
2566 FROM
2567 $from_qpart
2568 WHERE
2569 $feed_check_qpart
2570 ttrss_user_entries.ref_id = ttrss_entries.id AND
2571 ttrss_user_entries.owner_uid = '$owner_uid' AND
2572 $search_query_part
2573 $filter_query_part
2574 $view_query_part
2575 $since_id_part
2576 $query_strategy_part ORDER BY $order_by
2577 $limit_query_part $offset_query_part";
2578
2579 if ($_REQUEST["debug"]) print $query;
2580
2581 $result = db_query($link, $query);
2582
2583 } else {
2584 // browsing by tag
2585
2586 $select_qpart = "SELECT DISTINCT " .
2587 "date_entered," .
2588 "guid," .
2589 "note," .
2590 "ttrss_entries.id as id," .
2591 "title," .
2592 "updated," .
2593 "unread," .
2594 "feed_id," .
2595 "orig_feed_id," .
2596 "marked," .
2597 "num_comments, " .
2598 "comments, " .
2599 "tag_cache," .
2600 "label_cache," .
2601 "link," .
2602 "last_read," .
2603 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
2604 $since_id_part .
2605 $vfeed_query_part .
2606 $content_query_part .
2607 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
2608 "score ";
2609
2610 $feed_kind = "Tags";
2611 $all_tags = explode(",", $feed);
2612 if ($search_mode == 'any') {
2613 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2614 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2615 $where_qpart = " WHERE " .
2616 "ref_id = ttrss_entries.id AND " .
2617 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2618 "post_int_id = int_id AND $tag_sql AND " .
2619 $view_query_part .
2620 $search_query_part .
2621 $query_strategy_part . " ORDER BY $order_by " .
2622 $limit_query_part;
2623
2624 } else {
2625 $i = 1;
2626 $sub_selects = array();
2627 $sub_ands = array();
2628 foreach ($all_tags as $term) {
2629 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
2630 $i++;
2631 }
2632 if ($i > 2) {
2633 $x = 1;
2634 $y = 2;
2635 do {
2636 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2637 $x++;
2638 $y++;
2639 } while ($y < $i);
2640 }
2641 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2642 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2643 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2644 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2645 }
2646 // error_log("TAG SQL: " . $tag_sql);
2647 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2648
2649 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2650 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2651 }
2652
2653 return array($result, $feed_title, $feed_site_url, $last_error);
2654
2655 }
2656
2657 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2658 if (!$owner) $owner = $_SESSION["uid"];
2659
2660 $res = trim($str); if (!$res) return '';
2661
2662 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1, 'balance' => 0);
2663 $res = htmLawed($res, $config);
2664
2665 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2666 $res = preg_replace('/<img[^>]+>/is', '', $res);
2667 }
2668
2669 if (strpos($res, "href=") === false)
2670 $res = rewrite_urls($res);
2671
2672 $charset_hack = '<head>
2673 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2674 </head>';
2675
2676 $res = trim($res); if (!$res) return '';
2677
2678 libxml_use_internal_errors(true);
2679
2680 $doc = new DOMDocument();
2681 $doc->loadHTML($charset_hack . $res);
2682 $xpath = new DOMXPath($doc);
2683
2684 $entries = $xpath->query('(//a[@href]|//img[@src])');
2685 $br_inserted = 0;
2686
2687 foreach ($entries as $entry) {
2688
2689 if ($site_url) {
2690
2691 if ($entry->hasAttribute('href'))
2692 $entry->setAttribute('href',
2693 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2694
2695 if ($entry->hasAttribute('src'))
2696 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2697 $entry->setAttribute('src',
2698 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2699 }
2700
2701 if (strtolower($entry->nodeName) == "a") {
2702 $entry->setAttribute("target", "_blank");
2703 }
2704
2705 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
2706 $br = $doc->createElement("br");
2707
2708 if ($entry->parentNode->nextSibling) {
2709 $entry->parentNode->insertBefore($br, $entry->nextSibling);
2710 $br_inserted = 1;
2711 }
2712
2713 }
2714 }
2715
2716 $node = $doc->getElementsByTagName('body')->item(0);
2717
2718 // http://tt-rss.org/redmine/issues/357
2719 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
2720 }
2721
2722 function check_for_update($link) {
2723 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
2724 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
2725
2726 $version_data = @fetch_file_contents($version_url);
2727
2728 if ($version_data) {
2729 $version_data = json_decode($version_data, true);
2730 if ($version_data && $version_data['version']) {
2731
2732 if (version_compare(VERSION, $version_data['version']) == -1) {
2733 return $version_data;
2734 }
2735 }
2736 }
2737 }
2738 return false;
2739 }
2740
2741 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2742
2743 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2744 if (count($ids) == 0) return;
2745
2746 $tmp_ids = array();
2747
2748 foreach ($ids as $id) {
2749 array_push($tmp_ids, "ref_id = '$id'");
2750 }
2751
2752 $ids_qpart = join(" OR ", $tmp_ids);
2753
2754 if ($cmode == 0) {
2755 db_query($link, "UPDATE ttrss_user_entries SET
2756 unread = false,last_read = NOW()
2757 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2758 } else if ($cmode == 1) {
2759 db_query($link, "UPDATE ttrss_user_entries SET
2760 unread = true
2761 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2762 } else {
2763 db_query($link, "UPDATE ttrss_user_entries SET
2764 unread = NOT unread,last_read = NOW()
2765 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2766 }
2767
2768 /* update ccache */
2769
2770 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2771 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2772
2773 while ($line = db_fetch_assoc($result)) {
2774 ccache_update($link, $line["feed_id"], $owner_uid);
2775 }
2776 }
2777
2778 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2779
2780 $a_id = db_escape_string($id);
2781
2782 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2783
2784 $query = "SELECT DISTINCT tag_name,
2785 owner_uid as owner FROM
2786 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2787 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2788
2789 $obj_id = md5("TAGS:$owner_uid:$id");
2790 $tags = array();
2791
2792 /* check cache first */
2793
2794 if ($tag_cache === false) {
2795 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2796 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2797
2798 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2799 }
2800
2801 if ($tag_cache) {
2802 $tags = explode(",", $tag_cache);
2803 } else {
2804
2805 /* do it the hard way */
2806
2807 $tmp_result = db_query($link, $query);
2808
2809 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2810 array_push($tags, $tmp_line["tag_name"]);
2811 }
2812
2813 /* update the cache */
2814
2815 $tags_str = db_escape_string(join(",", $tags));
2816
2817 db_query($link, "UPDATE ttrss_user_entries
2818 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2819 AND owner_uid = $owner_uid");
2820 }
2821
2822 return $tags;
2823 }
2824
2825 function trim_array($array) {
2826 $tmp = $array;
2827 array_walk($tmp, 'trim');
2828 return $tmp;
2829 }
2830
2831 function tag_is_valid($tag) {
2832 if ($tag == '') return false;
2833 if (preg_match("/^[0-9]*$/", $tag)) return false;
2834 if (mb_strlen($tag) > 250) return false;
2835
2836 if (function_exists('iconv')) {
2837 $tag = iconv("utf-8", "utf-8", $tag);
2838 }
2839
2840 if (!$tag) return false;
2841
2842 return true;
2843 }
2844
2845 function render_login_form($link, $form_id = 0) {
2846 switch ($form_id) {
2847 case 0:
2848 require_once "login_form.php";
2849 break;
2850 case 1:
2851 require_once "mobile/login_form.php";
2852 break;
2853 }
2854 exit;
2855 }
2856
2857 // from http://developer.apple.com/internet/safari/faq.html
2858 function no_cache_incantation() {
2859 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2860 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2861 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2862 header("Cache-Control: post-check=0, pre-check=0", false);
2863 header("Pragma: no-cache"); // HTTP/1.0
2864 }
2865
2866 function format_warning($msg, $id = "") {
2867 global $link;
2868 return "<div class=\"warning\" id=\"$id\">
2869 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2870 }
2871
2872 function format_notice($msg, $id = "") {
2873 global $link;
2874 return "<div class=\"notice\" id=\"$id\">
2875 <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
2876 }
2877
2878 function format_error($msg, $id = "") {
2879 global $link;
2880 return "<div class=\"error\" id=\"$id\">
2881 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2882 }
2883
2884 function print_notice($msg) {
2885 return print format_notice($msg);
2886 }
2887
2888 function print_warning($msg) {
2889 return print format_warning($msg);
2890 }
2891
2892 function print_error($msg) {
2893 return print format_error($msg);
2894 }
2895
2896
2897 function T_sprintf() {
2898 $args = func_get_args();
2899 return vsprintf(__(array_shift($args)), $args);
2900 }
2901
2902 function format_inline_player($link, $url, $ctype) {
2903
2904 $entry = "";
2905
2906 if (strpos($ctype, "audio/") === 0) {
2907
2908 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2909 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2910 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2911
2912 $id = 'AUDIO-' . uniqid();
2913
2914 $entry .= "<audio id=\"$id\"\" controls>
2915 <source type=\"$ctype\" src=\"$url\"></source>
2916 </audio>";
2917
2918 $entry .= "<span onclick=\"player(this)\"
2919 title=\"".__("Click to play")."\" status=\"0\"
2920 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2921
2922 } else {
2923
2924 $entry .= "<object type=\"application/x-shockwave-flash\"
2925 data=\"lib/button/musicplayer.swf?song_url=$url\"
2926 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2927 <param name=\"movie\"
2928 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2929 </object>";
2930 }
2931
2932 if ($entry) $entry .= "&nbsp;" . basename($url);
2933
2934 return $entry;
2935
2936 }
2937
2938 return "";
2939
2940 /* $filename = substr($url, strrpos($url, "/")+1);
2941
2942 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2943 $filename . " (" . $ctype . ")" . "</a>"; */
2944
2945 }
2946
2947 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2948 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2949
2950 $rv = array();
2951
2952 $rv['id'] = $id;
2953
2954 /* we can figure out feed_id from article id anyway, why do we
2955 * pass feed_id here? let's ignore the argument :( */
2956
2957 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2958 WHERE ref_id = '$id'");
2959
2960 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2961
2962 $rv['feed_id'] = $feed_id;
2963
2964 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2965
2966 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
2967 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
2968
2969 if (db_num_rows($result) == 1) {
2970 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
2971 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
2972 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2973 } else {
2974 $rtl_content = false;
2975 $always_display_enclosures = false;
2976 $cache_content = false;
2977 }
2978
2979 if ($rtl_content) {
2980 $rtl_tag = "dir=\"RTL\"";
2981 $rtl_class = "RTL";
2982 } else {
2983 $rtl_tag = "";
2984 $rtl_class = "";
2985 }
2986
2987 if ($mark_as_read) {
2988 $result = db_query($link, "UPDATE ttrss_user_entries
2989 SET unread = false,last_read = NOW()
2990 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2991
2992 ccache_update($link, $feed_id, $owner_uid);
2993 }
2994
2995 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
2996 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
2997 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
2998 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
2999 num_comments,
3000 tag_cache,
3001 author,
3002 orig_feed_id,
3003 note,
3004 cached_content
3005 FROM ttrss_entries,ttrss_user_entries
3006 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
3007
3008 if ($result) {
3009
3010 $line = db_fetch_assoc($result);
3011
3012 if ($line["icon_url"]) {
3013 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3014 } else {
3015 $feed_icon = "&nbsp;";
3016 }
3017
3018 $feed_site_url = $line['site_url'];
3019
3020 $num_comments = $line["num_comments"];
3021 $entry_comments = "";
3022
3023 if ($num_comments > 0) {
3024 if ($line["comments"]) {
3025 $comments_url = htmlspecialchars($line["comments"]);
3026 } else {
3027 $comments_url = htmlspecialchars($line["link"]);
3028 }
3029 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3030 } else {
3031 if ($line["comments"] && $line["link"] != $line["comments"]) {
3032 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
3033 }
3034 }
3035
3036 if ($zoom_mode) {
3037 header("Content-Type: text/html");
3038 $rv['content'] .= "<html><head>
3039 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3040 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3041 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3042 </head><body>";
3043 }
3044
3045 $title_escaped = htmlspecialchars($line['title']);
3046
3047 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3048 truncate_string(strip_tags($line['title']), 15) . "</div>";
3049
3050 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
3051 strip_tags($line['title']) . "</div>";
3052
3053 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3054
3055 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3056 class=\"postHeader\" id=\"POSTHDR-$id\">";
3057
3058 $entry_author = $line["author"];
3059
3060 if ($entry_author) {
3061 $entry_author = __(" - ") . $entry_author;
3062 }
3063
3064 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3065 $owner_uid, true);
3066
3067 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3068
3069 if ($line["link"]) {
3070 $rv['content'] .= "<div class='postTitle'><a target='_blank'
3071 title=\"".htmlspecialchars($line['title'])."\"
3072 href=\"" .
3073 htmlspecialchars($line["link"]) . "\">" .
3074 $line["title"] .
3075 "<span class='author'>$entry_author</span></a></div>";
3076 } else {
3077 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
3078 }
3079
3080 $tag_cache = $line["tag_cache"];
3081
3082 if (!$tag_cache)
3083 $tags = get_article_tags($link, $id, $owner_uid);
3084 else
3085 $tags = explode(",", $tag_cache);
3086
3087 $tags_str = format_tags_string($tags, $id);
3088 $tags_str_full = join(", ", $tags);
3089
3090 if (!$tags_str_full) $tags_str_full = __("no tags");
3091
3092 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3093
3094 $rv['content'] .= "<div class='postTags' style='float : right'>
3095 <img src='".theme_image($link, 'images/tag.png')."'
3096 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
3097
3098 if (!$zoom_mode) {
3099 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3100 <a title=\"".__('Edit tags for this article')."\"
3101 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3102
3103 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3104 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3105 position=\"below\">$tags_str_full</div>";
3106
3107 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3108 class='tagsPic' style=\"cursor : pointer\"
3109 onclick=\"postOpenInNewTab(event, $id)\"
3110 alt='Zoom' title='".__('Open article in new tab')."'>";
3111
3112 global $pluginhost;
3113
3114 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON) as $p) {
3115 $rv['content'] .= $p->hook_article_button($line);
3116 }
3117
3118
3119 } else {
3120 $tags_str = strip_tags($tags_str);
3121 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3122 }
3123 $rv['content'] .= "</div>";
3124 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3125
3126 if ($line["orig_feed_id"]) {
3127
3128 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3129 WHERE id = ".$line["orig_feed_id"]);
3130
3131 if (db_num_rows($tmp_result) != 0) {
3132
3133 $rv['content'] .= "<div clear='both'>";
3134 $rv['content'] .= __("Originally from:");
3135
3136 $rv['content'] .= "&nbsp;";
3137
3138 $tmp_line = db_fetch_assoc($tmp_result);
3139
3140 $rv['content'] .= "<a target='_blank'
3141 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3142 $tmp_line['title'] . "</a>";
3143
3144 $rv['content'] .= "&nbsp;";
3145
3146 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3147 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
3148
3149 $rv['content'] .= "</div>";
3150 }
3151 }
3152
3153 $rv['content'] .= "</div>";
3154
3155 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3156 if ($line['note']) {
3157 $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
3158 }
3159 $rv['content'] .= "</div>";
3160
3161 $rv['content'] .= "<div class=\"postIcon\">" .
3162 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3163 href=\"".htmlspecialchars($feed_site_url)."\">".
3164 $feed_icon . "</a></div>";
3165
3166 $rv['content'] .= "<div class=\"postContent\">";
3167
3168 // N-grams
3169
3170 if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3171
3172 $ngram_result = db_query($link, "SELECT id,title FROM
3173 ttrss_entries,ttrss_user_entries
3174 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3175 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD."
3176 AND title != '$title_escaped'
3177 AND owner_uid = $owner_uid");
3178
3179 if (db_num_rows($ngram_result) > 0) {
3180 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3181 "<span>" . __('Related')."</span>";
3182 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3183
3184 while ($nline = db_fetch_assoc($ngram_result)) {
3185 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3186 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3187
3188 }
3189 $rv['content'] .= "</div></div><br/";
3190 }
3191 }
3192
3193 if ($cache_content && $line["cached_content"] != "") {
3194 $line["content"] =& $line["cached_content"];
3195 }
3196
3197 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3198 $feed_site_url);
3199
3200 $rv['content'] .= $article_content;
3201
3202 $rv['content'] .= format_article_enclosures($link, $id,
3203 $always_display_enclosures, $article_content);
3204
3205 $rv['content'] .= "</div>";
3206
3207 $rv['content'] .= "</div>";
3208
3209 }
3210
3211 if ($zoom_mode) {
3212 $rv['content'] .= "
3213 <div style=\"text-align : center\">
3214 <button onclick=\"return window.close()\">".
3215 __("Close this window")."</button></div>";
3216 $rv['content'] .= "</body></html>";
3217 }
3218
3219 return $rv;
3220
3221 }
3222
3223 function print_checkpoint($n, $s) {
3224 $ts = getmicrotime();
3225 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3226 return $ts;
3227 }
3228
3229 function sanitize_tag($tag) {
3230 $tag = trim($tag);
3231
3232 $tag = mb_strtolower($tag, 'utf-8');
3233
3234 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3235
3236 // $tag = str_replace('"', "", $tag);
3237 // $tag = str_replace("+", " ", $tag);
3238 $tag = str_replace("technorati tag: ", "", $tag);
3239
3240 return $tag;
3241 }
3242
3243 function get_self_url_prefix() {
3244 if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
3245 return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
3246 } else {
3247 return SELF_URL_PATH;
3248 }
3249 }
3250
3251 /**
3252 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3253 *
3254 * @return string The Mozilla Firefox feed adding URL.
3255 */
3256 function add_feed_url() {
3257 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3258
3259 $url_path = get_self_url_prefix() .
3260 "/public.php?op=subscribe&feed_url=%s";
3261 return $url_path;
3262 } // function add_feed_url
3263
3264 function encrypt_password($pass, $salt = '', $mode2 = false) {
3265 if ($salt && $mode2) {
3266 return "MODE2:" . hash('sha256', $salt . $pass);
3267 } else if ($salt) {
3268 return "SHA1X:" . sha1("$salt:$pass");
3269 } else {
3270 return "SHA1:" . sha1($pass);
3271 }
3272 } // function encrypt_password
3273
3274 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3275 $filters = array();
3276
3277 $cat_id = (int)getFeedCategory($link, $feed_id);
3278
3279 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3280 owner_uid = $owner_uid AND enabled = true");
3281
3282 $check_cats = join(",", array_merge(
3283 getParentCategories($link, $cat_id, $owner_uid),
3284 array($cat_id)));
3285
3286 while ($line = db_fetch_assoc($result)) {
3287 $filter_id = $line["id"];
3288
3289 $result2 = db_query($link, "SELECT
3290 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3291 FROM ttrss_filters2_rules AS r,
3292 ttrss_filter_types AS t
3293 WHERE
3294 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3295 (feed_id IS NULL OR feed_id = '$feed_id') AND
3296 filter_type = t.id AND filter_id = '$filter_id'");
3297
3298 $rules = array();
3299 $actions = array();
3300
3301 while ($rule_line = db_fetch_assoc($result2)) {
3302 # print_r($rule_line);
3303
3304 $rule = array();
3305 $rule["reg_exp"] = $rule_line["reg_exp"];
3306 $rule["type"] = $rule_line["type_name"];
3307
3308 array_push($rules, $rule);
3309 }
3310
3311 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3312 FROM ttrss_filters2_actions AS a,
3313 ttrss_filter_actions AS t
3314 WHERE
3315 action_id = t.id AND filter_id = '$filter_id'");
3316
3317 while ($action_line = db_fetch_assoc($result2)) {
3318 # print_r($action_line);
3319
3320 $action = array();
3321 $action["type"] = $action_line["type_name"];
3322 $action["param"] = $action_line["action_param"];
3323
3324 array_push($actions, $action);
3325 }
3326
3327
3328 $filter = array();
3329 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3330 $filter["rules"] = $rules;
3331 $filter["actions"] = $actions;
3332
3333 if (count($rules) > 0 && count($actions) > 0) {
3334 array_push($filters, $filter);
3335 }
3336 }
3337
3338 return $filters;
3339 }
3340
3341 function get_score_pic($score) {
3342 if ($score > 100) {
3343 return "score_high.png";
3344 } else if ($score > 0) {
3345 return "score_half_high.png";
3346 } else if ($score < -100) {
3347 return "score_low.png";
3348 } else if ($score < 0) {
3349 return "score_half_low.png";
3350 } else {
3351 return "score_neutral.png";
3352 }
3353 }
3354
3355 function feed_has_icon($id) {
3356 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
3357 }
3358
3359 function init_connection($link) {
3360 if ($link) {
3361
3362 if (DB_TYPE == "pgsql") {
3363 pg_query($link, "set client_encoding = 'UTF-8'");
3364 pg_set_client_encoding("UNICODE");
3365 pg_query($link, "set datestyle = 'ISO, european'");
3366 pg_query($link, "set TIME ZONE 0");
3367 } else {
3368 db_query($link, "SET time_zone = '+0:0'");
3369
3370 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
3371 db_query($link, "SET NAMES " . MYSQL_CHARSET);
3372 }
3373 }
3374
3375 global $pluginhost;
3376
3377 $pluginhost = new PluginHost($link);
3378 $pluginhost->load(PLUGINS, $pluginhost::KIND_ALL);
3379
3380 return true;
3381 } else {
3382 print "Unable to connect to database:" . db_last_error();
3383 return false;
3384 }
3385 }
3386
3387 function format_tags_string($tags, $id) {
3388
3389 $tags_str = "";
3390 $tags_nolinks_str = "";
3391
3392 $num_tags = 0;
3393
3394 $tag_limit = 6;
3395
3396 $formatted_tags = array();
3397
3398 foreach ($tags as $tag) {
3399 $num_tags++;
3400 $tag_escaped = str_replace("'", "\\'", $tag);
3401
3402 if (mb_strlen($tag) > 30) {
3403 $tag = truncate_string($tag, 30);
3404 }
3405
3406 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3407
3408 array_push($formatted_tags, $tag_str);
3409
3410 $tmp_tags_str = implode(", ", $formatted_tags);
3411
3412 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
3413 break;
3414 }
3415 }
3416
3417 $tags_str = implode(", ", $formatted_tags);
3418
3419 if ($num_tags < count($tags)) {
3420 $tags_str .= ", &hellip;";
3421 }
3422
3423 if ($num_tags == 0) {
3424 $tags_str = __("no tags");
3425 }
3426
3427 return $tags_str;
3428
3429 }
3430
3431 function format_article_labels($labels, $id) {
3432
3433 $labels_str = "";
3434
3435 foreach ($labels as $l) {
3436 $labels_str .= sprintf("<span class='hlLabelRef'
3437 style='color : %s; background-color : %s'>%s</span>",
3438 $l[2], $l[3], $l[1]);
3439 }
3440
3441 return $labels_str;
3442
3443 }
3444
3445 function format_article_note($id, $note, $allow_edit = true) {
3446
3447 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3448 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3449 ($allow_edit ? __('(edit note)') : "")."</div>$note</div>";
3450
3451 return $str;
3452 }
3453
3454 function toggle_collapse_cat($link, $cat_id, $mode) {
3455 if ($cat_id > 0) {
3456 $mode = bool_to_sql_bool($mode);
3457
3458 db_query($link, "UPDATE ttrss_feed_categories SET
3459 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
3460 $_SESSION["uid"]);
3461 } else {
3462 $pref_name = '';
3463
3464 switch ($cat_id) {
3465 case -1:
3466 $pref_name = '_COLLAPSED_SPECIAL';
3467 break;
3468 case -2:
3469 $pref_name = '_COLLAPSED_LABELS';
3470 break;
3471 case 0:
3472 $pref_name = '_COLLAPSED_UNCAT';
3473 break;
3474 }
3475
3476 if ($pref_name) {
3477 if ($mode) {
3478 set_pref($link, $pref_name, 'true');
3479 } else {
3480 set_pref($link, $pref_name, 'false');
3481 }
3482 }
3483 }
3484 }
3485
3486
3487 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3488 if ($parent_cat_id) {
3489 $parent_qpart = "parent_cat = '$parent_cat_id'";
3490 $parent_insert = "'$parent_cat_id'";
3491 } else {
3492 $parent_qpart = "parent_cat IS NULL";
3493 $parent_insert = "NULL";
3494 }
3495
3496 $result = db_query($link,
3497 "SELECT id FROM ttrss_feed_categories
3498 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3499
3500 if (db_num_rows($result) == 0) {
3501 return false;
3502 } else {
3503 return db_fetch_result($result, 0, "id");
3504 }
3505 }
3506
3507 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3508
3509 if (!$feed_cat) return false;
3510
3511 db_query($link, "BEGIN");
3512
3513 if ($parent_cat_id) {
3514 $parent_qpart = "parent_cat = '$parent_cat_id'";
3515 $parent_insert = "'$parent_cat_id'";
3516 } else {
3517 $parent_qpart = "parent_cat IS NULL";
3518 $parent_insert = "NULL";
3519 }
3520
3521 $result = db_query($link,
3522 "SELECT id FROM ttrss_feed_categories
3523 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3524
3525 if (db_num_rows($result) == 0) {
3526
3527 $result = db_query($link,
3528 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3529 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3530
3531 db_query($link, "COMMIT");
3532
3533 return true;
3534 }
3535
3536 return false;
3537 }
3538
3539 function getArticleFeed($link, $id) {
3540 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3541 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3542
3543 if (db_num_rows($result) != 0) {
3544 return db_fetch_result($result, 0, "feed_id");
3545 } else {
3546 return 0;
3547 }
3548 }
3549
3550 /**
3551 * Fixes incomplete URLs by prepending "http://".
3552 * Also replaces feed:// with http://, and
3553 * prepends a trailing slash if the url is a domain name only.
3554 *
3555 * @param string $url Possibly incomplete URL
3556 *
3557 * @return string Fixed URL.
3558 */
3559 function fix_url($url) {
3560 if (strpos($url, '://') === false) {
3561 $url = 'http://' . $url;
3562 } else if (substr($url, 0, 5) == 'feed:') {
3563 $url = 'http:' . substr($url, 5);
3564 }
3565
3566 //prepend slash if the URL has no slash in it
3567 // "http://www.example" -> "http://www.example/"
3568 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
3569 $url .= '/';
3570 }
3571
3572 if ($url != "http:///")
3573 return $url;
3574 else
3575 return '';
3576 }
3577
3578 function validate_feed_url($url) {
3579 $parts = parse_url($url);
3580
3581 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
3582
3583 }
3584
3585 function get_article_enclosures($link, $id) {
3586
3587 $query = "SELECT * FROM ttrss_enclosures
3588 WHERE post_id = '$id' AND content_url != ''";
3589
3590 $rv = array();
3591
3592 $result = db_query($link, $query);
3593
3594 if (db_num_rows($result) > 0) {
3595 while ($line = db_fetch_assoc($result)) {
3596 array_push($rv, $line);
3597 }
3598 }
3599
3600 return $rv;
3601 }
3602
3603 function save_email_address($link, $email) {
3604 // FIXME: implement persistent storage of emails
3605
3606 if (!$_SESSION['stored_emails'])
3607 $_SESSION['stored_emails'] = array();
3608
3609 if (!in_array($email, $_SESSION['stored_emails']))
3610 array_push($_SESSION['stored_emails'], $email);
3611 }
3612
3613
3614 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
3615
3616 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3617
3618 $sql_is_cat = bool_to_sql_bool($is_cat);
3619
3620 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
3621 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
3622 AND owner_uid = " . $owner_uid);
3623
3624 if (db_num_rows($result) == 1) {
3625 return db_fetch_result($result, 0, "access_key");
3626 } else {
3627 $key = db_escape_string(sha1(uniqid(rand(), true)));
3628
3629 $result = db_query($link, "INSERT INTO ttrss_access_keys
3630 (access_key, feed_id, is_cat, owner_uid)
3631 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
3632
3633 return $key;
3634 }
3635 return false;
3636 }
3637
3638 function get_feeds_from_html($url, $content)
3639 {
3640 $url = fix_url($url);
3641 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
3642
3643 libxml_use_internal_errors(true);
3644
3645 $doc = new DOMDocument();
3646 $doc->loadHTML($content);
3647 $xpath = new DOMXPath($doc);
3648 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
3649 $feedUrls = array();
3650 foreach ($entries as $entry) {
3651 if ($entry->hasAttribute('href')) {
3652 $title = $entry->getAttribute('title');
3653 if ($title == '') {
3654 $title = $entry->getAttribute('type');
3655 }
3656 $feedUrl = rewrite_relative_url(
3657 $baseUrl, $entry->getAttribute('href')
3658 );
3659 $feedUrls[$feedUrl] = $title;
3660 }
3661 }
3662 return $feedUrls;
3663 }
3664
3665 function is_html($content) {
3666 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
3667 }
3668
3669 function url_is_html($url, $login = false, $pass = false) {
3670 return is_html(fetch_file_contents($url, false, $login, $pass));
3671 }
3672
3673 function print_label_select($link, $name, $value, $attributes = "") {
3674
3675 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3676 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
3677
3678 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
3679 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
3680
3681 while ($line = db_fetch_assoc($result)) {
3682
3683 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
3684
3685 print "<option value=\"".htmlspecialchars($line["caption"])."\"
3686 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
3687
3688 }
3689
3690 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
3691
3692 print "</select>";
3693
3694
3695 }
3696
3697 function format_article_enclosures($link, $id, $always_display_enclosures,
3698 $article_content) {
3699
3700 $result = get_article_enclosures($link, $id);
3701 $rv = '';
3702
3703 if (count($result) > 0) {
3704
3705 $entries_html = array();
3706 $entries = array();
3707 $entries_inline = array();
3708
3709 foreach ($result as $line) {
3710
3711 $url = $line["content_url"];
3712 $ctype = $line["content_type"];
3713
3714 if (!$ctype) $ctype = __("unknown type");
3715
3716 $filename = substr($url, strrpos($url, "/")+1);
3717
3718 $player = format_inline_player($link, $url, $ctype);
3719
3720 if ($player) array_push($entries_inline, $player);
3721
3722 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3723 # $filename . " (" . $ctype . ")" . "</a>";
3724
3725 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
3726 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
3727
3728 array_push($entries_html, $entry);
3729
3730 $entry = array();
3731
3732 $entry["type"] = $ctype;
3733 $entry["filename"] = $filename;
3734 $entry["url"] = $url;
3735
3736 array_push($entries, $entry);
3737 }
3738
3739 if (!get_pref($link, "STRIP_IMAGES")) {
3740 if ($always_display_enclosures ||
3741 !preg_match("/<img/i", $article_content)) {
3742
3743 foreach ($entries as $entry) {
3744
3745 if (preg_match("/image/", $entry["type"]) ||
3746 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
3747
3748 $rv .= "<p><img
3749 alt=\"".htmlspecialchars($entry["filename"])."\"
3750 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
3751
3752 }
3753 }
3754 }
3755 }
3756
3757 if (count($entries_inline) > 0) {
3758 $rv .= "<hr clear='both'/>";
3759 foreach ($entries_inline as $entry) { $rv .= $entry; };
3760 $rv .= "<hr clear='both'/>";
3761 }
3762
3763 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
3764 "<span>" . __('Attachments')."</span>";
3765 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3766
3767 foreach ($entries_html as $entry) { $rv .= $entry; };
3768
3769 $rv .= "</div></div>";
3770 }
3771
3772 return $rv;
3773 }
3774
3775 function getLastArticleId($link) {
3776 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
3777 WHERE owner_uid = " . $_SESSION["uid"]);
3778
3779 if (db_num_rows($result) == 1) {
3780 return db_fetch_result($result, 0, "id");
3781 } else {
3782 return -1;
3783 }
3784 }
3785
3786 function build_url($parts) {
3787 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
3788 }
3789
3790 /**
3791 * Converts a (possibly) relative URL to a absolute one.
3792 *
3793 * @param string $url Base URL (i.e. from where the document is)
3794 * @param string $rel_url Possibly relative URL in the document
3795 *
3796 * @return string Absolute URL
3797 */
3798 function rewrite_relative_url($url, $rel_url) {
3799 if (strpos($rel_url, "magnet:") === 0) {
3800 return $rel_url;
3801 } else if (strpos($rel_url, "://") !== false) {
3802 return $rel_url;
3803 } else if (strpos($rel_url, "//") === 0) {
3804 # protocol-relative URL (rare but they exist)
3805 return $rel_url;
3806 } else if (strpos($rel_url, "/") === 0)
3807 {
3808 $parts = parse_url($url);
3809 $parts['path'] = $rel_url;
3810
3811 return build_url($parts);
3812
3813 } else {
3814 $parts = parse_url($url);
3815 if (!isset($parts['path'])) {
3816 $parts['path'] = '/';
3817 }
3818 $dir = $parts['path'];
3819 if (substr($dir, -1) !== '/') {
3820 $dir = dirname($parts['path']);
3821 $dir !== '/' && $dir .= '/';
3822 }
3823 $parts['path'] = $dir . $rel_url;
3824
3825 return build_url($parts);
3826 }
3827 }
3828
3829 function sphinx_search($query, $offset = 0, $limit = 30) {
3830 require_once 'lib/sphinxapi.php';
3831
3832 $sphinxClient = new SphinxClient();
3833
3834 $sphinxClient->SetServer('localhost', 9312);
3835 $sphinxClient->SetConnectTimeout(1);
3836
3837 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
3838 'feed_title' => 20));
3839
3840 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
3841 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
3842 $sphinxClient->SetLimits($offset, $limit, 1000);
3843 $sphinxClient->SetArrayResult(false);
3844 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
3845
3846 $result = $sphinxClient->Query($query, SPHINX_INDEX);
3847
3848 $ids = array();
3849
3850 if (is_array($result['matches'])) {
3851 foreach (array_keys($result['matches']) as $int_id) {
3852 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
3853 array_push($ids, $ref_id);
3854 }
3855 }
3856
3857 return $ids;
3858 }
3859
3860 function cleanup_tags($link, $days = 14, $limit = 1000) {
3861
3862 if (DB_TYPE == "pgsql") {
3863 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
3864 } else if (DB_TYPE == "mysql") {
3865 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
3866 }
3867
3868 $tags_deleted = 0;
3869
3870 while ($limit > 0) {
3871 $limit_part = 500;
3872
3873 $query = "SELECT ttrss_tags.id AS id
3874 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
3875 WHERE post_int_id = int_id AND $interval_query AND
3876 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
3877
3878 $result = db_query($link, $query);
3879
3880 $ids = array();
3881
3882 while ($line = db_fetch_assoc($result)) {
3883 array_push($ids, $line['id']);
3884 }
3885
3886 if (count($ids) > 0) {
3887 $ids = join(",", $ids);
3888 print ".";
3889
3890 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
3891 $tags_deleted += db_affected_rows($link, $tmp_result);
3892 } else {
3893 break;
3894 }
3895
3896 $limit -= $limit_part;
3897 }
3898
3899 print "\n";
3900
3901 return $tags_deleted;
3902 }
3903
3904 function print_user_stylesheet($link) {
3905 $value = get_pref($link, 'USER_STYLESHEET');
3906
3907 if ($value) {
3908 print "<style type=\"text/css\">";
3909 print str_replace("<br/>", "\n", $value);
3910 print "</style>";
3911 }
3912
3913 }
3914
3915 function rewrite_urls($html) {
3916 libxml_use_internal_errors(true);
3917
3918 $charset_hack = '<head>
3919 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3920 </head>';
3921
3922 $doc = new DOMDocument();
3923 $doc->loadHTML($charset_hack . $html);
3924 $xpath = new DOMXPath($doc);
3925
3926 $entries = $xpath->query('//*/text()');
3927
3928 foreach ($entries as $entry) {
3929 if (strstr($entry->wholeText, "://") !== false) {
3930 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
3931 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText);
3932
3933 if ($text != $entry->wholeText) {
3934 $cdoc = new DOMDocument();
3935 $cdoc->loadHTML($charset_hack . $text);
3936
3937
3938 foreach ($cdoc->childNodes as $cnode) {
3939 $cnode = $doc->importNode($cnode, true);
3940
3941 if ($cnode) {
3942 $entry->parentNode->insertBefore($cnode);
3943 }
3944 }
3945
3946 $entry->parentNode->removeChild($entry);
3947
3948 }
3949 }
3950 }
3951
3952 $node = $doc->getElementsByTagName('body')->item(0);
3953
3954 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
3955 if ($node)
3956 return $doc->saveXML($node, LIBXML_NOEMPTYTAG);
3957 else
3958 return $html;
3959 }
3960
3961 function filter_to_sql($link, $filter, $owner_uid) {
3962 $query = array();
3963
3964 if (DB_TYPE == "pgsql")
3965 $reg_qpart = "~";
3966 else
3967 $reg_qpart = "REGEXP";
3968
3969 foreach ($filter["rules"] AS $rule) {
3970 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
3971 $rule['reg_exp']) !== FALSE;
3972
3973 if ($regexp_valid) {
3974
3975 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
3976
3977 switch ($rule["type"]) {
3978 case "title":
3979 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3980 $rule['reg_exp'] . "')";
3981 break;
3982 case "content":
3983 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
3984 $rule['reg_exp'] . "')";
3985 break;
3986 case "both":
3987 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3988 $rule['reg_exp'] . "') OR LOWER(" .
3989 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
3990 break;
3991 case "tag":
3992 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
3993 $rule['reg_exp'] . "')";
3994 break;
3995 case "link":
3996 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
3997 $rule['reg_exp'] . "')";
3998 break;
3999 case "author":
4000 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4001 $rule['reg_exp'] . "')";
4002 break;
4003 }
4004
4005 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
4006 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
4007 }
4008
4009 if (isset($rule["cat_id"])) {
4010
4011 if ($rule["cat_id"] > 0) {
4012 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
4013 array_push($children, $rule["cat_id"]);
4014
4015 $children = join(",", $children);
4016
4017 $cat_qpart = "cat_id IN ($children)";
4018 } else {
4019 $cat_qpart = "cat_id IS NULL";
4020 }
4021
4022 $qpart .= " AND $cat_qpart";
4023 }
4024
4025 array_push($query, "($qpart)");
4026
4027 }
4028 }
4029
4030 if (count($query) > 0) {
4031 return "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
4032 } else {
4033 return "(false)";
4034 }
4035 }
4036
4037 if (!function_exists('gzdecode')) {
4038 function gzdecode($string) { // no support for 2nd argument
4039 return file_get_contents('compress.zlib://data:who/cares;base64,'.
4040 base64_encode($string));
4041 }
4042 }
4043
4044 function get_random_bytes($length) {
4045 if (function_exists('openssl_random_pseudo_bytes')) {
4046 return openssl_random_pseudo_bytes($length);
4047 } else {
4048 $output = "";
4049
4050 for ($i = 0; $i < $length; $i++)
4051 $output .= chr(mt_rand(0, 255));
4052
4053 return $output;
4054 }
4055 }
4056
4057 function read_stdin() {
4058 $fp = fopen("php://stdin", "r");
4059
4060 if ($fp) {
4061 $line = trim(fgets($fp));
4062 fclose($fp);
4063 return $line;
4064 }
4065
4066 return null;
4067 }
4068
4069 function tmpdirname($path, $prefix) {
4070 // Use PHP's tmpfile function to create a temporary
4071 // directory name. Delete the file and keep the name.
4072 $tempname = tempnam($path,$prefix);
4073 if (!$tempname)
4074 return false;
4075
4076 if (!unlink($tempname))
4077 return false;
4078
4079 return $tempname;
4080 }
4081
4082 function getFeedCategory($link, $feed) {
4083 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
4084 WHERE id = '$feed'");
4085
4086 if (db_num_rows($result) > 0) {
4087 return db_fetch_result($result, 0, "cat_id");
4088 } else {
4089 return false;
4090 }
4091
4092 }
4093
4094 function implements_interface($class, $interface) {
4095 return in_array($interface, class_implements($class));
4096 }
4097
4098 ?>