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