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