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