]> git.wh0rd.org - tt-rss.git/blob - functions.php
clear_feed, purge_feed: update ccache
[tt-rss.git] / functions.php
1 <?php
2
3 /* if ($_GET["debug"]) {
4 define('DEFAULT_ERROR_LEVEL', E_ALL);
5 } else {
6 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
7 } */
8
9 require_once 'config.php';
10
11 if (DB_TYPE == "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
13 } else {
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
15 }
16
17 /**
18 * Return available translations names.
19 *
20 * @access public
21 * @return array A array of available translations.
22 */
23 function get_translations() {
24 $tr = array(
25 "auto" => "Detect automatically",
26 "en_US" => "English",
27 "fr_FR" => "Français",
28 "hu_HU" => "Magyar (Hungarian)",
29 "it_IT" => "Italiano",
30 "ja_JP" => "日本語 (Japanese)",
31 "nb_NO" => "Norwegian bokmål",
32 "ru_RU" => "Русский",
33 "pt_BR" => "Portuguese/Brazil",
34 "zh_CN" => "Simplified Chinese");
35
36 return $tr;
37 }
38
39 if (ENABLE_TRANSLATIONS == true) { // If translations are enabled.
40 require_once "accept-to-gettext.php";
41 require_once "gettext/gettext.inc";
42
43 function startup_gettext() {
44
45 # Get locale from Accept-Language header
46 $lang = al2gt(array_keys(get_translations()), "text/html");
47
48 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
49 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
50 }
51
52 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
53 $lang = $_COOKIE["ttrss_lang"];
54 }
55
56 /* In login action of mobile version */
57 if ($_POST["language"] && defined('MOBILE_VERSION')) {
58 $lang = $_POST["language"];
59 $_COOKIE["ttrss_lang"] = $lang;
60 }
61
62 if ($lang) {
63 if (defined('LC_MESSAGES')) {
64 _setlocale(LC_MESSAGES, $lang);
65 } else if (defined('LC_ALL')) {
66 _setlocale(LC_ALL, $lang);
67 } else {
68 die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
69 }
70
71 if (defined('MOBILE_VERSION')) {
72 _bindtextdomain("messages", "../locale");
73 } else {
74 _bindtextdomain("messages", "locale");
75 }
76
77 _textdomain("messages");
78 _bind_textdomain_codeset("messages", "UTF-8");
79 }
80 }
81
82 startup_gettext();
83
84 } else { // If translations are enabled.
85 function __($msg) {
86 return $msg;
87 }
88 function startup_gettext() {
89 // no-op
90 return true;
91 }
92 } // If translations are enabled.
93
94 require_once 'db-prefs.php';
95 require_once 'compat.php';
96 require_once 'errors.php';
97 require_once 'version.php';
98
99 require_once 'phpmailer/class.phpmailer.php';
100
101 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
102 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
103 define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
104
105 require_once "simplepie/simplepie.inc";
106 require_once "magpierss/rss_fetch.inc";
107 require_once 'magpierss/rss_utils.inc';
108
109 /**
110 * Print a timestamped debug message.
111 *
112 * @param string $msg The debug message.
113 * @return void
114 */
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
119 }
120 print "[$ts] $msg\n";
121 } // function _debug
122
123 /**
124 * Purge a feed old posts.
125 *
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
130 * @access public
131 * @return void
132 */
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
134
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
136
137 $rows = -1;
138
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
141
142 $owner_uid = false;
143
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
146 }
147
148 if (!$owner_uid) return;
149
150 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
151 $owner_uid, false);
152
153 if (!$purge_unread) $query_limit = " unread = false AND ";
154
155 if (DB_TYPE == "pgsql") {
156 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
157 marked = false AND feed_id = '$feed_id' AND
158 (SELECT date_entered FROM ttrss_entries WHERE
159 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
160
161 $pg_version = get_pgsql_version($link);
162
163 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
164
165 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
166 ttrss_entries.id = ref_id AND
167 marked = false AND
168 feed_id = '$feed_id' AND
169 $query_limit
170 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
171
172 } else {
173
174 $result = db_query($link, "DELETE FROM ttrss_user_entries
175 USING ttrss_entries
176 WHERE ttrss_entries.id = ref_id AND
177 marked = false AND
178 feed_id = '$feed_id' AND
179 $query_limit
180 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
181 }
182
183 $rows = pg_affected_rows($result);
184
185 } else {
186
187 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
188 marked = false AND feed_id = '$feed_id' AND
189 (SELECT date_entered FROM ttrss_entries WHERE
190 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
191
192 $result = db_query($link, "DELETE FROM ttrss_user_entries
193 USING ttrss_user_entries, ttrss_entries
194 WHERE ttrss_entries.id = ref_id AND
195 marked = false AND
196 feed_id = '$feed_id' AND
197 $query_limit
198 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
199
200 $rows = mysql_affected_rows($link);
201
202 }
203
204 ccache_update($link, $feed_id, $owner_uid);
205
206 if ($debug) {
207 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
208 }
209 } // function purge_feed
210
211 /**
212 * Purge old posts from old feeds.
213 *
214 * @param mixed $link A database connection
215 * @param boolean $do_output Set to true to enable printed output, false by default.
216 * @param integer $limit The maximal number of removed posts.
217 * @access public
218 * @return void
219 */
220 function global_purge_old_posts($link, $do_output = false, $limit = false) {
221
222 $random_qpart = sql_random_function();
223
224 if ($limit) {
225 $limit_qpart = "LIMIT $limit";
226 } else {
227 $limit_qpart = "";
228 }
229
230 $result = db_query($link,
231 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
232 ORDER BY $random_qpart $limit_qpart");
233
234 while ($line = db_fetch_assoc($result)) {
235
236 $feed_id = $line["id"];
237 $purge_interval = $line["purge_interval"];
238 $owner_uid = $line["owner_uid"];
239
240 if ($purge_interval == 0) {
241
242 $tmp_result = db_query($link,
243 "SELECT value FROM ttrss_user_prefs WHERE
244 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
245
246 if (db_num_rows($tmp_result) != 0) {
247 $purge_interval = db_fetch_result($tmp_result, 0, "value");
248 }
249 }
250
251 if ($do_output) {
252 // print "Feed $feed_id: purge interval = $purge_interval\n";
253 }
254
255 if ($purge_interval > 0) {
256 purge_feed($link, $feed_id, $purge_interval, $do_output);
257 }
258 }
259
260 // purge orphaned posts in main content table
261 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
262 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
263
264 if ($do_output) {
265 $rows = db_affected_rows($link, $result);
266 _debug("Purged $rows orphaned posts.");
267 }
268
269 } // function global_purge_old_posts
270
271 function feed_purge_interval($link, $feed_id) {
272
273 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
274 WHERE id = '$feed_id'");
275
276 if (db_num_rows($result) == 1) {
277 $purge_interval = db_fetch_result($result, 0, "purge_interval");
278 $owner_uid = db_fetch_result($result, 0, "owner_uid");
279
280 if ($purge_interval == 0) $purge_interval = get_pref($link,
281 'PURGE_OLD_DAYS', $user_id);
282
283 return $purge_interval;
284
285 } else {
286 return -1;
287 }
288 }
289
290 function purge_old_posts($link) {
291
292 $user_id = $_SESSION["uid"];
293
294 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
295 WHERE owner_uid = '$user_id'");
296
297 while ($line = db_fetch_assoc($result)) {
298
299 $feed_id = $line["id"];
300 $purge_interval = $line["purge_interval"];
301
302 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
303
304 if ($purge_interval > 0) {
305 purge_feed($link, $feed_id, $purge_interval);
306 }
307 }
308
309 // purge orphaned posts in main content table
310 db_query($link, "DELETE FROM ttrss_entries WHERE
311 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
312 }
313
314 function get_feed_update_interval($link, $feed_id) {
315 $result = db_query($link, "SELECT owner_uid, update_interval FROM
316 ttrss_feeds WHERE id = '$feed_id'");
317
318 if (db_num_rows($result) == 1) {
319 $update_interval = db_fetch_result($result, 0, "update_interval");
320 $owner_uid = db_fetch_result($result, 0, "owner_uid");
321
322 if ($update_interval != 0) {
323 return $update_interval;
324 } else {
325 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
326 }
327
328 } else {
329 return -1;
330 }
331 }
332
333 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
334
335 if (WEB_DEMO_MODE) return;
336
337 if (!$user_id) {
338 $user_id = $_SESSION["uid"];
339 purge_old_posts($link);
340 }
341
342 // db_query($link, "BEGIN");
343
344 if (MAX_UPDATE_TIME > 0) {
345 if (DB_TYPE == "mysql") {
346 $q_order = "RAND()";
347 } else {
348 $q_order = "RANDOM()";
349 }
350 } else {
351 $q_order = "last_updated DESC";
352 }
353
354 $result = db_query($link, "SELECT feed_url,id,
355 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated,
356 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
357 ORDER BY $q_order");
358
359 $upd_start = time();
360
361 while ($line = db_fetch_assoc($result)) {
362 $upd_intl = $line["update_interval"];
363
364 if (!$upd_intl || $upd_intl == 0) {
365 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
366 }
367
368 if ($upd_intl < 0) {
369 // Updates for this feed are disabled
370 continue;
371 }
372
373 if ($fetch || (!$line["last_updated"] ||
374 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
375
376 // print "<!-- feed: ".$line["feed_url"]." -->";
377
378 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
379
380 $upd_elapsed = time() - $upd_start;
381
382 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
383 return;
384 }
385 }
386 }
387
388 // db_query($link, "COMMIT");
389
390 }
391
392 function fetch_file_contents($url) {
393 if (USE_CURL_FOR_ICONS) {
394 $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
395
396 $ch = curl_init($url);
397 $fp = fopen($tmpfile, "w");
398
399 if ($fp) {
400 curl_setopt($ch, CURLOPT_FILE, $fp);
401 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
402 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
403 curl_exec($ch);
404 curl_close($ch);
405 fclose($fp);
406 }
407
408 $contents = file_get_contents($tmpfile);
409 unlink($tmpfile);
410
411 return $contents;
412
413 } else {
414 return file_get_contents($url);
415 }
416
417 }
418
419 /**
420 * Try to determine the favicon URL for a feed.
421 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
422 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
423 *
424 * @param string $url A feed or page URL
425 * @access public
426 * @return mixed The favicon URL, or false if none was found.
427 */
428 function get_favicon_url($url) {
429
430 if ($html = @fetch_file_contents($url)) {
431
432 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
433 // Attempt to grab a favicon link from their webpage url
434 $linkUrl = html_entity_decode($matches[1]);
435
436 if (substr($linkUrl, 0, 1) == '/') {
437 $urlParts = parse_url($url);
438 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
439 } else if (substr($linkUrl, 0, 7) == 'http://') {
440 $faviconURL = $linkUrl;
441 } else if (substr($url, -1, 1) == '/') {
442 $faviconURL = $url.$linkUrl;
443 } else {
444 $faviconURL = $url.'/'.$linkUrl;
445 }
446
447 } else {
448 // If unsuccessful, attempt to "guess" the favicon location
449 $urlParts = parse_url($url);
450 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
451 }
452 }
453
454 // Run a test to see if what we have attempted to get actually exists.
455 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
456 return $faviconURL;
457 } else {
458 return false;
459 }
460 } // function get_favicon_url
461
462 /**
463 * Check if a link is a valid and working URL.
464 *
465 * @param mixed $link A URL to check
466 * @access public
467 * @return boolean True if the URL is valid, false otherwise.
468 */
469 function url_validate($link) {
470
471 $url_parts = @parse_url($link);
472
473 if ( empty( $url_parts["host"] ) )
474 return false;
475
476 if ( !empty( $url_parts["path"] ) ) {
477 $documentpath = $url_parts["path"];
478 } else {
479 $documentpath = "/";
480 }
481
482 if ( !empty( $url_parts["query"] ) )
483 $documentpath .= "?" . $url_parts["query"];
484
485 $host = $url_parts["host"];
486 $port = $url_parts["port"];
487
488 if ( empty($port) )
489 $port = "80";
490
491 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
492
493 if ( !$socket )
494 return false;
495
496 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
497
498 $http_response = fgets( $socket, 22 );
499
500 $responses = "/(200 OK)|(30[0-9] Moved)/";
501 if ( preg_match($responses, $http_response) ) {
502 fclose($socket);
503 return true;
504 } else {
505 return false;
506 }
507
508 } // function url_validate
509
510 function check_feed_favicon($site_url, $feed, $link) {
511 $favicon_url = get_favicon_url($site_url);
512
513 # print "FAVICON [$site_url]: $favicon_url\n";
514
515 error_reporting(0);
516
517 $icon_file = ICONS_DIR . "/$feed.ico";
518
519 if ($favicon_url && !file_exists($icon_file)) {
520 $contents = fetch_file_contents($favicon_url);
521
522 $fp = fopen($icon_file, "w");
523
524 if ($fp) {
525 fwrite($fp, $contents);
526 fclose($fp);
527 chmod($icon_file, 0644);
528 }
529 }
530
531 error_reporting(DEFAULT_ERROR_LEVEL);
532
533 }
534
535 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
536
537 if (!$_GET["daemon"] && !$ignore_daemon) {
538 return false;
539 }
540
541 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
542 _debug("update_rss_feed: start");
543 }
544
545 if (!$ignore_daemon) {
546
547 if (DB_TYPE == "pgsql") {
548 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
549 } else {
550 $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
551 }
552
553 $result = db_query($link, "SELECT id,update_interval,auth_login,
554 auth_pass,cache_images,update_method
555 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
556
557 } else {
558
559 $result = db_query($link, "SELECT id,update_interval,auth_login,
560 auth_pass,cache_images,update_method,hidden
561 FROM ttrss_feeds WHERE id = '$feed'");
562
563 }
564
565 if (db_num_rows($result) == 0) {
566 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
567 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
568 }
569 return false;
570 }
571
572 $hidden = sql_bool_to_bool(db_fetch_result($result, 0, "hidden"));
573 $update_method = db_fetch_result($result, 0, "update_method");
574
575 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
576 WHERE id = '$feed'");
577
578 $auth_login = db_fetch_result($result, 0, "auth_login");
579 $auth_pass = db_fetch_result($result, 0, "auth_pass");
580
581 if (ALLOW_SELECT_UPDATE_METHOD) {
582 if (ENABLE_SIMPLEPIE) {
583 $use_simplepie = $update_method != 1;
584 } else {
585 $use_simplepie = $update_method == 2;
586 }
587 } else {
588 $use_simplepie = ENABLE_SIMPLEPIE;
589 }
590
591 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
592 _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
593 }
594
595 if (!$use_simplepie) {
596 $auth_login = urlencode($auth_login);
597 $auth_pass = urlencode($auth_pass);
598 }
599
600 $update_interval = db_fetch_result($result, 0, "update_interval");
601 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
602
603 if ($update_interval < 0) { return; }
604
605 $feed = db_escape_string($feed);
606
607 $fetch_url = $feed_url;
608
609 if ($auth_login && $auth_pass) {
610 $url_parts = array();
611 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
612
613 if ($url_parts[1] && $url_parts[2]) {
614 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
615 }
616
617 }
618
619 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
620 _debug("update_rss_feed: fetching [$fetch_url]...");
621 }
622
623 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
624 error_reporting(0);
625 }
626
627 if (!$use_simplepie) {
628 $rss = fetch_rss($fetch_url);
629 } else {
630 if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
631 mkdir(SIMPLEPIE_CACHE_DIR);
632 }
633
634 $rss = new SimplePie();
635 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
636 # $rss->set_timeout(10);
637 $rss->set_feed_url($fetch_url);
638 $rss->set_output_encoding('UTF-8');
639
640 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
641 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
642 _debug("enabling image cache");
643 }
644
645 $rss->set_image_handler('./image.php', 'i');
646 }
647
648 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
649 _debug("feed update interval (sec): " .
650 get_feed_update_interval($link, $feed)*60);
651 }
652
653 if (is_dir(SIMPLEPIE_CACHE_DIR)) {
654 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
655 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
656 }
657
658 $rss->init();
659 }
660
661 // print_r($rss);
662
663 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
664 _debug("update_rss_feed: fetch done, parsing...");
665 } else {
666 error_reporting (DEFAULT_ERROR_LEVEL);
667 }
668
669 $feed = db_escape_string($feed);
670
671 if ($use_simplepie) {
672 $fetch_ok = !$rss->error();
673 } else {
674 $fetch_ok = !!$rss;
675 }
676
677 if ($fetch_ok) {
678
679 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
680 _debug("update_rss_feed: processing feed data...");
681 }
682
683 // db_query($link, "BEGIN");
684
685 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
686 FROM ttrss_feeds WHERE id = '$feed'");
687
688 $registered_title = db_fetch_result($result, 0, "title");
689 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
690 $orig_site_url = db_fetch_result($result, 0, "site_url");
691
692 $owner_uid = db_fetch_result($result, 0, "owner_uid");
693
694 if ($use_simplepie) {
695 $site_url = $rss->get_link();
696 } else {
697 $site_url = $rss->channel["link"];
698 }
699
700 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
701 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
702 _debug("update_rss_feed: checking favicon...");
703 }
704
705 check_feed_favicon($site_url, $feed, $link);
706 }
707
708 if (!$registered_title || $registered_title == "[Unknown]") {
709
710 if ($use_simplepie) {
711 $feed_title = db_escape_string($rss->get_title());
712 } else {
713 $feed_title = db_escape_string($rss->channel["title"]);
714 }
715
716 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
717 _debug("update_rss_feed: registering title: $feed_title");
718 }
719
720 db_query($link, "UPDATE ttrss_feeds SET
721 title = '$feed_title' WHERE id = '$feed'");
722 }
723
724 // weird, weird Magpie
725 if (!$use_simplepie) {
726 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
727 }
728
729 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
730 db_query($link, "UPDATE ttrss_feeds SET
731 site_url = '$site_url' WHERE id = '$feed'");
732 }
733
734 // print "I: " . $rss->channel["image"]["url"];
735
736 if (!$use_simplepie) {
737 $icon_url = $rss->image["url"];
738 } else {
739 $icon_url = $rss->get_image_url();
740 }
741
742 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
743 $icon_url = db_escape_string($icon_url);
744 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
745 }
746
747 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
748 _debug("update_rss_feed: loading filters...");
749 }
750
751 $filters = load_filters($link, $feed, $owner_uid);
752
753 if ($use_simplepie) {
754 $iterator = $rss->get_items();
755 } else {
756 $iterator = $rss->items;
757 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
758 if (!$iterator || !is_array($iterator)) $iterator = $rss;
759 }
760
761 if (!is_array($iterator)) {
762 /* db_query($link, "UPDATE ttrss_feeds
763 SET last_error = 'Parse error: can\'t find any articles.'
764 WHERE id = '$feed'"); */
765
766 // clear any errors and mark feed as updated if fetched okay
767 // even if it's blank
768
769 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
770 _debug("update_rss_feed: entry iterator is not an array, no articles?");
771 }
772
773 db_query($link, "UPDATE ttrss_feeds
774 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
775
776 return; // no articles
777 }
778
779 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
780 _debug("update_rss_feed: processing articles...");
781 }
782
783 foreach ($iterator as $item) {
784
785 if ($_GET['xdebug']) {
786 print_r($item);
787
788 }
789
790 if ($use_simplepie) {
791 $entry_guid = $item->get_id();
792 if (!$entry_guid) $entry_guid = $item->get_link();
793 if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
794
795 } else {
796
797 $entry_guid = $item["id"];
798
799 if (!$entry_guid) $entry_guid = $item["guid"];
800 if (!$entry_guid) $entry_guid = $item["link"];
801 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
802 }
803
804 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
805 _debug("update_rss_feed: guid $entry_guid");
806 }
807
808 if (!$entry_guid) continue;
809
810 $entry_timestamp = "";
811
812 if ($use_simplepie) {
813 $entry_timestamp = strtotime($item->get_date());
814 } else {
815 $rss_2_date = $item['pubdate'];
816 $rss_1_date = $item['dc']['date'];
817 $atom_date = $item['issued'];
818 if (!$atom_date) $atom_date = $item['updated'];
819
820 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
821 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
822 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
823 }
824
825 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
826 $entry_timestamp = time();
827 $no_orig_date = 'true';
828 } else {
829 $no_orig_date = 'false';
830 }
831
832 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
833
834 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
835 _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
836 }
837
838 if ($use_simplepie) {
839 $entry_title = $item->get_title();
840 } else {
841 $entry_title = trim(strip_tags($item["title"]));
842 }
843
844 if ($use_simplepie) {
845 $entry_link = $item->get_link();
846 } else {
847 // strange Magpie workaround
848 $entry_link = $item["link_"];
849 if (!$entry_link) $entry_link = $item["link"];
850 }
851
852 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
853 _debug("update_rss_feed: title $entry_title");
854 }
855
856 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
857
858 $entry_link = strip_tags($entry_link);
859
860 if ($use_simplepie) {
861 $entry_content = $item->get_content();
862 if (!$entry_content) $entry_content = $item->get_description();
863 } else {
864 $entry_content = $item["content:escaped"];
865
866 if (!$entry_content) $entry_content = $item["content:encoded"];
867 if (!$entry_content) $entry_content = $item["content"]["encoded"];
868 if (!$entry_content) $entry_content = $item["content"];
869
870 // Magpie bugs are getting ridiculous
871 if (trim($entry_content) == "Array") $entry_content = false;
872
873 if (!$entry_content) $entry_content = $item["atom_content"];
874 if (!$entry_content) $entry_content = $item["summary"];
875
876 if (!$entry_content ||
877 strlen($entry_content) < strlen($item["description"])) {
878 $entry_content = $item["description"];
879 };
880
881 // WTF
882 if (is_array($entry_content)) {
883 $entry_content = $entry_content["encoded"];
884 if (!$entry_content) $entry_content = $entry_content["escaped"];
885 }
886 }
887
888 if ($_GET["xdebug"]) {
889 print "update_rss_feed: content: ";
890 print_r(htmlspecialchars($entry_content));
891 }
892
893 $entry_content_unescaped = $entry_content;
894
895 if ($use_simplepie) {
896 $entry_comments = strip_tags($item->data["comments"]);
897 if ($item->get_author()) {
898 $entry_author_item = $item->get_author();
899 $entry_author = $entry_author_item->get_name();
900 if (!$entry_author) $entry_author = $entry_author_item->get_email();
901
902 $entry_author = db_escape_string($entry_author);
903 }
904 } else {
905 $entry_comments = strip_tags($item["comments"]);
906
907 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
908
909 if ($item['author']) {
910
911 if (is_array($item['author'])) {
912
913 if (!$entry_author) {
914 $entry_author = db_escape_string(strip_tags($item['author']['name']));
915 }
916
917 if (!$entry_author) {
918 $entry_author = db_escape_string(strip_tags($item['author']['email']));
919 }
920 }
921
922 if (!$entry_author) {
923 $entry_author = db_escape_string(strip_tags($item['author']));
924 }
925 }
926 }
927
928 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
929
930 $entry_guid = db_escape_string(strip_tags($entry_guid));
931 $entry_guid = mb_substr($entry_guid, 0, 250);
932
933 $result = db_query($link, "SELECT id FROM ttrss_entries
934 WHERE guid = '$entry_guid'");
935
936 $entry_content = db_escape_string($entry_content);
937
938 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
939
940 $entry_title = db_escape_string($entry_title);
941 $entry_link = db_escape_string($entry_link);
942 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
943 $entry_author = mb_substr($entry_author, 0, 250);
944
945 if ($use_simplepie) {
946 $num_comments = 0; #FIXME#
947 } else {
948 $num_comments = db_escape_string($item["slash"]["comments"]);
949 }
950
951 if (!$num_comments) $num_comments = 0;
952
953 // parse <category> entries into tags
954
955 if ($use_simplepie) {
956
957 $additional_tags = array();
958 $additional_tags_src = $item->get_categories();
959
960 if (is_array($additional_tags_src)) {
961 foreach ($additional_tags_src as $tobj) {
962 array_push($additional_tags, $tobj->get_term());
963 }
964 }
965
966 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
967 _debug("update_rss_feed: category tags:");
968 print_r($additional_tags);
969 }
970
971 } else {
972
973 $t_ctr = $item['category#'];
974
975 $additional_tags = false;
976
977 if ($t_ctr == 0) {
978 $additional_tags = false;
979 } else if ($t_ctr > 0) {
980 $additional_tags = array($item['category']);
981
982 if ($item['category@term']) {
983 array_push($additional_tags, $item['category@term']);
984 }
985
986 for ($i = 0; $i <= $t_ctr; $i++ ) {
987 if ($item["category#$i"]) {
988 array_push($additional_tags, $item["category#$i"]);
989 }
990
991 if ($item["category#$i@term"]) {
992 array_push($additional_tags, $item["category#$i@term"]);
993 }
994 }
995 }
996
997 // parse <dc:subject> elements
998
999 $t_ctr = $item['dc']['subject#'];
1000
1001 if ($t_ctr > 0) {
1002 $additional_tags = array($item['dc']['subject']);
1003
1004 for ($i = 0; $i <= $t_ctr; $i++ ) {
1005 if ($item['dc']["subject#$i"]) {
1006 array_push($additional_tags, $item['dc']["subject#$i"]);
1007 }
1008 }
1009 }
1010 }
1011
1012 // enclosures
1013
1014 $enclosures = array();
1015
1016 if ($use_simplepie) {
1017 $encs = $item->get_enclosures();
1018
1019 if (is_array($encs)) {
1020 foreach ($encs as $e) {
1021 $e_item = array(
1022 $e->link, $e->type, $e->length);
1023
1024 array_push($enclosures, $e_item);
1025 }
1026 }
1027
1028 } else {
1029 // <enclosure>
1030
1031 $e_ctr = $item['enclosure#'];
1032
1033 if ($e_ctr > 0) {
1034 $e_item = array($item['enclosure@url'],
1035 $item['enclosure@type'],
1036 $item['enclosure@length']);
1037
1038 array_push($enclosures, $e_item);
1039
1040 for ($i = 0; $i <= $e_ctr; $i++ ) {
1041
1042 if ($item["enclosure#$i@url"]) {
1043 $e_item = array($item["enclosure#$i@url"],
1044 $item["enclosure#$i@type"],
1045 $item["enclosure#$i@length"]);
1046 array_push($enclosures, $e_item);
1047 }
1048 }
1049 }
1050
1051 // <media:content>
1052 // can there be many of those? yes -fox
1053
1054 $m_ctr = $item['media']['content#'];
1055
1056 if ($m_ctr > 0) {
1057 $e_item = array($item['media']['content@url'],
1058 $item['media']['content@medium'],
1059 $item['media']['content@length']);
1060
1061 array_push($enclosures, $e_item);
1062
1063 for ($i = 0; $i <= $m_ctr; $i++ ) {
1064
1065 if ($item["media"]["content#$i@url"]) {
1066 $e_item = array($item["media"]["content#$i@url"],
1067 $item["media"]["content#$i@medium"],
1068 $item["media"]["content#$i@length"]);
1069 array_push($enclosures, $e_item);
1070 }
1071 }
1072
1073 }
1074 }
1075
1076 # sanitize content
1077
1078 $entry_content = sanitize_article_content($entry_content);
1079 $entry_title = sanitize_article_content($entry_title);
1080
1081 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1082 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1083 }
1084
1085 db_query($link, "BEGIN");
1086
1087 if (db_num_rows($result) == 0) {
1088
1089 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1090 _debug("update_rss_feed: base guid not found");
1091 }
1092
1093 // base post entry does not exist, create it
1094
1095 $result = db_query($link,
1096 "INSERT INTO ttrss_entries
1097 (title,
1098 guid,
1099 link,
1100 updated,
1101 content,
1102 content_hash,
1103 no_orig_date,
1104 date_entered,
1105 comments,
1106 num_comments,
1107 author)
1108 VALUES
1109 ('$entry_title',
1110 '$entry_guid',
1111 '$entry_link',
1112 '$entry_timestamp_fmt',
1113 '$entry_content',
1114 '$content_hash',
1115 $no_orig_date,
1116 NOW(),
1117 '$entry_comments',
1118 '$num_comments',
1119 '$entry_author')");
1120 } else {
1121 // we keep encountering the entry in feeds, so we need to
1122 // update date_entered column so that we don't get horrible
1123 // dupes when the entry gets purged and reinserted again e.g.
1124 // in the case of SLOW SLOW OMG SLOW updating feeds
1125
1126 $base_entry_id = db_fetch_result($result, 0, "id");
1127
1128 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1129 WHERE id = '$base_entry_id'");
1130 }
1131
1132 // now it should exist, if not - bad luck then
1133
1134 $result = db_query($link, "SELECT
1135 id,content_hash,no_orig_date,title,
1136 ".SUBSTRING_FOR_DATE."(date_entered,1,19) as date_entered,
1137 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
1138 num_comments
1139 FROM
1140 ttrss_entries
1141 WHERE guid = '$entry_guid'");
1142
1143 $entry_ref_id = 0;
1144 $entry_int_id = 0;
1145
1146 if (db_num_rows($result) == 1) {
1147
1148 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1149 _debug("update_rss_feed: base guid found, checking for user record");
1150 }
1151
1152 // this will be used below in update handler
1153 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1154 $orig_title = db_fetch_result($result, 0, "title");
1155 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1156 $orig_date_entered = strtotime(db_fetch_result($result,
1157 0, "date_entered"));
1158
1159 $ref_id = db_fetch_result($result, 0, "id");
1160 $entry_ref_id = $ref_id;
1161
1162 // check for user post link to main table
1163
1164 // do we allow duplicate posts with same GUID in different feeds?
1165 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1166 $dupcheck_qpart = "AND feed_id = '$feed'";
1167 } else {
1168 $dupcheck_qpart = "";
1169 }
1170
1171 // error_reporting(0);
1172
1173 $article_filters = get_article_filters($filters, $entry_title,
1174 $entry_content, $entry_link, $entry_timestamp);
1175
1176 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1177 _debug("update_rss_feed: article filters: ");
1178 if (count($article_filters) != 0) {
1179 print_r($article_filters);
1180 }
1181 }
1182
1183 if (find_article_filter($article_filters, "filter")) {
1184 db_query($link, "COMMIT"); // close transaction in progress
1185 continue;
1186 }
1187
1188 // error_reporting (DEFAULT_ERROR_LEVEL);
1189
1190 $score = calculate_article_score($article_filters);
1191
1192 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1193 _debug("update_rss_feed: initial score: $score");
1194 }
1195
1196 $result = db_query($link,
1197 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1198 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1199 $dupcheck_qpart");
1200
1201 // okay it doesn't exist - create user entry
1202 if (db_num_rows($result) == 0) {
1203
1204 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1205 _debug("update_rss_feed: user record not found, creating...");
1206 }
1207
1208 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1209 $unread = 'true';
1210 $last_read_qpart = 'NULL';
1211 } else {
1212 $unread = 'false';
1213 $last_read_qpart = 'NOW()';
1214 }
1215
1216 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
1217 $marked = 'true';
1218 } else {
1219 $marked = 'false';
1220 }
1221
1222 if (find_article_filter($article_filters, 'publish')) {
1223 $published = 'true';
1224 } else {
1225 $published = 'false';
1226 }
1227
1228 $result = db_query($link,
1229 "INSERT INTO ttrss_user_entries
1230 (ref_id, owner_uid, feed_id, unread, last_read, marked,
1231 published, score)
1232 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1233 $last_read_qpart, $marked, $published, '$score')");
1234
1235 $result = db_query($link,
1236 "SELECT int_id FROM ttrss_user_entries WHERE
1237 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1238 feed_id = '$feed' LIMIT 1");
1239
1240 if (db_num_rows($result) == 1) {
1241 $entry_int_id = db_fetch_result($result, 0, "int_id");
1242 }
1243 } else {
1244 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1245 $entry_int_id = db_fetch_result($result, 0, "int_id");
1246 }
1247
1248 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1249 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1250 }
1251
1252 $post_needs_update = false;
1253
1254 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1255 ($content_hash != $orig_content_hash)) {
1256 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1257 $post_needs_update = true;
1258 }
1259
1260 if (db_escape_string($orig_title) != $entry_title) {
1261 $post_needs_update = true;
1262 }
1263
1264 if ($orig_num_comments != $num_comments) {
1265 $post_needs_update = true;
1266 }
1267
1268 // this doesn't seem to be very reliable
1269 //
1270 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1271 // $post_needs_update = true;
1272 // }
1273
1274 // if post needs update, update it and mark all user entries
1275 // linking to this post as updated
1276 if ($post_needs_update) {
1277
1278 if (defined('DAEMON_EXTENDED_DEBUG')) {
1279 _debug("update_rss_feed: post $entry_guid needs update...");
1280 }
1281
1282 // print "<!-- post $orig_title needs update : $post_needs_update -->";
1283
1284 db_query($link, "UPDATE ttrss_entries
1285 SET title = '$entry_title', content = '$entry_content',
1286 content_hash = '$content_hash',
1287 num_comments = '$num_comments'
1288 WHERE id = '$ref_id'");
1289
1290 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1291 db_query($link, "UPDATE ttrss_user_entries
1292 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1293 } else {
1294 db_query($link, "UPDATE ttrss_user_entries
1295 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1296 }
1297
1298 }
1299 }
1300
1301 db_query($link, "COMMIT");
1302
1303 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1304 _debug("update_rss_feed: looking for enclosures...");
1305 }
1306
1307 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1308 print_r($enclosures);
1309 }
1310
1311 db_query($link, "BEGIN");
1312
1313 foreach ($enclosures as $enc) {
1314 $enc_url = db_escape_string($enc[0]);
1315 $enc_type = db_escape_string($enc[1]);
1316 $enc_dur = db_escape_string($enc[2]);
1317
1318 $result = db_query($link, "SELECT id FROM ttrss_enclosures
1319 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1320
1321 if (db_num_rows($result) == 0) {
1322 db_query($link, "INSERT INTO ttrss_enclosures
1323 (content_url, content_type, title, duration, post_id) VALUES
1324 ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1325 }
1326 }
1327
1328 db_query($link, "COMMIT");
1329
1330 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1331 _debug("update_rss_feed: looking for tags...");
1332 }
1333
1334 /* taaaags */
1335 // <a href="..." rel="tag">Xorg</a>, //
1336
1337 $entry_tags = null;
1338
1339 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
1340 $entry_content_unescaped, $entry_tags);
1341
1342 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1343 print_r($entry_tags);
1344 print "<br/></p>"; */
1345
1346 $entry_tags = $entry_tags[1];
1347
1348 # check for manual tags
1349
1350 $tag_filter = find_article_filter($article_filters, "tag");
1351
1352 if ($tag_filter) {
1353
1354 $manual_tags = trim_array(split(",", $tag_filter[1]));
1355
1356 foreach ($manual_tags as $tag) {
1357 if (tag_is_valid($tag)) {
1358 array_push($entry_tags, $tag);
1359 }
1360 }
1361 }
1362
1363 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
1364 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1365
1366 if ($additional_tags && is_array($additional_tags)) {
1367 foreach ($additional_tags as $tag) {
1368 if (tag_is_valid($tag) &&
1369 array_search($tag, $boring_tags) === FALSE) {
1370 array_push($entry_tags, $tag);
1371 }
1372 }
1373 }
1374
1375 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1376
1377 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1378 print_r($entry_tags);
1379 }
1380
1381 if (count($entry_tags) > 0) {
1382
1383 db_query($link, "BEGIN");
1384
1385 foreach ($entry_tags as $tag) {
1386
1387 $tag = sanitize_tag($tag);
1388 $tag = db_escape_string($tag);
1389
1390 if (!tag_is_valid($tag)) continue;
1391
1392 $result = db_query($link, "SELECT id FROM ttrss_tags
1393 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
1394 owner_uid = '$owner_uid' LIMIT 1");
1395
1396 // print db_fetch_result($result, 0, "id");
1397
1398 if ($result && db_num_rows($result) == 0) {
1399
1400 db_query($link, "INSERT INTO ttrss_tags
1401 (owner_uid,tag_name,post_int_id)
1402 VALUES ('$owner_uid','$tag', '$entry_int_id')");
1403 }
1404 }
1405
1406 db_query($link, "COMMIT");
1407 }
1408
1409 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1410 _debug("update_rss_feed: article processed");
1411 }
1412 }
1413
1414 if (!$hidden) {
1415 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1416 _debug("update_rss_feed: updating counters cache...");
1417 }
1418
1419 ccache_update($link, $feed, $owner_uid);
1420 }
1421
1422 db_query($link, "UPDATE ttrss_feeds
1423 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1424
1425 // db_query($link, "COMMIT");
1426
1427 } else {
1428
1429 if ($use_simplepie) {
1430 $error_msg = mb_substr($rss->error(), 0, 250);
1431 } else {
1432 $error_msg = mb_substr(magpie_error(), 0, 250);
1433 }
1434
1435 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1436 _debug("update_rss_feed: error fetching feed: $error_msg");
1437 }
1438
1439 $error_msg = db_escape_string($error_msg);
1440
1441 db_query($link,
1442 "UPDATE ttrss_feeds SET last_error = '$error_msg',
1443 last_updated = NOW() WHERE id = '$feed'");
1444 }
1445
1446 if ($use_simplepie) {
1447 unset($rss);
1448 }
1449
1450 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1451 _debug("update_rss_feed: done");
1452 }
1453
1454 }
1455
1456 function print_select($id, $default, $values, $attributes = "") {
1457 print "<select name=\"$id\" id=\"$id\" $attributes>";
1458 foreach ($values as $v) {
1459 if ($v == $default)
1460 $sel = " selected";
1461 else
1462 $sel = "";
1463
1464 print "<option$sel>$v</option>";
1465 }
1466 print "</select>";
1467 }
1468
1469 function print_select_hash($id, $default, $values, $attributes = "") {
1470 print "<select name=\"$id\" id='$id' $attributes>";
1471 foreach (array_keys($values) as $v) {
1472 if ($v == $default)
1473 $sel = 'selected="selected"';
1474 else
1475 $sel = "";
1476
1477 print "<option $sel value=\"$v\">".$values[$v]."</option>";
1478 }
1479
1480 print "</select>";
1481 }
1482
1483 function get_article_filters($filters, $title, $content, $link, $timestamp) {
1484 $matches = array();
1485
1486 if ($filters["title"]) {
1487 foreach ($filters["title"] as $filter) {
1488 $reg_exp = $filter["reg_exp"];
1489 $inverse = $filter["inverse"];
1490 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1491 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1492
1493 array_push($matches, array($filter["action"], $filter["action_param"]));
1494 }
1495 }
1496 }
1497
1498 if ($filters["content"]) {
1499 foreach ($filters["content"] as $filter) {
1500 $reg_exp = $filter["reg_exp"];
1501 $inverse = $filter["inverse"];
1502
1503 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1504 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1505
1506 array_push($matches, array($filter["action"], $filter["action_param"]));
1507 }
1508 }
1509 }
1510
1511 if ($filters["both"]) {
1512 foreach ($filters["both"] as $filter) {
1513 $reg_exp = $filter["reg_exp"];
1514 $inverse = $filter["inverse"];
1515
1516 if ($inverse) {
1517 if (!preg_match("/$reg_exp/i", $title) || !preg_match("/$reg_exp/i", $content)) {
1518 array_push($matches, array($filter["action"], $filter["action_param"]));
1519 }
1520 } else {
1521 if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1522 array_push($matches, array($filter["action"], $filter["action_param"]));
1523 }
1524 }
1525 }
1526 }
1527
1528 if ($filters["link"]) {
1529 $reg_exp = $filter["reg_exp"];
1530 foreach ($filters["link"] as $filter) {
1531 $reg_exp = $filter["reg_exp"];
1532 $inverse = $filter["inverse"];
1533
1534 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1535 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1536
1537 array_push($matches, array($filter["action"], $filter["action_param"]));
1538 }
1539 }
1540 }
1541
1542 if ($filters["date"]) {
1543 $reg_exp = $filter["reg_exp"];
1544 foreach ($filters["date"] as $filter) {
1545 $date_modifier = $filter["filter_param"];
1546 $inverse = $filter["inverse"];
1547 $check_timestamp = strtotime($filter["reg_exp"]);
1548
1549 # no-op when timestamp doesn't parse to prevent misfires
1550
1551 if ($check_timestamp) {
1552 $match_ok = false;
1553
1554 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1555 $date_modifier == "after" && $timestamp > $check_timestamp) {
1556 $match_ok = true;
1557 }
1558
1559 if ($inverse) $match_ok = !$match_ok;
1560
1561 if ($match_ok) {
1562 array_push($matches, array($filter["action"], $filter["action_param"]));
1563 }
1564 }
1565 }
1566 }
1567
1568 return $matches;
1569 }
1570
1571 function find_article_filter($filters, $filter_name) {
1572 foreach ($filters as $f) {
1573 if ($f[0] == $filter_name) {
1574 return $f;
1575 };
1576 }
1577 return false;
1578 }
1579
1580 function calculate_article_score($filters) {
1581 $score = 0;
1582
1583 foreach ($filters as $f) {
1584 if ($f[0] == "score") {
1585 $score += $f[1];
1586 };
1587 }
1588 return $score;
1589 }
1590
1591
1592 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1593 $rtl_content = false, $last_updated = false, $last_error = false) {
1594
1595 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1596 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1597 } else {
1598 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1599 }
1600
1601 if ($rtl_content) {
1602 $rtl_tag = "dir=\"rtl\"";
1603 } else {
1604 $rtl_tag = "dir=\"ltr\"";
1605 }
1606
1607 $error_notify_msg = "";
1608
1609 if ($last_error) {
1610 $link_title = "Error: $last_error ($last_updated)";
1611 $error_notify_msg = "(Error)";
1612 } else if ($last_updated) {
1613 $link_title = "Updated: $last_updated";
1614 }
1615
1616 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1617 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1618
1619 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1620 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1621 print "$feed_icon";
1622 }
1623
1624 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1625
1626 if ($unread != 0) {
1627 $fctr_class = "class=\"feedCtrHasUnread\"";
1628 } else {
1629 $fctr_class = "class=\"feedCtrNoUnread\"";
1630 }
1631
1632 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1633 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1634
1635 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1636 $total = getFeedArticles($link, $feed_id);
1637 print "<div class=\"feedExtInfo\">
1638 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1639 }
1640
1641 print "</li>";
1642
1643 }
1644
1645 function getmicrotime() {
1646 list($usec, $sec) = explode(" ",microtime());
1647 return ((float)$usec + (float)$sec);
1648 }
1649
1650 function print_radio($id, $default, $true_is, $values, $attributes = "") {
1651 foreach ($values as $v) {
1652
1653 if ($v == $default)
1654 $sel = "checked";
1655 else
1656 $sel = "";
1657
1658 if ($v == $true_is) {
1659 $sel .= " value=\"1\"";
1660 } else {
1661 $sel .= " value=\"0\"";
1662 }
1663
1664 print "<input class=\"noborder\"
1665 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1666
1667 }
1668 }
1669
1670 function initialize_user_prefs($link, $uid) {
1671
1672 $uid = db_escape_string($uid);
1673
1674 db_query($link, "BEGIN");
1675
1676 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1677
1678 $u_result = db_query($link, "SELECT pref_name
1679 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1680
1681 $active_prefs = array();
1682
1683 while ($line = db_fetch_assoc($u_result)) {
1684 array_push($active_prefs, $line["pref_name"]);
1685 }
1686
1687 while ($line = db_fetch_assoc($result)) {
1688 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1689 // print "adding " . $line["pref_name"] . "<br>";
1690
1691 db_query($link, "INSERT INTO ttrss_user_prefs
1692 (owner_uid,pref_name,value) VALUES
1693 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1694
1695 }
1696 }
1697
1698 db_query($link, "COMMIT");
1699
1700 }
1701
1702 function lookup_user_id($link, $user) {
1703
1704 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1705 login = '$login'");
1706
1707 if (db_num_rows($result) == 1) {
1708 return db_fetch_result($result, 0, "id");
1709 } else {
1710 return false;
1711 }
1712 }
1713
1714 function http_authenticate_user($link) {
1715
1716 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1717
1718 if (!$_SERVER["PHP_AUTH_USER"]) {
1719
1720 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1721 header('HTTP/1.0 401 Unauthorized');
1722 exit;
1723
1724 } else {
1725 $auth_result = authenticate_user($link,
1726 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1727
1728 if (!$auth_result) {
1729 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1730 header('HTTP/1.0 401 Unauthorized');
1731 exit;
1732 }
1733 }
1734
1735 return true;
1736 }
1737
1738 function authenticate_user($link, $login, $password, $force_auth = false) {
1739
1740 if (!SINGLE_USER_MODE) {
1741
1742 $pwd_hash1 = encrypt_password($password);
1743 $pwd_hash2 = encrypt_password($password, $login);
1744
1745 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
1746 && $_SERVER["REMOTE_USER"] && $login != "admin") {
1747
1748 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1749
1750 $query = "SELECT id,login,access_level,pwd_hash
1751 FROM ttrss_users WHERE
1752 login = '$login'";
1753
1754 } else {
1755 $query = "SELECT id,login,access_level,pwd_hash
1756 FROM ttrss_users WHERE
1757 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1758 pwd_hash = '$pwd_hash2')";
1759 }
1760
1761 $result = db_query($link, $query);
1762
1763 if (db_num_rows($result) == 1) {
1764 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1765 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1766 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1767
1768 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1769 $_SESSION["uid"]);
1770
1771 $user_theme = get_user_theme_path($link);
1772
1773 $_SESSION["theme"] = $user_theme;
1774 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1775 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1776
1777 initialize_user_prefs($link, $_SESSION["uid"]);
1778
1779 return true;
1780 }
1781
1782 return false;
1783
1784 } else {
1785
1786 $_SESSION["uid"] = 1;
1787 $_SESSION["name"] = "admin";
1788
1789 $user_theme = get_user_theme_path($link);
1790
1791 $_SESSION["theme"] = $user_theme;
1792 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1793
1794 initialize_user_prefs($link, $_SESSION["uid"]);
1795
1796 return true;
1797 }
1798 }
1799
1800 function make_password($length = 8) {
1801
1802 $password = "";
1803 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1804
1805 $i = 0;
1806
1807 while ($i < $length) {
1808 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1809
1810 if (!strstr($password, $char)) {
1811 $password .= $char;
1812 $i++;
1813 }
1814 }
1815 return $password;
1816 }
1817
1818 // this is called after user is created to initialize default feeds, labels
1819 // or whatever else
1820
1821 // user preferences are checked on every login, not here
1822
1823 function initialize_user($link, $uid) {
1824
1825 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1826 values ('$uid','unread = true', 'Unread articles')");
1827
1828 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1829 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1830
1831 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1832 values ('$uid', 'Tiny Tiny RSS: New Releases',
1833 'http://tt-rss.org/releases.rss')");
1834
1835 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1836 values ('$uid', 'Tiny Tiny RSS: Forum',
1837 'http://tt-rss.org/forum/rss.php')");
1838 }
1839
1840 function logout_user() {
1841 session_destroy();
1842 if (isset($_COOKIE[session_name()])) {
1843 setcookie(session_name(), '', time()-42000, '/');
1844 }
1845 }
1846
1847 function get_script_urlpath() {
1848 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1849 }
1850
1851 function validate_session($link) {
1852 if (SINGLE_USER_MODE) {
1853 return true;
1854 }
1855
1856 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1857 if ($_SESSION["ip_address"]) {
1858 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1859 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1860 return false;
1861 }
1862 }
1863 }
1864
1865 if ($_SESSION["uid"]) {
1866
1867 $result = db_query($link,
1868 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1869
1870 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1871
1872 if ($pwd_hash != $_SESSION["pwd_hash"]) {
1873 return false;
1874 }
1875 }
1876
1877 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1878
1879 //print_r($_SESSION);
1880
1881 if (time() > $_SESSION["cookie_lifetime"]) {
1882 return false;
1883 }
1884 } */
1885
1886 return true;
1887 }
1888
1889 function login_sequence($link, $mobile = false) {
1890 if (!SINGLE_USER_MODE) {
1891
1892 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1893 $swu = db_escape_string($_REQUEST["swu"]);
1894 if ($swu) {
1895 $_SESSION["prefs_cache"] = false;
1896 return authenticate_user($link, $swu, null, true);
1897 }
1898 }
1899
1900 $login_action = $_POST["login_action"];
1901
1902 # try to authenticate user if called from login form
1903 if ($login_action == "do_login") {
1904 $login = $_POST["login"];
1905 $password = $_POST["password"];
1906 $remember_me = $_POST["remember_me"];
1907
1908 if (authenticate_user($link, $login, $password)) {
1909 $_POST["password"] = "";
1910
1911 $_SESSION["language"] = $_POST["language"];
1912 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1913
1914 header("Location: " . $_SERVER["REQUEST_URI"]);
1915 exit;
1916
1917 return;
1918 } else {
1919 $_SESSION["login_error_msg"] = "Incorrect username or password";
1920 }
1921 }
1922
1923 // print session_id();
1924 // print_r($_SESSION);
1925
1926 if (!$_SESSION["uid"] || !validate_session($link)) {
1927 render_login_form($link, $mobile);
1928 exit;
1929 } else {
1930 /* bump login timestamp */
1931 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1932 $_SESSION["uid"]);
1933
1934 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
1935 setcookie("ttrss_lang", $_SESSION["language"],
1936 time() + SESSION_COOKIE_LIFETIME);
1937 }
1938
1939 /* bump counters stamp since we're getting reloaded anyway */
1940
1941 $_SESSION["get_all_counters_stamp"] = time();
1942 }
1943
1944 } else {
1945 return authenticate_user($link, "admin", null);
1946 }
1947 }
1948
1949 function truncate_string($str, $max_len) {
1950 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1951 return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
1952 } else {
1953 return $str;
1954 }
1955 }
1956
1957 function get_user_theme_path($link) {
1958 $result = db_query($link, "SELECT theme_path
1959 FROM
1960 ttrss_themes,ttrss_users
1961 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1962 if (db_num_rows($result) != 0) {
1963 return db_fetch_result($result, 0, "theme_path");
1964 } else {
1965 return null;
1966 }
1967 }
1968
1969 function smart_date_time($timestamp) {
1970 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1971 return date("G:i", $timestamp);
1972 } else if (date("Y", $timestamp) == date("Y")) {
1973 return date("M d, G:i", $timestamp);
1974 } else {
1975 return date("Y/m/d, G:i", $timestamp);
1976 }
1977 }
1978
1979 function smart_date($timestamp) {
1980 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1981 return "Today";
1982 } else if (date("Y", $timestamp) == date("Y")) {
1983 return date("D m", $timestamp);
1984 } else {
1985 return date("Y/m/d", $timestamp);
1986 }
1987 }
1988
1989 function sql_bool_to_string($s) {
1990 if ($s == "t" || $s == "1") {
1991 return "true";
1992 } else {
1993 return "false";
1994 }
1995 }
1996
1997 function sql_bool_to_bool($s) {
1998 if ($s == "t" || $s == "1") {
1999 return true;
2000 } else {
2001 return false;
2002 }
2003 }
2004
2005
2006 function toggleEvenOdd($a) {
2007 if ($a == "even")
2008 return "odd";
2009 else
2010 return "even";
2011 }
2012
2013 function sanity_check($link) {
2014
2015 error_reporting(0);
2016
2017 $error_code = 0;
2018 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2019 $schema_version = db_fetch_result($result, 0, "schema_version");
2020
2021 if ($schema_version != SCHEMA_VERSION) {
2022 $error_code = 5;
2023 }
2024
2025 if (DB_TYPE == "mysql") {
2026 $result = db_query($link, "SELECT true", false);
2027 if (db_num_rows($result) != 1) {
2028 $error_code = 10;
2029 }
2030 }
2031
2032 if (db_escape_string("testTEST") != "testTEST") {
2033 $error_code = 12;
2034 }
2035
2036 error_reporting (DEFAULT_ERROR_LEVEL);
2037
2038 if ($error_code != 0) {
2039 print_error_xml($error_code);
2040 return false;
2041 } else {
2042 return true;
2043 }
2044 }
2045
2046 function file_is_locked($filename) {
2047 if (function_exists('flock')) {
2048 error_reporting(0);
2049 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2050 error_reporting(DEFAULT_ERROR_LEVEL);
2051 if ($fp) {
2052 if (flock($fp, LOCK_EX | LOCK_NB)) {
2053 flock($fp, LOCK_UN);
2054 fclose($fp);
2055 return false;
2056 }
2057 fclose($fp);
2058 return true;
2059 } else {
2060 return false;
2061 }
2062 }
2063 return true; // consider the file always locked and skip the test
2064 }
2065
2066 function make_lockfile($filename) {
2067 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2068
2069 if (flock($fp, LOCK_EX | LOCK_NB)) {
2070 return $fp;
2071 } else {
2072 return false;
2073 }
2074 }
2075
2076 function make_stampfile($filename) {
2077 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2078
2079 if (flock($fp, LOCK_EX | LOCK_NB)) {
2080 fwrite($fp, time() . "\n");
2081 flock($fp, LOCK_UN);
2082 fclose($fp);
2083 return true;
2084 } else {
2085 return false;
2086 }
2087 }
2088
2089 function read_stampfile($filename) {
2090
2091 error_reporting(0);
2092 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2093 error_reporting (DEFAULT_ERROR_LEVEL);
2094
2095 if ($fp) {
2096 if (flock($fp, LOCK_EX)) {
2097 $stamp = fgets($fp);
2098 flock($fp, LOCK_UN);
2099 fclose($fp);
2100 return $stamp;
2101 } else {
2102 return false;
2103 }
2104 } else {
2105 return false;
2106 }
2107 }
2108
2109 function sql_random_function() {
2110 if (DB_TYPE == "mysql") {
2111 return "RAND()";
2112 } else {
2113 return "RANDOM()";
2114 }
2115 }
2116
2117 function catchup_feed($link, $feed, $cat_view) {
2118
2119 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2120
2121 if ($cat_view) {
2122
2123 if ($feed > 0) {
2124 $cat_qpart = "cat_id = '$feed'";
2125 } else {
2126 $cat_qpart = "cat_id IS NULL";
2127 }
2128
2129 $tmp_result = db_query($link, "SELECT id
2130 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2131 $_SESSION["uid"]);
2132
2133 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2134
2135 $tmp_feed = $tmp_line["id"];
2136
2137 db_query($link, "UPDATE ttrss_user_entries
2138 SET unread = false,last_read = NOW()
2139 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2140 }
2141
2142 } else if ($feed > 0) {
2143
2144 $tmp_result = db_query($link, "SELECT id
2145 FROM ttrss_feeds WHERE parent_feed = '$feed'
2146 ORDER BY cat_id,title");
2147
2148 $parent_ids = array();
2149
2150 if (db_num_rows($tmp_result) > 0) {
2151 while ($p = db_fetch_assoc($tmp_result)) {
2152 array_push($parent_ids, "feed_id = " . $p["id"]);
2153 }
2154
2155 $children_qpart = implode(" OR ", $parent_ids);
2156
2157 db_query($link, "UPDATE ttrss_user_entries
2158 SET unread = false,last_read = NOW()
2159 WHERE (feed_id = '$feed' OR $children_qpart)
2160 AND owner_uid = " . $_SESSION["uid"]);
2161
2162 } else {
2163 db_query($link, "UPDATE ttrss_user_entries
2164 SET unread = false,last_read = NOW()
2165 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2166 }
2167
2168 } else if ($feed < 0 && $feed > -10) { // special, like starred
2169
2170 if ($feed == -1) {
2171 db_query($link, "UPDATE ttrss_user_entries
2172 SET unread = false,last_read = NOW()
2173 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2174 }
2175
2176 if ($feed == -2) {
2177 db_query($link, "UPDATE ttrss_user_entries
2178 SET unread = false,last_read = NOW()
2179 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2180 }
2181
2182 if ($feed == -3) {
2183
2184 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2185
2186 if (DB_TYPE == "pgsql") {
2187 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2188 } else {
2189 $match_part = "updated > DATE_SUB(NOW(),
2190 INTERVAL $intl HOUR) ";
2191 }
2192
2193 $result = db_query($link, "SELECT id FROM ttrss_entries,
2194 ttrss_user_entries WHERE $match_part AND
2195 unread = true AND
2196 ttrss_user_entries.ref_id = ttrss_entries.id AND
2197 owner_uid = ".$_SESSION["uid"]);
2198
2199 $affected_ids = array();
2200
2201 while ($line = db_fetch_assoc($result)) {
2202 array_push($affected_ids, $line["id"]);
2203 }
2204
2205 catchupArticlesById($link, $affected_ids, 0);
2206 }
2207
2208 } else if ($feed < -10) { // label
2209
2210 // TODO make this more efficient
2211
2212 $label_id = -$feed - 11;
2213
2214 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2215 WHERE id = '$label_id'");
2216
2217 if ($tmp_result) {
2218 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2219
2220 db_query($link, "BEGIN");
2221
2222 $tmp2_result = db_query($link,
2223 "SELECT
2224 int_id
2225 FROM
2226 ttrss_user_entries,ttrss_entries,ttrss_feeds
2227 WHERE
2228 ref_id = ttrss_entries.id AND
2229 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2230 $sql_exp AND
2231 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2232
2233 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2234 db_query($link, "UPDATE
2235 ttrss_user_entries
2236 SET
2237 unread = false, last_read = NOW()
2238 WHERE
2239 int_id = " . $tmp_line["int_id"]);
2240 }
2241
2242 db_query($link, "COMMIT");
2243
2244 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
2245 SET unread = false,last_read = NOW()
2246 WHERE $sql_exp
2247 AND ref_id = id
2248 AND owner_uid = ".$_SESSION["uid"]); */
2249 }
2250 }
2251
2252 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2253
2254 } else { // tag
2255 db_query($link, "BEGIN");
2256
2257 $tag_name = db_escape_string($feed);
2258
2259 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2260 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2261
2262 while ($line = db_fetch_assoc($result)) {
2263 db_query($link, "UPDATE ttrss_user_entries SET
2264 unread = false, last_read = NOW()
2265 WHERE int_id = " . $line["post_int_id"]);
2266 }
2267 db_query($link, "COMMIT");
2268 }
2269 }
2270
2271 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2272 if ($cat_view) {
2273
2274 if ($feed > 0) {
2275 $cat_qpart = "cat_id = '$feed'";
2276 } else {
2277 $cat_qpart = "cat_id IS NULL";
2278 }
2279
2280 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2281 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2282
2283 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2284 $feed_url = $tmp_line["feed_url"];
2285 $feed_id = $tmp_line["id"];
2286 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2287 }
2288
2289 } else {
2290 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2291 WHERE id = '$feed'");
2292 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2293 update_rss_feed($link, $feed_url, $feed, $force_update);
2294 }
2295 }
2296
2297 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2298
2299 /* getting all counters is a resource intensive operation, so we
2300 * rate limit it a little bit */
2301
2302
2303
2304 // if (get_pref($link, "SYNC_COUNTERS") ||
2305 // time() - $_SESSION["get_all_counters_stamp"] > 5) {
2306
2307 if (!$omode) $omode = "flc";
2308
2309 getGlobalCounters($link);
2310
2311 if (strchr($omode, "l")) getLabelCounters($link);
2312 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS, $active_feed);
2313 if (strchr($omode, "t")) getTagCounters($link);
2314 if (strchr($omode, "c")) {
2315 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2316 getCategoryCounters($link);
2317 }
2318 }
2319
2320 $_SESSION["get_all_counters_stamp"] = time();
2321 // }
2322
2323 }
2324
2325 function getCategoryCounters($link) {
2326 # two special categories are -1 and -2 (all virtuals; all labels)
2327
2328 $ctr = getCategoryUnread($link, -1);
2329
2330 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2331
2332 $ctr = getCategoryUnread($link, -2);
2333
2334 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2335
2336 $age_qpart = getMaxAgeSubquery();
2337
2338 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2339 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2340 WHERE ttrss_cat_counters_cache.feed_id = id AND
2341 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2342
2343 while ($line = db_fetch_assoc($result)) {
2344 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2345
2346 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2347 $line["unread"]."\"/>";
2348 }
2349
2350 /* Special case: NULL category doesn't actually exist in the DB */
2351
2352 print "<counter type=\"category\" id=\"0\" counter=\"".
2353 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2354
2355 }
2356
2357 function getCategoryUnread($link, $cat, $owner_uid = false) {
2358
2359 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2360
2361 if ($cat >= 0) {
2362
2363 if ($cat != 0) {
2364 $cat_query = "cat_id = '$cat'";
2365 } else {
2366 $cat_query = "cat_id IS NULL";
2367 }
2368
2369 $age_qpart = getMaxAgeSubquery();
2370
2371 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2372 AND hidden = false
2373 AND owner_uid = " . $owner_uid);
2374
2375 $cat_feeds = array();
2376 while ($line = db_fetch_assoc($result)) {
2377 array_push($cat_feeds, "feed_id = " . $line["id"]);
2378 }
2379
2380 if (count($cat_feeds) == 0) return 0;
2381
2382 $match_part = implode(" OR ", $cat_feeds);
2383
2384 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2385 FROM ttrss_user_entries,ttrss_entries
2386 WHERE unread = true AND ($match_part) AND id = ref_id
2387 AND $age_qpart AND owner_uid = " . $owner_uid);
2388
2389 $unread = 0;
2390
2391 # this needs to be rewritten
2392 while ($line = db_fetch_assoc($result)) {
2393 $unread += $line["unread"];
2394 }
2395
2396 return $unread;
2397 } else if ($cat == -1) {
2398 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3);
2399 } else if ($cat == -2) {
2400
2401 $rv = getLabelCounters($link, false, true);
2402 $ctr = 0;
2403
2404 foreach (array_keys($rv) as $k) {
2405 if ($k < -10) {
2406 $ctr += $rv[$k]["counter"];
2407 }
2408 }
2409
2410 return $ctr;
2411 }
2412 }
2413
2414 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2415 if (DB_TYPE == "pgsql") {
2416 return "ttrss_entries.date_entered >
2417 NOW() - INTERVAL '$days days'";
2418 } else {
2419 return "ttrss_entries.date_entered >
2420 DATE_SUB(NOW(), INTERVAL $days DAY)";
2421 }
2422 }
2423
2424 function getFeedUnread($link, $feed, $is_cat = false) {
2425 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2426 }
2427
2428 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2429 $owner_uid = false) {
2430
2431 $n_feed = sprintf("%d", $feed);
2432
2433 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2434
2435 if ($unread_only) {
2436 $unread_qpart = "unread = true";
2437 } else {
2438 $unread_qpart = "true";
2439 }
2440
2441 $age_qpart = getMaxAgeSubquery();
2442
2443 if ($is_cat) {
2444 return getCategoryUnread($link, $n_feed, $owner_uid);
2445 } else if ($n_feed == -1) {
2446 $match_part = "marked = true";
2447 } else if ($n_feed == -2) {
2448 $match_part = "published = true";
2449 } else if ($n_feed == -3) {
2450 $match_part = "unread = true";
2451
2452 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2453
2454 if (DB_TYPE == "pgsql") {
2455 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2456 } else {
2457 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2458 }
2459
2460 } else if ($n_feed > 0) {
2461
2462 $result = db_query($link, "SELECT id FROM ttrss_feeds
2463 WHERE parent_feed = '$n_feed'
2464 AND hidden = false
2465 AND owner_uid = " . $owner_uid);
2466
2467 if (db_num_rows($result) > 0) {
2468
2469 $linked_feeds = array();
2470 while ($line = db_fetch_assoc($result)) {
2471 array_push($linked_feeds, "feed_id = " . $line["id"]);
2472 }
2473
2474 array_push($linked_feeds, "feed_id = $n_feed");
2475
2476 $match_part = implode(" OR ", $linked_feeds);
2477
2478 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2479 FROM ttrss_user_entries,ttrss_entries
2480 WHERE $unread_qpart AND
2481 ttrss_user_entries.ref_id = ttrss_entries.id AND
2482 $age_qpart AND
2483 ($match_part) AND
2484 owner_uid = " . $owner_uid);
2485
2486 $unread = 0;
2487
2488 # this needs to be rewritten
2489 while ($line = db_fetch_assoc($result)) {
2490 $unread += $line["unread"];
2491 }
2492
2493 return $unread;
2494
2495 } else {
2496 $match_part = "feed_id = '$n_feed'";
2497 }
2498 } else if ($feed < -10) {
2499
2500 $label_id = -$feed - 11;
2501
2502 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2503 id = '$label_id' AND owner_uid = " . $owner_uid);
2504
2505 $match_part = db_fetch_result($result, 0, "sql_exp");
2506 }
2507
2508 if ($match_part) {
2509
2510 $result = db_query($link, "SELECT count(int_id) AS unread
2511 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2512 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2513 ttrss_user_entries.ref_id = ttrss_entries.id AND
2514 ttrss_feeds.hidden = false AND
2515 $age_qpart AND
2516 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2517
2518 } else {
2519
2520 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2521 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2522 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2523 AND $unread_qpart AND $age_qpart AND
2524 ttrss_tags.owner_uid = " . $owner_uid);
2525 }
2526
2527 $unread = db_fetch_result($result, 0, "unread");
2528
2529 return $unread;
2530 }
2531
2532 function getGlobalUnread($link, $user_id = false) {
2533
2534 if (!$user_id) {
2535 $user_id = $_SESSION["uid"];
2536 }
2537
2538 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2539 WHERE owner_uid = '$user_id' AND feed_id > 0");
2540
2541 $c_id = db_fetch_result($result, 0, "c_id");
2542
2543 return $c_id;
2544 }
2545
2546 function getGlobalCounters($link, $global_unread = -1) {
2547 if ($global_unread == -1) {
2548 $global_unread = getGlobalUnread($link);
2549 }
2550 print "<counter type=\"global\" id='global-unread'
2551 counter='$global_unread'/>";
2552
2553 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2554 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2555
2556 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2557
2558 print "<counter type=\"global\" id='subscribed-feeds'
2559 counter='$subscribed_feeds'/>";
2560
2561 }
2562
2563 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
2564
2565 if ($smart_mode) {
2566 if (!$_SESSION["tctr_last_value"]) {
2567 $_SESSION["tctr_last_value"] = array();
2568 }
2569 }
2570
2571 $old_counters = $_SESSION["tctr_last_value"];
2572
2573 $tctrs_modified = false;
2574
2575 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2576 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2577 ttrss_user_entries.ref_id = ttrss_entries.id AND
2578 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2579 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
2580 UNION
2581 select tag_name,0 as count FROM ttrss_tags
2582 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2583
2584 $age_qpart = getMaxAgeSubquery();
2585
2586 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2587 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2588 AND ref_id = id AND $age_qpart
2589 AND unread = true)) AS count FROM ttrss_tags
2590 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2591 ORDER BY count DESC LIMIT 55");
2592
2593 $tags = array();
2594
2595 while ($line = db_fetch_assoc($result)) {
2596 $tags[$line["tag_name"]] += $line["count"];
2597 }
2598
2599 foreach (array_keys($tags) as $tag) {
2600 $unread = $tags[$tag];
2601
2602 $tag = htmlspecialchars($tag);
2603
2604 if (!$smart_mode || $old_counters[$tag] != $unread) {
2605 $old_counters[$tag] = $unread;
2606 $tctrs_modified = true;
2607 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2608 }
2609
2610 }
2611
2612 if ($smart_mode && $tctrs_modified) {
2613 $_SESSION["tctr_last_value"] = $old_counters;
2614 }
2615
2616 }
2617
2618 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
2619
2620 $age_qpart = getMaxAgeSubquery();
2621
2622 if ($smart_mode) {
2623 if (!$_SESSION["lctr_last_value"]) {
2624 $_SESSION["lctr_last_value"] = array();
2625 }
2626 }
2627
2628 $ret_arr = array();
2629
2630 $old_counters = $_SESSION["lctr_last_value"];
2631 $lctrs_modified = false;
2632
2633 $count = getFeedUnread($link, -1);
2634
2635 if (!$ret_mode) {
2636
2637 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2638 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2639 } else {
2640 $xmsg_part = "";
2641 }
2642
2643 print "<counter type=\"label\" id=\"-1\" counter=\"$count\" $xmsg_part/>";
2644 } else {
2645 $ret_arr["-1"]["counter"] = $count;
2646 $ret_arr["-1"]["description"] = __("Starred articles");
2647 }
2648
2649 $count = getFeedUnread($link, -2);
2650
2651 if (!$ret_mode) {
2652
2653 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2654 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2655 } else {
2656 $xmsg_part = "";
2657 }
2658
2659 print "<counter type=\"label\" id=\"-2\" counter=\"$count\" $xmsg_part/>";
2660 } else {
2661 $ret_arr["-2"]["counter"] = $count;
2662 $ret_arr["-2"]["description"] = __("Published articles");
2663 }
2664
2665 $count = getFeedUnread($link, -3);
2666
2667 if (!$ret_mode) {
2668
2669 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2670 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2671 } else {
2672 $xmsg_part = "";
2673 }
2674
2675 print "<counter type=\"label\" id=\"-3\" counter=\"$count\" $xmsg_part/>";
2676 } else {
2677 $ret_arr["-3"]["counter"] = $count;
2678 $ret_arr["-3"]["description"] = __("Fresh articles");
2679 }
2680
2681
2682 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2683 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2684
2685 while ($line = db_fetch_assoc($result)) {
2686
2687 $id = -$line["id"] - 11;
2688
2689 $label_name = $line["description"];
2690
2691 error_reporting (0);
2692
2693 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2694 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
2695 ttrss_feeds.hidden = false AND
2696 $age_qpart AND
2697 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2698 ttrss_user_entries.ref_id = ttrss_entries.id AND
2699 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2700
2701 $count = db_fetch_result($tmp_result, 0, "count");
2702
2703 if (!$smart_mode || $old_counters[$id] != $count) {
2704 $old_counters[$id] = $count;
2705 $lctrs_modified = true;
2706 if (!$ret_mode) {
2707
2708 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2709 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2710 } else {
2711 $xmsg_part = "";
2712 }
2713
2714 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2715 } else {
2716 $ret_arr[$id]["counter"] = $count;
2717 $ret_arr[$id]["description"] = $label_name;
2718 }
2719 }
2720
2721 error_reporting (DEFAULT_ERROR_LEVEL);
2722 }
2723
2724 if ($smart_mode && $lctrs_modified) {
2725 $_SESSION["lctr_last_value"] = $old_counters;
2726 }
2727
2728 return $ret_arr;
2729 }
2730
2731 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS, $active_feed = false) {
2732
2733 $age_qpart = getMaxAgeSubquery();
2734
2735 if ($smart_mode) {
2736 if (!$_SESSION["fctr_last_value"]) {
2737 $_SESSION["fctr_last_value"] = array();
2738 }
2739 }
2740
2741 $old_counters = $_SESSION["fctr_last_value"];
2742
2743 /* $query = "SELECT ttrss_feeds.id,
2744 ttrss_feeds.title,
2745 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2746 last_error,
2747 COUNT(ttrss_entries.id) AS count
2748 FROM ttrss_feeds
2749 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id
2750 AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid
2751 AND ttrss_user_entries.unread = true)
2752 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2753 $age_qpart)
2754 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2755 AND parent_feed IS NULL
2756 GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error"; */
2757
2758 $query = "SELECT ttrss_feeds.id,
2759 ttrss_feeds.title,
2760 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2761 last_error, value AS count
2762 FROM ttrss_feeds, ttrss_counters_cache
2763 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2764 AND parent_feed IS NULL
2765 AND ttrss_counters_cache.feed_id = id";
2766
2767 $result = db_query($link, $query);
2768 $fctrs_modified = false;
2769
2770 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2771
2772 while ($line = db_fetch_assoc($result)) {
2773
2774 $id = $line["id"];
2775 $count = $line["count"];
2776 $last_error = htmlspecialchars($line["last_error"]);
2777
2778 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2779 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2780 } else {
2781 $last_updated = date($short_date, strtotime($line["last_updated"]));
2782 }
2783
2784 $last_updated = htmlspecialchars($last_updated);
2785
2786 $has_img = feed_has_icon($id);
2787
2788 /* $tmp_result = db_query($link,
2789 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2790 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2791 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2792 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id)
2793 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id"); */
2794
2795 $tmp_result = db_query($link,
2796 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2797 WHERE parent_feed = '$id' AND feed_id = id");
2798
2799 $count += db_fetch_result($tmp_result, 0, "unread");
2800
2801 if (!$smart_mode || $old_counters[$id] != $count) {
2802 $old_counters[$id] = $count;
2803 $fctrs_modified = true;
2804
2805 if ($last_error) {
2806 $error_part = "error=\"$last_error\"";
2807 } else {
2808 $error_part = "";
2809 }
2810
2811 if ($has_img) {
2812 $has_img_part = "hi=\"$has_img\"";
2813 } else {
2814 $has_img_part = "";
2815 }
2816
2817 if ($active_feed && $id == $active_feed) {
2818 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2819 } else {
2820 $has_title_part = "";
2821 }
2822
2823 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2824 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2825 }
2826
2827 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2828 }
2829 }
2830
2831 if ($smart_mode && $fctrs_modified) {
2832 $_SESSION["fctr_last_value"] = $old_counters;
2833 }
2834 }
2835
2836 function get_script_dt_add() {
2837 if (strpos(VERSION, ".99") === false) {
2838 return VERSION;
2839 } else {
2840 return time();
2841 }
2842 }
2843
2844 function get_pgsql_version($link) {
2845 $result = db_query($link, "SELECT version() AS version");
2846 $version = split(" ", db_fetch_result($result, 0, "version"));
2847 return $version[1];
2848 }
2849
2850 function print_error_xml($code, $add_msg = "") {
2851 global $ERRORS;
2852
2853 $error_msg = $ERRORS[$code];
2854
2855 if ($add_msg) {
2856 $error_msg = "$error_msg; $add_msg";
2857 }
2858
2859 print "<rpc-reply>";
2860 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2861 print "</rpc-reply>";
2862 }
2863
2864 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2865 $auth_login = '', $auth_pass = '') {
2866
2867 # check for feed:http://url
2868 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2869
2870 # check for feed://URL
2871 if (strpos($feed_link, "//") === 0) {
2872 $feed_link = "http:$feed_link";
2873 }
2874
2875 if ($feed_link == "") return;
2876
2877 if ($cat_id == "0" || !$cat_id) {
2878 $cat_qpart = "NULL";
2879 } else {
2880 $cat_qpart = "'$cat_id'";
2881 }
2882
2883 $result = db_query($link,
2884 "SELECT id FROM ttrss_feeds
2885 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2886
2887 if (db_num_rows($result) == 0) {
2888
2889 $result = db_query($link,
2890 "INSERT INTO ttrss_feeds
2891 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2892 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2893 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2894
2895 $result = db_query($link,
2896 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2897 AND owner_uid = " . $_SESSION["uid"]);
2898
2899 $feed_id = db_fetch_result($result, 0, "id");
2900
2901 if ($feed_id) {
2902 update_rss_feed($link, $feed_link, $feed_id, true);
2903 }
2904
2905 return true;
2906 } else {
2907 return false;
2908 }
2909 }
2910
2911 function print_feed_select($link, $id, $default_id = "",
2912 $attributes = "", $include_all_feeds = true) {
2913
2914 print "<select id=\"$id\" name=\"$id\" $attributes>";
2915 if ($include_all_feeds) {
2916 print "<option value=\"0\">".__('All feeds')."</option>";
2917 }
2918
2919 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2920 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2921
2922 if (db_num_rows($result) > 0 && $include_all_feeds) {
2923 print "<option disabled>--------</option>";
2924 }
2925
2926 while ($line = db_fetch_assoc($result)) {
2927 if ($line["id"] == $default_id) {
2928 $is_selected = "selected";
2929 } else {
2930 $is_selected = "";
2931 }
2932 printf("<option $is_selected value='%d'>%s</option>",
2933 $line["id"], htmlspecialchars($line["title"]));
2934 }
2935
2936 print "</select>";
2937 }
2938
2939 function print_feed_cat_select($link, $id, $default_id = "",
2940 $attributes = "", $include_all_cats = true) {
2941
2942 print "<select id=\"$id\" name=\"$id\" $attributes>";
2943
2944 if ($include_all_cats) {
2945 print "<option value=\"0\">".__('Uncategorized')."</option>";
2946 }
2947
2948 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2949 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2950
2951 if (db_num_rows($result) > 0 && $include_all_cats) {
2952 print "<option disabled>--------</option>";
2953 }
2954
2955 while ($line = db_fetch_assoc($result)) {
2956 if ($line["id"] == $default_id) {
2957 $is_selected = "selected";
2958 } else {
2959 $is_selected = "";
2960 }
2961 printf("<option $is_selected value='%d'>%s</option>",
2962 $line["id"], htmlspecialchars($line["title"]));
2963 }
2964
2965 print "</select>";
2966 }
2967
2968 function checkbox_to_sql_bool($val) {
2969 return ($val == "on") ? "true" : "false";
2970 }
2971
2972 function getFeedCatTitle($link, $id) {
2973 if ($id == -1) {
2974 return __("Special");
2975 } else if ($id < -10) {
2976 return __("Labels");
2977 } else if ($id > 0) {
2978 $result = db_query($link, "SELECT ttrss_feed_categories.title
2979 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2980 cat_id = ttrss_feed_categories.id");
2981 if (db_num_rows($result) == 1) {
2982 return db_fetch_result($result, 0, "title");
2983 } else {
2984 return __("Uncategorized");
2985 }
2986 } else {
2987 return "getFeedCatTitle($id) failed";
2988 }
2989
2990 }
2991
2992 function getFeedTitle($link, $id) {
2993 if ($id == -1) {
2994 return __("Starred articles");
2995 } else if ($id == -2) {
2996 return __("Published articles");
2997 } else if ($id == -3) {
2998 return __("Fresh articles");
2999 } else if ($id < -10) {
3000 $label_id = -$id - 11;
3001 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
3002 if (db_num_rows($result) == 1) {
3003 return db_fetch_result($result, 0, "description");
3004 } else {
3005 return "Unknown label ($label_id)";
3006 }
3007
3008 } else if ($id > 0) {
3009 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3010 if (db_num_rows($result) == 1) {
3011 return db_fetch_result($result, 0, "title");
3012 } else {
3013 return "Unknown feed ($id)";
3014 }
3015 } else {
3016 return "getFeedTitle($id) failed";
3017 }
3018
3019 }
3020
3021 function get_session_cookie_name() {
3022 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
3023 }
3024
3025 function print_init_params($link) {
3026 print "<init-params>";
3027 if ($_SESSION["stored-params"]) {
3028 foreach (array_keys($_SESSION["stored-params"]) as $key) {
3029 if ($key) {
3030 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
3031 print "<param key=\"$key\" value=\"$value\"/>";
3032 }
3033 }
3034 }
3035
3036 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
3037 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
3038 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
3039 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
3040
3041 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
3042 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
3043
3044 print "<param key=\"hide_read_feeds\" value=\"" .
3045 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
3046
3047 print "<param key=\"feeds_sort_by_unread\" value=\"" .
3048 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
3049
3050 print "<param key=\"confirm_feed_catchup\" value=\"" .
3051 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
3052
3053 print "<param key=\"cdm_auto_catchup\" value=\"" .
3054 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
3055
3056 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
3057
3058 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
3059
3060 print "<param key=\"default_view_mode\" value=\"" .
3061 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
3062
3063 print "<param key=\"default_view_limit\" value=\"" .
3064 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
3065
3066 print "<param key=\"default_view_order_by\" value=\"" .
3067 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
3068
3069 print "<param key=\"prefs_active_tab\" value=\"" .
3070 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3071
3072 print "<param key=\"infobox_disable_overlay\" value=\"" .
3073 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3074
3075 print "<param key=\"icons_location\" value=\"" .
3076 ICONS_URL . "\"/>";
3077
3078 print "<param key=\"hide_read_shows_special\" value=\"" .
3079 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3080
3081 print "<param key=\"hide_feedlist\" value=\"" .
3082 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3083
3084 print "<param key=\"bw_limit\" value=\"".
3085 (int) $_SESSION["bw_limit"]."\"/>";
3086
3087 // print "<param key=\"sync_counters\" value=\"" .
3088 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3089
3090 print "<param key=\"sync_counters\" value=\"1\"/>";
3091
3092 print "</init-params>";
3093 }
3094
3095 function print_runtime_info($link) {
3096 print "<runtime-info>";
3097
3098 if (ENABLE_UPDATE_DAEMON) {
3099 print "<param key=\"daemon_is_running\" value=\"".
3100 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3101
3102 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3103
3104 $stamp = (int)read_stampfile("update_daemon.stamp");
3105
3106 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3107
3108 if ($stamp) {
3109 $stamp_delta = time() - $stamp;
3110
3111 if ($stamp_delta > 1800) {
3112 $stamp_check = 0;
3113 } else {
3114 $stamp_check = 1;
3115 $_SESSION["daemon_stamp_check"] = time();
3116 }
3117
3118 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3119
3120 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3121
3122 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3123 }
3124 }
3125 }
3126
3127 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
3128
3129 if ($_SESSION["last_version_check"] + 86400 < time()) {
3130 $new_version_details = check_for_update($link);
3131
3132 print "<param key=\"new_version_available\" value=\"".
3133 sprintf("%d", $new_version_details != ""). "\"/>";
3134
3135 $_SESSION["last_version_check"] = time();
3136 }
3137 }
3138
3139 // print "<param key=\"new_version_available\" value=\"1\"/>";
3140
3141 print "</runtime-info>";
3142 }
3143
3144 function getSearchSql($search, $match_on) {
3145
3146 $search_query_part = "";
3147
3148 $keywords = split(" ", $search);
3149 $query_keywords = array();
3150
3151 if ($match_on == "both") {
3152
3153 foreach ($keywords as $k) {
3154 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3155 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3156 }
3157
3158 $search_query_part = implode("AND", $query_keywords) . " AND ";
3159
3160 } else if ($match_on == "title") {
3161
3162 foreach ($keywords as $k) {
3163 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3164 }
3165
3166 $search_query_part = implode("AND", $query_keywords) . " AND ";
3167
3168 } else if ($match_on == "content") {
3169
3170 foreach ($keywords as $k) {
3171 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3172 }
3173 }
3174
3175 $search_query_part = implode("AND", $query_keywords);
3176
3177 return $search_query_part;
3178 }
3179
3180 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3181
3182 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3183
3184 if ($search) {
3185
3186 $search_query_part = getSearchSql($search, $match_on);
3187 $search_query_part .= " AND ";
3188
3189 } else {
3190 $search_query_part = "";
3191 }
3192
3193 $view_query_part = "";
3194
3195 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
3196 if ($search) {
3197 $view_query_part = " ";
3198 } else if ($feed != -1) {
3199 $unread = getFeedUnread($link, $feed, $cat_view);
3200 if ($unread > 0) {
3201 $view_query_part = " unread = true AND ";
3202 }
3203 }
3204 }
3205
3206 if ($view_mode == "marked") {
3207 $view_query_part = " marked = true AND ";
3208 }
3209
3210 if ($view_mode == "unread") {
3211 $view_query_part = " unread = true AND ";
3212 }
3213
3214 if ($limit > 0) {
3215 $limit_query_part = "LIMIT " . $limit;
3216 }
3217
3218 $vfeed_query_part = "";
3219
3220 // override query strategy and enable feed display when searching globally
3221 if ($search && $search_mode == "all_feeds") {
3222 $query_strategy_part = "ttrss_entries.id > 0";
3223 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3224 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3225 $query_strategy_part = "ttrss_entries.id > 0";
3226 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3227 id = feed_id) as feed_title,";
3228 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3229
3230 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3231
3232 $tmp_result = false;
3233
3234 if ($cat_view) {
3235 $tmp_result = db_query($link, "SELECT id
3236 FROM ttrss_feeds WHERE cat_id = '$feed'");
3237 } else {
3238 $tmp_result = db_query($link, "SELECT id
3239 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3240 WHERE id = '$feed') AND id != '$feed'");
3241 }
3242
3243 $cat_siblings = array();
3244
3245 if (db_num_rows($tmp_result) > 0) {
3246 while ($p = db_fetch_assoc($tmp_result)) {
3247 array_push($cat_siblings, "feed_id = " . $p["id"]);
3248 }
3249
3250 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3251 $feed, implode(" OR ", $cat_siblings));
3252
3253 } else {
3254 $query_strategy_part = "ttrss_entries.id > 0";
3255 }
3256
3257 } else if ($feed >= 0) {
3258
3259 if ($cat_view) {
3260
3261 if ($feed > 0) {
3262 $query_strategy_part = "cat_id = '$feed'";
3263 } else {
3264 $query_strategy_part = "cat_id IS NULL";
3265 }
3266
3267 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3268
3269 } else {
3270 $tmp_result = db_query($link, "SELECT id
3271 FROM ttrss_feeds WHERE parent_feed = '$feed'
3272 ORDER BY cat_id,title");
3273
3274 $parent_ids = array();
3275
3276 if (db_num_rows($tmp_result) > 0) {
3277 while ($p = db_fetch_assoc($tmp_result)) {
3278 array_push($parent_ids, "feed_id = " . $p["id"]);
3279 }
3280
3281 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3282 $feed, implode(" OR ", $parent_ids));
3283
3284 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3285 } else {
3286 $query_strategy_part = "feed_id = '$feed'";
3287 }
3288 }
3289 } else if ($feed == -1) { // starred virtual feed
3290 $query_strategy_part = "marked = true";
3291 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3292 } else if ($feed == -2) { // published virtual feed
3293 $query_strategy_part = "published = true";
3294 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3295 } else if ($feed == -3) { // fresh virtual feed
3296 $query_strategy_part = "unread = true";
3297
3298 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3299
3300 if (DB_TYPE == "pgsql") {
3301 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3302 } else {
3303 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3304 }
3305
3306 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3307 } else if ($feed <= -10) { // labels
3308 $label_id = -$feed - 11;
3309
3310 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3311 WHERE id = '$label_id'");
3312
3313 $query_strategy_part = "(" . db_fetch_result($tmp_result, 0, "sql_exp") . ")";
3314
3315 if (!$query_strategy_part) {
3316 return false;
3317 }
3318
3319 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3320 } else {
3321 $query_strategy_part = "id > 0"; // dumb
3322 }
3323
3324 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3325 $order_by = "updated";
3326 } else {
3327 $order_by = "updated DESC";
3328 }
3329
3330 if ($view_mode != "noscores") {
3331 $order_by = "score DESC, $order_by";
3332 }
3333
3334 if ($override_order) {
3335 $order_by = $override_order;
3336 }
3337
3338 $feed_title = "";
3339
3340 if ($search && $search_mode == "all_feeds") {
3341 $feed_title = __("Search results")." ($search)";
3342 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3343 $feed_title = __("Search results")." ($search, $feed)";
3344 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3345 $feed_title = $feed;
3346 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3347
3348 if ($cat_view) {
3349
3350 if ($feed != 0) {
3351 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3352 WHERE id = '$feed' AND owner_uid = $owner_uid");
3353 $feed_title = db_fetch_result($result, 0, "title");
3354 } else {
3355 $feed_title = __("Uncategorized");
3356 }
3357
3358 if ($search) {
3359 $feed_title = __("Searched for")." $search ($feed_title)";
3360 }
3361
3362 } else {
3363
3364 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3365 WHERE id = '$feed' AND owner_uid = $owner_uid");
3366
3367 $feed_title = db_fetch_result($result, 0, "title");
3368 $feed_site_url = db_fetch_result($result, 0, "site_url");
3369 $last_error = db_fetch_result($result, 0, "last_error");
3370
3371 if ($search) {
3372 $feed_title = __("Searched for") . " $search ($feed_title)";
3373 }
3374 }
3375
3376 } else if ($feed == -1) {
3377 $feed_title = __("Starred articles");
3378 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3379 } else if ($feed == -2) {
3380 $feed_title = __("Published articles");
3381 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3382 } else if ($feed == -3) {
3383 $feed_title = __("Fresh articles");
3384 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3385 } else if ($feed < -10) {
3386 $label_id = -$feed - 11;
3387 $result = db_query($link, "SELECT description FROM ttrss_labels
3388 WHERE id = '$label_id'");
3389 $feed_title = db_fetch_result($result, 0, "description");
3390
3391 if ($search) {
3392 $feed_title = __("Searched for") . " $search ($feed_title)";
3393 }
3394 } else {
3395 $feed_title = "?";
3396 }
3397
3398 if ($feed < -10) error_reporting (0);
3399
3400 $content_query_part = "content as content_preview,";
3401
3402 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3403
3404 if ($feed >= 0) {
3405 $feed_kind = "Feeds";
3406 } else {
3407 $feed_kind = "Labels";
3408 }
3409
3410 if ($limit_query_part) {
3411 $offset_query_part = "OFFSET $offset";
3412 }
3413
3414 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3415 if (!$override_order) {
3416 $order_by = "ttrss_feeds.title, $order_by";
3417 }
3418
3419 // Special output for Fresh feed
3420
3421 /* if ($feed == -3) {
3422 $group_limit_part = "(select count(*) from
3423 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3424 t1.ref_id = t2.id and t1.owner_uid = 2 and
3425 t1.feed_id = ttrss_user_entries.feed_id and
3426 t2.updated > ttrss_entries.updated) <= 5 AND";
3427 } */
3428 }
3429
3430 $query = "SELECT
3431 guid,
3432 ttrss_entries.id,ttrss_entries.title,
3433 updated,
3434 unread,feed_id,marked,published,link,last_read,
3435 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3436 $vfeed_query_part
3437 $content_query_part
3438 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3439 author,score
3440 FROM
3441 ttrss_entries,ttrss_user_entries,ttrss_feeds
3442 WHERE
3443 $group_limit_part
3444 ttrss_feeds.hidden = false AND
3445 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3446 ttrss_user_entries.ref_id = ttrss_entries.id AND
3447 ttrss_user_entries.owner_uid = '$owner_uid' AND
3448 $search_query_part
3449 $view_query_part
3450 $query_strategy_part ORDER BY $order_by
3451 $limit_query_part $offset_query_part";
3452
3453 if ($_GET["debug"]) print $query;
3454
3455 $result = db_query($link, $query);
3456
3457 } else {
3458 // browsing by tag
3459
3460 $feed_kind = "Tags";
3461
3462 $result = db_query($link, "SELECT
3463 guid,
3464 ttrss_entries.id as id,title,
3465 updated,
3466 unread,feed_id,
3467 marked,link,last_read,
3468 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3469 $vfeed_query_part
3470 $content_query_part
3471 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3472 score
3473 FROM
3474 ttrss_entries,ttrss_user_entries,ttrss_tags
3475 WHERE
3476 ref_id = ttrss_entries.id AND
3477 ttrss_user_entries.owner_uid = '$owner_uid' AND
3478 post_int_id = int_id AND tag_name = '$feed' AND
3479 $view_query_part
3480 $search_query_part
3481 $query_strategy_part ORDER BY $order_by
3482 $limit_query_part");
3483 }
3484
3485 return array($result, $feed_title, $feed_site_url, $last_error);
3486
3487 }
3488
3489 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3490 $limit, $search, $search_mode, $match_on) {
3491
3492 if (!$limit) $limit = 30;
3493
3494 $qfh_ret = queryFeedHeadlines($link, $feed,
3495 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3496 $owner_uid);
3497
3498 $result = $qfh_ret[0];
3499 $feed_title = htmlspecialchars($qfh_ret[1]);
3500 $feed_site_url = $qfh_ret[2];
3501 $last_error = $qfh_ret[3];
3502
3503 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3504
3505 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3506 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3507 <rss version=\"2.0\">
3508 <channel>
3509 <title>$feed_title</title>
3510 <link>$feed_site_url</link>
3511 <description>Feed generated by Tiny Tiny RSS</description>";
3512
3513 while ($line = db_fetch_assoc($result)) {
3514 print "<item>";
3515 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3516 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3517
3518 $tags = get_article_tags($link, $line["id"], $owner_uid);
3519
3520 foreach ($tags as $tag) {
3521 print "<category>" . htmlspecialchars($tag) . "</category>";
3522 }
3523
3524 $rfc822_date = date('r', strtotime($line["updated"]));
3525
3526 print "<pubDate>$rfc822_date</pubDate>";
3527
3528 print "<title>" .
3529 htmlspecialchars($line["title"]) . "</title>";
3530
3531 print "<description><![CDATA[" .
3532 $line["content_preview"] . "]]></description>";
3533
3534 print "</item>";
3535 }
3536
3537 print "</channel></rss>";
3538
3539 }
3540
3541 function getCategoryTitle($link, $cat_id) {
3542
3543 if ($cat_id == -1) {
3544 return __("Special");
3545 } else if ($cat_id == -2) {
3546 return __("Labels");
3547 } else {
3548
3549 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3550 id = '$cat_id'");
3551
3552 if (db_num_rows($result) == 1) {
3553 return db_fetch_result($result, 0, "title");
3554 } else {
3555 return "Uncategorized";
3556 }
3557 }
3558 }
3559
3560 // http://ru2.php.net/strip-tags
3561
3562 function strip_tags_long($textstring, $allowed){
3563 while($textstring != strip_tags($textstring, $allowed))
3564 {
3565 while (strlen($textstring) != 0)
3566 {
3567 if (strlen($textstring) > 1024) {
3568 $otherlen = 1024;
3569 } else {
3570 $otherlen = strlen($textstring);
3571 }
3572 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3573 $safetext .= $temptext;
3574 $textstring = substr_replace($textstring,'',0,$otherlen);
3575 }
3576 $textstring = $safetext;
3577 }
3578 return $textstring;
3579 }
3580
3581
3582 function sanitize_rss($link, $str, $force_strip_tags = false) {
3583 $res = $str;
3584
3585 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
3586
3587 $res = strip_tags_long($res,
3588 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3589
3590 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3591 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3592 }
3593
3594 if (get_pref($link, "STRIP_IMAGES")) {
3595
3596 $res = preg_replace('/<img[^>]+>/is', '', $res);
3597
3598 }
3599
3600 return $res;
3601 }
3602
3603 /**
3604 * Send by mail a digest of last articles.
3605 *
3606 * @param mixed $link The database connection.
3607 * @param integer $limit The maximum number of articles by digest.
3608 * @return boolean Return false if digests are not enabled.
3609 */
3610 function send_headlines_digests($link, $limit = 100) {
3611
3612 if (!DIGEST_ENABLE) return false;
3613
3614 $user_limit = DIGEST_EMAIL_LIMIT;
3615 $days = 1;
3616
3617 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3618
3619 if (DB_TYPE == "pgsql") {
3620 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3621 } else if (DB_TYPE == "mysql") {
3622 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3623 }
3624
3625 $result = db_query($link, "SELECT id,email FROM ttrss_users
3626 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3627
3628 while ($line = db_fetch_assoc($result)) {
3629
3630 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3631 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3632
3633 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3634
3635 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3636 $digest = $tuple[0];
3637 $headlines_count = $tuple[1];
3638 $affected_ids = $tuple[2];
3639 $digest_text = $tuple[3];
3640
3641 if ($headlines_count > 0) {
3642
3643 $mail = new PHPMailer();
3644
3645 $mail->PluginDir = "phpmailer/";
3646 $mail->SetLanguage("en", "phpmailer/language/");
3647
3648 $mail->CharSet = "UTF-8";
3649
3650 $mail->From = DIGEST_FROM_ADDRESS;
3651 $mail->FromName = DIGEST_FROM_NAME;
3652 $mail->AddAddress($line["email"], $line["login"]);
3653
3654 if (DIGEST_SMTP_HOST) {
3655 $mail->Host = DIGEST_SMTP_HOST;
3656 $mail->Mailer = "smtp";
3657 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
3658 $mail->Username = DIGEST_SMTP_LOGIN;
3659 $mail->Password = DIGEST_SMTP_PASSWORD;
3660 }
3661
3662 $mail->IsHTML(true);
3663 $mail->Subject = DIGEST_SUBJECT;
3664 $mail->Body = $digest;
3665 $mail->AltBody = $digest_text;
3666
3667 $rc = $mail->Send();
3668
3669 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
3670
3671 print "RC=$rc\n";
3672
3673 if ($rc && $do_catchup) {
3674 print "Marking affected articles as read...\n";
3675 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3676 }
3677
3678 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3679 WHERE id = " . $line["id"]);
3680 } else {
3681 print "No headlines\n";
3682 }
3683 }
3684 }
3685
3686 print "All done.\n";
3687
3688 }
3689
3690 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3691
3692 require_once "MiniTemplator.class.php";
3693
3694 $tpl = new MiniTemplator;
3695 $tpl_t = new MiniTemplator;
3696
3697 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3698 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3699
3700 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3701 $tpl->setVariable('CUR_TIME', date('G:i'));
3702
3703 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3704 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3705
3706 $affected_ids = array();
3707
3708 if (DB_TYPE == "pgsql") {
3709 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3710 } else if (DB_TYPE == "mysql") {
3711 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3712 }
3713
3714 $result = db_query($link, "SELECT ttrss_entries.title,
3715 ttrss_feeds.title AS feed_title,
3716 date_entered,
3717 ttrss_user_entries.ref_id,
3718 link,
3719 SUBSTRING(content, 1, 120) AS excerpt,
3720 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
3721 FROM
3722 ttrss_user_entries,ttrss_entries,ttrss_feeds
3723 WHERE
3724 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3725 AND include_in_digest = true
3726 AND $interval_query
3727 AND hidden = false
3728 AND ttrss_user_entries.owner_uid = $user_id
3729 AND unread = true
3730 ORDER BY ttrss_feeds.title, date_entered DESC
3731 LIMIT $limit");
3732
3733 $cur_feed_title = "";
3734
3735 $headlines_count = db_num_rows($result);
3736
3737 $headlines = array();
3738
3739 while ($line = db_fetch_assoc($result)) {
3740 array_push($headlines, $line);
3741 }
3742
3743 for ($i = 0; $i < sizeof($headlines); $i++) {
3744
3745 $line = $headlines[$i];
3746
3747 array_push($affected_ids, $line["ref_id"]);
3748
3749 $updated = smart_date_time(strtotime($line["last_updated"]));
3750
3751 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3752 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3753 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3754 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3755 $tpl->setVariable('ARTICLE_EXCERPT',
3756 truncate_string(strip_tags($line["excerpt"]), 100));
3757
3758 $tpl->addBlock('article');
3759
3760 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3761 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3762 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3763 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3764 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3765 // truncate_string(strip_tags($line["excerpt"]), 100));
3766
3767 $tpl_t->addBlock('article');
3768
3769 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3770 $tpl->addBlock('feed');
3771 $tpl_t->addBlock('feed');
3772 }
3773
3774 }
3775
3776 $tpl->addBlock('digest');
3777 $tpl->generateOutputToString($tmp);
3778
3779 $tpl_t->addBlock('digest');
3780 $tpl_t->generateOutputToString($tmp_t);
3781
3782 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3783 }
3784
3785 function check_for_update($link, $brief_fmt = true) {
3786 $releases_feed = "http://tt-rss.org/releases.rss";
3787
3788 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
3789 return;
3790 }
3791
3792 error_reporting(0);
3793 if (ENABLE_SIMPLEPIE) {
3794 $rss = new SimplePie();
3795 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
3796 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3797 $rss->set_feed_url($fetch_url);
3798 $rss->set_output_encoding('UTF-8');
3799 $rss->init();
3800 } else {
3801 $rss = fetch_rss($releases_feed);
3802 }
3803 error_reporting (DEFAULT_ERROR_LEVEL);
3804
3805 if ($rss) {
3806
3807 if (ENABLE_SIMPLEPIE) {
3808 $items = $rss->get_items();
3809 } else {
3810 $items = $rss->items;
3811
3812 if (!$items || !is_array($items)) $items = $rss->entries;
3813 if (!$items || !is_array($items)) $items = $rss;
3814 }
3815
3816 if (!is_array($items) || count($items) == 0) {
3817 return;
3818 }
3819
3820 $latest_item = $items[0];
3821
3822 if (ENABLE_SIMPLEPIE) {
3823 $last_title = $latest_item->get_title();
3824 } else {
3825 $last_title = $latest_item["title"];
3826 }
3827
3828 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3829
3830 if (ENABLE_SIMPLEPIE) {
3831 $release_url = sanitize_rss($link, $latest_item->get_link());
3832 $content = sanitize_rss($link, $latest_item->get_description());
3833 } else {
3834 $release_url = sanitize_rss($link, $latest_item["link"]);
3835 $content = sanitize_rss($link, $latest_item["description"]);
3836 }
3837
3838 if (version_compare(VERSION, $latest_version) == -1) {
3839 if ($brief_fmt) {
3840 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
3841 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3842 <div id=\"milestoneDetails\">$content</div>");
3843 } else {
3844 return "New version of Tiny-Tiny RSS ($latest_version) is available:
3845 <div class='milestoneDetails'>$content</div>
3846 Visit <a target=\"_blank\" href=\"http://tt-rss.org/\">official site</a> for
3847 download and update information.";
3848 }
3849
3850 }
3851 }
3852 }
3853
3854 function markArticlesById($link, $ids, $cmode) {
3855
3856 $tmp_ids = array();
3857
3858 foreach ($ids as $id) {
3859 array_push($tmp_ids, "ref_id = '$id'");
3860 }
3861
3862 $ids_qpart = join(" OR ", $tmp_ids);
3863
3864 if ($cmode == 0) {
3865 db_query($link, "UPDATE ttrss_user_entries SET
3866 marked = false,last_read = NOW()
3867 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3868 } else if ($cmode == 1) {
3869 db_query($link, "UPDATE ttrss_user_entries SET
3870 marked = true
3871 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3872 } else {
3873 db_query($link, "UPDATE ttrss_user_entries SET
3874 marked = NOT marked,last_read = NOW()
3875 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3876 }
3877 }
3878
3879 function publishArticlesById($link, $ids, $cmode) {
3880
3881 $tmp_ids = array();
3882
3883 foreach ($ids as $id) {
3884 array_push($tmp_ids, "ref_id = '$id'");
3885 }
3886
3887 $ids_qpart = join(" OR ", $tmp_ids);
3888
3889 if ($cmode == 0) {
3890 db_query($link, "UPDATE ttrss_user_entries SET
3891 published = false,last_read = NOW()
3892 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3893 } else if ($cmode == 1) {
3894 db_query($link, "UPDATE ttrss_user_entries SET
3895 published = true
3896 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3897 } else {
3898 db_query($link, "UPDATE ttrss_user_entries SET
3899 published = NOT published,last_read = NOW()
3900 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3901 }
3902 }
3903
3904 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3905
3906 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3907
3908 $tmp_ids = array();
3909
3910 foreach ($ids as $id) {
3911 array_push($tmp_ids, "ref_id = '$id'");
3912 }
3913
3914 $ids_qpart = join(" OR ", $tmp_ids);
3915
3916 if ($cmode == 0) {
3917 db_query($link, "UPDATE ttrss_user_entries SET
3918 unread = false,last_read = NOW()
3919 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3920 } else if ($cmode == 1) {
3921 db_query($link, "UPDATE ttrss_user_entries SET
3922 unread = true
3923 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3924 } else {
3925 db_query($link, "UPDATE ttrss_user_entries SET
3926 unread = NOT unread,last_read = NOW()
3927 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3928 }
3929
3930 /* update ccache */
3931
3932 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3933 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3934
3935 while ($line = db_fetch_assoc($result)) {
3936 ccache_update($link, $line["feed_id"], $owner_uid);
3937 }
3938 }
3939
3940 function catchupArticleById($link, $id, $cmode) {
3941
3942 if ($cmode == 0) {
3943 db_query($link, "UPDATE ttrss_user_entries SET
3944 unread = false,last_read = NOW()
3945 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3946 } else if ($cmode == 1) {
3947 db_query($link, "UPDATE ttrss_user_entries SET
3948 unread = true
3949 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3950 } else {
3951 db_query($link, "UPDATE ttrss_user_entries SET
3952 unread = NOT unread,last_read = NOW()
3953 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3954 }
3955 }
3956
3957 function make_guid_from_title($title) {
3958 return preg_replace("/[ \"\',.:;]/", "-",
3959 mb_strtolower(strip_tags($title), 'utf-8'));
3960 }
3961
3962 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3963 $bottom = false, $rtl_content = false, $feed_id = 0,
3964 $is_cat = false, $search = false, $match_on = false,
3965 $search_mode = false, $offset = 0, $limit = 0,
3966 $dashboard_menu = 0, $disable_feed = 0, $feed_small_icon = 0) {
3967
3968 $user_page_offset = $offset + 1;
3969
3970 if (!$bottom) {
3971 $class = "headlinesSubToolbar";
3972 $tid = "headlineActionsTop";
3973 } else {
3974 $class = "headlinesSubToolbar";
3975 $tid = "headlineActionsBottom";
3976 }
3977
3978 print "<nobr><table class=\"$class\" id=\"$tid\"
3979 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3980
3981 if ($rtl_content) {
3982 $rtl_cpart = "RTL";
3983 } else {
3984 $rtl_cpart = "";
3985 }
3986
3987 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3988 $page_next_link = "javascript:viewFeedGoPage(1)";
3989 $page_first_link = "javascript:viewFeedGoPage(0)";
3990
3991 $catchup_page_link = "javascript:catchupPage()";
3992 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3993 $catchup_sel_link = "javascript:catchupSelection()";
3994
3995 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3996
3997 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3998 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3999 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
4000 $sel_inv_link = "javascript:invertHeadlineSelection()";
4001
4002 $tog_unread_link = "javascript:selectionToggleUnread()";
4003 $tog_marked_link = "javascript:selectionToggleMarked()";
4004 $tog_published_link = "javascript:selectionTogglePublished()";
4005
4006 } else {
4007
4008 $sel_all_link = "javascript:cdmSelectArticles('all')";
4009 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
4010 $sel_none_link = "javascript:cdmSelectArticles('none')";
4011
4012 $sel_inv_link = "javascript:invertHeadlineSelection()";
4013
4014 $tog_unread_link = "javascript:selectionToggleUnread(true)";
4015 $tog_marked_link = "javascript:selectionToggleMarked(true)";
4016 $tog_published_link = "javascript:selectionTogglePublished(true)";
4017
4018 }
4019
4020 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
4021
4022 print "<td class=\"headlineActions$rtl_cpart\">
4023 <ul class=\"headlineDropdownMenu\">
4024 <li class=\"top2\">
4025 ".__('Select:')."
4026 <a href=\"$sel_all_link\">".__('All')."</a>,
4027 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4028 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4029 <a href=\"$sel_none_link\">".__('None')."</a></li>
4030 <li class=\"vsep\">&nbsp;</li>
4031 <li class=\"top\">".__('Actions...')."<ul>
4032 <li><span class=\"insensitive\">".__('Selection toggle:')."</span></li>
4033 <li onclick=\"$tog_unread_link\">&nbsp;&nbsp;".__('Unread')."</li>
4034 <li onclick=\"$tog_marked_link\">&nbsp;&nbsp;".__('Starred')."</li>
4035 <li onclick=\"$tog_published_link\">&nbsp;&nbsp;".__('Published')."</li>
4036 <li><span class=\"insensitive\">--------</span></li>
4037 <li><span class=\"insensitive\">".__('Mark as read:')."</span></li>
4038 <li onclick=\"$catchup_sel_link\">&nbsp;&nbsp;".__('Selection')."</li>";
4039
4040 /* if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4041
4042 print "
4043 <li onclick=\"catchupRelativeToArticle(0)\">&nbsp;&nbsp;".__("Above active article")."</li>
4044 <li onclick=\"catchupRelativeToArticle(1)\">&nbsp;&nbsp;".__("Below active article")."</li>";
4045 } else {
4046 print "
4047 <li><span class=\"insensitive\">&nbsp;&nbsp;".__("Above active article")."</span></li>
4048 <li><span class=\"insensitive\">&nbsp;&nbsp;".__("Below active article")."</span></li>";
4049
4050 } */
4051
4052 print "<li onclick=\"$catchup_feed_link\">&nbsp;&nbsp;".__('Entire feed')."</li>";
4053
4054 print "<li><span class=\"insensitive\">--------</span></li>";
4055 print "<li><span class=\"insensitive\">".__('Other actions:')."</span></li>";
4056
4057
4058 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
4059 print "
4060 <li onclick=\"javascript:labelFromSearch('$search', '$search_mode',
4061 '$match_on', '$feed_id', '$is_cat');\">&nbsp;&nbsp;
4062 ".__('Search to label')."</li>";
4063 } else {
4064 print "<li><span class=\"insensitive\">&nbsp;&nbsp;".__('Search to label')."</li>";
4065
4066 }
4067
4068 print "</ul></li></ul>";
4069 print "</td>";
4070
4071 } else {
4072 // old style subtoolbar:
4073
4074 print "<td class=\"headlineActions$rtl_cpart\">".
4075 __('Select:')."
4076 <a href=\"$sel_all_link\">".__('All')."</a>,
4077 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4078 <a href=\"$sel_none_link\">".__('None')."</a>
4079 &nbsp;&nbsp;".
4080 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
4081 <a href=\"$tog_marked_link\">".__('Starred')."</a>
4082 &nbsp;&nbsp;".
4083 __('Mark as read:')."
4084 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
4085 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
4086
4087 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
4088
4089 print "&nbsp;&nbsp;
4090 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
4091 '$match_on', '$feed_id', '$is_cat');\">
4092 ".__('Convert to label')."</a>";
4093 }
4094
4095 print "</td>";
4096
4097 }
4098
4099 print "<td class=\"headlineTitle$rtl_cpart\">";
4100
4101 print "<span id=\"subtoolbar_search\"
4102 style=\"display : none\"><input
4103 id=\"subtoolbar_search_box\"
4104 onblur=\"javascript:enableHotkeys();\"
4105 onfocus=\"javascript:disableHotkeys();\"
4106 onchange=\"subtoolbarSearch()\"
4107 onkeyup=\"subtoolbarSearch()\" type=\"search\"></span>";
4108
4109 print "<span id=\"subtoolbar_ftitle\">";
4110
4111 if ($feed_site_url) {
4112 if (!$bottom) {
4113 $target = "target=\"_blank\"";
4114 }
4115 print "<a $target href=\"$feed_site_url\">".
4116 truncate_string($feed_title,30)."</a>";
4117 } else {
4118 print $feed_title;
4119 }
4120
4121 if ($search) {
4122 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4123 }
4124
4125 if ($user_page_offset > 1) {
4126 print " [$user_page_offset] ";
4127 }
4128
4129 if (!$bottom && !$disable_feed) {
4130 print "
4131 <a target=\"_blank\"
4132 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
4133 <img class=\"noborder\"
4134 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
4135 </a>";
4136 } else if ($feed_small_icon) {
4137 print "<img class=\"noborder\" alt=\"\" src=\"images/$feed_small_icon\">";
4138 }
4139
4140 print "</span>";
4141
4142 print "</td>";
4143 print "</tr></table></nobr>";
4144
4145 }
4146
4147 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4148
4149 $tmp_category = getCategoryTitle($link, $cat_id);
4150
4151 if ($cat_id > 0) {
4152 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4153 } else {
4154 $cat_unread = getCategoryUnread($link, $cat_id);
4155 }
4156
4157 if ($hidden) {
4158 $holder_style = "display:none;";
4159 $ellipsis = "…";
4160 } else {
4161 $holder_style = "";
4162 $ellipsis = "";
4163 }
4164
4165 $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4166
4167 if ($can_browse) {
4168 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4169 $inner_title_class = "catTitle";
4170 } else {
4171 $browse_cat_link = "";
4172 $inner_title_class = "catTitleNL";
4173 }
4174
4175 if ($cat_id >= 0) {
4176 $cat_class = "feedCat";
4177 } else {
4178 $cat_class = "virtCat";
4179 }
4180
4181 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4182 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4183 title=\"".__('Click to collapse category')."\"
4184 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4185 id=\"FCATN-$cat_id\" $browse_cat_link
4186 \">$tmp_category</span>";
4187
4188 print "<span id=\"FCAP-$cat_id\">";
4189
4190 print " <span id=\"FCATCTR-$cat_id\"
4191 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4192
4193 print "</span>";
4194
4195 //print "</li>";
4196
4197 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4198
4199 }
4200
4201 function outputFeedList($link, $tags = false) {
4202
4203 print "<ul class=\"feedList\" id=\"feedList\">";
4204
4205 $owner_uid = $_SESSION["uid"];
4206
4207 /* virtual feeds */
4208
4209 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4210
4211 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4212 $cat_hidden = true;
4213 } else {
4214 $cat_hidden = false;
4215 }
4216
4217 printCategoryHeader($link, -1, $cat_hidden, false);
4218 }
4219
4220 $num_starred = getFeedUnread($link, -1);
4221 $num_published = getFeedUnread($link, -2);
4222 $num_fresh = getFeedUnread($link, -3);
4223
4224 $class = "virt";
4225
4226 if ($num_fresh > 0) $class .= "Unread";
4227
4228 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4229 "images/fresh.png", $link);
4230
4231 $class = "virt";
4232
4233 if ($num_starred > 0) $class .= "Unread";
4234
4235 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4236
4237 if ($is_ie) {
4238 $mark_img_ext = "gif";
4239 } else {
4240 $mark_img_ext = "png";
4241 }
4242
4243 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4244 "images/mark_set.$mark_img_ext", $link);
4245
4246 $class = "virt";
4247
4248 if ($num_published > 0) $class .= "Unread";
4249
4250 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4251 "images/pub_set.gif", $link);
4252
4253 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4254 print "</ul></li>";
4255 }
4256
4257 if (!$tags) {
4258
4259 if (GLOBAL_ENABLE_LABELS && get_pref($link, 'ENABLE_LABELS')) {
4260
4261 $result = db_query($link, "SELECT id,sql_exp,description FROM
4262 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
4263
4264 if (db_num_rows($result) > 0) {
4265 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4266
4267 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4268 $cat_hidden = true;
4269 } else {
4270 $cat_hidden = false;
4271 }
4272
4273 printCategoryHeader($link, -2, $cat_hidden, false);
4274
4275 } else {
4276 print "<li><hr></li>";
4277 }
4278 }
4279
4280 while ($line = db_fetch_assoc($result)) {
4281
4282 error_reporting (0);
4283
4284 $label_id = -$line['id'] - 11;
4285 $count = getFeedUnread($link, $label_id);
4286
4287 $class = "label";
4288
4289 if ($count > 0) {
4290 $class .= "Unread";
4291 }
4292
4293 error_reporting (DEFAULT_ERROR_LEVEL);
4294
4295 printFeedEntry($label_id,
4296 $class, $line["description"],
4297 $count, "images/label.png", $link);
4298
4299 }
4300
4301 if (db_num_rows($result) > 0) {
4302 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4303 print "</ul>";
4304 }
4305 }
4306
4307 }
4308
4309 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4310 print "<li><hr></li>";
4311 }
4312
4313 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4314 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4315 $order_by_qpart = "order_id,category,unread DESC,title";
4316 } else {
4317 $order_by_qpart = "order_id,category,title";
4318 }
4319 } else {
4320 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4321 $order_by_qpart = "unread DESC,title";
4322 } else {
4323 $order_by_qpart = "title";
4324 }
4325 }
4326
4327 $age_qpart = getMaxAgeSubquery();
4328
4329 $query = "SELECT ttrss_feeds.*,
4330 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4331 cat_id,last_error,
4332 ttrss_feed_categories.title AS category,
4333 ttrss_feed_categories.collapsed
4334 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4335 ON (ttrss_feed_categories.id = cat_id)
4336 WHERE
4337 ttrss_feeds.hidden = false AND
4338 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4339 ORDER BY $order_by_qpart";
4340
4341 $result = db_query($link, $query);
4342
4343 $actid = $_GET["actid"];
4344
4345 /* real feeds */
4346
4347 $lnum = 0;
4348
4349 $total_unread = 0;
4350
4351 $category = "";
4352
4353 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4354
4355 while ($line = db_fetch_assoc($result)) {
4356
4357 $feed = trim($line["title"]);
4358
4359 if (!$feed) $feed = "[Untitled]";
4360
4361 $feed_id = $line["id"];
4362
4363 $subop = $_GET["subop"];
4364
4365 $unread = ccache_find($link, $feed_id, $_SESSION["uid"]);
4366
4367 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4368 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4369 } else {
4370 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4371 }
4372
4373 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4374
4375 if ($rtl_content) {
4376 $rtl_tag = "dir=\"RTL\"";
4377 } else {
4378 $rtl_tag = "";
4379 }
4380
4381 $tmp_result = db_query($link,
4382 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4383 WHERE parent_feed = '$feed_id' AND feed_id = id");
4384
4385 $unread += db_fetch_result($tmp_result, 0, "unread");
4386
4387 $cat_id = $line["cat_id"];
4388
4389 $tmp_category = $line["category"];
4390
4391 if (!$tmp_category) {
4392 $tmp_category = __("Uncategorized");
4393 }
4394
4395 // $class = ($lnum % 2) ? "even" : "odd";
4396
4397 if ($line["last_error"]) {
4398 $class = "error";
4399 } else {
4400 $class = "feed";
4401 }
4402
4403 if ($unread > 0) $class .= "Unread";
4404
4405 if ($actid == $feed_id) {
4406 $class .= "Selected";
4407 }
4408
4409 $total_unread += $unread;
4410
4411 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4412
4413 if ($category) {
4414 print "</ul></li>";
4415 }
4416
4417 $category = $tmp_category;
4418
4419 $collapsed = sql_bool_to_bool($line["collapsed"]);
4420
4421 // workaround for NULL category
4422 if ($category == __("Uncategorized")) {
4423 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4424 $collapsed = "t";
4425 }
4426 }
4427
4428 $cat_id = sprintf("%d", $cat_id);
4429
4430 printCategoryHeader($link, $cat_id, $collapsed, true);
4431
4432 }
4433
4434 printFeedEntry($feed_id, $class, $feed, $unread,
4435 ICONS_URL."/$feed_id.ico", $link, $rtl_content,
4436 $last_updated, $line["last_error"]);
4437
4438 ++$lnum;
4439 }
4440
4441 if (db_num_rows($result) == 0) {
4442 print "<li>".__('No feeds to display.')."</li>";
4443 }
4444
4445 } else {
4446
4447 // tags
4448
4449 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4450 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4451 post_int_id = ttrss_user_entries.int_id AND
4452 unread = true AND ref_id = ttrss_entries.id
4453 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4454 UNION
4455 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4456 ORDER BY tag_name"); */
4457
4458 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4459 print "<li class=\"feedCat\">".__('Tags')."</li>";
4460 print "<ul class=\"feedCatList\">";
4461 }
4462
4463 $age_qpart = getMaxAgeSubquery();
4464
4465 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4466 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4467 AND ref_id = id AND $age_qpart
4468 AND unread = true)) AS count FROM ttrss_tags
4469 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4470 ORDER BY count DESC LIMIT 50");
4471
4472 $tags = array();
4473
4474 while ($line = db_fetch_assoc($result)) {
4475 $tags[$line["tag_name"]] += $line["count"];
4476 }
4477
4478 foreach (array_keys($tags) as $tag) {
4479
4480 $unread = $tags[$tag];
4481
4482 $class = "tag";
4483
4484 if ($unread > 0) {
4485 $class .= "Unread";
4486 }
4487
4488 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4489
4490 }
4491
4492 if (db_num_rows($result) == 0) {
4493 print "<li>No tags to display.</li>";
4494 }
4495
4496 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4497 print "</ul>";
4498 }
4499
4500 }
4501
4502 print "</ul>";
4503
4504 }
4505
4506 function get_article_tags($link, $id, $owner_uid = 0) {
4507
4508 $a_id = db_escape_string($id);
4509
4510 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4511
4512 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4513 owner_uid as owner FROM
4514 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4515 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4516
4517 $tags = array();
4518
4519 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4520 array_push($tags, $tmp_line["tag_name"]);
4521 }
4522
4523 return $tags;
4524 }
4525
4526 function trim_value(&$value) {
4527 $value = trim($value);
4528 }
4529
4530 function trim_array($array) {
4531 $tmp = $array;
4532 array_walk($tmp, 'trim_value');
4533 return $tmp;
4534 }
4535
4536 function tag_is_valid($tag) {
4537 if ($tag == '') return false;
4538 if (preg_match("/^[0-9]*$/", $tag)) return false;
4539
4540 if (function_exists('iconv')) {
4541 $tag = iconv("utf-8", "utf-8", $tag);
4542 }
4543
4544 if (!$tag) return false;
4545
4546 return true;
4547 }
4548
4549 function render_login_form($link, $mobile = false) {
4550 if (!$mobile) {
4551 require_once "login_form.php";
4552 } else {
4553 require_once "mobile/login_form.php";
4554 }
4555 }
4556
4557 // from http://developer.apple.com/internet/safari/faq.html
4558 function no_cache_incantation() {
4559 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4560 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4561 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4562 header("Cache-Control: post-check=0, pre-check=0", false);
4563 header("Pragma: no-cache"); // HTTP/1.0
4564 }
4565
4566 function format_warning($msg, $id = "") {
4567 return "<div class=\"warning\" id=\"$id\">
4568 <img src=\"images/sign_excl.gif\">$msg</div>";
4569 }
4570
4571 function format_notice($msg) {
4572 return "<div class=\"notice\">
4573 <img src=\"images/sign_info.gif\">$msg</div>";
4574 }
4575
4576 function format_error($msg) {
4577 return "<div class=\"error\">
4578 <img src=\"images/sign_excl.gif\">$msg</div>";
4579 }
4580
4581 function print_notice($msg) {
4582 return print format_notice($msg);
4583 }
4584
4585 function print_warning($msg) {
4586 return print format_warning($msg);
4587 }
4588
4589 function print_error($msg) {
4590 return print format_error($msg);
4591 }
4592
4593
4594 function T_sprintf() {
4595 $args = func_get_args();
4596 return vsprintf(__(array_shift($args)), $args);
4597 }
4598
4599 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4600 $zoom_mode = false) {
4601
4602 /* we can figure out feed_id from article id anyway, why do we
4603 * pass feed_id here? */
4604
4605 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4606 WHERE ref_id = '$id'");
4607
4608 $feed_id = db_fetch_result($result, 0, "feed_id");
4609
4610 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4611
4612 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4613 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4614
4615 if (db_num_rows($result) == 1) {
4616 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4617 } else {
4618 $rtl_content = false;
4619 }
4620
4621 if ($rtl_content) {
4622 $rtl_tag = "dir=\"RTL\"";
4623 $rtl_class = "RTL";
4624 } else {
4625 $rtl_tag = "";
4626 $rtl_class = "";
4627 }
4628
4629 if ($mark_as_read) {
4630 $result = db_query($link, "UPDATE ttrss_user_entries
4631 SET unread = false,last_read = NOW()
4632 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4633
4634 ccache_update($link, $feed_id, $_SESSION["uid"]);
4635 }
4636
4637 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4638 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
4639 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4640 num_comments,
4641 author
4642 FROM ttrss_entries,ttrss_user_entries
4643 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4644
4645 if ($result) {
4646
4647 $link_target = "";
4648
4649 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4650 $link_target = "target=\"_blank\"";
4651 }
4652
4653 $line = db_fetch_assoc($result);
4654
4655 if ($line["icon_url"]) {
4656 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4657 } else {
4658 $feed_icon = "&nbsp;";
4659 }
4660
4661 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
4662 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4663 } else {
4664 $entry_comments = "";
4665 } */
4666
4667 $num_comments = $line["num_comments"];
4668 $entry_comments = "";
4669
4670 if ($num_comments > 0) {
4671 if ($line["comments"]) {
4672 $comments_url = $line["comments"];
4673 } else {
4674 $comments_url = $line["link"];
4675 }
4676 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4677 } else {
4678 if ($line["comments"] && $line["link"] != $line["comments"]) {
4679 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4680 }
4681 }
4682
4683 if ($zoom_mode) {
4684 header("Content-Type: text/html");
4685 print "<html><head>
4686 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4687 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4688 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4689 </head><body>";
4690 }
4691
4692
4693 print "<div class=\"postReply\">";
4694
4695 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4696 onmouseout=\"enable_resize(false)\">";
4697
4698 $entry_author = $line["author"];
4699
4700 if ($entry_author) {
4701 $entry_author = __(" - ") . $entry_author;
4702 }
4703
4704 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4705 strtotime($line["updated"]));
4706
4707 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4708
4709 if ($line["link"]) {
4710 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4711 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4712 } else {
4713 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4714 }
4715
4716 /* $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4717 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4718 ORDER BY tag_name"); */
4719
4720 $tags = get_article_tags($link, $id);
4721
4722 $tags_str = "";
4723 $tags_nolinks_str = "";
4724 $f_tags_str = "";
4725
4726 $num_tags = 0;
4727
4728 if ($_SESSION["theme"] == "3pane") {
4729 $tag_limit = 3;
4730 } else {
4731 $tag_limit = 6;
4732 }
4733
4734 foreach ($tags as $tag) {
4735 $num_tags++;
4736 $tag_escaped = str_replace("'", "\\'", $tag);
4737
4738 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4739
4740 if ($num_tags == $tag_limit) {
4741 $tags_str .= "&hellip;";
4742 $tags_nolinks_str .= "&hellip;";
4743
4744 } else if ($num_tags < $tag_limit) {
4745 $tags_str .= $tag_str;
4746 $tags_nolinks_str .= "$tag, ";
4747 }
4748 $f_tags_str .= $tag_str;
4749 }
4750
4751 $tags_str = preg_replace("/, $/", "", $tags_str);
4752 $tags_nolinks_str = preg_replace("/, $/", "", $tags_nolinks_str);
4753 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4754
4755 $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4756 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4757
4758 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4759
4760 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4761 if (!$tags_nolinks_str) $tags_nolinks_str = '<span class="tagList">'.__('no tags').'</span>';
4762
4763 print "<div style='float : right'>
4764 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4765
4766 if (!$zoom_mode) {
4767 print "$tags_str
4768 <a title=\"".__('Edit tags for this article')."\"
4769 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4770
4771 if (defined('_ENABLE_INLINE_VIEW')) {
4772
4773 print "<img src=\"images/art-inline.png\" class='tagsPic'
4774 style=\"cursor : pointer\" style=\"cursor : pointer\"
4775 onclick=\"showOriginalArticleInline($id)\"
4776 alt='Inline' title='".__('Display original article content')."'>";
4777
4778 }
4779
4780 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4781 style=\"cursor : pointer\" style=\"cursor : pointer\"
4782 onclick=\"zoomToArticle($id)\"
4783 alt='Zoom' title='".__('Show article summary in new window')."'>";
4784 } else {
4785 print "$tags_nolinks_str";
4786 }
4787 print "</div>";
4788 print "<div clear='both'>$entry_comments</div>";
4789
4790 print "</div>";
4791
4792 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4793 print "<div class=\"postContent\">";
4794
4795 #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4796
4797 $article_content = sanitize_rss($link, $line["content"]);
4798
4799 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4800 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4801 $article_content);
4802 }
4803
4804 print $article_content;
4805
4806 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4807 post_id = '$id' AND content_url != ''");
4808
4809 if (db_num_rows($result) > 0) {
4810
4811 $entries_html = array();
4812 $entries = array();
4813
4814 while ($line = db_fetch_assoc($result)) {
4815
4816 $url = $line["content_url"];
4817 $ctype = $line["content_type"];
4818
4819 if (!$ctype) $ctype = __("unknown type");
4820
4821 $filename = substr($url, strrpos($url, "/")+1);
4822
4823 $entry = "";
4824
4825 if (($ctype == __("audio/mpeg")) &&
4826 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4827
4828 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
4829
4830 }
4831
4832 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4833 $filename . " (" . $ctype . ")" . "</a>";
4834
4835 array_push($entries_html, $entry);
4836
4837 $entry = array();
4838
4839 $entry["type"] = $ctype;
4840 $entry["filename"] = $filename;
4841 $entry["url"] = $url;
4842
4843 array_push($entries, $entry);
4844 }
4845
4846 print "<div class=\"postEnclosures\">";
4847
4848 if (!preg_match("/img/i", $article_content)) {
4849 foreach ($entries as $entry) {
4850 if (preg_match("/image/", $entry["type"])) {
4851 print "<p><img
4852 alt=\"".htmlspecialchars($entry["filename"])."\"
4853 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4854 }
4855 }
4856 }
4857
4858 print "<div class=\"postEnclosures\">";
4859
4860 if (db_num_rows($result) == 1) {
4861 print __("Attachment:") . " ";
4862 } else {
4863 print __("Attachments:") . " ";
4864 }
4865
4866 print join(", ", $entries_html);
4867
4868 print "</div>";
4869 }
4870
4871 print "</div>";
4872
4873 print "</div>";
4874
4875 }
4876
4877 if (!$zoom_mode) {
4878 print "]]></article>";
4879 } else {
4880 print "
4881 <div style=\"text-align : center\">
4882 <input type=\"submit\" onclick=\"return window.close()\"
4883 value=\"".__("Close this window")."\"></div>";
4884 print "</body></html>";
4885
4886 }
4887
4888 }
4889
4890 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4891 $next_unread_feed, $offset, $vgr_last_feed = false,
4892 $override_order = false) {
4893
4894 $disable_cache = false;
4895
4896 $timing_info = getmicrotime();
4897
4898 $topmost_article_ids = array();
4899
4900 if (!$offset) {
4901 $offset = 0;
4902 }
4903
4904 if ($subop == "undefined") $subop = "";
4905
4906 $subop_split = split(":", $subop);
4907
4908 if ($subop == "CatchupSelected") {
4909 $ids = split(",", db_escape_string($_GET["ids"]));
4910 $cmode = sprintf("%d", $_GET["cmode"]);
4911
4912 catchupArticlesById($link, $ids, $cmode);
4913 }
4914
4915 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4916 update_generic_feed($link, $feed, $cat_view, true);
4917 }
4918
4919 if ($subop == "MarkAllRead") {
4920 catchup_feed($link, $feed, $cat_view);
4921
4922 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4923 if ($next_unread_feed) {
4924 $feed = $next_unread_feed;
4925 }
4926 }
4927 }
4928
4929 if ($subop_split[0] == "MarkAllReadGR") {
4930 catchup_feed($link, $subop_split[1], false);
4931 }
4932
4933
4934 if ($feed_id > 0) {
4935 $result = db_query($link,
4936 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4937
4938 if (db_num_rows($result) == 0) {
4939 print "<div align='center'>".__('Feed not found.')."</div>";
4940 return;
4941 }
4942 }
4943
4944 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4945
4946 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4947 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4948
4949 if (db_num_rows($result) == 1) {
4950 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4951 } else {
4952 $rtl_content = false;
4953 }
4954
4955 if ($rtl_content) {
4956 $rtl_tag = "dir=\"RTL\"";
4957 } else {
4958 $rtl_tag = "";
4959 }
4960 } else {
4961 $rtl_tag = "";
4962 $rtl_content = false;
4963 }
4964
4965 $script_dt_add = get_script_dt_add();
4966
4967 /// START /////////////////////////////////////////////////////////////////////////////////
4968
4969 $search = db_escape_string($_GET["query"]);
4970
4971 if ($search) {
4972 $disable_cache = true;
4973 }
4974
4975 $search_mode = db_escape_string($_GET["search_mode"]);
4976 $match_on = db_escape_string($_GET["match_on"]);
4977
4978 if (!$match_on) {
4979 $match_on = "both";
4980 }
4981
4982 $real_offset = $offset * $limit;
4983
4984 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4985
4986 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4987 $search, $search_mode, $match_on, $override_order, $real_offset);
4988
4989 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4990
4991 $result = $qfh_ret[0];
4992 $feed_title = $qfh_ret[1];
4993 $feed_site_url = $qfh_ret[2];
4994 $last_error = $qfh_ret[3];
4995
4996 $vgroup_last_feed = $vgr_last_feed;
4997
4998 if ($feed == -2) {
4999 $feed_site_url = article_publish_url($link);
5000 }
5001
5002 /// STOP //////////////////////////////////////////////////////////////////////////////////
5003
5004 if (!$offset) {
5005 print "<div id=\"headlinesContainer\" $rtl_tag>";
5006
5007 if (!$result) {
5008 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
5009 return;
5010 }
5011
5012 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
5013 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
5014 $offset, $limit);
5015
5016 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
5017 }
5018
5019 $headlines_count = db_num_rows($result);
5020
5021 if (db_num_rows($result) > 0) {
5022
5023 # print "\{$offset}";
5024
5025 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5026 print "<table class=\"headlinesList\" id=\"headlinesList\"
5027 cellspacing=\"0\">";
5028 }
5029
5030 $lnum = $limit*$offset;
5031
5032 error_reporting (DEFAULT_ERROR_LEVEL);
5033
5034 $num_unread = 0;
5035 $cur_feed_title = '';
5036
5037 while ($line = db_fetch_assoc($result)) {
5038
5039 $class = ($lnum % 2) ? "even" : "odd";
5040
5041 $id = $line["id"];
5042 $feed_id = $line["feed_id"];
5043
5044 if (count($topmost_article_ids) < 5) {
5045 array_push($topmost_article_ids, $id);
5046 }
5047
5048 if ($line["last_read"] == "" &&
5049 ($line["unread"] != "t" && $line["unread"] != "1")) {
5050
5051 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
5052 alt=\"Updated\">";
5053 } else {
5054 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5055 alt=\"Updated\">";
5056 }
5057
5058 if ($line["unread"] == "t" || $line["unread"] == "1") {
5059 $class .= "Unread";
5060 ++$num_unread;
5061 $is_unread = true;
5062 } else {
5063 $is_unread = false;
5064 }
5065
5066 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
5067
5068 if ($is_ie) {
5069 $mark_img_ext = "gif";
5070 } else {
5071 $mark_img_ext = "png";
5072 }
5073
5074 if ($line["marked"] == "t" || $line["marked"] == "1") {
5075 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
5076 class=\"markedPic\"
5077 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
5078 } else {
5079 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
5080 class=\"markedPic\"
5081 alt=\"Star article\" onclick='javascript:tMark($id)'>";
5082 }
5083
5084 if ($line["published"] == "t" || $line["published"] == "1") {
5085 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
5086 class=\"markedPic\"
5087 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5088 } else {
5089 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
5090 class=\"markedPic\"
5091 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5092 }
5093
5094 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5095 # $line["title"] . "</a>";
5096
5097 # $content_link = "<a
5098 # href=\"" . htmlspecialchars($line["link"]) . "\"
5099 # onclick=\"view($id,$feed_id);\">" .
5100 # $line["title"] . "</a>";
5101
5102 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5103 # $line["title"] . "</a>";
5104
5105 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5106 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5107 } else {
5108 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5109 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5110 }
5111
5112 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5113 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5114 100);
5115 }
5116
5117 $score = $line["score"];
5118
5119 $score_pic = get_score_pic($score);
5120
5121 $score_title = __("(Click to change)");
5122
5123 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5124 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">";
5125
5126 if ($score > 500) {
5127 $hlc_suffix = "H";
5128 } else if ($score < -100) {
5129 $hlc_suffix = "L";
5130 } else {
5131 $hlc_suffix = "";
5132 }
5133
5134 $entry_author = $line["author"];
5135
5136 if ($entry_author) {
5137 $entry_author = " - $entry_author";
5138 }
5139
5140 $has_feed_icon = feed_has_icon($feed_id);
5141
5142 if ($has_feed_icon) {
5143 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5144 } else {
5145 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5146 $feed_icon_img = "";
5147 }
5148
5149 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5150
5151 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5152 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5153
5154 $cur_feed_title = $line["feed_title"];
5155 $vgroup_last_feed = $feed_id;
5156
5157 $cur_feed_title = htmlspecialchars($cur_feed_title);
5158
5159 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5160
5161 print "<tr class='feedTitle'><td colspan='7'>".
5162 "<div style=\"float : right\">$feed_icon_img</div>".
5163 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5164 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5165 }
5166 }
5167
5168 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5169 onmouseout='postMouseOut($id)'";
5170
5171 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5172
5173 print "<td class='hlUpdPic'>$update_pic</td>";
5174
5175 print "<td class='hlSelectRow'>
5176 <input type=\"checkbox\" onclick=\"tSR(this)\"
5177 id=\"RCHK-$id\">
5178 </td>";
5179
5180 print "<td class='hlMarkedPic'>$marked_pic</td>";
5181 print "<td class='hlMarkedPic'>$published_pic</td>";
5182
5183 # if ($line["feed_title"]) {
5184 # print "<td class='hlContent'>$content_link</td>";
5185 # print "<td class='hlFeed'>
5186 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5187 # truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
5188 # } else {
5189
5190 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5191
5192 print "<a id=\"RTITLE-$id\"
5193 href=\"" . htmlspecialchars($line["link"]) . "\"
5194 onclick=\"return view($id,$feed_id);\">" .
5195 $line["title"];
5196
5197 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5198 if ($content_preview) {
5199 print "<span class=\"contentPreview\"> - $content_preview</span>";
5200 }
5201 }
5202
5203 print "</a>";
5204
5205 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5206 # $line["feed_title"]."</a>
5207
5208 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5209 if ($line["feed_title"]) {
5210 print "<span class=\"hlFeed\">
5211 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5212 $line["feed_title"]."</a>)
5213 </span>";
5214 }
5215 }
5216 print "</td>";
5217
5218 # }
5219
5220 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt&nbsp;</nobr></td>";
5221
5222 print "<td class='hlMarkedPic'>$score_pic</td>";
5223
5224 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5225 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5226 }
5227
5228 print "</tr>";
5229
5230 } else {
5231
5232 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5233 if ($feed_id != $vgroup_last_feed) {
5234
5235 $cur_feed_title = $line["feed_title"];
5236 $vgroup_last_feed = $feed_id;
5237
5238 $cur_feed_title = htmlspecialchars($cur_feed_title);
5239
5240 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5241
5242 $has_feed_icon = feed_has_icon($feed_id);
5243
5244 if ($has_feed_icon) {
5245 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5246 } else {
5247 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5248 }
5249
5250 print "<div class='cdmFeedTitle'>".
5251 "<div style=\"float : right\">$feed_icon_img</div>".
5252 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5253 $line["feed_title"]."</a> $vf_catchup_link</div>";
5254 }
5255 }
5256
5257 if ($is_unread) {
5258 $add_class = "Unread";
5259 } else {
5260 $add_class = "";
5261 }
5262
5263 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5264 $show_excerpt = false;
5265
5266 if ($expand_cdm && $score >= -100) {
5267 $cdm_cstyle = "";
5268 $show_excerpt = false;
5269 } else {
5270 $cdm_cstyle = "style=\"display : none\"";
5271 $show_excerpt = true;
5272 }
5273
5274 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5275 onmouseout='postMouseOut($id)'";
5276
5277 print "<div class=\"cdmArticle$add_class\"
5278 id=\"RROW-$id\"
5279 $mouseover_attrs'>";
5280
5281 print "<div class=\"cdmHeader\">";
5282
5283 if (!get_pref($link, "VFEED_GROUP_BY_FEED") || !$line["feed_title"]) {
5284 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5285 }
5286
5287 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5288 </div>";
5289
5290 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5291 onclick=\"javascript:toggleUnread($id, 0)\"
5292 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5293 ";
5294
5295 print $entry_author;
5296
5297 /* if (!$expand_cdm || $score < -100) {
5298 print "&nbsp;<a id=\"CICH-$id\"
5299 href=\"javascript:cdmExpandArticle($id)\">
5300 (".__('Show article').")</a>";
5301 } */
5302
5303
5304 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5305 if ($line["feed_title"]) {
5306 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5307 }
5308 }
5309
5310 print "</span></div>";
5311
5312 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5313 $line["content_preview"] = preg_replace("/href=/i",
5314 "target=\"_blank\" href=", $line["content_preview"]);
5315 }
5316
5317 if ($show_excerpt) {
5318 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5319 onclick=\"cdmExpandArticle($id)\"
5320 title=\"".__('Click to expand article')."\">";
5321 print truncate_string(strip_tags($line["content_preview"]), 100);
5322 print "</div>";
5323 }
5324
5325 print "<div class=\"cdmContent\"
5326 onclick=\"cdmClicked($id)\"
5327 id=\"CICD-$id\" $cdm_cstyle>";
5328
5329 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5330
5331 print sanitize_rss($link, $line["content_preview"]);
5332 $article_content = $line["content_preview"];
5333
5334 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5335 post_id = '$id' AND content_url != ''");
5336
5337 if (db_num_rows($e_result) > 0) {
5338
5339 $entries_html = array();
5340 $entries = array();
5341
5342 while ($e_line = db_fetch_assoc($e_result)) {
5343
5344 $url = $e_line["content_url"];
5345 $ctype = $e_line["content_type"];
5346 if (!$ctype) $ctype = __("unknown type");
5347
5348 $filename = substr($url, strrpos($url, "/")+1);
5349
5350 $entry = "";
5351
5352 if (($ctype == __("audio/mpeg")) &&
5353 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5354
5355 $entry .= "<object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object> ";
5356
5357 }
5358
5359 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5360 $filename . " (" . $ctype . ")" . "</a>";
5361
5362 array_push($entries_html, $entry);
5363
5364 $entry = array();
5365
5366 $entry["type"] = $ctype;
5367 $entry["filename"] = $filename;
5368 $entry["url"] = $url;
5369
5370 array_push($entries, $entry);
5371 }
5372
5373 if (!preg_match("/img/i", $article_content)) {
5374 foreach ($entries as $entry) {
5375 if (preg_match("/image/", $entry["type"])) {
5376 print "<p><img
5377 alt=\"".htmlspecialchars($entry["filename"])."\"
5378 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5379 }
5380 }
5381 }
5382
5383 print "<div class=\"cdmEnclosures\">";
5384
5385 if (db_num_rows($e_result) == 1) {
5386 print __("Attachment:") . " ";
5387 } else {
5388 print __("Attachments:") . " ";
5389 }
5390
5391 print join(", ", $entries_html);
5392
5393 print "</div>";
5394 }
5395
5396
5397 print "<br clear='both'>";
5398 // print "</div>";
5399
5400 /* if (!$expand_cdm) {
5401 print "<a id=\"CICH-$id\"
5402 href=\"javascript:cdmExpandArticle($id)\">
5403 Show article</a>";
5404 } */
5405
5406 print "</div>";
5407
5408 print "<div class=\"cdmFooter\"><span class='s0'>";
5409
5410 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5411
5412 print __("Select:").
5413 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5414 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5415
5416 print "</span><span class='s1'>$marked_pic</span> ";
5417 print "<span class='s1'>$published_pic</span> ";
5418 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5419 onclick=\"zoomToArticle($id)\"
5420 style=\"cursor : pointer\"
5421 alt='Zoom'
5422 title='".__('Show article summary in new window')."'></span>";
5423
5424 $tags = get_article_tags($link, $id);
5425
5426 $tags_str = "";
5427 $full_tags_str = "";
5428 $num_tags = 0;
5429
5430 foreach ($tags as $tag) {
5431 $num_tags++;
5432 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5433 if ($num_tags < 5) {
5434 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
5435 } else if ($num_tags == 5) {
5436 $tags_str .= "&hellip;";
5437 }
5438 }
5439
5440 $tags_str = preg_replace("/, $/", "", $tags_str);
5441 $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
5442
5443 $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
5444
5445 $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
5446
5447
5448 if ($tags_str == "") $tags_str = "no tags";
5449
5450 // print "<img src='images/tag.png' class='markedPic'>";
5451
5452 print "<span class='s1'>
5453 <img class='tagsPic' src='images/tag.png' alt='Tags'
5454 title='Tags'> $tags_str <a title=\"Edit tags for this article\"
5455 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5456
5457 print "</span>";
5458
5459 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5460 href=\"javascript:toggleUnread($id)\">
5461 Unread</a></span>";
5462
5463 print "</div>";
5464 print "</div>";
5465
5466 }
5467
5468 ++$lnum;
5469 }
5470
5471 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5472 print "</table>";
5473 }
5474
5475 // print_headline_subtoolbar($link,
5476 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
5477
5478
5479 } else {
5480 $message = "";
5481
5482 switch ($view_mode) {
5483 case "unread":
5484 $message = __("No unread articles found to display.");
5485 break;
5486 case "marked":
5487 $message = __("No starred articles found to display.");
5488 break;
5489 default:
5490 $message = __("No articles found to display.");
5491 }
5492
5493 if (!$offset) print "<div class='whiteBox'>$message</div>";
5494 }
5495
5496 if (!$offset) {
5497 print "</div>";
5498 print "</div>";
5499 }
5500
5501 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5502 }
5503
5504 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5505
5506 function printTagCloud($link) {
5507
5508 /* get first ref_id to count from */
5509
5510 /*
5511
5512 $query = "";
5513
5514 if (DB_TYPE == "pgsql") {
5515 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5516 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5517 AND date_entered > NOW() - INTERVAL '30 days'";
5518 } else {
5519 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
5520 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5521 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5522 }
5523
5524 $result = db_query($link, $query);
5525 $first_id = db_fetch_result($result, 0, "id"); */
5526
5527 //AND post_int_id >= '$first_id'
5528 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5529 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5530 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5531
5532 $result = db_query($link, $query);
5533
5534 $tags = array();
5535
5536 while ($line = db_fetch_assoc($result)) {
5537 $tags[$line["tag_name"]] = $line["count"];
5538 }
5539
5540 ksort($tags);
5541
5542 $max_size = 32; // max font size in pixels
5543 $min_size = 11; // min font size in pixels
5544
5545 // largest and smallest array values
5546 $max_qty = max(array_values($tags));
5547 $min_qty = min(array_values($tags));
5548
5549 // find the range of values
5550 $spread = $max_qty - $min_qty;
5551 if ($spread == 0) { // we don't want to divide by zero
5552 $spread = 1;
5553 }
5554
5555 // set the font-size increment
5556 $step = ($max_size - $min_size) / ($spread);
5557
5558 // loop through the tag array
5559 foreach ($tags as $key => $value) {
5560 // calculate font-size
5561 // find the $value in excess of $min_qty
5562 // multiply by the font-size increment ($size)
5563 // and add the $min_size set above
5564 $size = round($min_size + (($value - $min_qty) * $step));
5565
5566 $key_escaped = str_replace("'", "\\'", $key);
5567
5568 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5569 $size . "px\" title=\"$value articles tagged with " .
5570 $key . '">' . $key . '</a> ';
5571 }
5572 }
5573
5574 function print_checkpoint($n, $s) {
5575 $ts = getmicrotime();
5576 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5577 return $ts;
5578 }
5579
5580 function sanitize_tag($tag) {
5581 $tag = trim($tag);
5582
5583 $tag = mb_strtolower($tag, 'utf-8');
5584
5585 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5586
5587 // $tag = str_replace('"', "", $tag);
5588 // $tag = str_replace("+", " ", $tag);
5589 $tag = str_replace("technorati tag: ", "", $tag);
5590
5591 return $tag;
5592 }
5593
5594 function generate_publish_key() {
5595 return sha1(uniqid(rand(), true));
5596 }
5597
5598 function article_publish_url($link) {
5599
5600 $url_path = "";
5601
5602
5603 if ($_SERVER['HTTPS'] != "on") {
5604 $url_path = "http://";
5605 } else {
5606 $url_path = "https://";
5607 }
5608
5609 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5610 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5611
5612 return $url_path;
5613 }
5614
5615 /**
5616 * Purge a feed contents, marked articles excepted.
5617 *
5618 * @param mixed $link The database connection.
5619 * @param integer $id The id of the feed to purge.
5620 * @return void
5621 */
5622 function clear_feed_articles($link, $id) {
5623 $result = db_query($link, "DELETE FROM ttrss_user_entries
5624 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5625
5626 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5627 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5628
5629 ccache_update($link, $id, $_SESSION['uid']);
5630 } // function clear_feed_articles
5631
5632 /**
5633 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5634 *
5635 * @return string The Mozilla Firefox feed adding URL.
5636 */
5637 function add_feed_url() {
5638 $url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5639 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5640 return $url_path;
5641 } // function add_feed_url
5642
5643 /**
5644 * Encrypt a password in SHA1.
5645 *
5646 * @param string $pass The password to encrypt.
5647 * @param string $login A optionnal login.
5648 * @return string The encrypted password.
5649 */
5650 function encrypt_password($pass, $login = '') {
5651 if ($login) {
5652 return "SHA1X:" . sha1("$login:$pass");
5653 } else {
5654 return "SHA1:" . sha1($pass);
5655 }
5656 } // function encrypt_password
5657
5658 /**
5659 * Update a feed batch.
5660 * Used by daemons to update n feeds by run.
5661 * Only update feed needing a update, and not being processed
5662 * by another process.
5663 *
5664 * @param mixed $link Database link
5665 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5666 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5667 * @param boolean $debug Set to false to disable debug output. Default to true.
5668 * @return void
5669 */
5670 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5671 // Process all other feeds using last_updated and interval parameters
5672
5673 // Test if the user has loggued in recently. If not, it does not update its feeds.
5674 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5675 if (DB_TYPE == "pgsql") {
5676 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5677 } else {
5678 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5679 }
5680 } else {
5681 $login_thresh_qpart = "";
5682 }
5683
5684 // Test if the feed need a update (update interval exceded).
5685 if (DB_TYPE == "pgsql") {
5686 $update_limit_qpart = "AND ((
5687 ttrss_feeds.update_interval = 0
5688 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5689 ) OR (
5690 ttrss_feeds.update_interval > 0
5691 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5692 ) OR ttrss_feeds.last_updated IS NULL)";
5693 } else {
5694 $update_limit_qpart = "AND ((
5695 ttrss_feeds.update_interval = 0
5696 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5697 ) OR (
5698 ttrss_feeds.update_interval > 0
5699 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5700 ) OR ttrss_feeds.last_updated IS NULL)";
5701 }
5702
5703 // Test if feed is currently being updated by another process.
5704 if (DB_TYPE == "pgsql") {
5705 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5706 } else {
5707 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5708 }
5709
5710 // Test if there is a limit to number of updated feeds
5711 $query_limit = "";
5712 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5713
5714 $random_qpart = sql_random_function();
5715
5716 // We search for feed needing update.
5717 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5718 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5719 ttrss_feeds.update_interval
5720 FROM
5721 ttrss_feeds, ttrss_users, ttrss_user_prefs
5722 WHERE
5723 ttrss_feeds.owner_uid = ttrss_users.id
5724 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5725 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5726 $login_thresh_qpart $update_limit_qpart
5727 $updstart_thresh_qpart
5728 ORDER BY $random_qpart $query_limit");
5729
5730 $user_prefs_cache = array();
5731
5732 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5733
5734 // Here is a little cache magic in order to minimize risk of double feed updates.
5735 $feeds_to_update = array();
5736 while ($line = db_fetch_assoc($result)) {
5737 $feeds_to_update[$line['id']] = $line;
5738 }
5739
5740 // We update the feed last update started date before anything else.
5741 // There is no lag due to feed contents downloads
5742 // It prevent an other process to update the same feed.
5743 $feed_ids = array_keys($feeds_to_update);
5744 if($feed_ids) {
5745 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5746 WHERE id IN (%s)", implode(',', $feed_ids)));
5747 }
5748
5749 // For each feed, we call the feed update function.
5750 while ($line = array_pop($feeds_to_update)) {
5751
5752 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5753
5754 // We setup a alarm to alert if the feed take more than 300s to update.
5755 // => HANG alarm.
5756 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5757 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5758 // Cancel the alarm (the update went well)
5759 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5760
5761 sleep(1); // prevent flood (FIXME make this an option?)
5762 }
5763
5764 // Send feed digests by email if needed.
5765 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5766
5767 } // function update_daemon_common
5768
5769 function sanitize_article_content($text) {
5770 # we don't support CDATA sections in articles, they break our own escaping
5771 $text = preg_replace("/\[\[CDATA/", "", $text);
5772 $text = preg_replace("/\]\]\>/", "", $text);
5773 return $text;
5774 }
5775
5776 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5777 $filters = array();
5778
5779 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5780
5781 $result = db_query($link, "SELECT reg_exp,
5782 ttrss_filter_types.name AS name,
5783 ttrss_filter_actions.name AS action,
5784 inverse,
5785 action_param,
5786 filter_param
5787 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5788 enabled = true AND
5789 $ftype_query_part
5790 owner_uid = $owner_uid AND
5791 ttrss_filter_types.id = filter_type AND
5792 ttrss_filter_actions.id = action_id AND
5793 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5794
5795 while ($line = db_fetch_assoc($result)) {
5796 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5797 $filter["reg_exp"] = $line["reg_exp"];
5798 $filter["action"] = $line["action"];
5799 $filter["action_param"] = $line["action_param"];
5800 $filter["filter_param"] = $line["filter_param"];
5801 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5802
5803 array_push($filters[$line["name"]], $filter);
5804 }
5805
5806 return $filters;
5807 }
5808
5809 function get_score_pic($score) {
5810 if ($score > 100) {
5811 return "score_high.png";
5812 } else if ($score > 0) {
5813 return "score_half_high.png";
5814 } else if ($score < -100) {
5815 return "score_low.png";
5816 } else if ($score < 0) {
5817 return "score_half_low.png";
5818 } else {
5819 return "score_neutral.png";
5820 }
5821 }
5822
5823 function rounded_table_start($classname, $header = "&nbsp;") {
5824 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5825 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5826 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5827 }
5828
5829 function rounded_table_end($footer = "&nbsp;") {
5830 print "</td><td class='right'>&nbsp;</td></tr>";
5831 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5832 print "</table>";
5833 }
5834
5835 function print_label_dlg_common_examples() {
5836
5837 print __("Match ") . " ";
5838
5839 /* print "<select name=\"label_andor\">";
5840 print "<option value=\"and\">AND</option>";
5841 print "<option value=\"or\">OR</option>";
5842 print "</select>"; */
5843
5844 print "<select name=\"label_fields\" onchange=\"labelFieldsCheck(this)\">";
5845 print "<option value=\"unread\">".__("Unread articles")."</option>";
5846 print "<option value=\"updated\">".__("Updated articles")."</option>";
5847 print "<option value=\"kw_title\">".__("Title contains")."</option>";
5848 print "<option value=\"kw_content\">".__("Content contains")."</option>";
5849 print "<option value=\"scoreE\">".__("Score equals")."</option>";
5850 print "<option value=\"scoreG\">".__("Score is greater than")."</option>";
5851 print "<option value=\"scoreL\">".__("Score is less than")."</option>";
5852 print "<option value=\"newerH\">".__("Articles newer than X hours")."</option>";
5853 print "<option value=\"newerD\">".__("Articles newer than X days")."</option>";
5854
5855 print "</select>";
5856
5857 print "<input style=\"display : none\" name=\"label_fields_param\"
5858 size=\"10\">";
5859
5860 print " <input type=\"submit\"
5861 onclick=\"return addLabelExample()\"
5862 value=\"".__("Add")."\">";
5863 }
5864
5865 function feed_has_icon($id) {
5866 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5867 }
5868
5869 function init_connection($link) {
5870 if (DB_TYPE == "pgsql") {
5871 pg_query($link, "set client_encoding = 'UTF-8'");
5872 pg_set_client_encoding("UNICODE");
5873 pg_query($link, "set datestyle = 'ISO, european'");
5874 } else {
5875 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5876 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5877 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5878 }
5879 }
5880 }
5881
5882 function update_feedbrowser_cache($link) {
5883
5884 $result = db_query($link, "SELECT feed_url,COUNT(id) AS subscribers
5885 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5886 WHERE tf.feed_url = ttrss_feeds.feed_url
5887 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5888 GROUP BY feed_url ORDER BY subscribers DESC LIMIT 200");
5889
5890 db_query($link, "BEGIN");
5891
5892 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5893
5894 $count = 0;
5895
5896 while ($line = db_fetch_assoc($result)) {
5897 $subscribers = db_escape_string($line["subscribers"]);
5898 $feed_url = db_escape_string($line["feed_url"]);
5899
5900 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5901 (feed_url, subscribers) VALUES ('$feed_url', '$subscribers')");
5902
5903 ++$count;
5904 }
5905
5906 db_query($link, "COMMIT");
5907
5908 return $count;
5909
5910 }
5911
5912 function ccache_zero($link, $feed_id, $owner_uid) {
5913 db_query($link, "UPDATE ttrss_counters_cache SET
5914 value = 0, updated = NOW() WHERE
5915 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5916 }
5917
5918 function ccache_zero_all($link, $owner_uid) {
5919 db_query($link, "UPDATE ttrss_counters_cache SET
5920 value = 0 WHERE owner_uid = '$owner_uid'");
5921
5922 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5923 value = 0 WHERE owner_uid = '$owner_uid'");
5924 }
5925
5926 function ccache_update_all($link, $owner_uid) {
5927
5928 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5929
5930 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5931 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5932
5933 while ($line = db_fetch_assoc($result)) {
5934 ccache_update($link, $line["feed_id"], $owner_uid, true);
5935 }
5936
5937
5938 } else {
5939 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5940 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5941
5942 while ($line = db_fetch_assoc($result)) {
5943 print ccache_update($link, $line["feed_id"], $owner_uid);
5944
5945 }
5946
5947 }
5948 }
5949
5950 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5951 $no_update = false) {
5952
5953 if (!$is_cat) {
5954 $table = "ttrss_counters_cache";
5955 } else {
5956 $table = "ttrss_cat_counters_cache";
5957 }
5958
5959 if (DB_TYPE == "pgsql") {
5960 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5961 } else if (DB_TYPE == "mysql") {
5962 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5963 }
5964
5965 $result = db_query($link, "SELECT value FROM $table
5966 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5967 LIMIT 1");
5968
5969 if (db_num_rows($result) == 1) {
5970 return db_fetch_result($result, 0, "value");
5971 } else {
5972 if ($no_update) {
5973 return -1;
5974 } else {
5975 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5976 }
5977 }
5978
5979 }
5980
5981 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5982 $update_pcat = true) {
5983
5984 /* Labels are no currently supported */
5985
5986 if ($feed_id < 0) {
5987 return -1;
5988 }
5989
5990 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5991
5992 if (!$is_cat) {
5993 $table = "ttrss_counters_cache";
5994 } else {
5995 $table = "ttrss_cat_counters_cache";
5996 }
5997
5998 if ($is_cat && $feed_id >= 0) {
5999 if ($feed_id != 0) {
6000 $cat_qpart = "cat_id = '$feed_id'";
6001 } else {
6002 $cat_qpart = "cat_id IS NULL";
6003 }
6004
6005 /* Recalculate counters for child feeds */
6006
6007 $result = db_query($link, "SELECT id FROM ttrss_feeds
6008 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6009
6010 while ($line = db_fetch_assoc($result)) {
6011 ccache_update($link, $line["id"], $owner_uid, false, false);
6012 }
6013
6014 $result = db_query($link, "SELECT SUM(value) AS sv
6015 FROM ttrss_counters_cache, ttrss_feeds
6016 WHERE id = feed_id AND $cat_qpart AND
6017 ttrss_feeds.owner_uid = '$owner_uid'");
6018
6019 $unread = db_fetch_result($result, 0, "sv");
6020
6021 } else {
6022 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6023 }
6024
6025 $result = db_query($link, "SELECT feed_id FROM $table
6026 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6027
6028 if (db_num_rows($result) == 1) {
6029 db_query($link, "UPDATE $table SET
6030 value = '$unread', updated = NOW() WHERE
6031 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6032
6033 } else {
6034 db_query($link, "INSERT INTO $table
6035 (feed_id, value, owner_uid, updated)
6036 VALUES
6037 ($feed_id, $unread, $owner_uid, NOW())");
6038
6039 }
6040
6041 if ($feed_id > 0 && $prev_unread != $unread) {
6042
6043 if (!$is_cat) {
6044
6045 /* Update parent category */
6046
6047 if ($update_pcat) {
6048
6049 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6050 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6051
6052 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6053
6054 ccache_update($link, $cat_id, $owner_uid, true);
6055
6056 }
6057 }
6058 } else if ($feed_id < 0) {
6059 ccache_update_all($link, $owner_uid);
6060 }
6061
6062 return $unread;
6063 }
6064 ?>