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