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