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