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