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