]> git.wh0rd.org - tt-rss.git/blob - functions.php
50a4d607b17c90e3cb44580f593bbb14afabb034
[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 header("Location: login.php");
1923 exit;
1924 } else {
1925 /* bump login timestamp */
1926 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1927 $_SESSION["uid"]);
1928
1929 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
1930 setcookie("ttrss_lang", $_SESSION["language"],
1931 time() + SESSION_COOKIE_LIFETIME);
1932 }
1933
1934 /* bump counters stamp since we're getting reloaded anyway */
1935
1936 $_SESSION["get_all_counters_stamp"] = time();
1937 }
1938
1939 } else {
1940 return authenticate_user($link, "admin", null);
1941 }
1942 }
1943
1944 function truncate_string($str, $max_len) {
1945 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1946 return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
1947 } else {
1948 return $str;
1949 }
1950 }
1951
1952 function get_user_theme_path($link) {
1953 $result = db_query($link, "SELECT theme_path
1954 FROM
1955 ttrss_themes,ttrss_users
1956 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1957 if (db_num_rows($result) != 0) {
1958 return db_fetch_result($result, 0, "theme_path");
1959 } else {
1960 return null;
1961 }
1962 }
1963
1964 function smart_date_time($timestamp) {
1965 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1966 return date("G:i", $timestamp);
1967 } else if (date("Y", $timestamp) == date("Y")) {
1968 return date("M d, G:i", $timestamp);
1969 } else {
1970 return date("Y/m/d, G:i", $timestamp);
1971 }
1972 }
1973
1974 function smart_date($timestamp) {
1975 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1976 return "Today";
1977 } else if (date("Y", $timestamp) == date("Y")) {
1978 return date("D m", $timestamp);
1979 } else {
1980 return date("Y/m/d", $timestamp);
1981 }
1982 }
1983
1984 function sql_bool_to_string($s) {
1985 if ($s == "t" || $s == "1") {
1986 return "true";
1987 } else {
1988 return "false";
1989 }
1990 }
1991
1992 function sql_bool_to_bool($s) {
1993 if ($s == "t" || $s == "1") {
1994 return true;
1995 } else {
1996 return false;
1997 }
1998 }
1999
2000 function bool_to_sql_bool($s) {
2001 if ($s) {
2002 return "true";
2003 } else {
2004 return "false";
2005 }
2006 }
2007
2008 function toggleEvenOdd($a) {
2009 if ($a == "even")
2010 return "odd";
2011 else
2012 return "even";
2013 }
2014
2015 function sanity_check($link) {
2016
2017 error_reporting(0);
2018
2019 $error_code = 0;
2020 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2021 $schema_version = db_fetch_result($result, 0, "schema_version");
2022
2023 if ($schema_version != SCHEMA_VERSION) {
2024 $error_code = 5;
2025 }
2026
2027 if (DB_TYPE == "mysql") {
2028 $result = db_query($link, "SELECT true", false);
2029 if (db_num_rows($result) != 1) {
2030 $error_code = 10;
2031 }
2032 }
2033
2034 if (db_escape_string("testTEST") != "testTEST") {
2035 $error_code = 12;
2036 }
2037
2038 error_reporting (DEFAULT_ERROR_LEVEL);
2039
2040 if ($error_code != 0) {
2041 print_error_xml($error_code);
2042 return false;
2043 } else {
2044 return true;
2045 }
2046 }
2047
2048 function file_is_locked($filename) {
2049 if (function_exists('flock')) {
2050 error_reporting(0);
2051 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2052 error_reporting(DEFAULT_ERROR_LEVEL);
2053 if ($fp) {
2054 if (flock($fp, LOCK_EX | LOCK_NB)) {
2055 flock($fp, LOCK_UN);
2056 fclose($fp);
2057 return false;
2058 }
2059 fclose($fp);
2060 return true;
2061 } else {
2062 return false;
2063 }
2064 }
2065 return true; // consider the file always locked and skip the test
2066 }
2067
2068 function make_lockfile($filename) {
2069 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2070
2071 if (flock($fp, LOCK_EX | LOCK_NB)) {
2072 return $fp;
2073 } else {
2074 return false;
2075 }
2076 }
2077
2078 function make_stampfile($filename) {
2079 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2080
2081 if (flock($fp, LOCK_EX | LOCK_NB)) {
2082 fwrite($fp, time() . "\n");
2083 flock($fp, LOCK_UN);
2084 fclose($fp);
2085 return true;
2086 } else {
2087 return false;
2088 }
2089 }
2090
2091 function read_stampfile($filename) {
2092
2093 error_reporting(0);
2094 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2095 error_reporting (DEFAULT_ERROR_LEVEL);
2096
2097 if ($fp) {
2098 if (flock($fp, LOCK_EX)) {
2099 $stamp = fgets($fp);
2100 flock($fp, LOCK_UN);
2101 fclose($fp);
2102 return $stamp;
2103 } else {
2104 return false;
2105 }
2106 } else {
2107 return false;
2108 }
2109 }
2110
2111 function sql_random_function() {
2112 if (DB_TYPE == "mysql") {
2113 return "RAND()";
2114 } else {
2115 return "RANDOM()";
2116 }
2117 }
2118
2119 function catchup_feed($link, $feed, $cat_view) {
2120
2121 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2122
2123 if ($cat_view) {
2124
2125 if ($feed >= 0) {
2126
2127 if ($feed > 0) {
2128 $cat_qpart = "cat_id = '$feed'";
2129 } else {
2130 $cat_qpart = "cat_id IS NULL";
2131 }
2132
2133 $tmp_result = db_query($link, "SELECT id
2134 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
2135 $_SESSION["uid"]);
2136
2137 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2138
2139 $tmp_feed = $tmp_line["id"];
2140
2141 db_query($link, "UPDATE ttrss_user_entries
2142 SET unread = false,last_read = NOW()
2143 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
2144 }
2145 } else if ($feed == -2) {
2146
2147
2148 db_query($link, "UPDATE ttrss_user_entries
2149 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2150 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2151 AND unread = true AND owner_uid = " . $_SESSION["uid"]);
2152 }
2153
2154 } else if ($feed > 0) {
2155
2156 $tmp_result = db_query($link, "SELECT id
2157 FROM ttrss_feeds WHERE parent_feed = '$feed'
2158 ORDER BY cat_id,title");
2159
2160 $parent_ids = array();
2161
2162 if (db_num_rows($tmp_result) > 0) {
2163 while ($p = db_fetch_assoc($tmp_result)) {
2164 array_push($parent_ids, "feed_id = " . $p["id"]);
2165 }
2166
2167 $children_qpart = implode(" OR ", $parent_ids);
2168
2169 db_query($link, "UPDATE ttrss_user_entries
2170 SET unread = false,last_read = NOW()
2171 WHERE (feed_id = '$feed' OR $children_qpart)
2172 AND owner_uid = " . $_SESSION["uid"]);
2173
2174 } else {
2175 db_query($link, "UPDATE ttrss_user_entries
2176 SET unread = false,last_read = NOW()
2177 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2178 }
2179
2180 } else if ($feed < 0 && $feed > -10) { // special, like starred
2181
2182 if ($feed == -1) {
2183 db_query($link, "UPDATE ttrss_user_entries
2184 SET unread = false,last_read = NOW()
2185 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2186 }
2187
2188 if ($feed == -2) {
2189 db_query($link, "UPDATE ttrss_user_entries
2190 SET unread = false,last_read = NOW()
2191 WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2192 }
2193
2194 if ($feed == -3) {
2195
2196 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2197
2198 if (DB_TYPE == "pgsql") {
2199 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2200 } else {
2201 $match_part = "updated > DATE_SUB(NOW(),
2202 INTERVAL $intl HOUR) ";
2203 }
2204
2205 $result = db_query($link, "SELECT id FROM ttrss_entries,
2206 ttrss_user_entries WHERE $match_part AND
2207 unread = true AND
2208 ttrss_user_entries.ref_id = ttrss_entries.id AND
2209 owner_uid = ".$_SESSION["uid"]);
2210
2211 $affected_ids = array();
2212
2213 while ($line = db_fetch_assoc($result)) {
2214 array_push($affected_ids, $line["id"]);
2215 }
2216
2217 catchupArticlesById($link, $affected_ids, 0);
2218 }
2219
2220 if ($feed == -4) {
2221 db_query($link, "UPDATE ttrss_user_entries
2222 SET unread = false,last_read = NOW()
2223 WHERE owner_uid = ".$_SESSION["uid"]);
2224 }
2225
2226 } else if ($feed < -10) { // label
2227
2228 $label_id = -$feed - 11;
2229
2230 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2231 SET unread = false WHERE label_id = '$label_id' AND unread = true
2232 AND owner_uid = '".$_SESSION["uid"]."' AND ref_id = article_id");
2233
2234 }
2235
2236 ccache_update($link, $feed, $_SESSION["uid"], $cat_view);
2237
2238 } else { // tag
2239 db_query($link, "BEGIN");
2240
2241 $tag_name = db_escape_string($feed);
2242
2243 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2244 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2245
2246 while ($line = db_fetch_assoc($result)) {
2247 db_query($link, "UPDATE ttrss_user_entries SET
2248 unread = false, last_read = NOW()
2249 WHERE int_id = " . $line["post_int_id"]);
2250 }
2251 db_query($link, "COMMIT");
2252 }
2253 }
2254
2255 function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2256 if ($cat_view) {
2257
2258 if ($feed > 0) {
2259 $cat_qpart = "cat_id = '$feed'";
2260 } else {
2261 $cat_qpart = "cat_id IS NULL";
2262 }
2263
2264 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2265 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2266
2267 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2268 $feed_url = $tmp_line["feed_url"];
2269 $feed_id = $tmp_line["id"];
2270 update_rss_feed($link, $feed_url, $feed_id, $force_update);
2271 }
2272
2273 } else {
2274 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2275 WHERE id = '$feed'");
2276 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
2277 update_rss_feed($link, $feed_url, $feed, $force_update);
2278 }
2279 }
2280
2281 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2282
2283 if (!$omode) $omode = "flc";
2284
2285 getGlobalCounters($link);
2286
2287 if (strchr($omode, "l")) getLabelCounters($link);
2288 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS, $active_feed);
2289 if (strchr($omode, "t")) getTagCounters($link);
2290 if (strchr($omode, "c")) {
2291 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2292 getCategoryCounters($link);
2293 }
2294 }
2295 }
2296
2297 function getCategoryCounters($link) {
2298 # two special categories are -1 and -2 (all virtuals; all labels)
2299
2300 /* $ctr = getCategoryUnread($link, -1);
2301
2302 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>"; */
2303
2304 $ctr = getCategoryUnread($link, -2);
2305
2306 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2307
2308 $age_qpart = getMaxAgeSubquery();
2309
2310 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2311 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2312 WHERE ttrss_cat_counters_cache.feed_id = id AND
2313 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2314
2315 while ($line = db_fetch_assoc($result)) {
2316 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2317
2318 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2319 $line["unread"]."\"/>";
2320 }
2321
2322 /* Special case: NULL category doesn't actually exist in the DB */
2323
2324 print "<counter type=\"category\" id=\"0\" counter=\"".
2325 ccache_find($link, 0, $_SESSION["uid"], true)."\"/>";
2326
2327 }
2328
2329 function getCategoryUnread($link, $cat, $owner_uid = false) {
2330
2331 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2332
2333 if ($cat >= 0) {
2334
2335 if ($cat != 0) {
2336 $cat_query = "cat_id = '$cat'";
2337 } else {
2338 $cat_query = "cat_id IS NULL";
2339 }
2340
2341 $age_qpart = getMaxAgeSubquery();
2342
2343 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2344 AND hidden = false
2345 AND owner_uid = " . $owner_uid);
2346
2347 $cat_feeds = array();
2348 while ($line = db_fetch_assoc($result)) {
2349 array_push($cat_feeds, "feed_id = " . $line["id"]);
2350 }
2351
2352 if (count($cat_feeds) == 0) return 0;
2353
2354 $match_part = implode(" OR ", $cat_feeds);
2355
2356 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2357 FROM ttrss_user_entries,ttrss_entries
2358 WHERE unread = true AND ($match_part) AND id = ref_id
2359 AND $age_qpart AND owner_uid = " . $owner_uid);
2360
2361 $unread = 0;
2362
2363 # this needs to be rewritten
2364 while ($line = db_fetch_assoc($result)) {
2365 $unread += $line["unread"];
2366 }
2367
2368 return $unread;
2369 } else if ($cat == -1) {
2370 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3);
2371 } else if ($cat == -2) {
2372
2373 $result = db_query($link, "
2374 SELECT COUNT(unread) AS unread FROM
2375 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2376 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2377 ttrss_labels2.owner_uid = '$owner_uid'
2378 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2379 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2380
2381 $unread = db_fetch_result($result, 0, "unread");
2382
2383 return $unread;
2384
2385 }
2386 }
2387
2388 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2389 if (DB_TYPE == "pgsql") {
2390 return "ttrss_entries.date_entered >
2391 NOW() - INTERVAL '$days days'";
2392 } else {
2393 return "ttrss_entries.date_entered >
2394 DATE_SUB(NOW(), INTERVAL $days DAY)";
2395 }
2396 }
2397
2398 function getFeedUnread($link, $feed, $is_cat = false) {
2399 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2400 }
2401
2402 function getLabelUnread($link, $label_id, $owner_uid = false) {
2403 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2404
2405 $result = db_query($link, "
2406 SELECT COUNT(unread) AS unread FROM
2407 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2408 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2409 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2410 AND unread = true AND hidden = false AND feed_id = ttrss_feeds.id
2411 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2412
2413 if (db_num_rows($result) != 0) {
2414 return db_fetch_result($result, 0, "unread");
2415 } else {
2416 return 0;
2417 }
2418 }
2419
2420 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2421 $owner_uid = false) {
2422
2423 $n_feed = sprintf("%d", $feed);
2424
2425 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2426
2427 if ($unread_only) {
2428 $unread_qpart = "unread = true";
2429 } else {
2430 $unread_qpart = "true";
2431 }
2432
2433 $age_qpart = getMaxAgeSubquery();
2434
2435 if ($is_cat) {
2436 return getCategoryUnread($link, $n_feed, $owner_uid);
2437 } else if ($n_feed == -1) {
2438 $match_part = "marked = true";
2439 } else if ($n_feed == -2) {
2440 $match_part = "published = true";
2441 } else if ($n_feed == -3) {
2442 $match_part = "unread = true";
2443
2444 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2445
2446 if (DB_TYPE == "pgsql") {
2447 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2448 } else {
2449 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2450 }
2451 } else if ($n_feed == -4) {
2452 $match_part = "true";
2453 } else if ($n_feed > 0) {
2454
2455 $result = db_query($link, "SELECT id FROM ttrss_feeds
2456 WHERE parent_feed = '$n_feed'
2457 AND hidden = false
2458 AND owner_uid = " . $owner_uid);
2459
2460 if (db_num_rows($result) > 0) {
2461
2462 $linked_feeds = array();
2463 while ($line = db_fetch_assoc($result)) {
2464 array_push($linked_feeds, "feed_id = " . $line["id"]);
2465 }
2466
2467 array_push($linked_feeds, "feed_id = $n_feed");
2468
2469 $match_part = implode(" OR ", $linked_feeds);
2470
2471 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2472 FROM ttrss_user_entries,ttrss_entries
2473 WHERE $unread_qpart AND
2474 ttrss_user_entries.ref_id = ttrss_entries.id AND
2475 $age_qpart AND
2476 ($match_part) AND
2477 owner_uid = " . $owner_uid);
2478
2479 $unread = 0;
2480
2481 # this needs to be rewritten
2482 while ($line = db_fetch_assoc($result)) {
2483 $unread += $line["unread"];
2484 }
2485
2486 return $unread;
2487
2488 } else {
2489 $match_part = "feed_id = '$n_feed'";
2490 }
2491 } else if ($feed < -10) {
2492
2493 $label_id = -$feed - 11;
2494
2495 return getLabelUnread($link, $label_id, $owner_uid);
2496
2497 }
2498
2499 if ($match_part) {
2500
2501 $result = db_query($link, "SELECT count(int_id) AS unread
2502 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2503 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2504 ttrss_user_entries.ref_id = ttrss_entries.id AND
2505 ttrss_feeds.hidden = false AND
2506 $age_qpart AND
2507 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = " . $owner_uid);
2508
2509 } else {
2510
2511 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2512 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2513 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2514 AND $unread_qpart AND $age_qpart AND
2515 ttrss_tags.owner_uid = " . $owner_uid);
2516 }
2517
2518 $unread = db_fetch_result($result, 0, "unread");
2519
2520 return $unread;
2521 }
2522
2523 function getGlobalUnread($link, $user_id = false) {
2524
2525 if (!$user_id) {
2526 $user_id = $_SESSION["uid"];
2527 }
2528
2529 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2530 WHERE owner_uid = '$user_id' AND feed_id > 0");
2531
2532 $c_id = db_fetch_result($result, 0, "c_id");
2533
2534 return $c_id;
2535 }
2536
2537 function getGlobalCounters($link, $global_unread = -1) {
2538 if ($global_unread == -1) {
2539 $global_unread = getGlobalUnread($link);
2540 }
2541 print "<counter type=\"global\" id='global-unread'
2542 counter='$global_unread'/>";
2543
2544 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2545 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2546
2547 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2548
2549 print "<counter type=\"global\" id='subscribed-feeds'
2550 counter='$subscribed_feeds'/>";
2551
2552 }
2553
2554 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
2555
2556 if ($smart_mode) {
2557 if (!$_SESSION["tctr_last_value"]) {
2558 $_SESSION["tctr_last_value"] = array();
2559 }
2560 }
2561
2562 $old_counters = $_SESSION["tctr_last_value"];
2563
2564 $tctrs_modified = false;
2565
2566 $age_qpart = getMaxAgeSubquery();
2567
2568 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2569 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2570 AND ref_id = id AND $age_qpart
2571 AND unread = true)) AS count FROM ttrss_tags
2572 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2573 ORDER BY count DESC LIMIT 55");
2574
2575 $tags = array();
2576
2577 while ($line = db_fetch_assoc($result)) {
2578 $tags[$line["tag_name"]] += $line["count"];
2579 }
2580
2581 foreach (array_keys($tags) as $tag) {
2582 $unread = $tags[$tag];
2583
2584 $tag = htmlspecialchars($tag);
2585
2586 if (!$smart_mode || $old_counters[$tag] != $unread) {
2587 $old_counters[$tag] = $unread;
2588 $tctrs_modified = true;
2589 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2590 }
2591
2592 }
2593
2594 if ($smart_mode && $tctrs_modified) {
2595 $_SESSION["tctr_last_value"] = $old_counters;
2596 }
2597
2598 }
2599
2600 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
2601
2602 $age_qpart = getMaxAgeSubquery();
2603
2604 if ($smart_mode) {
2605 if (!$_SESSION["lctr_last_value"]) {
2606 $_SESSION["lctr_last_value"] = array();
2607 }
2608 }
2609
2610 $ret_arr = array();
2611
2612 for ($i = -1; $i >= -4; $i--) {
2613
2614 $count = getFeedUnread($link, $i);
2615
2616 if (!$ret_mode) {
2617
2618 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2619 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $i) . " total)\"";
2620 } else {
2621 $xmsg_part = "";
2622 }
2623
2624 print "<counter type=\"label\" id=\"$i\" counter=\"$count\" $xmsg_part/>";
2625 } else {
2626 $ret_arr[$i]["counter"] = $count;
2627 $ret_arr[$i]["description"] = getFeedTitle($link, $i);
2628 }
2629
2630 }
2631
2632 $old_counters = $_SESSION["lctr_last_value"];
2633 $lctrs_modified = false;
2634
2635
2636 $owner_uid = $_SESSION["uid"];
2637
2638 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2639 WHERE owner_uid = '$owner_uid'");
2640
2641 while ($line = db_fetch_assoc($result)) {
2642
2643 $id = -$line["id"] - 11;
2644
2645 $label_name = $line["caption"];
2646 $count = getFeedUnread($link, $id);
2647
2648 if (!$smart_mode || $old_counters[$id] != $count) {
2649 $old_counters[$id] = $count;
2650 $lctrs_modified = true;
2651 if (!$ret_mode) {
2652
2653 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2654 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2655 } else {
2656 $xmsg_part = "";
2657 }
2658
2659 print "<counter type=\"label\" id=\"$id\" counter=\"$count\" $xmsg_part/>";
2660 } else {
2661 $ret_arr[$id]["counter"] = $count;
2662 $ret_arr[$id]["description"] = $label_name;
2663 }
2664 }
2665
2666 error_reporting (DEFAULT_ERROR_LEVEL);
2667 }
2668
2669 if ($smart_mode && $lctrs_modified) {
2670 $_SESSION["lctr_last_value"] = $old_counters;
2671 }
2672
2673 return $ret_arr;
2674 }
2675
2676 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS, $active_feed = false) {
2677
2678 $age_qpart = getMaxAgeSubquery();
2679
2680 if ($smart_mode) {
2681 if (!$_SESSION["fctr_last_value"]) {
2682 $_SESSION["fctr_last_value"] = array();
2683 }
2684 }
2685
2686 $old_counters = $_SESSION["fctr_last_value"];
2687
2688 $query = "SELECT ttrss_feeds.id,
2689 ttrss_feeds.title,
2690 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2691 last_error, value AS count
2692 FROM ttrss_feeds, ttrss_counters_cache
2693 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2694 AND parent_feed IS NULL
2695 AND ttrss_counters_cache.feed_id = id";
2696
2697 $result = db_query($link, $query);
2698 $fctrs_modified = false;
2699
2700 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2701
2702 while ($line = db_fetch_assoc($result)) {
2703
2704 $id = $line["id"];
2705 $count = $line["count"];
2706 $last_error = htmlspecialchars($line["last_error"]);
2707
2708 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2709 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2710 } else {
2711 $last_updated = date($short_date, strtotime($line["last_updated"]));
2712 }
2713
2714 $last_updated = htmlspecialchars($last_updated);
2715
2716 $has_img = feed_has_icon($id);
2717
2718 $tmp_result = db_query($link,
2719 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
2720 WHERE parent_feed = '$id' AND feed_id = id");
2721
2722 $count += db_fetch_result($tmp_result, 0, "unread");
2723
2724 if (!$smart_mode || $old_counters[$id] != $count) {
2725 $old_counters[$id] = $count;
2726 $fctrs_modified = true;
2727
2728 if ($last_error) {
2729 $error_part = "error=\"$last_error\"";
2730 } else {
2731 $error_part = "";
2732 }
2733
2734 if ($has_img) {
2735 $has_img_part = "hi=\"$has_img\"";
2736 } else {
2737 $has_img_part = "";
2738 }
2739
2740 if ($active_feed && $id == $active_feed) {
2741 $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2742 } else {
2743 $has_title_part = "";
2744 }
2745
2746 if (get_pref($link, 'EXTENDED_FEEDLIST')) {
2747 $xmsg_part = "xmsg=\"(" . getFeedArticles($link, $id) . " total)\"";
2748 }
2749
2750 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $xmsg_part $has_title_part/>";
2751 }
2752 }
2753
2754 if ($smart_mode && $fctrs_modified) {
2755 $_SESSION["fctr_last_value"] = $old_counters;
2756 }
2757 }
2758
2759 function get_script_dt_add() {
2760 /* if (strpos(VERSION, ".99") === false) {
2761 return VERSION;
2762 } else {
2763 return time();
2764 } */
2765 return time();
2766 }
2767
2768 function get_pgsql_version($link) {
2769 $result = db_query($link, "SELECT version() AS version");
2770 $version = split(" ", db_fetch_result($result, 0, "version"));
2771 return $version[1];
2772 }
2773
2774 function print_error_xml($code, $add_msg = "") {
2775 global $ERRORS;
2776
2777 $error_msg = $ERRORS[$code];
2778
2779 if ($add_msg) {
2780 $error_msg = "$error_msg; $add_msg";
2781 }
2782
2783 print "<rpc-reply>";
2784 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2785 print "</rpc-reply>";
2786 }
2787
2788 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2789 $auth_login = '', $auth_pass = '') {
2790
2791 # check for feed:http://url
2792 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2793
2794 # check for feed://URL
2795 if (strpos($feed_link, "//") === 0) {
2796 $feed_link = "http:$feed_link";
2797 }
2798
2799 if ($feed_link == "") return;
2800
2801 if ($cat_id == "0" || !$cat_id) {
2802 $cat_qpart = "NULL";
2803 } else {
2804 $cat_qpart = "'$cat_id'";
2805 }
2806
2807 $result = db_query($link,
2808 "SELECT id FROM ttrss_feeds
2809 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2810
2811 if (db_num_rows($result) == 0) {
2812
2813 $result = db_query($link,
2814 "INSERT INTO ttrss_feeds
2815 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2816 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2817 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2818
2819 $result = db_query($link,
2820 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2821 AND owner_uid = " . $_SESSION["uid"]);
2822
2823 $feed_id = db_fetch_result($result, 0, "id");
2824
2825 if ($feed_id) {
2826 update_rss_feed($link, $feed_link, $feed_id, true);
2827 }
2828
2829 return true;
2830 } else {
2831 return false;
2832 }
2833 }
2834
2835 function print_feed_select($link, $id, $default_id = "",
2836 $attributes = "", $include_all_feeds = true) {
2837
2838 print "<select id=\"$id\" name=\"$id\" $attributes>";
2839 if ($include_all_feeds) {
2840 print "<option value=\"0\">".__('All feeds')."</option>";
2841 }
2842
2843 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2844 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2845
2846 if (db_num_rows($result) > 0 && $include_all_feeds) {
2847 print "<option disabled>--------</option>";
2848 }
2849
2850 while ($line = db_fetch_assoc($result)) {
2851 if ($line["id"] == $default_id) {
2852 $is_selected = "selected";
2853 } else {
2854 $is_selected = "";
2855 }
2856 printf("<option $is_selected value='%d'>%s</option>",
2857 $line["id"], htmlspecialchars($line["title"]));
2858 }
2859
2860 print "</select>";
2861 }
2862
2863 function print_feed_cat_select($link, $id, $default_id = "",
2864 $attributes = "", $include_all_cats = true) {
2865
2866 print "<select id=\"$id\" name=\"$id\" $attributes>";
2867
2868 if ($include_all_cats) {
2869 print "<option value=\"0\">".__('Uncategorized')."</option>";
2870 }
2871
2872 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2873 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2874
2875 if (db_num_rows($result) > 0 && $include_all_cats) {
2876 print "<option disabled>--------</option>";
2877 }
2878
2879 while ($line = db_fetch_assoc($result)) {
2880 if ($line["id"] == $default_id) {
2881 $is_selected = "selected";
2882 } else {
2883 $is_selected = "";
2884 }
2885 printf("<option $is_selected value='%d'>%s</option>",
2886 $line["id"], htmlspecialchars($line["title"]));
2887 }
2888
2889 print "</select>";
2890 }
2891
2892 function checkbox_to_sql_bool($val) {
2893 return ($val == "on") ? "true" : "false";
2894 }
2895
2896 function getFeedCatTitle($link, $id) {
2897 if ($id == -1) {
2898 return __("Special");
2899 } else if ($id < -10) {
2900 return __("Labels");
2901 } else if ($id > 0) {
2902 $result = db_query($link, "SELECT ttrss_feed_categories.title
2903 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2904 cat_id = ttrss_feed_categories.id");
2905 if (db_num_rows($result) == 1) {
2906 return db_fetch_result($result, 0, "title");
2907 } else {
2908 return __("Uncategorized");
2909 }
2910 } else {
2911 return "getFeedCatTitle($id) failed";
2912 }
2913
2914 }
2915
2916 function getFeedTitle($link, $id) {
2917 if ($id == -1) {
2918 return __("Starred articles");
2919 } else if ($id == -2) {
2920 return __("Published articles");
2921 } else if ($id == -3) {
2922 return __("Fresh articles");
2923 } else if ($id == -4) {
2924 return __("All articles");
2925 } else if ($id < -10) {
2926 $label_id = -$id - 11;
2927 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2928 if (db_num_rows($result) == 1) {
2929 return db_fetch_result($result, 0, "caption");
2930 } else {
2931 return "Unknown label ($label_id)";
2932 }
2933
2934 } else if ($id > 0) {
2935 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2936 if (db_num_rows($result) == 1) {
2937 return db_fetch_result($result, 0, "title");
2938 } else {
2939 return "Unknown feed ($id)";
2940 }
2941 } else {
2942 return "getFeedTitle($id) failed";
2943 }
2944
2945 }
2946
2947 function get_session_cookie_name() {
2948 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2949 }
2950
2951 function print_init_params($link) {
2952 print "<init-params>";
2953 if ($_SESSION["stored-params"]) {
2954 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2955 if ($key) {
2956 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2957 print "<param key=\"$key\" value=\"$value\"/>";
2958 }
2959 }
2960 }
2961
2962 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2963 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2964 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2965 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2966
2967 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2968 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2969
2970 print "<param key=\"hide_read_feeds\" value=\"" .
2971 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2972
2973 print "<param key=\"enable_feed_cats\" value=\"" .
2974 (int) get_pref($link, "ENABLE_FEED_CATS") . "\"/>";
2975
2976 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2977 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2978
2979 print "<param key=\"confirm_feed_catchup\" value=\"" .
2980 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2981
2982 print "<param key=\"cdm_auto_catchup\" value=\"" .
2983 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2984
2985 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
2986
2987 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
2988
2989 print "<param key=\"default_view_mode\" value=\"" .
2990 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2991
2992 print "<param key=\"default_view_limit\" value=\"" .
2993 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2994
2995 print "<param key=\"default_view_order_by\" value=\"" .
2996 get_pref($link, "_DEFAULT_VIEW_ORDER_BY") . "\"/>";
2997
2998 print "<param key=\"prefs_active_tab\" value=\"" .
2999 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
3000
3001 print "<param key=\"infobox_disable_overlay\" value=\"" .
3002 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
3003
3004 print "<param key=\"icons_location\" value=\"" .
3005 ICONS_URL . "\"/>";
3006
3007 print "<param key=\"hide_read_shows_special\" value=\"" .
3008 (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
3009
3010 print "<param key=\"hide_feedlist\" value=\"" .
3011 (int) get_pref($link, "HIDE_FEEDLIST") . "\"/>";
3012
3013 print "<param key=\"bw_limit\" value=\"".
3014 (int) $_SESSION["bw_limit"]."\"/>";
3015
3016 // print "<param key=\"sync_counters\" value=\"" .
3017 // (int) get_pref($link, "SYNC_COUNTERS") . "\"/>";
3018
3019 print "<param key=\"sync_counters\" value=\"1\"/>";
3020
3021 print "<param key=\"offline_enabled\" value=\"".
3022 (int) get_pref($link, "ENABLE_OFFLINE_READING") . "\"/>";
3023
3024 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3025 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3026
3027 $num_feeds = db_fetch_result($result, 0, "cf");
3028
3029 print "<param key=\"num_feeds\" value=\"".
3030 (int)$num_feeds. "\"/>";
3031
3032 print "</init-params>";
3033 }
3034
3035 function print_runtime_info($link) {
3036 print "<runtime-info>";
3037
3038 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3039 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3040
3041 $num_feeds = db_fetch_result($result, 0, "cf");
3042
3043 print "<param key=\"num_feeds\" value=\"".
3044 (int)$num_feeds. "\"/>";
3045
3046 if (ENABLE_UPDATE_DAEMON) {
3047 print "<param key=\"daemon_is_running\" value=\"".
3048 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
3049
3050 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3051
3052 $stamp = (int)read_stampfile("update_daemon.stamp");
3053
3054 // print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
3055
3056 if ($stamp) {
3057 $stamp_delta = time() - $stamp;
3058
3059 if ($stamp_delta > 1800) {
3060 $stamp_check = 0;
3061 } else {
3062 $stamp_check = 1;
3063 $_SESSION["daemon_stamp_check"] = time();
3064 }
3065
3066 print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3067
3068 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3069
3070 print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3071 }
3072 }
3073 }
3074
3075 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
3076
3077 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
3078 $new_version_details = check_for_update($link);
3079
3080 print "<param key=\"new_version_available\" value=\"".
3081 sprintf("%d", $new_version_details != ""). "\"/>";
3082
3083 $_SESSION["last_version_check"] = time();
3084 }
3085 }
3086
3087 // print "<param key=\"new_version_available\" value=\"1\"/>";
3088
3089 print "</runtime-info>";
3090 }
3091
3092 function getSearchSql($search, $match_on) {
3093
3094 $search_query_part = "";
3095
3096 $keywords = split(" ", $search);
3097 $query_keywords = array();
3098
3099 if ($match_on == "both") {
3100
3101 foreach ($keywords as $k) {
3102 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
3103 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3104 }
3105
3106 $search_query_part = implode("AND", $query_keywords) . " AND ";
3107
3108 } else if ($match_on == "title") {
3109
3110 foreach ($keywords as $k) {
3111 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
3112 }
3113
3114 $search_query_part = implode("AND", $query_keywords) . " AND ";
3115
3116 } else if ($match_on == "content") {
3117
3118 foreach ($keywords as $k) {
3119 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
3120 }
3121 }
3122
3123 $search_query_part = implode("AND", $query_keywords);
3124
3125 return $search_query_part;
3126 }
3127
3128 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3129
3130 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3131
3132 if ($search) {
3133
3134 $search_query_part = getSearchSql($search, $match_on);
3135 $search_query_part .= " AND ";
3136
3137 } else {
3138 $search_query_part = "";
3139 }
3140
3141 $view_query_part = "";
3142
3143 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
3144 if ($search) {
3145 $view_query_part = " ";
3146 } else if ($feed != -1) {
3147 $unread = getFeedUnread($link, $feed, $cat_view);
3148 if ($unread > 0) {
3149 $view_query_part = " unread = true AND ";
3150 }
3151 }
3152 }
3153
3154 if ($view_mode == "marked") {
3155 $view_query_part = " marked = true AND ";
3156 }
3157
3158 if ($view_mode == "unread") {
3159 $view_query_part = " unread = true AND ";
3160 }
3161
3162 if ($view_mode == "updated") {
3163 $view_query_part = " (last_read is null and unread = false) AND ";
3164 }
3165
3166 if ($limit > 0) {
3167 $limit_query_part = "LIMIT " . $limit;
3168 }
3169
3170 $vfeed_query_part = "";
3171
3172 // override query strategy and enable feed display when searching globally
3173 if ($search && $search_mode == "all_feeds") {
3174 $query_strategy_part = "ttrss_entries.id > 0";
3175 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3176 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3177 $query_strategy_part = "ttrss_entries.id > 0";
3178 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3179 id = feed_id) as feed_title,";
3180 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3181
3182 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3183
3184 $tmp_result = false;
3185
3186 if ($cat_view) {
3187 $tmp_result = db_query($link, "SELECT id
3188 FROM ttrss_feeds WHERE cat_id = '$feed'");
3189 } else {
3190 $tmp_result = db_query($link, "SELECT id
3191 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3192 WHERE id = '$feed') AND id != '$feed'");
3193 }
3194
3195 $cat_siblings = array();
3196
3197 if (db_num_rows($tmp_result) > 0) {
3198 while ($p = db_fetch_assoc($tmp_result)) {
3199 array_push($cat_siblings, "feed_id = " . $p["id"]);
3200 }
3201
3202 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3203 $feed, implode(" OR ", $cat_siblings));
3204
3205 } else {
3206 $query_strategy_part = "ttrss_entries.id > 0";
3207 }
3208
3209 } else if ($feed >= 0) {
3210
3211 if ($cat_view) {
3212
3213 if ($feed > 0) {
3214 $query_strategy_part = "cat_id = '$feed'";
3215 } else {
3216 $query_strategy_part = "cat_id IS NULL";
3217 }
3218
3219 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3220
3221 } else {
3222 $tmp_result = db_query($link, "SELECT id
3223 FROM ttrss_feeds WHERE parent_feed = '$feed'
3224 ORDER BY cat_id,title");
3225
3226 $parent_ids = array();
3227
3228 if (db_num_rows($tmp_result) > 0) {
3229 while ($p = db_fetch_assoc($tmp_result)) {
3230 array_push($parent_ids, "feed_id = " . $p["id"]);
3231 }
3232
3233 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3234 $feed, implode(" OR ", $parent_ids));
3235
3236 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3237 } else {
3238 $query_strategy_part = "feed_id = '$feed'";
3239 }
3240 }
3241 } else if ($feed == -1) { // starred virtual feed
3242 $query_strategy_part = "marked = true";
3243 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3244 } else if ($feed == -2) { // published virtual feed OR labels category
3245
3246 if (!$cat_view) {
3247 $query_strategy_part = "published = true";
3248 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3249 } else {
3250 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3251
3252 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3253
3254 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3255 ttrss_user_labels2.article_id = ref_id";
3256
3257 }
3258
3259 } else if ($feed == -3) { // fresh virtual feed
3260 $query_strategy_part = "unread = true";
3261
3262 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3263
3264 if (DB_TYPE == "pgsql") {
3265 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3266 } else {
3267 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3268 }
3269
3270 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3271 } else if ($feed == -4) { // all articles virtual feed
3272 $query_strategy_part = "true";
3273 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3274 } else if ($feed <= -10) { // labels
3275 $label_id = -$feed - 11;
3276
3277 $query_strategy_part = "label_id = '$label_id' AND
3278 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3279 ttrss_user_labels2.article_id = ref_id";
3280
3281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3282 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3283
3284 } else {
3285 $query_strategy_part = "id > 0"; // dumb
3286 }
3287
3288 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3289 $order_by = "updated";
3290 } else {
3291 $order_by = "updated DESC";
3292 }
3293
3294 if ($view_mode != "noscores") {
3295 $order_by = "score DESC, $order_by";
3296 }
3297
3298 if ($override_order) {
3299 $order_by = $override_order;
3300 }
3301
3302 $feed_title = "";
3303
3304 if ($search && $search_mode == "all_feeds") {
3305 $feed_title = __("Search results")." ($search)";
3306 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3307 $feed_title = __("Search results")." ($search, $feed)";
3308 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3309 $feed_title = $feed;
3310 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3311
3312 if ($cat_view) {
3313
3314 if ($feed != 0) {
3315 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3316 WHERE id = '$feed' AND owner_uid = $owner_uid");
3317 $feed_title = db_fetch_result($result, 0, "title");
3318 } else {
3319 $feed_title = __("Uncategorized");
3320 }
3321
3322 if ($search) {
3323 $feed_title = __("Searched for")." $search ($feed_title)";
3324 }
3325
3326 } else {
3327
3328 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
3329 WHERE id = '$feed' AND owner_uid = $owner_uid");
3330
3331 $feed_title = db_fetch_result($result, 0, "title");
3332 $feed_site_url = db_fetch_result($result, 0, "site_url");
3333 $last_error = db_fetch_result($result, 0, "last_error");
3334
3335 if ($search) {
3336 $feed_title = __("Searched for") . " $search ($feed_title)";
3337 }
3338 }
3339
3340 } else if ($feed == -1) {
3341 $feed_title = __("Starred articles");
3342 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3343 } else if ($feed == -2) {
3344 if (!$cat_view) {
3345 $feed_title = __("Published articles");
3346 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3347 } else {
3348 $feed_title = __("Labels");
3349 }
3350 } else if ($feed == -3) {
3351 $feed_title = __("Fresh articles");
3352 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3353 } else if ($feed == -4) {
3354 $feed_title = __("All articles");
3355 if ($search) { $feed_title = __("Searched for") . " $search ($feed_title)"; }
3356 } else if ($feed < -10) {
3357 $label_id = -$feed - 11;
3358 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3359 WHERE id = '$label_id'");
3360 $feed_title = db_fetch_result($result, 0, "caption");
3361
3362 if ($search) {
3363 $feed_title = __("Searched for") . " $search ($feed_title)";
3364 }
3365 } else {
3366 $feed_title = "?";
3367 }
3368
3369 $content_query_part = "content as content_preview,";
3370
3371 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3372
3373 if ($feed >= 0) {
3374 $feed_kind = "Feeds";
3375 } else {
3376 $feed_kind = "Labels";
3377 }
3378
3379 if ($limit_query_part) {
3380 $offset_query_part = "OFFSET $offset";
3381 }
3382
3383 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3384 if (!$override_order) {
3385 $order_by = "ttrss_feeds.title, $order_by";
3386 }
3387
3388 // Special output for Fresh feed
3389
3390 /* if ($feed == -3) {
3391 $group_limit_part = "(select count(*) from
3392 ttrss_user_entries AS t1, ttrss_entries AS t2 where
3393 t1.ref_id = t2.id and t1.owner_uid = 2 and
3394 t1.feed_id = ttrss_user_entries.feed_id and
3395 t2.updated > ttrss_entries.updated) <= 5 AND";
3396 } */
3397 }
3398
3399 $query = "SELECT DISTINCT
3400 guid,
3401 ttrss_entries.id,ttrss_entries.title,
3402 updated,
3403 unread,feed_id,marked,published,link,last_read,
3404 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3405 $vfeed_query_part
3406 $content_query_part
3407 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3408 author,score
3409 FROM
3410 ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part
3411 WHERE
3412 $group_limit_part
3413 ttrss_feeds.hidden = false AND
3414 ttrss_user_entries.feed_id = ttrss_feeds.id AND
3415 ttrss_user_entries.ref_id = ttrss_entries.id AND
3416 ttrss_user_entries.owner_uid = '$owner_uid' AND
3417 $search_query_part
3418 $view_query_part
3419 $query_strategy_part ORDER BY $order_by
3420 $limit_query_part $offset_query_part";
3421
3422 if ($_GET["debug"]) print $query;
3423
3424 $result = db_query($link, $query);
3425
3426 } else {
3427 // browsing by tag
3428
3429 $feed_kind = "Tags";
3430
3431 $result = db_query($link, "SELECT
3432 guid,
3433 ttrss_entries.id as id,title,
3434 updated,
3435 unread,feed_id,
3436 marked,link,last_read,
3437 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3438 $vfeed_query_part
3439 $content_query_part
3440 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3441 score
3442 FROM
3443 ttrss_entries,ttrss_user_entries,ttrss_tags
3444 WHERE
3445 ref_id = ttrss_entries.id AND
3446 ttrss_user_entries.owner_uid = '$owner_uid' AND
3447 post_int_id = int_id AND tag_name = '$feed' AND
3448 $view_query_part
3449 $search_query_part
3450 $query_strategy_part ORDER BY $order_by
3451 $limit_query_part");
3452 }
3453
3454 return array($result, $feed_title, $feed_site_url, $last_error);
3455
3456 }
3457
3458 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3459 $limit, $search, $search_mode, $match_on) {
3460
3461 if (!$limit) $limit = 30;
3462
3463 $qfh_ret = queryFeedHeadlines($link, $feed,
3464 $limit, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3465 $owner_uid);
3466
3467 $result = $qfh_ret[0];
3468 $feed_title = htmlspecialchars($qfh_ret[1]);
3469 $feed_site_url = $qfh_ret[2];
3470 $last_error = $qfh_ret[3];
3471
3472 // if (!$feed_site_url) $feed_site_url = "http://localhost/";
3473
3474 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3475 <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3476 <rss version=\"2.0\">
3477 <channel>
3478 <title>$feed_title</title>
3479 <link>$feed_site_url</link>
3480 <description>Feed generated by Tiny Tiny RSS</description>";
3481
3482 while ($line = db_fetch_assoc($result)) {
3483 print "<item>";
3484 print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3485 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3486
3487 $tags = get_article_tags($link, $line["id"], $owner_uid);
3488
3489 foreach ($tags as $tag) {
3490 print "<category>" . htmlspecialchars($tag) . "</category>";
3491 }
3492
3493 $rfc822_date = date('r', strtotime($line["updated"]));
3494
3495 print "<pubDate>$rfc822_date</pubDate>";
3496
3497 print "<title>" .
3498 htmlspecialchars($line["title"]) . "</title>";
3499
3500 print "<description><![CDATA[" .
3501 $line["content_preview"] . "]]></description>";
3502
3503 print "</item>";
3504 }
3505
3506 print "</channel></rss>";
3507
3508 }
3509
3510 function getCategoryTitle($link, $cat_id) {
3511
3512 if ($cat_id == -1) {
3513 return __("Special");
3514 } else if ($cat_id == -2) {
3515 return __("Labels");
3516 } else {
3517
3518 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3519 id = '$cat_id'");
3520
3521 if (db_num_rows($result) == 1) {
3522 return db_fetch_result($result, 0, "title");
3523 } else {
3524 return "Uncategorized";
3525 }
3526 }
3527 }
3528
3529 // http://ru2.php.net/strip-tags
3530
3531 function strip_tags_long($textstring, $allowed){
3532 while($textstring != strip_tags($textstring, $allowed))
3533 {
3534 while (strlen($textstring) != 0)
3535 {
3536 if (strlen($textstring) > 1024) {
3537 $otherlen = 1024;
3538 } else {
3539 $otherlen = strlen($textstring);
3540 }
3541 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3542 $safetext .= $temptext;
3543 $textstring = substr_replace($textstring,'',0,$otherlen);
3544 }
3545 $textstring = $safetext;
3546 }
3547 return $textstring;
3548 }
3549
3550
3551 function sanitize_rss($link, $str, $force_strip_tags = false) {
3552 $res = $str;
3553
3554 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
3555
3556 $res = strip_tags_long($res,
3557 "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3558
3559 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
3560 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
3561 }
3562
3563 if (get_pref($link, "STRIP_IMAGES")) {
3564
3565 $res = preg_replace('/<img[^>]+>/is', '', $res);
3566
3567 }
3568
3569 return $res;
3570 }
3571
3572 /**
3573 * Send by mail a digest of last articles.
3574 *
3575 * @param mixed $link The database connection.
3576 * @param integer $limit The maximum number of articles by digest.
3577 * @return boolean Return false if digests are not enabled.
3578 */
3579 function send_headlines_digests($link, $limit = 100) {
3580
3581 if (!DIGEST_ENABLE) return false;
3582
3583 $user_limit = DIGEST_EMAIL_LIMIT;
3584 $days = 1;
3585
3586 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3587
3588 if (DB_TYPE == "pgsql") {
3589 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3590 } else if (DB_TYPE == "mysql") {
3591 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3592 }
3593
3594 $result = db_query($link, "SELECT id,email FROM ttrss_users
3595 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3596
3597 while ($line = db_fetch_assoc($result)) {
3598
3599 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3600 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3601
3602 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3603
3604 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3605 $digest = $tuple[0];
3606 $headlines_count = $tuple[1];
3607 $affected_ids = $tuple[2];
3608 $digest_text = $tuple[3];
3609
3610 if ($headlines_count > 0) {
3611
3612 $mail = new PHPMailer();
3613
3614 $mail->PluginDir = "lib/phpmailer/";
3615 $mail->SetLanguage("en", "lib/phpmailer/language/");
3616
3617 $mail->CharSet = "UTF-8";
3618
3619 $mail->From = DIGEST_FROM_ADDRESS;
3620 $mail->FromName = DIGEST_FROM_NAME;
3621 $mail->AddAddress($line["email"], $line["login"]);
3622
3623 if (DIGEST_SMTP_HOST) {
3624 $mail->Host = DIGEST_SMTP_HOST;
3625 $mail->Mailer = "smtp";
3626 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
3627 $mail->Username = DIGEST_SMTP_LOGIN;
3628 $mail->Password = DIGEST_SMTP_PASSWORD;
3629 }
3630
3631 $mail->IsHTML(true);
3632 $mail->Subject = DIGEST_SUBJECT;
3633 $mail->Body = $digest;
3634 $mail->AltBody = $digest_text;
3635
3636 $rc = $mail->Send();
3637
3638 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
3639
3640 print "RC=$rc\n";
3641
3642 if ($rc && $do_catchup) {
3643 print "Marking affected articles as read...\n";
3644 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3645 }
3646
3647 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
3648 WHERE id = " . $line["id"]);
3649 } else {
3650 print "No headlines\n";
3651 }
3652 }
3653 }
3654
3655 print "All done.\n";
3656
3657 }
3658
3659 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3660
3661 require_once "lib/MiniTemplator.class.php";
3662
3663 $tpl = new MiniTemplator;
3664 $tpl_t = new MiniTemplator;
3665
3666 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3667 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3668
3669 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3670 $tpl->setVariable('CUR_TIME', date('G:i'));
3671
3672 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3673 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3674
3675 $affected_ids = array();
3676
3677 if (DB_TYPE == "pgsql") {
3678 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3679 } else if (DB_TYPE == "mysql") {
3680 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3681 }
3682
3683 $result = db_query($link, "SELECT ttrss_entries.title,
3684 ttrss_feeds.title AS feed_title,
3685 date_entered,
3686 ttrss_user_entries.ref_id,
3687 link,
3688 SUBSTRING(content, 1, 120) AS excerpt,
3689 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
3690 FROM
3691 ttrss_user_entries,ttrss_entries,ttrss_feeds
3692 WHERE
3693 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
3694 AND include_in_digest = true
3695 AND $interval_query
3696 AND hidden = false
3697 AND ttrss_user_entries.owner_uid = $user_id
3698 AND unread = true
3699 ORDER BY ttrss_feeds.title, date_entered DESC
3700 LIMIT $limit");
3701
3702 $cur_feed_title = "";
3703
3704 $headlines_count = db_num_rows($result);
3705
3706 $headlines = array();
3707
3708 while ($line = db_fetch_assoc($result)) {
3709 array_push($headlines, $line);
3710 }
3711
3712 for ($i = 0; $i < sizeof($headlines); $i++) {
3713
3714 $line = $headlines[$i];
3715
3716 array_push($affected_ids, $line["ref_id"]);
3717
3718 $updated = smart_date_time(strtotime($line["last_updated"]));
3719
3720 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3721 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3722 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3723 $tpl->setVariable('ARTICLE_UPDATED', $updated);
3724 $tpl->setVariable('ARTICLE_EXCERPT',
3725 truncate_string(strip_tags($line["excerpt"]), 100));
3726
3727 $tpl->addBlock('article');
3728
3729 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3730 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3731 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3732 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3733 // $tpl_t->setVariable('ARTICLE_EXCERPT',
3734 // truncate_string(strip_tags($line["excerpt"]), 100));
3735
3736 $tpl_t->addBlock('article');
3737
3738 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3739 $tpl->addBlock('feed');
3740 $tpl_t->addBlock('feed');
3741 }
3742
3743 }
3744
3745 $tpl->addBlock('digest');
3746 $tpl->generateOutputToString($tmp);
3747
3748 $tpl_t->addBlock('digest');
3749 $tpl_t->generateOutputToString($tmp_t);
3750
3751 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3752 }
3753
3754 function check_for_update($link) {
3755 $releases_feed = "http://tt-rss.org/releases.rss";
3756
3757 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
3758 return;
3759 }
3760
3761 error_reporting(0);
3762 if (ENABLE_SIMPLEPIE) {
3763 $rss = new SimplePie();
3764 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
3765 // $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3766 $rss->set_feed_url($fetch_url);
3767 $rss->set_output_encoding('UTF-8');
3768 $rss->init();
3769 } else {
3770 $rss = fetch_rss($releases_feed);
3771 }
3772 error_reporting (DEFAULT_ERROR_LEVEL);
3773
3774 if ($rss) {
3775
3776 if (ENABLE_SIMPLEPIE) {
3777 $items = $rss->get_items();
3778 } else {
3779 $items = $rss->items;
3780
3781 if (!$items || !is_array($items)) $items = $rss->entries;
3782 if (!$items || !is_array($items)) $items = $rss;
3783 }
3784
3785 if (!is_array($items) || count($items) == 0) {
3786 return;
3787 }
3788
3789 $latest_item = $items[0];
3790
3791 if (ENABLE_SIMPLEPIE) {
3792 $last_title = $latest_item->get_title();
3793 } else {
3794 $last_title = $latest_item["title"];
3795 }
3796
3797 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3798
3799 if (ENABLE_SIMPLEPIE) {
3800 $release_url = sanitize_rss($link, $latest_item->get_link());
3801 $content = sanitize_rss($link, $latest_item->get_description());
3802 } else {
3803 $release_url = sanitize_rss($link, $latest_item["link"]);
3804 $content = sanitize_rss($link, $latest_item["description"]);
3805 }
3806
3807 if (version_compare(VERSION, $latest_version) == -1) {
3808 return sprintf("New version of Tiny-Tiny RSS (%s) is available:",
3809 $latest_version)."<div class='milestoneDetails'>$content</div>";
3810 } else {
3811 return false;
3812 }
3813 }
3814 }
3815
3816 function markArticlesById($link, $ids, $cmode) {
3817
3818 $tmp_ids = array();
3819
3820 foreach ($ids as $id) {
3821 array_push($tmp_ids, "ref_id = '$id'");
3822 }
3823
3824 $ids_qpart = join(" OR ", $tmp_ids);
3825
3826 if ($cmode == 0) {
3827 db_query($link, "UPDATE ttrss_user_entries SET
3828 marked = false,last_read = NOW()
3829 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3830 } else if ($cmode == 1) {
3831 db_query($link, "UPDATE ttrss_user_entries SET
3832 marked = true
3833 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3834 } else {
3835 db_query($link, "UPDATE ttrss_user_entries SET
3836 marked = NOT marked,last_read = NOW()
3837 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3838 }
3839 }
3840
3841 function publishArticlesById($link, $ids, $cmode) {
3842
3843 $tmp_ids = array();
3844
3845 foreach ($ids as $id) {
3846 array_push($tmp_ids, "ref_id = '$id'");
3847 }
3848
3849 $ids_qpart = join(" OR ", $tmp_ids);
3850
3851 if ($cmode == 0) {
3852 db_query($link, "UPDATE ttrss_user_entries SET
3853 published = false,last_read = NOW()
3854 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3855 } else if ($cmode == 1) {
3856 db_query($link, "UPDATE ttrss_user_entries SET
3857 published = true
3858 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3859 } else {
3860 db_query($link, "UPDATE ttrss_user_entries SET
3861 published = NOT published,last_read = NOW()
3862 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3863 }
3864 }
3865
3866 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3867
3868 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3869
3870 $tmp_ids = array();
3871
3872 foreach ($ids as $id) {
3873 array_push($tmp_ids, "ref_id = '$id'");
3874 }
3875
3876 $ids_qpart = join(" OR ", $tmp_ids);
3877
3878 if ($cmode == 0) {
3879 db_query($link, "UPDATE ttrss_user_entries SET
3880 unread = false,last_read = NOW()
3881 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3882 } else if ($cmode == 1) {
3883 db_query($link, "UPDATE ttrss_user_entries SET
3884 unread = true
3885 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3886 } else {
3887 db_query($link, "UPDATE ttrss_user_entries SET
3888 unread = NOT unread,last_read = NOW()
3889 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3890 }
3891
3892 /* update ccache */
3893
3894 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
3895 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3896
3897 while ($line = db_fetch_assoc($result)) {
3898 ccache_update($link, $line["feed_id"], $owner_uid);
3899 }
3900 }
3901
3902 function catchupArticleById($link, $id, $cmode) {
3903
3904 if ($cmode == 0) {
3905 db_query($link, "UPDATE ttrss_user_entries SET
3906 unread = false,last_read = NOW()
3907 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3908 } else if ($cmode == 1) {
3909 db_query($link, "UPDATE ttrss_user_entries SET
3910 unread = true
3911 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3912 } else {
3913 db_query($link, "UPDATE ttrss_user_entries SET
3914 unread = NOT unread,last_read = NOW()
3915 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3916 }
3917 }
3918
3919 function make_guid_from_title($title) {
3920 return preg_replace("/[ \"\',.:;]/", "-",
3921 mb_strtolower(strip_tags($title), 'utf-8'));
3922 }
3923
3924 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
3925 $feed_id, $is_cat, $search, $match_on,
3926 $search_mode) {
3927
3928 print "<div class=\"headlinesSubToolbar\">";
3929
3930 $page_prev_link = "javascript:viewFeedGoPage(-1)";
3931 $page_next_link = "javascript:viewFeedGoPage(1)";
3932 $page_first_link = "javascript:viewFeedGoPage(0)";
3933
3934 $catchup_page_link = "javascript:catchupPage()";
3935 $catchup_feed_link = "javascript:catchupCurrentFeed()";
3936 $catchup_sel_link = "javascript:catchupSelection()";
3937
3938 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3939
3940 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3941 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3942 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3943 $sel_inv_link = "javascript:invertHeadlineSelection()";
3944
3945 $tog_unread_link = "javascript:selectionToggleUnread()";
3946 $tog_marked_link = "javascript:selectionToggleMarked()";
3947 $tog_published_link = "javascript:selectionTogglePublished()";
3948
3949 } else {
3950
3951 $sel_all_link = "javascript:cdmSelectArticles('all')";
3952 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3953 $sel_none_link = "javascript:cdmSelectArticles('none')";
3954
3955 $sel_inv_link = "javascript:invertHeadlineSelection()";
3956
3957 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3958 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3959 $tog_published_link = "javascript:selectionTogglePublished(true)";
3960
3961 }
3962
3963 print "<div id=\"subtoolbar_ftitle\">";
3964
3965 if ($feed_site_url) {
3966 if (!$bottom) {
3967 $target = "target=\"_blank\"";
3968 }
3969 print "<a $target href=\"$feed_site_url\">".
3970 truncate_string($feed_title,30)."</a>";
3971 } else {
3972 print $feed_title;
3973 }
3974
3975 if ($search) {
3976 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3977 }
3978
3979 print "
3980 <a target=\"_blank\"
3981 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3982 <img class=\"noborder\"
3983 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3984 </a>";
3985
3986 print "</div>";
3987
3988 print __('Select:')."
3989 <a href=\"$sel_all_link\">".__('All')."</a>,
3990 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3991 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
3992 <a href=\"$sel_none_link\">".__('None')."</a></li>";
3993
3994 print "&nbsp;&nbsp;";
3995
3996 print "<span
3997 onmouseover=\"enable_selection(false)\"
3998 onmouseout=\"enable_selection(true)\"
3999 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4000 __("Actions...") . "&nbsp;&nbsp;<img src=\"images/down_arrow.png\">
4001 </span>";
4002
4003 print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4004
4005 print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4006 <li onclick=\"$tog_unread_link\">&nbsp;&nbsp;".__('Unread')."</li>
4007 <li onclick=\"$tog_marked_link\">&nbsp;&nbsp;".__('Starred')."</li>
4008 <li onclick=\"$tog_published_link\">&nbsp;&nbsp;".__('Published')."</li>
4009 <!-- <li><span class=\"insensitive\">--------</span></li> -->
4010 <li class=\"insensitive\">".__('Mark as read:')."</li>
4011 <li onclick=\"$catchup_sel_link\">&nbsp;&nbsp;".__('Selection')."</li>";
4012
4013 print "<li onclick=\"$catchup_feed_link\">&nbsp;&nbsp;".__('Entire feed').
4014 "</li>";
4015
4016 //print "<li><span class=\"insensitive\">--------</span></li>";
4017 print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4018
4019 print_labels_headlines_dropdown($link, $feed_id);
4020
4021 print "</ul>";
4022
4023 print "</div>";
4024 }
4025
4026 function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4027
4028 $tmp_category = getCategoryTitle($link, $cat_id);
4029
4030 if ($cat_id > 0) {
4031 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4032 } else if ($cat_id == 0 || $cat_id == -2) {
4033 $cat_unread = getCategoryUnread($link, $cat_id);
4034 }
4035
4036 if ($hidden) {
4037 $holder_style = "display:none;";
4038 $ellipsis = "…";
4039 } else {
4040 $holder_style = "";
4041 $ellipsis = "";
4042 }
4043
4044 $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4045
4046 if ($can_browse) {
4047 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4048 $inner_title_class = "catTitle";
4049 } else {
4050 $browse_cat_link = "";
4051 $inner_title_class = "catTitleNL";
4052 }
4053
4054 $cat_class = "feedCat";
4055
4056 print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4057 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4058 title=\"".__('Click to collapse category')."\"
4059 src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\"
4060 id=\"FCATN-$cat_id\" $browse_cat_link
4061 \">$tmp_category</span>";
4062
4063 print "<span id=\"FCAP-$cat_id\">";
4064
4065 print " <span id=\"FCATCTR-$cat_id\"
4066 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4067
4068 print "</span>";
4069
4070 //print "</li>";
4071
4072 print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4073
4074 }
4075
4076 function outputFeedList($link, $tags = false) {
4077
4078 print "<ul class=\"feedList\" id=\"feedList\">";
4079
4080 $owner_uid = $_SESSION["uid"];
4081
4082 /* virtual feeds */
4083
4084 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4085
4086 if ($_COOKIE["ttrss_vf_vclps"] == 1) {
4087 $cat_hidden = true;
4088 } else {
4089 $cat_hidden = false;
4090 }
4091
4092 printCategoryHeader($link, -1, $cat_hidden, false);
4093 }
4094
4095 $num_starred = getFeedUnread($link, -1);
4096 $num_published = getFeedUnread($link, -2);
4097 $num_fresh = getFeedUnread($link, -3);
4098 $num_total = getFeedUnread($link, -4);
4099
4100 $class = "virt";
4101
4102 if ($num_total > 0) $class .= "Unread";
4103
4104 printFeedEntry(-4, $class, __("All articles"), $num_total,
4105 "images/tag.png", $link);
4106
4107 $class = "virt";
4108
4109 if ($num_fresh > 0) $class .= "Unread";
4110
4111 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh,
4112 "images/fresh.png", $link);
4113
4114 $class = "virt";
4115
4116 if ($num_starred > 0) $class .= "Unread";
4117
4118 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4119
4120 if ($is_ie) {
4121 $mark_img_ext = "gif";
4122 } else {
4123 $mark_img_ext = "png";
4124 }
4125
4126 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
4127 "images/mark_set.$mark_img_ext", $link);
4128
4129 $class = "virt";
4130
4131 if ($num_published > 0) $class .= "Unread";
4132
4133 printFeedEntry(-2, $class, __("Published articles"), $num_published,
4134 "images/pub_set.gif", $link);
4135
4136 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4137 print "</ul></li>";
4138 }
4139
4140 if (!$tags) {
4141
4142
4143 $result = db_query($link, "SELECT * FROM
4144 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4145
4146 if (db_num_rows($result) > 0) {
4147 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4148
4149 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
4150 $cat_hidden = true;
4151 } else {
4152 $cat_hidden = false;
4153 }
4154
4155 printCategoryHeader($link, -2, $cat_hidden, true);
4156
4157 } else {
4158 print "<li><hr></li>";
4159 }
4160 }
4161
4162 while ($line = db_fetch_assoc($result)) {
4163
4164 $label_id = -$line['id'] - 11;
4165 $count = getFeedUnread($link, $label_id);
4166
4167 $class = "label";
4168
4169 if ($count > 0) {
4170 $class .= "Unread";
4171 }
4172
4173 printFeedEntry($label_id,
4174 $class, $line["caption"],
4175 $count, "images/label.png", $link,
4176 false, false, false,
4177 $line['fg_color'], $line['bg_color']);
4178
4179 }
4180
4181 if (db_num_rows($result) > 0) {
4182 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4183 print "</ul>";
4184 }
4185 }
4186
4187
4188 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4189 print "<li><hr></li>";
4190 }
4191
4192 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4193 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4194 $order_by_qpart = "order_id,category,unread DESC,title";
4195 } else {
4196 $order_by_qpart = "order_id,category,title";
4197 }
4198 } else {
4199 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4200 $order_by_qpart = "unread DESC,title";
4201 } else {
4202 $order_by_qpart = "title";
4203 }
4204 }
4205
4206 $age_qpart = getMaxAgeSubquery();
4207
4208 $query = "SELECT ttrss_feeds.*,
4209 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4210 cat_id,last_error,
4211 ttrss_feed_categories.title AS category,
4212 ttrss_feed_categories.collapsed,
4213 value AS unread
4214 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4215 ON (ttrss_feed_categories.id = cat_id)
4216 LEFT JOIN ttrss_counters_cache
4217 ON
4218 (ttrss_feeds.id = feed_id)
4219 WHERE
4220 ttrss_feeds.hidden = false AND
4221 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4222 ORDER BY $order_by_qpart";
4223
4224 $result = db_query($link, $query);
4225
4226 $actid = $_GET["actid"];
4227
4228 /* real feeds */
4229
4230 $lnum = 0;
4231
4232 $total_unread = 0;
4233
4234 $category = "";
4235
4236 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4237
4238 while ($line = db_fetch_assoc($result)) {
4239
4240 $feed = trim($line["title"]);
4241
4242 if (!$feed) $feed = "[Untitled]";
4243
4244 $feed_id = $line["id"];
4245 $unread = $line["unread"];
4246
4247 $subop = $_GET["subop"];
4248
4249 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4250 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4251 } else {
4252 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4253 }
4254
4255 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4256
4257 if ($rtl_content) {
4258 $rtl_tag = "dir=\"RTL\"";
4259 } else {
4260 $rtl_tag = "";
4261 }
4262
4263 $tmp_result = db_query($link,
4264 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache
4265 WHERE parent_feed = '$feed_id' AND feed_id = id");
4266
4267 $unread += db_fetch_result($tmp_result, 0, "unread");
4268
4269 $cat_id = $line["cat_id"];
4270
4271 $tmp_category = $line["category"];
4272
4273 if (!$tmp_category) {
4274 $tmp_category = __("Uncategorized");
4275 }
4276
4277 // $class = ($lnum % 2) ? "even" : "odd";
4278
4279 if ($line["last_error"]) {
4280 $class = "error";
4281 } else {
4282 $class = "feed";
4283 }
4284
4285 if ($unread > 0) $class .= "Unread";
4286
4287 if ($actid == $feed_id) {
4288 $class .= "Selected";
4289 }
4290
4291 $total_unread += $unread;
4292
4293 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4294
4295 if ($category) {
4296 print "</ul></li>";
4297 }
4298
4299 $category = $tmp_category;
4300
4301 $collapsed = sql_bool_to_bool($line["collapsed"]);
4302
4303 // workaround for NULL category
4304 if ($category == __("Uncategorized")) {
4305 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4306 $collapsed = "t";
4307 }
4308 }
4309
4310 $cat_id = sprintf("%d", $cat_id);
4311
4312 printCategoryHeader($link, $cat_id, $collapsed, true);
4313
4314 }
4315
4316 printFeedEntry($feed_id, $class, $feed, $unread,
4317 ICONS_URL."/$feed_id.ico", $link, $rtl_content,
4318 $last_updated, $line["last_error"]);
4319
4320 ++$lnum;
4321 }
4322
4323 if (db_num_rows($result) == 0) {
4324 print "<li>".__('No feeds to display.')."</li>";
4325 }
4326
4327 } else {
4328
4329 // tags
4330
4331 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4332 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4333 post_int_id = ttrss_user_entries.int_id AND
4334 unread = true AND ref_id = ttrss_entries.id
4335 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
4336 UNION
4337 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4338 ORDER BY tag_name"); */
4339
4340 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4341 print "<li class=\"feedCat\">".__('Tags')."</li>";
4342 print "<ul class=\"feedCatList\">";
4343 }
4344
4345 $age_qpart = getMaxAgeSubquery();
4346
4347 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
4348 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
4349 AND ref_id = id AND $age_qpart
4350 AND unread = true)) AS count FROM ttrss_tags
4351 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
4352 ORDER BY count DESC LIMIT 50");
4353
4354 $tags = array();
4355
4356 while ($line = db_fetch_assoc($result)) {
4357 $tags[$line["tag_name"]] += $line["count"];
4358 }
4359
4360 foreach (array_keys($tags) as $tag) {
4361
4362 $unread = $tags[$tag];
4363
4364 $class = "tag";
4365
4366 if ($unread > 0) {
4367 $class .= "Unread";
4368 }
4369
4370 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4371
4372 }
4373
4374 if (db_num_rows($result) == 0) {
4375 print "<li>No tags to display.</li>";
4376 }
4377
4378 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4379 print "</ul>";
4380 }
4381
4382 }
4383
4384 print "</ul>";
4385
4386 }
4387
4388 function get_article_tags($link, $id, $owner_uid = 0) {
4389
4390 $a_id = db_escape_string($id);
4391
4392 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4393
4394 $tmp_result = db_query($link, "SELECT DISTINCT tag_name,
4395 owner_uid as owner FROM
4396 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4397 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4398
4399 $tags = array();
4400
4401 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4402 array_push($tags, $tmp_line["tag_name"]);
4403 }
4404
4405 return $tags;
4406 }
4407
4408 function trim_value(&$value) {
4409 $value = trim($value);
4410 }
4411
4412 function trim_array($array) {
4413 $tmp = $array;
4414 array_walk($tmp, 'trim_value');
4415 return $tmp;
4416 }
4417
4418 function tag_is_valid($tag) {
4419 if ($tag == '') return false;
4420 if (preg_match("/^[0-9]*$/", $tag)) return false;
4421
4422 if (function_exists('iconv')) {
4423 $tag = iconv("utf-8", "utf-8", $tag);
4424 }
4425
4426 if (!$tag) return false;
4427
4428 return true;
4429 }
4430
4431 function render_login_form($link, $mobile = false) {
4432 if (!$mobile) {
4433 require_once "login_form.php";
4434 } else {
4435 require_once "mobile/login_form.php";
4436 }
4437 }
4438
4439 // from http://developer.apple.com/internet/safari/faq.html
4440 function no_cache_incantation() {
4441 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4442 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4443 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4444 header("Cache-Control: post-check=0, pre-check=0", false);
4445 header("Pragma: no-cache"); // HTTP/1.0
4446 }
4447
4448 function format_warning($msg, $id = "") {
4449 return "<div class=\"warning\" id=\"$id\">
4450 <img src=\"images/sign_excl.gif\">$msg</div>";
4451 }
4452
4453 function format_notice($msg) {
4454 return "<div class=\"notice\">
4455 <img src=\"images/sign_info.gif\">$msg</div>";
4456 }
4457
4458 function format_error($msg) {
4459 return "<div class=\"error\">
4460 <img src=\"images/sign_excl.gif\">$msg</div>";
4461 }
4462
4463 function print_notice($msg) {
4464 return print format_notice($msg);
4465 }
4466
4467 function print_warning($msg) {
4468 return print format_warning($msg);
4469 }
4470
4471 function print_error($msg) {
4472 return print format_error($msg);
4473 }
4474
4475
4476 function T_sprintf() {
4477 $args = func_get_args();
4478 return vsprintf(__(array_shift($args)), $args);
4479 }
4480
4481 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4482 $zoom_mode = false) {
4483
4484 /* we can figure out feed_id from article id anyway, why do we
4485 * pass feed_id here? */
4486
4487 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4488 WHERE ref_id = '$id'");
4489
4490 $feed_id = db_fetch_result($result, 0, "feed_id");
4491
4492 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4493
4494 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4495 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4496
4497 if (db_num_rows($result) == 1) {
4498 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4499 } else {
4500 $rtl_content = false;
4501 }
4502
4503 if ($rtl_content) {
4504 $rtl_tag = "dir=\"RTL\"";
4505 $rtl_class = "RTL";
4506 } else {
4507 $rtl_tag = "";
4508 $rtl_class = "";
4509 }
4510
4511 if ($mark_as_read) {
4512 $result = db_query($link, "UPDATE ttrss_user_entries
4513 SET unread = false,last_read = NOW()
4514 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4515
4516 ccache_update($link, $feed_id, $_SESSION["uid"]);
4517 }
4518
4519 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4520 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
4521 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4522 num_comments,
4523 author
4524 FROM ttrss_entries,ttrss_user_entries
4525 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4526
4527 if ($result) {
4528
4529 $link_target = "";
4530
4531 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4532 $link_target = "target=\"_blank\"";
4533 }
4534
4535 $line = db_fetch_assoc($result);
4536
4537 if ($line["icon_url"]) {
4538 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4539 } else {
4540 $feed_icon = "&nbsp;";
4541 }
4542
4543 $num_comments = $line["num_comments"];
4544 $entry_comments = "";
4545
4546 if ($num_comments > 0) {
4547 if ($line["comments"]) {
4548 $comments_url = $line["comments"];
4549 } else {
4550 $comments_url = $line["link"];
4551 }
4552 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4553 } else {
4554 if ($line["comments"] && $line["link"] != $line["comments"]) {
4555 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4556 }
4557 }
4558
4559 if ($zoom_mode) {
4560 header("Content-Type: text/html");
4561 print "<html><head>
4562 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4563 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4564 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4565 </head><body>";
4566 }
4567
4568
4569 print "<div class=\"postReply\">";
4570
4571 print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\"
4572 onmouseout=\"enable_resize(false)\">";
4573
4574 $entry_author = $line["author"];
4575
4576 if ($entry_author) {
4577 $entry_author = __(" - ") . $entry_author;
4578 }
4579
4580 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
4581 strtotime($line["updated"]));
4582
4583 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4584
4585 if ($line["link"]) {
4586 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
4587 $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4588 } else {
4589 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4590 }
4591
4592 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4593
4594 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4595
4596 print "<div style='float : right'>
4597 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>";
4598
4599 if (!$zoom_mode) {
4600 print "<span id=\"ATSTR-$id\">$tags_str</span>
4601 <a title=\"".__('Edit tags for this article')."\"
4602 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4603
4604 if (defined('_ENABLE_INLINE_VIEW')) {
4605
4606 print "<img src=\"images/art-inline.png\" class='tagsPic'
4607 style=\"cursor : pointer\" style=\"cursor : pointer\"
4608 onclick=\"showOriginalArticleInline($id)\"
4609 alt='Inline' title='".__('Display original article content')."'>";
4610
4611 }
4612
4613 print "<img src=\"images/art-zoom.png\" class='tagsPic'
4614 style=\"cursor : pointer\" style=\"cursor : pointer\"
4615 onclick=\"zoomToArticle($id)\"
4616 alt='Zoom' title='".__('Show article summary in new window')."'>";
4617 }
4618 print "</div>";
4619 print "<div clear='both'>$entry_comments</div>";
4620
4621 print "</div>";
4622
4623 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4624
4625 print "<div class=\"postContent\">";
4626
4627 $article_content = sanitize_rss($link, $line["content"]);
4628
4629 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4630 $article_content = preg_replace("/href=/i", "target=\"_blank\" href=",
4631 $article_content);
4632 }
4633
4634 print $article_content;
4635
4636 $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4637 post_id = '$id' AND content_url != ''");
4638
4639 if (db_num_rows($result) > 0) {
4640
4641 $entries_html = array();
4642 $entries = array();
4643
4644 while ($line = db_fetch_assoc($result)) {
4645
4646 $url = $line["content_url"];
4647 $ctype = $line["content_type"];
4648
4649 if (!$ctype) $ctype = __("unknown type");
4650
4651 $filename = substr($url, strrpos($url, "/")+1);
4652
4653 $entry = "";
4654
4655 if (($ctype == __("audio/mpeg")) &&
4656 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4657
4658 $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> ";
4659
4660 }
4661
4662 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4663 $filename . " (" . $ctype . ")" . "</a>";
4664
4665 array_push($entries_html, $entry);
4666
4667 $entry = array();
4668
4669 $entry["type"] = $ctype;
4670 $entry["filename"] = $filename;
4671 $entry["url"] = $url;
4672
4673 array_push($entries, $entry);
4674 }
4675
4676 print "<div class=\"postEnclosures\">";
4677
4678 if (!preg_match("/img/i", $article_content)) {
4679 foreach ($entries as $entry) {
4680 if (preg_match("/image/", $entry["type"])) {
4681 print "<p><img
4682 alt=\"".htmlspecialchars($entry["filename"])."\"
4683 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
4684 }
4685 }
4686 }
4687
4688 print "<div class=\"postEnclosures\">";
4689
4690 if (db_num_rows($result) == 1) {
4691 print __("Attachment:") . " ";
4692 } else {
4693 print __("Attachments:") . " ";
4694 }
4695
4696 print join(", ", $entries_html);
4697
4698 print "</div>";
4699 }
4700
4701 print "</div>";
4702
4703 print "</div>";
4704
4705 }
4706
4707 if (!$zoom_mode) {
4708 print "]]></article>";
4709 } else {
4710 print "
4711 <div style=\"text-align : center\">
4712 <input type=\"submit\" onclick=\"return window.close()\"
4713 value=\"".__("Close this window")."\"></div>";
4714 print "</body></html>";
4715
4716 }
4717
4718 }
4719
4720 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4721 $next_unread_feed, $offset, $vgr_last_feed = false,
4722 $override_order = false) {
4723
4724 $disable_cache = false;
4725
4726 $timing_info = getmicrotime();
4727
4728 $topmost_article_ids = array();
4729
4730 if (!$offset) {
4731 $offset = 0;
4732 }
4733
4734 if ($subop == "undefined") $subop = "";
4735
4736 $subop_split = split(":", $subop);
4737
4738 if ($subop == "CatchupSelected") {
4739 $ids = split(",", db_escape_string($_GET["ids"]));
4740 $cmode = sprintf("%d", $_GET["cmode"]);
4741
4742 catchupArticlesById($link, $ids, $cmode);
4743 }
4744
4745 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4746 update_generic_feed($link, $feed, $cat_view, true);
4747 }
4748
4749 if ($subop == "MarkAllRead") {
4750 catchup_feed($link, $feed, $cat_view);
4751
4752 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4753 if ($next_unread_feed) {
4754 $feed = $next_unread_feed;
4755 }
4756 }
4757 }
4758
4759 if ($subop_split[0] == "MarkAllReadGR") {
4760 catchup_feed($link, $subop_split[1], false);
4761 }
4762
4763
4764 if ($feed_id > 0) {
4765 $result = db_query($link,
4766 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4767
4768 if (db_num_rows($result) == 0) {
4769 print "<div align='center'>".__('Feed not found.')."</div>";
4770 return;
4771 }
4772 }
4773
4774 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4775
4776 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4777 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4778
4779 if (db_num_rows($result) == 1) {
4780 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4781 } else {
4782 $rtl_content = false;
4783 }
4784
4785 if ($rtl_content) {
4786 $rtl_tag = "dir=\"RTL\"";
4787 } else {
4788 $rtl_tag = "";
4789 }
4790 } else {
4791 $rtl_tag = "";
4792 $rtl_content = false;
4793 }
4794
4795 $script_dt_add = get_script_dt_add();
4796
4797 /// START /////////////////////////////////////////////////////////////////////////////////
4798
4799 $search = db_escape_string($_GET["query"]);
4800
4801 if ($search) {
4802 $disable_cache = true;
4803 }
4804
4805 $search_mode = db_escape_string($_GET["search_mode"]);
4806 $match_on = db_escape_string($_GET["match_on"]);
4807
4808 if (!$match_on) {
4809 $match_on = "both";
4810 }
4811
4812 $real_offset = $offset * $limit;
4813
4814 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4815
4816 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4817 $search, $search_mode, $match_on, $override_order, $real_offset);
4818
4819 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4820
4821 $result = $qfh_ret[0];
4822 $feed_title = $qfh_ret[1];
4823 $feed_site_url = $qfh_ret[2];
4824 $last_error = $qfh_ret[3];
4825
4826 $vgroup_last_feed = $vgr_last_feed;
4827
4828 if ($feed == -2) {
4829 $feed_site_url = article_publish_url($link);
4830 }
4831
4832 /// STOP //////////////////////////////////////////////////////////////////////////////////
4833
4834 if (!$offset) {
4835 print "<div id=\"headlinesContainer\" $rtl_tag>";
4836
4837 if (!$result) {
4838 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4839 return;
4840 }
4841
4842 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4843 $feed, $cat_view, $search, $match_on, $search_mode);
4844
4845 print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4846 }
4847
4848 $headlines_count = db_num_rows($result);
4849
4850 if (db_num_rows($result) > 0) {
4851
4852 # print "\{$offset}";
4853
4854 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4855 print "<table class=\"headlinesList\" id=\"headlinesList\"
4856 cellspacing=\"0\">";
4857 }
4858
4859 $lnum = $limit*$offset;
4860
4861 error_reporting (DEFAULT_ERROR_LEVEL);
4862
4863 $num_unread = 0;
4864 $cur_feed_title = '';
4865
4866 while ($line = db_fetch_assoc($result)) {
4867
4868 $class = ($lnum % 2) ? "even" : "odd";
4869
4870 $id = $line["id"];
4871 $feed_id = $line["feed_id"];
4872
4873 $labels = get_article_labels($link, $id);
4874
4875 $labels_str = "<span id=\"HLLCTR-$id\">";
4876 $labels_str .= format_article_labels($labels, $id);
4877 $labels_str .= "</span>";
4878
4879 if (count($topmost_article_ids) < 5) {
4880 array_push($topmost_article_ids, $id);
4881 }
4882
4883 if ($line["last_read"] == "" &&
4884 ($line["unread"] != "t" && $line["unread"] != "1")) {
4885
4886 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
4887 alt=\"Updated\">";
4888 } else {
4889 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4890 alt=\"Updated\">";
4891 }
4892
4893 if ($line["unread"] == "t" || $line["unread"] == "1") {
4894 $class .= "Unread";
4895 ++$num_unread;
4896 $is_unread = true;
4897 } else {
4898 $is_unread = false;
4899 }
4900
4901 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4902
4903 if ($is_ie) {
4904 $mark_img_ext = "gif";
4905 } else {
4906 $mark_img_ext = "png";
4907 }
4908
4909 if ($line["marked"] == "t" || $line["marked"] == "1") {
4910 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\"
4911 class=\"markedPic\"
4912 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4913 } else {
4914 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\"
4915 class=\"markedPic\"
4916 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4917 }
4918
4919 if ($line["published"] == "t" || $line["published"] == "1") {
4920 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\"
4921 class=\"markedPic\"
4922 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4923 } else {
4924 $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\"
4925 class=\"markedPic\"
4926 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4927 }
4928
4929 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4930 # $line["title"] . "</a>";
4931
4932 # $content_link = "<a
4933 # href=\"" . htmlspecialchars($line["link"]) . "\"
4934 # onclick=\"view($id,$feed_id);\">" .
4935 # $line["title"] . "</a>";
4936
4937 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4938 # $line["title"] . "</a>";
4939
4940 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4941 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4942 } else {
4943 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4944 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4945 }
4946
4947 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4948 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4949 100);
4950 }
4951
4952 $score = $line["score"];
4953
4954 $score_pic = get_score_pic($score);
4955
4956 /* $score_title = __("(Click to change)");
4957 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4958 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4959
4960 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4961 title=\"$score\">";
4962
4963 if ($score > 500) {
4964 $hlc_suffix = "H";
4965 } else if ($score < -100) {
4966 $hlc_suffix = "L";
4967 } else {
4968 $hlc_suffix = "";
4969 }
4970
4971 $entry_author = $line["author"];
4972
4973 if ($entry_author) {
4974 $entry_author = " - $entry_author";
4975 }
4976
4977 $has_feed_icon = feed_has_icon($feed_id);
4978
4979 if ($has_feed_icon) {
4980 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
4981 } else {
4982 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
4983 $feed_icon_img = "";
4984 }
4985
4986 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4987
4988 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
4989 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
4990
4991 $cur_feed_title = $line["feed_title"];
4992 $vgroup_last_feed = $feed_id;
4993
4994 $cur_feed_title = htmlspecialchars($cur_feed_title);
4995
4996 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
4997
4998 print "<tr class='feedTitle'><td colspan='7'>".
4999 "<div style=\"float : right\">$feed_icon_img</div>".
5000 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5001 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5002 }
5003 }
5004
5005 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5006 onmouseout='postMouseOut($id)'";
5007
5008 print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5009
5010 print "<td class='hlUpdPic'>$update_pic</td>";
5011
5012 print "<td class='hlSelectRow'>
5013 <input type=\"checkbox\" onclick=\"tSR(this)\"
5014 id=\"RCHK-$id\">
5015 </td>";
5016
5017 print "<td class='hlMarkedPic'>$marked_pic</td>";
5018 print "<td class='hlMarkedPic'>$published_pic</td>";
5019
5020 # if ($line["feed_title"]) {
5021 # print "<td class='hlContent'>$content_link</td>";
5022 # print "<td class='hlFeed'>
5023 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5024 # truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
5025 # } else {
5026
5027 print "<td onclick='view($id,$feed_id)' class='hlContent$hlc_suffix' valign='middle'>";
5028
5029 print "<a id=\"RTITLE-$id\"
5030 href=\"" . htmlspecialchars($line["link"]) . "\"
5031 onclick=\"return view($id,$feed_id);\">" .
5032 $line["title"];
5033
5034 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5035 if ($content_preview) {
5036 print "<span class=\"contentPreview\"> - $content_preview</span>";
5037 }
5038 }
5039
5040 print "</a>";
5041
5042 print $labels_str;
5043
5044 # <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5045 # $line["feed_title"]."</a>
5046
5047 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5048 if ($line["feed_title"]) {
5049 print "<span class=\"hlFeed\">
5050 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5051 $line["feed_title"]."</a>)
5052 </span>";
5053 }
5054 }
5055 print "</td>";
5056
5057 # }
5058
5059 print "<td class=\"hlUpdated\" onclick='view($id,$feed_id)'><nobr>$updated_fmt&nbsp;</nobr></td>";
5060
5061 print "<td class='hlMarkedPic'>$score_pic</td>";
5062
5063 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5064 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5065 }
5066
5067 print "</tr>";
5068
5069 } else {
5070
5071 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5072 if ($feed_id != $vgroup_last_feed) {
5073
5074 $cur_feed_title = $line["feed_title"];
5075 $vgroup_last_feed = $feed_id;
5076
5077 $cur_feed_title = htmlspecialchars($cur_feed_title);
5078
5079 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>mark as read</a>)";
5080
5081 $has_feed_icon = feed_has_icon($feed_id);
5082
5083 if ($has_feed_icon) {
5084 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5085 } else {
5086 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5087 }
5088
5089 print "<div class='cdmFeedTitle'>".
5090 "<div style=\"float : right\">$feed_icon_img</div>".
5091 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5092 $line["feed_title"]."</a> $vf_catchup_link</div>";
5093 }
5094 }
5095
5096 if ($is_unread) {
5097 $add_class = "Unread";
5098 } else {
5099 $add_class = "";
5100 }
5101
5102 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5103 $show_excerpt = false;
5104
5105 if ($expand_cdm && $score >= -100) {
5106 $cdm_cstyle = "";
5107 $show_excerpt = false;
5108 } else {
5109 $cdm_cstyle = "style=\"display : none\"";
5110 $show_excerpt = true;
5111 }
5112
5113 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5114 onmouseout='postMouseOut($id)'";
5115
5116 print "<div class=\"cdmArticle$add_class\"
5117 id=\"RROW-$id\"
5118 $mouseover_attrs'>";
5119
5120 print "<div class=\"cdmHeader\">";
5121
5122 if (!get_pref($link, "VFEED_GROUP_BY_FEED") || !$line["feed_title"]) {
5123 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5124 }
5125
5126 print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5127 </div>";
5128
5129 print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\"
5130 onclick=\"javascript:toggleUnread($id, 0)\"
5131 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5132 ";
5133
5134 print $entry_author;
5135
5136 /* if (!$expand_cdm || $score < -100) {
5137 print "&nbsp;<a id=\"CICH-$id\"
5138 href=\"javascript:cdmExpandArticle($id)\">
5139 (".__('Show article').")</a>";
5140 } */
5141
5142 print $labels_str;
5143
5144 if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5145 if ($line["feed_title"]) {
5146 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5147 }
5148 }
5149
5150 print "</span></div>";
5151
5152 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
5153 $line["content_preview"] = preg_replace("/href=/i",
5154 "target=\"_blank\" href=", $line["content_preview"]);
5155 }
5156
5157 if ($show_excerpt) {
5158 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5159 onclick=\"cdmExpandArticle($id)\"
5160 title=\"".__('Click to expand article')."\">";
5161 print truncate_string(strip_tags($line["content_preview"]), 100);
5162 print "</div>";
5163 }
5164
5165 print "<div class=\"cdmContent\"
5166 onclick=\"cdmClicked($id)\"
5167 id=\"CICD-$id\" $cdm_cstyle>";
5168
5169 // print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5170
5171 print sanitize_rss($link, $line["content_preview"]);
5172 $article_content = $line["content_preview"];
5173
5174 $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5175 post_id = '$id' AND content_url != ''");
5176
5177 if (db_num_rows($e_result) > 0) {
5178
5179 $entries_html = array();
5180 $entries = array();
5181
5182 while ($e_line = db_fetch_assoc($e_result)) {
5183
5184 $url = $e_line["content_url"];
5185 $ctype = $e_line["content_type"];
5186 if (!$ctype) $ctype = __("unknown type");
5187
5188 $filename = substr($url, strrpos($url, "/")+1);
5189
5190 $entry = "";
5191
5192 if (($ctype == __("audio/mpeg")) &&
5193 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
5194
5195 $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> ";
5196
5197 }
5198
5199 $entry .= "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5200 $filename . " (" . $ctype . ")" . "</a>";
5201
5202 array_push($entries_html, $entry);
5203
5204 $entry = array();
5205
5206 $entry["type"] = $ctype;
5207 $entry["filename"] = $filename;
5208 $entry["url"] = $url;
5209
5210 array_push($entries, $entry);
5211 }
5212
5213 if (!preg_match("/img/i", $article_content)) {
5214 foreach ($entries as $entry) {
5215 if (preg_match("/image/", $entry["type"])) {
5216 print "<p><img
5217 alt=\"".htmlspecialchars($entry["filename"])."\"
5218 src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5219 }
5220 }
5221 }
5222
5223 print "<div class=\"cdmEnclosures\">";
5224
5225 if (db_num_rows($e_result) == 1) {
5226 print __("Attachment:") . " ";
5227 } else {
5228 print __("Attachments:") . " ";
5229 }
5230
5231 print join(", ", $entries_html);
5232
5233 print "</div>";
5234 }
5235
5236
5237 print "<br clear='both'>";
5238 // print "</div>";
5239
5240 /* if (!$expand_cdm) {
5241 print "<a id=\"CICH-$id\"
5242 href=\"javascript:cdmExpandArticle($id)\">
5243 Show article</a>";
5244 } */
5245
5246 print "</div>";
5247
5248 print "<div class=\"cdmFooter\"><span class='s0'>";
5249
5250 /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5251
5252 print __("Select:").
5253 " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5254 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5255
5256 print "</span><span class='s1'>$marked_pic</span> ";
5257 print "<span class='s1'>$published_pic</span> ";
5258 print "<span class='s1'><img src=\"images/art-zoom.png\" class='tagsPic'
5259 onclick=\"zoomToArticle($id)\"
5260 style=\"cursor : pointer\"
5261 alt='Zoom'
5262 title='".__('Show article summary in new window')."'></span>";
5263
5264 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5265
5266 // print "<img src='images/tag.png' class='markedPic'>";
5267
5268 print "<span class='s1'>
5269 <img class='tagsPic' src='images/tag.png' alt='Tags' title='Tags'>
5270 <span id=\"ATSTR-$id\">$tags_str</span>
5271 <a title=\"".__('Edit tags for this article')."\"
5272 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5273
5274 print "</span>";
5275
5276 print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
5277 href=\"javascript:toggleUnread($id)\">
5278 Unread</a></span>";
5279
5280 print "</div>";
5281 print "</div>";
5282
5283 }
5284
5285 ++$lnum;
5286 }
5287
5288 if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5289 print "</table>";
5290 }
5291
5292 } else {
5293 $message = "";
5294
5295 switch ($view_mode) {
5296 case "unread":
5297 $message = __("No unread articles found to display.");
5298 break;
5299 case "updated":
5300 $message = __("No updated articles found to display.");
5301 break;
5302 case "marked":
5303 $message = __("No starred articles found to display.");
5304 break;
5305 default:
5306 if ($feed < -10) {
5307 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5308 } else {
5309 $message = __("No articles found to display.");
5310 }
5311 }
5312
5313 if (!$offset) print "<div class='whiteBox'>$message</div>";
5314 }
5315
5316 if (!$offset) {
5317 print "</div>";
5318 print "</div>";
5319 }
5320
5321 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5322 }
5323
5324 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5325
5326 function printTagCloud($link) {
5327
5328 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5329 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5330 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5331
5332 $result = db_query($link, $query);
5333
5334 $tags = array();
5335
5336 while ($line = db_fetch_assoc($result)) {
5337 $tags[$line["tag_name"]] = $line["count"];
5338 }
5339
5340 ksort($tags);
5341
5342 $max_size = 32; // max font size in pixels
5343 $min_size = 11; // min font size in pixels
5344
5345 // largest and smallest array values
5346 $max_qty = max(array_values($tags));
5347 $min_qty = min(array_values($tags));
5348
5349 // find the range of values
5350 $spread = $max_qty - $min_qty;
5351 if ($spread == 0) { // we don't want to divide by zero
5352 $spread = 1;
5353 }
5354
5355 // set the font-size increment
5356 $step = ($max_size - $min_size) / ($spread);
5357
5358 // loop through the tag array
5359 foreach ($tags as $key => $value) {
5360 // calculate font-size
5361 // find the $value in excess of $min_qty
5362 // multiply by the font-size increment ($size)
5363 // and add the $min_size set above
5364 $size = round($min_size + (($value - $min_qty) * $step));
5365
5366 $key_escaped = str_replace("'", "\\'", $key);
5367
5368 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5369 $size . "px\" title=\"$value articles tagged with " .
5370 $key . '">' . $key . '</a> ';
5371 }
5372 }
5373
5374 function print_checkpoint($n, $s) {
5375 $ts = getmicrotime();
5376 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5377 return $ts;
5378 }
5379
5380 function sanitize_tag($tag) {
5381 $tag = trim($tag);
5382
5383 $tag = mb_strtolower($tag, 'utf-8');
5384
5385 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5386
5387 // $tag = str_replace('"', "", $tag);
5388 // $tag = str_replace("+", " ", $tag);
5389 $tag = str_replace("technorati tag: ", "", $tag);
5390
5391 return $tag;
5392 }
5393
5394 function generate_publish_key() {
5395 return sha1(uniqid(rand(), true));
5396 }
5397
5398 function article_publish_url($link) {
5399
5400 $url_path = "";
5401
5402
5403 if ($_SERVER['HTTPS'] != "on") {
5404 $url_path = "http://";
5405 } else {
5406 $url_path = "https://";
5407 }
5408
5409 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5410 $url_path .= "/backend.php?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5411
5412 return $url_path;
5413 }
5414
5415 /**
5416 * Purge a feed contents, marked articles excepted.
5417 *
5418 * @param mixed $link The database connection.
5419 * @param integer $id The id of the feed to purge.
5420 * @return void
5421 */
5422 function clear_feed_articles($link, $id) {
5423 $result = db_query($link, "DELETE FROM ttrss_user_entries
5424 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5425
5426 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5427 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5428
5429 ccache_update($link, $id, $_SESSION['uid']);
5430 } // function clear_feed_articles
5431
5432 /**
5433 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5434 *
5435 * @return string The Mozilla Firefox feed adding URL.
5436 */
5437 function add_feed_url() {
5438 $url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5439 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5440 return $url_path;
5441 } // function add_feed_url
5442
5443 /**
5444 * Encrypt a password in SHA1.
5445 *
5446 * @param string $pass The password to encrypt.
5447 * @param string $login A optionnal login.
5448 * @return string The encrypted password.
5449 */
5450 function encrypt_password($pass, $login = '') {
5451 if ($login) {
5452 return "SHA1X:" . sha1("$login:$pass");
5453 } else {
5454 return "SHA1:" . sha1($pass);
5455 }
5456 } // function encrypt_password
5457
5458 /**
5459 * Update a feed batch.
5460 * Used by daemons to update n feeds by run.
5461 * Only update feed needing a update, and not being processed
5462 * by another process.
5463 *
5464 * @param mixed $link Database link
5465 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5466 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5467 * @param boolean $debug Set to false to disable debug output. Default to true.
5468 * @return void
5469 */
5470 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5471 // Process all other feeds using last_updated and interval parameters
5472
5473 // Test if the user has loggued in recently. If not, it does not update its feeds.
5474 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5475 if (DB_TYPE == "pgsql") {
5476 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5477 } else {
5478 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5479 }
5480 } else {
5481 $login_thresh_qpart = "";
5482 }
5483
5484 // Test if the feed need a update (update interval exceded).
5485 if (DB_TYPE == "pgsql") {
5486 $update_limit_qpart = "AND ((
5487 ttrss_feeds.update_interval = 0
5488 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5489 ) OR (
5490 ttrss_feeds.update_interval > 0
5491 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5492 ) OR ttrss_feeds.last_updated IS NULL)";
5493 } else {
5494 $update_limit_qpart = "AND ((
5495 ttrss_feeds.update_interval = 0
5496 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5497 ) OR (
5498 ttrss_feeds.update_interval > 0
5499 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5500 ) OR ttrss_feeds.last_updated IS NULL)";
5501 }
5502
5503 // Test if feed is currently being updated by another process.
5504 if (DB_TYPE == "pgsql") {
5505 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5506 } else {
5507 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5508 }
5509
5510 // Test if there is a limit to number of updated feeds
5511 $query_limit = "";
5512 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5513
5514 $random_qpart = sql_random_function();
5515
5516 // We search for feed needing update.
5517 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5518 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5519 ttrss_feeds.update_interval
5520 FROM
5521 ttrss_feeds, ttrss_users, ttrss_user_prefs
5522 WHERE
5523 ttrss_feeds.owner_uid = ttrss_users.id
5524 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5525 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5526 $login_thresh_qpart $update_limit_qpart
5527 $updstart_thresh_qpart
5528 ORDER BY $random_qpart $query_limit");
5529
5530 $user_prefs_cache = array();
5531
5532 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5533
5534 // Here is a little cache magic in order to minimize risk of double feed updates.
5535 $feeds_to_update = array();
5536 while ($line = db_fetch_assoc($result)) {
5537 $feeds_to_update[$line['id']] = $line;
5538 }
5539
5540 // We update the feed last update started date before anything else.
5541 // There is no lag due to feed contents downloads
5542 // It prevent an other process to update the same feed.
5543 $feed_ids = array_keys($feeds_to_update);
5544 if($feed_ids) {
5545 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5546 WHERE id IN (%s)", implode(',', $feed_ids)));
5547 }
5548
5549 // For each feed, we call the feed update function.
5550 while ($line = array_pop($feeds_to_update)) {
5551
5552 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5553
5554 // We setup a alarm to alert if the feed take more than 300s to update.
5555 // => HANG alarm.
5556 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(300);
5557 update_rss_feed($link, $line["feed_url"], $line["id"], true);
5558 // Cancel the alarm (the update went well)
5559 if(!$from_http && function_exists('pcntl_alarm')) pcntl_alarm(0);
5560
5561 sleep(1); // prevent flood (FIXME make this an option?)
5562 }
5563
5564 // Send feed digests by email if needed.
5565 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5566
5567 purge_orphans($link);
5568
5569 } // function update_daemon_common
5570
5571 function sanitize_article_content($text) {
5572 # we don't support CDATA sections in articles, they break our own escaping
5573 $text = preg_replace("/\[\[CDATA/", "", $text);
5574 $text = preg_replace("/\]\]\>/", "", $text);
5575 return $text;
5576 }
5577
5578 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5579 $filters = array();
5580
5581 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5582
5583 $result = db_query($link, "SELECT reg_exp,
5584 ttrss_filter_types.name AS name,
5585 ttrss_filter_actions.name AS action,
5586 inverse,
5587 action_param,
5588 filter_param
5589 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5590 enabled = true AND
5591 $ftype_query_part
5592 owner_uid = $owner_uid AND
5593 ttrss_filter_types.id = filter_type AND
5594 ttrss_filter_actions.id = action_id AND
5595 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5596
5597 while ($line = db_fetch_assoc($result)) {
5598 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5599 $filter["reg_exp"] = $line["reg_exp"];
5600 $filter["action"] = $line["action"];
5601 $filter["action_param"] = $line["action_param"];
5602 $filter["filter_param"] = $line["filter_param"];
5603 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5604
5605 array_push($filters[$line["name"]], $filter);
5606 }
5607
5608 return $filters;
5609 }
5610
5611 function get_score_pic($score) {
5612 if ($score > 100) {
5613 return "score_high.png";
5614 } else if ($score > 0) {
5615 return "score_half_high.png";
5616 } else if ($score < -100) {
5617 return "score_low.png";
5618 } else if ($score < 0) {
5619 return "score_half_low.png";
5620 } else {
5621 return "score_neutral.png";
5622 }
5623 }
5624
5625 function rounded_table_start($classname, $header = "&nbsp;") {
5626 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5627 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5628 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5629 }
5630
5631 function rounded_table_end($footer = "&nbsp;") {
5632 print "</td><td class='right'>&nbsp;</td></tr>";
5633 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5634 print "</table>";
5635 }
5636
5637 function feed_has_icon($id) {
5638 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5639 }
5640
5641 function init_connection($link) {
5642 if (DB_TYPE == "pgsql") {
5643 pg_query($link, "set client_encoding = 'UTF-8'");
5644 pg_set_client_encoding("UNICODE");
5645 pg_query($link, "set datestyle = 'ISO, european'");
5646 } else {
5647 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5648 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5649 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5650 }
5651 }
5652 }
5653
5654 function update_feedbrowser_cache($link) {
5655
5656 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5657 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5658 WHERE tf.feed_url = ttrss_feeds.feed_url
5659 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5660 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5661
5662 db_query($link, "BEGIN");
5663
5664 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5665
5666 $count = 0;
5667
5668 while ($line = db_fetch_assoc($result)) {
5669 $subscribers = db_escape_string($line["subscribers"]);
5670 $feed_url = db_escape_string($line["feed_url"]);
5671 $title = db_escape_string($line["title"]);
5672
5673 $tmp_result = db_query($link, "SELECT subscribers FROM
5674 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5675
5676 if (db_num_rows($tmp_result) == 0) {
5677
5678 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5679 (feed_url, title, subscribers) VALUES ('$feed_url',
5680 '$title', '$subscribers')");
5681
5682 ++$count;
5683
5684 }
5685
5686 }
5687
5688 db_query($link, "COMMIT");
5689
5690 return $count;
5691
5692 }
5693
5694 function ccache_zero($link, $feed_id, $owner_uid) {
5695 db_query($link, "UPDATE ttrss_counters_cache SET
5696 value = 0, updated = NOW() WHERE
5697 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5698 }
5699
5700 function ccache_zero_all($link, $owner_uid) {
5701 db_query($link, "UPDATE ttrss_counters_cache SET
5702 value = 0 WHERE owner_uid = '$owner_uid'");
5703
5704 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5705 value = 0 WHERE owner_uid = '$owner_uid'");
5706 }
5707
5708 function ccache_update_all($link, $owner_uid) {
5709
5710 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5711
5712 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5713 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5714
5715 while ($line = db_fetch_assoc($result)) {
5716 ccache_update($link, $line["feed_id"], $owner_uid, true);
5717 }
5718
5719 /* We have to manually include category 0 */
5720
5721 ccache_update($link, 0, $owner_uid, true);
5722
5723 } else {
5724 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5725 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5726
5727 while ($line = db_fetch_assoc($result)) {
5728 print ccache_update($link, $line["feed_id"], $owner_uid);
5729
5730 }
5731
5732 }
5733 }
5734
5735 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5736 $no_update = false) {
5737
5738 if (!is_numeric($feed_id)) return;
5739
5740 if (!$is_cat) {
5741 $table = "ttrss_counters_cache";
5742 } else {
5743 $table = "ttrss_cat_counters_cache";
5744 }
5745
5746 if (DB_TYPE == "pgsql") {
5747 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5748 } else if (DB_TYPE == "mysql") {
5749 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5750 }
5751
5752 $result = db_query($link, "SELECT value FROM $table
5753 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5754 LIMIT 1");
5755
5756 if (db_num_rows($result) == 1) {
5757 return db_fetch_result($result, 0, "value");
5758 } else {
5759 if ($no_update) {
5760 return -1;
5761 } else {
5762 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5763 }
5764 }
5765
5766 }
5767
5768 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5769 $update_pcat = true) {
5770
5771 if (!is_numeric($feed_id)) return;
5772
5773 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5774
5775 /* When updating a label, all we need to do is recalculate feed counters
5776 * because labels are not cached */
5777
5778 if ($feed_id < 0) {
5779 ccache_update_all($link, $owner_uid);
5780 return;
5781 }
5782
5783 if (!$is_cat) {
5784 $table = "ttrss_counters_cache";
5785 } else {
5786 $table = "ttrss_cat_counters_cache";
5787 }
5788
5789 if ($is_cat && $feed_id >= 0) {
5790 if ($feed_id != 0) {
5791 $cat_qpart = "cat_id = '$feed_id'";
5792 } else {
5793 $cat_qpart = "cat_id IS NULL";
5794 }
5795
5796 /* Recalculate counters for child feeds */
5797
5798 $result = db_query($link, "SELECT id FROM ttrss_feeds
5799 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5800
5801 while ($line = db_fetch_assoc($result)) {
5802 ccache_update($link, $line["id"], $owner_uid, false, false);
5803 }
5804
5805 $result = db_query($link, "SELECT SUM(value) AS sv
5806 FROM ttrss_counters_cache, ttrss_feeds
5807 WHERE id = feed_id AND $cat_qpart AND
5808 ttrss_feeds.owner_uid = '$owner_uid'");
5809
5810 $unread = (int) db_fetch_result($result, 0, "sv");
5811
5812 } else {
5813 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5814 }
5815
5816 $result = db_query($link, "SELECT feed_id FROM $table
5817 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5818
5819 if (db_num_rows($result) == 1) {
5820 db_query($link, "UPDATE $table SET
5821 value = '$unread', updated = NOW() WHERE
5822 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5823
5824 } else {
5825 db_query($link, "INSERT INTO $table
5826 (feed_id, value, owner_uid, updated)
5827 VALUES
5828 ($feed_id, $unread, $owner_uid, NOW())");
5829 }
5830
5831 if ($feed_id > 0 && $prev_unread != $unread) {
5832
5833 if (!$is_cat) {
5834
5835 /* Update parent category */
5836
5837 if ($update_pcat) {
5838
5839 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5840 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5841
5842 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5843
5844 ccache_update($link, $cat_id, $owner_uid, true);
5845
5846 }
5847 }
5848 } else if ($feed_id < 0) {
5849 ccache_update_all($link, $owner_uid);
5850 }
5851
5852 return $unread;
5853 }
5854
5855 function label_find_id($link, $label, $owner_uid) {
5856 $result = db_query($link,
5857 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5858 AND owner_uid = '$owner_uid' LIMIT 1");
5859
5860 if (db_num_rows($result) == 1) {
5861 return db_fetch_result($result, 0, "id");
5862 } else {
5863 return 0;
5864 }
5865 }
5866
5867 function get_article_labels($link, $id) {
5868 $result = db_query($link,
5869 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5870 FROM ttrss_labels2, ttrss_user_labels2
5871 WHERE id = label_id
5872 AND article_id = '$id'
5873 AND owner_uid = ".$_SESSION["uid"] . "
5874 ORDER BY caption");
5875
5876 $rv = array();
5877
5878 while ($line = db_fetch_assoc($result)) {
5879 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5880 $line["bg_color"]);
5881 array_push($rv, $rk);
5882 }
5883
5884 return $rv;
5885 }
5886
5887
5888 function label_find_caption($link, $label, $owner_uid) {
5889 $result = db_query($link,
5890 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5891 AND owner_uid = '$owner_uid' LIMIT 1");
5892
5893 if (db_num_rows($result) == 1) {
5894 return db_fetch_result($result, 0, "caption");
5895 } else {
5896 return "";
5897 }
5898 }
5899
5900 function label_remove_article($link, $id, $label, $owner_uid) {
5901
5902 $label_id = label_find_id($link, $label, $owner_uid);
5903
5904 if (!$label_id) return;
5905
5906 $result = db_query($link,
5907 "DELETE FROM ttrss_user_labels2
5908 WHERE
5909 label_id = '$label_id' AND
5910 article_id = '$id'");
5911 }
5912
5913 function label_add_article($link, $id, $label, $owner_uid) {
5914
5915 $label_id = label_find_id($link, $label, $owner_uid);
5916
5917 if (!$label_id) return;
5918
5919 $result = db_query($link,
5920 "SELECT
5921 article_id FROM ttrss_labels2, ttrss_user_labels2
5922 WHERE
5923 label_id = id AND
5924 label_id = '$label_id' AND
5925 article_id = '$id' AND owner_uid = '$owner_uid'
5926 LIMIT 1");
5927
5928 if (db_num_rows($result) == 0) {
5929 db_query($link, "INSERT INTO ttrss_user_labels2
5930 (label_id, article_id) VALUES ('$label_id', '$id')");
5931 }
5932 }
5933
5934 function label_remove($link, $id, $owner_uid) {
5935
5936 db_query($link, "BEGIN");
5937
5938 $result = db_query($link, "SELECT caption FROM ttrss_labels2
5939 WHERE id = '$id'");
5940
5941 $caption = db_fetch_result($result, 0, "caption");
5942
5943 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
5944 AND owner_uid = " . $_SESSION["uid"]);
5945
5946 if (db_affected_rows($link, $result) != 0 && $caption) {
5947
5948 /* Disable filters that reference label being removed */
5949
5950 db_query($link, "UPDATE ttrss_filters SET
5951 enabled = false WHERE action_param = '$caption'
5952 AND action_id = 7
5953 AND owner_uid = " . $_SESSION["uid"]);
5954 }
5955
5956 db_query($link, "COMMIT");
5957 }
5958
5959 function label_create($link, $caption) {
5960
5961 db_query($link, "BEGIN");
5962
5963 $result = false;
5964
5965 $result = db_query($link, "SELECT id FROM ttrss_labels2
5966 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
5967
5968 if (db_num_rows($result) == 0) {
5969 $result = db_query($link,
5970 "INSERT INTO ttrss_labels2 (caption,owner_uid)
5971 VALUES ('$caption', '".$_SESSION["uid"]."')");
5972
5973 $result = db_affected_rows($link, $result) != 0;
5974 }
5975
5976 db_query($link, "COMMIT");
5977
5978 return $result;
5979 }
5980
5981 function print_labels_headlines_dropdown($link, $feed_id) {
5982 print "<li onclick=\"javascript:addLabel()\">
5983 &nbsp;&nbsp;".__("Create label...")."</li>";
5984
5985 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
5986 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
5987
5988 while ($line = db_fetch_assoc($result)) {
5989
5990 $label_id = $line["id"];
5991 $label_caption = $line["caption"];
5992
5993 if ($feed_id < -10 && $feed_id == -11-$label_id) {
5994 print "<li id=\"LHDL-$id\"
5995 onclick=\"javascript:selectionRemoveLabel($label_id)\">
5996 &nbsp;&nbsp;$label_caption ".__('(remove)')."</li>";
5997 } else {
5998 print "<li id=\"LHDL-$id\"
5999 onclick=\"javascript:selectionAssignLabel($label_id)\">
6000 &nbsp;&nbsp;$label_caption</li>";
6001 }
6002 }
6003 }
6004
6005 function format_tags_string($tags, $id) {
6006
6007 $tags_str = "";
6008 $tags_nolinks_str = "";
6009
6010 $num_tags = 0;
6011
6012 if ($_SESSION["theme"] == "3pane") {
6013 $tag_limit = 3;
6014 } else {
6015 $tag_limit = 6;
6016 }
6017
6018 $formatted_tags = array();
6019
6020 foreach ($tags as $tag) {
6021 $num_tags++;
6022 $tag_escaped = str_replace("'", "\\'", $tag);
6023
6024 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6025
6026 array_push($formatted_tags, $tag_str);
6027
6028 if ($num_tags == $tag_limit) {
6029 break;
6030 }
6031 }
6032
6033 $tags_str = implode(", ", $formatted_tags);
6034
6035 if ($num_tags < count($tags)) {
6036 $tags_str .= ", &hellip;";
6037 }
6038
6039 if ($num_tags == 0) {
6040 $tags_str = __("no tags");
6041 }
6042
6043 return $tags_str;
6044
6045 }
6046
6047 function format_article_labels($labels, $id) {
6048
6049 $labels_str = "";
6050
6051 foreach ($labels as $l) {
6052 $labels_str .= sprintf("<span class='hlLabelRef'
6053 style='color : %s; background-color : %s'>%s</span>",
6054 $l[2], $l[3], $l[1]);
6055 }
6056
6057 return $labels_str;
6058
6059 }
6060 ?>