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