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