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