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