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