]> git.wh0rd.org - tt-rss.git/blob - functions.php
Extended Actions to include Select by tag (add local modifications, fix
[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 $query2 = "INSERT INTO ttrss_users
1927 (login,access_level,last_login,created)
1928 VALUES ('$login', 0, null, NOW())";
1929 db_query($link, $query2);
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 $fullname = $_SERVER['HTTP_USER_NAME'] ? $_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
1955 if ($fullname){
1956 $fullname = db_escape_string($fullname);
1957 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
1958 $_SESSION["uid"]);
1959 }
1960 // update user mail
1961 $email = $_SERVER['HTTP_USER_MAIL'] ? $_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
1962 if ($email){
1963 $email = db_escape_string($email);
1964 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
1965 $_SESSION["uid"]);
1966 }
1967 }
1968
1969 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1970 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1971
1972 $_SESSION["last_version_check"] = time();
1973
1974 initialize_user_prefs($link, $_SESSION["uid"]);
1975
1976 return true;
1977 }
1978
1979 return false;
1980
1981 } else {
1982
1983 $_SESSION["uid"] = 1;
1984 $_SESSION["name"] = "admin";
1985
1986 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1987
1988 initialize_user_prefs($link, $_SESSION["uid"]);
1989
1990 return true;
1991 }
1992 }
1993
1994 function make_password($length = 8) {
1995
1996 $password = "";
1997 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1998
1999 $i = 0;
2000
2001 while ($i < $length) {
2002 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
2003
2004 if (!strstr($password, $char)) {
2005 $password .= $char;
2006 $i++;
2007 }
2008 }
2009 return $password;
2010 }
2011
2012 // this is called after user is created to initialize default feeds, labels
2013 // or whatever else
2014
2015 // user preferences are checked on every login, not here
2016
2017 function initialize_user($link, $uid) {
2018
2019 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2020 values ('$uid', 'Tiny Tiny RSS: New Releases',
2021 'http://tt-rss.org/releases.rss')");
2022
2023 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
2024 values ('$uid', 'Tiny Tiny RSS: Forum',
2025 'http://tt-rss.org/forum/rss.php')");
2026 }
2027
2028 function logout_user() {
2029 session_destroy();
2030 if (isset($_COOKIE[session_name()])) {
2031 setcookie(session_name(), '', time()-42000, '/');
2032 }
2033 }
2034
2035 function get_script_urlpath() {
2036 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
2037 }
2038
2039 function validate_session($link) {
2040 if (SINGLE_USER_MODE) return true;
2041
2042 $check_ip = $_SESSION['ip_address'];
2043
2044 switch (SESSION_CHECK_ADDRESS) {
2045 case 0:
2046 $check_ip = '';
2047 break;
2048 case 1:
2049 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
2050 break;
2051 case 2:
2052 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
2053 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+1);
2054 break;
2055 };
2056
2057 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
2058 $_SESSION["login_error_msg"] =
2059 __("Session failed to validate (incorrect IP)");
2060 return false;
2061 }
2062
2063 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
2064 return false;
2065
2066 if ($_SESSION["uid"]) {
2067
2068 $result = db_query($link,
2069 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
2070
2071 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
2072
2073 if ($pwd_hash != $_SESSION["pwd_hash"]) {
2074 return false;
2075 }
2076 }
2077
2078 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
2079
2080 //print_r($_SESSION);
2081
2082 if (time() > $_SESSION["cookie_lifetime"]) {
2083 return false;
2084 }
2085 } */
2086
2087 return true;
2088 }
2089
2090 function login_sequence($link, $mobile = false) {
2091 if (!SINGLE_USER_MODE) {
2092
2093 $login_action = $_POST["login_action"];
2094
2095 # try to authenticate user if called from login form
2096 if ($login_action == "do_login") {
2097 $login = $_POST["login"];
2098 $password = $_POST["password"];
2099 $remember_me = $_POST["remember_me"];
2100
2101 if (authenticate_user($link, $login, $password)) {
2102 $_POST["password"] = "";
2103
2104 $_SESSION["language"] = $_POST["language"];
2105 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2106 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
2107
2108 if ($_POST["profile"]) {
2109
2110 $profile = db_escape_string($_POST["profile"]);
2111
2112 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
2113 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
2114
2115 if (db_num_rows($result) != 0) {
2116 $_SESSION["profile"] = $profile;
2117 $_SESSION["prefs_cache"] = array();
2118 }
2119 }
2120
2121 if ($_REQUEST['return']) {
2122 header("Location: " . $_REQUEST['return']);
2123 } else {
2124 header("Location: " . $_SERVER["REQUEST_URI"]);
2125 }
2126
2127 exit;
2128
2129 return;
2130 } else {
2131 $_SESSION["login_error_msg"] = __("Incorrect username or password");
2132 }
2133 }
2134
2135 if (!$_SESSION["uid"] || !validate_session($link)) {
2136
2137 if (get_remote_user($link) && AUTO_LOGIN) {
2138 authenticate_user($link, get_remote_user($link), null);
2139 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
2140 } else {
2141 render_login_form($link, $mobile);
2142 //header("Location: login.php");
2143 exit;
2144 }
2145 } else {
2146 /* bump login timestamp */
2147 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
2148 $_SESSION["uid"]);
2149
2150 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
2151 setcookie("ttrss_lang", $_SESSION["language"],
2152 time() + SESSION_COOKIE_LIFETIME);
2153 }
2154
2155 // try to remove possible duplicates from feed counter cache
2156 // ccache_cleanup($link, $_SESSION["uid"]);
2157 }
2158
2159 } else {
2160 return authenticate_user($link, "admin", null);
2161 }
2162 }
2163
2164 function truncate_string($str, $max_len, $suffix = '&hellip;') {
2165 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2166 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
2167 } else {
2168 return $str;
2169 }
2170 }
2171
2172 function theme_image($link, $filename) {
2173 if ($link) {
2174 $theme_path = get_user_theme_path($link);
2175
2176 if ($theme_path && is_file($theme_path.$filename)) {
2177 return $theme_path.$filename;
2178 } else {
2179 return $filename;
2180 }
2181 } else {
2182 return $filename;
2183 }
2184 }
2185
2186 function get_user_theme($link) {
2187
2188 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2189 $theme_name = get_pref($link, "_THEME_ID");
2190 if (is_dir("themes/$theme_name")) {
2191 return $theme_name;
2192 } else {
2193 return '';
2194 }
2195 } else {
2196 return '';
2197 }
2198
2199 }
2200
2201 function get_user_theme_path($link) {
2202 $theme_path = '';
2203
2204 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2205 $theme_name = get_pref($link, "_THEME_ID");
2206
2207 if ($theme_name && is_dir("themes/$theme_name")) {
2208 $theme_path = "themes/$theme_name/";
2209 } else {
2210 $theme_name = '';
2211 }
2212 } else {
2213 $theme_path = '';
2214 }
2215
2216 if ($theme_path) {
2217 if (is_file("$theme_path/theme.ini")) {
2218 $ini = parse_ini_file("$theme_path/theme.ini", true);
2219 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED) {
2220 return $theme_path;
2221 }
2222 }
2223 }
2224 return '';
2225 }
2226
2227 function get_user_theme_options($link) {
2228 $t = get_user_theme_path($link);
2229
2230 if ($t) {
2231 if (is_file("$t/theme.ini")) {
2232 $ini = parse_ini_file("$t/theme.ini", true);
2233 if ($ini['theme']['version']) {
2234 return $ini['theme']['options'];
2235 }
2236 }
2237 }
2238 return '';
2239 }
2240
2241 function print_theme_includes($link) {
2242
2243 $t = get_user_theme_path($link);
2244 $time = time();
2245
2246 if ($t) {
2247 print "<link rel=\"stylesheet\" type=\"text/css\"
2248 href=\"$t/theme.css?$time \">";
2249 if (file_exists("$t/theme.js")) {
2250 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
2251 </script>";
2252 }
2253 }
2254 }
2255
2256 function get_all_themes() {
2257 $themes = glob("themes/*");
2258
2259 asort($themes);
2260
2261 $rv = array();
2262
2263 foreach ($themes as $t) {
2264 if (is_file("$t/theme.ini")) {
2265 $ini = parse_ini_file("$t/theme.ini", true);
2266 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED &&
2267 !$ini['theme']['disabled']) {
2268 $entry = array();
2269 $entry["path"] = $t;
2270 $entry["base"] = basename($t);
2271 $entry["name"] = $ini['theme']['name'];
2272 $entry["version"] = $ini['theme']['version'];
2273 $entry["author"] = $ini['theme']['author'];
2274 $entry["options"] = $ini['theme']['options'];
2275 array_push($rv, $entry);
2276 }
2277 }
2278 }
2279
2280 return $rv;
2281 }
2282
2283 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
2284
2285 try {
2286 $source_tz = new DateTimeZone($source_tz);
2287 } catch (Exception $e) {
2288 $source_tz = new DateTimeZone('UTC');
2289 }
2290
2291 try {
2292 $dest_tz = new DateTimeZone($dest_tz);
2293 } catch (Exception $e) {
2294 $dest_tz = new DateTimeZone('UTC');
2295 }
2296
2297 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
2298 return $dt->format('U') + $dest_tz->getOffset($dt);
2299 }
2300
2301 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
2302 $no_smart_dt = false) {
2303
2304 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2305 if (!$timestamp) $timestamp = '1970-01-01 0:00';
2306
2307 global $utc_tz;
2308 global $tz_offset;
2309
2310 # We store date in UTC internally
2311 $dt = new DateTime($timestamp, $utc_tz);
2312
2313 if ($tz_offset == -1) {
2314
2315 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
2316
2317 try {
2318 $user_tz = new DateTimeZone($user_tz_string);
2319 } catch (Exception $e) {
2320 $user_tz = $utc_tz;
2321 }
2322
2323 $tz_offset = $user_tz->getOffset($dt);
2324 }
2325
2326 $user_timestamp = $dt->format('U') + $tz_offset;
2327
2328 if (!$no_smart_dt) {
2329 return smart_date_time($link, $user_timestamp,
2330 $tz_offset, $owner_uid);
2331 } else {
2332 if ($long)
2333 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2334 else
2335 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2336
2337 return date($format, $user_timestamp);
2338 }
2339 }
2340
2341 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
2342 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2343
2344 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
2345 return date("G:i", $timestamp);
2346 } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
2347 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
2348 return date($format, $timestamp);
2349 } else {
2350 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
2351 return date($format, $timestamp);
2352 }
2353 }
2354
2355 function smart_date($timestamp) {
2356 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2357 return "Today";
2358 } else if (date("Y", $timestamp) == date("Y")) {
2359 return date("D m", $timestamp);
2360 } else {
2361 return date("Y/m/d", $timestamp);
2362 }
2363 }
2364
2365 function sql_bool_to_string($s) {
2366 if ($s == "t" || $s == "1") {
2367 return "true";
2368 } else {
2369 return "false";
2370 }
2371 }
2372
2373 function sql_bool_to_bool($s) {
2374 if ($s == "t" || $s == "1" || $s == "true") {
2375 return true;
2376 } else {
2377 return false;
2378 }
2379 }
2380
2381 function bool_to_sql_bool($s) {
2382 if ($s) {
2383 return "true";
2384 } else {
2385 return "false";
2386 }
2387 }
2388
2389 function toggleEvenOdd($a) {
2390 if ($a == "even")
2391 return "odd";
2392 else
2393 return "even";
2394 }
2395
2396 // Session caching removed due to causing wrong redirects to upgrade
2397 // script when get_schema_version() is called on an obsolete session
2398 // created on a previous schema version.
2399 function get_schema_version($link, $nocache = false) {
2400 global $schema_version;
2401
2402 if (!$schema_version) {
2403 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2404 $version = db_fetch_result($result, 0, "schema_version");
2405 $schema_version = $version;
2406 return $version;
2407 } else {
2408 return $schema_version;
2409 }
2410 }
2411
2412 function sanity_check($link) {
2413
2414 global $ERRORS;
2415
2416 $error_code = 0;
2417 $schema_version = get_schema_version($link, true);
2418
2419 if ($schema_version != SCHEMA_VERSION) {
2420 $error_code = 5;
2421 }
2422
2423 if (DB_TYPE == "mysql") {
2424 $result = db_query($link, "SELECT true", false);
2425 if (db_num_rows($result) != 1) {
2426 $error_code = 10;
2427 }
2428 }
2429
2430 if (db_escape_string("testTEST") != "testTEST") {
2431 $error_code = 12;
2432 }
2433
2434 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
2435 }
2436
2437 function file_is_locked($filename) {
2438 if (function_exists('flock')) {
2439 $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
2440 if ($fp) {
2441 if (flock($fp, LOCK_EX | LOCK_NB)) {
2442 flock($fp, LOCK_UN);
2443 fclose($fp);
2444 return false;
2445 }
2446 fclose($fp);
2447 return true;
2448 } else {
2449 return false;
2450 }
2451 }
2452 return true; // consider the file always locked and skip the test
2453 }
2454
2455 function make_lockfile($filename) {
2456 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2457
2458 if (flock($fp, LOCK_EX | LOCK_NB)) {
2459 if (function_exists('posix_getpid')) {
2460 fwrite($fp, posix_getpid() . "\n");
2461 }
2462 return $fp;
2463 } else {
2464 return false;
2465 }
2466 }
2467
2468 function make_stampfile($filename) {
2469 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2470
2471 if (flock($fp, LOCK_EX | LOCK_NB)) {
2472 fwrite($fp, time() . "\n");
2473 flock($fp, LOCK_UN);
2474 fclose($fp);
2475 return true;
2476 } else {
2477 return false;
2478 }
2479 }
2480
2481 function sql_random_function() {
2482 if (DB_TYPE == "mysql") {
2483 return "RAND()";
2484 } else {
2485 return "RANDOM()";
2486 }
2487 }
2488
2489 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
2490
2491 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2492
2493 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2494
2495 if ($cat_view) {
2496
2497 if ($feed >= 0) {
2498
2499 if ($feed > 0) {
2500 $cat_qpart = "cat_id = '$feed'";
2501 } else {
2502 $cat_qpart = "cat_id IS NULL";
2503 }
2504
2505 $tmp_result = db_query($link, "SELECT id
2506 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2507
2508 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2509
2510 $tmp_feed = $tmp_line["id"];
2511
2512 db_query($link, "UPDATE ttrss_user_entries
2513 SET unread = false,last_read = NOW()
2514 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2515 }
2516 } else if ($feed == -2) {
2517
2518
2519 db_query($link, "UPDATE ttrss_user_entries
2520 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
2521 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
2522 AND unread = true AND owner_uid = $owner_uid");
2523 }
2524
2525 } else if ($feed > 0) {
2526
2527 db_query($link, "UPDATE ttrss_user_entries
2528 SET unread = false,last_read = NOW()
2529 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2530
2531 } else if ($feed < 0 && $feed > -10) { // special, like starred
2532
2533 if ($feed == -1) {
2534 db_query($link, "UPDATE ttrss_user_entries
2535 SET unread = false,last_read = NOW()
2536 WHERE marked = true AND owner_uid = $owner_uid");
2537 }
2538
2539 if ($feed == -2) {
2540 db_query($link, "UPDATE ttrss_user_entries
2541 SET unread = false,last_read = NOW()
2542 WHERE published = true AND owner_uid = $owner_uid");
2543 }
2544
2545 if ($feed == -3) {
2546
2547 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2548
2549 if (DB_TYPE == "pgsql") {
2550 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
2551 } else {
2552 $match_part = "updated > DATE_SUB(NOW(),
2553 INTERVAL $intl HOUR) ";
2554 }
2555
2556 $result = db_query($link, "SELECT id FROM ttrss_entries,
2557 ttrss_user_entries WHERE $match_part AND
2558 unread = true AND
2559 ttrss_user_entries.ref_id = ttrss_entries.id AND
2560 owner_uid = $owner_uid");
2561
2562 $affected_ids = array();
2563
2564 while ($line = db_fetch_assoc($result)) {
2565 array_push($affected_ids, $line["id"]);
2566 }
2567
2568 catchupArticlesById($link, $affected_ids, 0);
2569 }
2570
2571 if ($feed == -4) {
2572 db_query($link, "UPDATE ttrss_user_entries
2573 SET unread = false,last_read = NOW()
2574 WHERE owner_uid = $owner_uid");
2575 }
2576
2577 } else if ($feed < -10) { // label
2578
2579 $label_id = -$feed - 11;
2580
2581 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
2582 SET unread = false, last_read = NOW()
2583 WHERE label_id = '$label_id' AND unread = true
2584 AND owner_uid = '$owner_uid' AND ref_id = article_id");
2585
2586 }
2587
2588 ccache_update($link, $feed, $owner_uid, $cat_view);
2589
2590 } else { // tag
2591 db_query($link, "BEGIN");
2592
2593 $tag_name = db_escape_string($feed);
2594
2595 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2596 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2597
2598 while ($line = db_fetch_assoc($result)) {
2599 db_query($link, "UPDATE ttrss_user_entries SET
2600 unread = false, last_read = NOW()
2601 WHERE int_id = " . $line["post_int_id"]);
2602 }
2603 db_query($link, "COMMIT");
2604 }
2605 }
2606
2607 function getAllCounters($link, $omode = "flc", $active_feed = false) {
2608
2609 if (!$omode) $omode = "flc";
2610
2611 $data = getGlobalCounters($link);
2612
2613 $data = array_merge($data, getVirtCounters($link));
2614
2615 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2616 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2617 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2618 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
2619
2620 return $data;
2621 }
2622
2623 function getCategoryCounters($link) {
2624 $ret_arr = array();
2625
2626 /* Labels category */
2627
2628 $cv = array("id" => -2, "kind" => "cat",
2629 "counter" => getCategoryUnread($link, -2));
2630
2631 array_push($ret_arr, $cv);
2632
2633 $age_qpart = getMaxAgeSubquery();
2634
2635 $result = db_query($link, "SELECT id AS cat_id, value AS unread
2636 FROM ttrss_feed_categories, ttrss_cat_counters_cache
2637 WHERE ttrss_cat_counters_cache.feed_id = id AND
2638 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2639
2640 while ($line = db_fetch_assoc($result)) {
2641 $line["cat_id"] = (int) $line["cat_id"];
2642
2643 $cv = array("id" => $line["cat_id"], "kind" => "cat",
2644 "counter" => $line["unread"]);
2645
2646 array_push($ret_arr, $cv);
2647 }
2648
2649 /* Special case: NULL category doesn't actually exist in the DB */
2650
2651 $cv = array("id" => 0, "kind" => "cat",
2652 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2653
2654 array_push($ret_arr, $cv);
2655
2656 return $ret_arr;
2657 }
2658
2659 function getCategoryUnread($link, $cat, $owner_uid = false) {
2660
2661 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2662
2663 if ($cat >= 0) {
2664
2665 if ($cat != 0) {
2666 $cat_query = "cat_id = '$cat'";
2667 } else {
2668 $cat_query = "cat_id IS NULL";
2669 }
2670
2671 $age_qpart = getMaxAgeSubquery();
2672
2673 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
2674 AND owner_uid = " . $owner_uid);
2675
2676 $cat_feeds = array();
2677 while ($line = db_fetch_assoc($result)) {
2678 array_push($cat_feeds, "feed_id = " . $line["id"]);
2679 }
2680
2681 if (count($cat_feeds) == 0) return 0;
2682
2683 $match_part = implode(" OR ", $cat_feeds);
2684
2685 $result = db_query($link, "SELECT COUNT(int_id) AS unread
2686 FROM ttrss_user_entries,ttrss_entries
2687 WHERE unread = true AND ($match_part) AND id = ref_id
2688 AND $age_qpart AND owner_uid = " . $owner_uid);
2689
2690 $unread = 0;
2691
2692 # this needs to be rewritten
2693 while ($line = db_fetch_assoc($result)) {
2694 $unread += $line["unread"];
2695 }
2696
2697 return $unread;
2698 } else if ($cat == -1) {
2699 return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
2700 } else if ($cat == -2) {
2701
2702 $result = db_query($link, "
2703 SELECT COUNT(unread) AS unread FROM
2704 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2705 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2706 ttrss_labels2.owner_uid = '$owner_uid'
2707 AND unread = true AND feed_id = ttrss_feeds.id
2708 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2709
2710 $unread = db_fetch_result($result, 0, "unread");
2711
2712 return $unread;
2713
2714 }
2715 }
2716
2717 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2718 if (DB_TYPE == "pgsql") {
2719 return "ttrss_entries.date_updated >
2720 NOW() - INTERVAL '$days days'";
2721 } else {
2722 return "ttrss_entries.date_updated >
2723 DATE_SUB(NOW(), INTERVAL $days DAY)";
2724 }
2725 }
2726
2727 function getFeedUnread($link, $feed, $is_cat = false) {
2728 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2729 }
2730
2731 function getLabelUnread($link, $label_id, $owner_uid = false) {
2732 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2733
2734 $result = db_query($link, "
2735 SELECT COUNT(unread) AS unread FROM
2736 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
2737 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
2738 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2739 AND unread = true AND feed_id = ttrss_feeds.id
2740 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2741
2742 if (db_num_rows($result) != 0) {
2743 return db_fetch_result($result, 0, "unread");
2744 } else {
2745 return 0;
2746 }
2747 }
2748
2749 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2750 $owner_uid = false) {
2751
2752 $n_feed = (int) $feed;
2753
2754 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2755
2756 if ($unread_only) {
2757 $unread_qpart = "unread = true";
2758 } else {
2759 $unread_qpart = "true";
2760 }
2761
2762 $age_qpart = getMaxAgeSubquery();
2763
2764 if ($is_cat) {
2765 return getCategoryUnread($link, $n_feed, $owner_uid);
2766 } if ($feed != "0" && $n_feed == 0) {
2767
2768 $feed = db_escape_string($feed);
2769
2770 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2771 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2772 AND ref_id = id AND $age_qpart
2773 AND $unread_qpart)) AS count FROM ttrss_tags
2774 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2775 return db_fetch_result($result, 0, "count");
2776
2777 } else if ($n_feed == -1) {
2778 $match_part = "marked = true";
2779 } else if ($n_feed == -2) {
2780 $match_part = "published = true";
2781 } else if ($n_feed == -3) {
2782 $match_part = "unread = true AND score >= 0";
2783
2784 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2785
2786 if (DB_TYPE == "pgsql") {
2787 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2788 } else {
2789 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2790 }
2791 } else if ($n_feed == -4) {
2792 $match_part = "true";
2793 } else if ($n_feed >= 0) {
2794
2795 if ($n_feed != 0) {
2796 $match_part = "feed_id = '$n_feed'";
2797 } else {
2798 $match_part = "feed_id IS NULL";
2799 }
2800
2801 } else if ($feed < -10) {
2802
2803 $label_id = -$feed - 11;
2804
2805 return getLabelUnread($link, $label_id, $owner_uid);
2806
2807 }
2808
2809 if ($match_part) {
2810
2811 if ($n_feed != 0) {
2812 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2813 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2814 } else {
2815 $from_qpart = "ttrss_user_entries,ttrss_entries";
2816 $feeds_qpart = '';
2817 }
2818
2819 $query = "SELECT count(int_id) AS unread
2820 FROM $from_qpart WHERE
2821 ttrss_user_entries.ref_id = ttrss_entries.id AND
2822 $age_qpart AND
2823 $feeds_qpart
2824 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2825
2826 $result = db_query($link, $query);
2827
2828 } else {
2829
2830 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2831 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
2832 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
2833 AND $unread_qpart AND $age_qpart AND
2834 ttrss_tags.owner_uid = " . $owner_uid);
2835 }
2836
2837 $unread = db_fetch_result($result, 0, "unread");
2838
2839 return $unread;
2840 }
2841
2842 function getGlobalUnread($link, $user_id = false) {
2843
2844 if (!$user_id) {
2845 $user_id = $_SESSION["uid"];
2846 }
2847
2848 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2849 WHERE owner_uid = '$user_id' AND feed_id > 0");
2850
2851 $c_id = db_fetch_result($result, 0, "c_id");
2852
2853 return $c_id;
2854 }
2855
2856 function getGlobalCounters($link, $global_unread = -1) {
2857 $ret_arr = array();
2858
2859 if ($global_unread == -1) {
2860 $global_unread = getGlobalUnread($link);
2861 }
2862
2863 $cv = array("id" => "global-unread",
2864 "counter" => $global_unread);
2865
2866 array_push($ret_arr, $cv);
2867
2868 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2869 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2870
2871 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2872
2873 $cv = array("id" => "subscribed-feeds",
2874 "counter" => $subscribed_feeds);
2875
2876 array_push($ret_arr, $cv);
2877
2878 return $ret_arr;
2879 }
2880
2881 function getSubscribedFeeds($link) {
2882 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
2883 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2884
2885 return db_fetch_result($result, 0, "fn");
2886 }
2887
2888 function getTagCounters($link) {
2889
2890 $ret_arr = array();
2891
2892 $age_qpart = getMaxAgeSubquery();
2893
2894 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
2895 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
2896 AND ref_id = id AND $age_qpart
2897 AND unread = true)) AS count FROM ttrss_tags
2898 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
2899 ORDER BY count DESC LIMIT 55");
2900
2901 $tags = array();
2902
2903 while ($line = db_fetch_assoc($result)) {
2904 $tags[$line["tag_name"]] += $line["count"];
2905 }
2906
2907 foreach (array_keys($tags) as $tag) {
2908 $unread = $tags[$tag];
2909 $tag = htmlspecialchars($tag);
2910
2911 $cv = array("id" => $tag,
2912 "kind" => "tag",
2913 "counter" => $unread);
2914
2915 array_push($ret_arr, $cv);
2916 }
2917
2918 return $ret_arr;
2919 }
2920
2921 function getVirtCounters($link) {
2922
2923 $ret_arr = array();
2924
2925 for ($i = 0; $i >= -4; $i--) {
2926
2927 $count = getFeedUnread($link, $i);
2928
2929 $cv = array("id" => $i,
2930 "counter" => $count);
2931
2932 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2933 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2934
2935 array_push($ret_arr, $cv);
2936 }
2937
2938 return $ret_arr;
2939 }
2940
2941 function getLabelCounters($link, $descriptions = false) {
2942
2943 $ret_arr = array();
2944
2945 $age_qpart = getMaxAgeSubquery();
2946
2947 $owner_uid = $_SESSION["uid"];
2948
2949 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2950 WHERE owner_uid = '$owner_uid'");
2951
2952 while ($line = db_fetch_assoc($result)) {
2953
2954 $id = -$line["id"] - 11;
2955
2956 $label_name = $line["caption"];
2957 $count = getFeedUnread($link, $id);
2958
2959 $cv = array("id" => $id,
2960 "counter" => $count);
2961
2962 if ($descriptions)
2963 $cv["description"] = $label_name;
2964
2965 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
2966 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2967
2968 array_push($ret_arr, $cv);
2969 }
2970
2971 return $ret_arr;
2972 }
2973
2974 function getFeedCounters($link, $active_feed = false) {
2975
2976 $ret_arr = array();
2977
2978 $age_qpart = getMaxAgeSubquery();
2979
2980 $query = "SELECT ttrss_feeds.id,
2981 ttrss_feeds.title,
2982 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
2983 last_error, value AS count
2984 FROM ttrss_feeds, ttrss_counters_cache
2985 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
2986 AND ttrss_counters_cache.feed_id = id";
2987
2988 $result = db_query($link, $query);
2989 $fctrs_modified = false;
2990
2991 while ($line = db_fetch_assoc($result)) {
2992
2993 $id = $line["id"];
2994 $count = $line["count"];
2995 $last_error = htmlspecialchars($line["last_error"]);
2996
2997 $last_updated = make_local_datetime($link, $line['last_updated'], false);
2998
2999 $has_img = feed_has_icon($id);
3000
3001 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
3002 $last_updated = '';
3003
3004 $cv = array("id" => $id,
3005 "updated" => $last_updated,
3006 "counter" => $count,
3007 "has_img" => (int) $has_img);
3008
3009 if ($last_error)
3010 $cv["error"] = $last_error;
3011
3012 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
3013 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
3014
3015 if ($active_feed && $id == $active_feed)
3016 $cv["title"] = truncate_string($line["title"], 30);
3017
3018 array_push($ret_arr, $cv);
3019
3020 }
3021
3022 return $ret_arr;
3023 }
3024
3025 function get_pgsql_version($link) {
3026 $result = db_query($link, "SELECT version() AS version");
3027 $version = explode(" ", db_fetch_result($result, 0, "version"));
3028 return $version[1];
3029 }
3030
3031 /**
3032 * Subscribes the user to the given feed
3033 *
3034 * @param resource $link Database connection
3035 * @param string $url Feed URL to subscribe to
3036 * @param integer $cat_id Category ID the feed shall be added to
3037 * @param string $auth_login (optional) Feed username
3038 * @param string $auth_pass (optional) Feed password
3039 *
3040 * @return integer Status code:
3041 * 0 - OK, Feed already exists
3042 * 1 - OK, Feed added
3043 * 2 - Invalid URL
3044 * 3 - URL content is HTML, no feeds available
3045 * 4 - URL content is HTML which contains multiple feeds.
3046 * Here you should call extractfeedurls in rpc-backend
3047 * to get all possible feeds.
3048 * 5 - Couldn't download the URL content.
3049 */
3050 function subscribe_to_feed($link, $url, $cat_id = 0,
3051 $auth_login = '', $auth_pass = '') {
3052
3053 $url = fix_url($url);
3054
3055 if (!$url || !validate_feed_url($url)) return 2;
3056
3057 $update_method = 0;
3058
3059 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
3060 WHERE id = ".$_SESSION['uid']);
3061
3062 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
3063
3064 if (!$has_oauth || strpos($url, '://api.twitter.com') === false) {
3065 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
3066
3067 if (url_is_html($url, $auth_login, $auth_pass)) {
3068 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
3069 if (count($feedUrls) == 0) {
3070 return 3;
3071 } else if (count($feedUrls) > 1) {
3072 return 4;
3073 }
3074 //use feed url as new URL
3075 $url = key($feedUrls);
3076 }
3077
3078 } else {
3079 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
3080 return 5;
3081
3082 $update_method = 3;
3083 }
3084 if ($cat_id == "0" || !$cat_id) {
3085 $cat_qpart = "NULL";
3086 } else {
3087 $cat_qpart = "'$cat_id'";
3088 }
3089
3090 $result = db_query($link,
3091 "SELECT id FROM ttrss_feeds
3092 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
3093
3094 if (db_num_rows($result) == 0) {
3095 $result = db_query($link,
3096 "INSERT INTO ttrss_feeds
3097 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
3098 VALUES ('".$_SESSION["uid"]."', '$url',
3099 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
3100
3101 $result = db_query($link,
3102 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
3103 AND owner_uid = " . $_SESSION["uid"]);
3104
3105 $feed_id = db_fetch_result($result, 0, "id");
3106
3107 if ($feed_id) {
3108 update_rss_feed($link, $feed_id, true);
3109 }
3110
3111 return 1;
3112 } else {
3113 return 0;
3114 }
3115 }
3116
3117 function print_feed_select($link, $id, $default_id = "",
3118 $attributes = "", $include_all_feeds = true) {
3119
3120 print "<select id=\"$id\" name=\"$id\" $attributes>";
3121 if ($include_all_feeds) {
3122 print "<option value=\"0\">".__('All feeds')."</option>";
3123 }
3124
3125 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
3126 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3127
3128 if (db_num_rows($result) > 0 && $include_all_feeds) {
3129 print "<option disabled>--------</option>";
3130 }
3131
3132 while ($line = db_fetch_assoc($result)) {
3133 if ($line["id"] == $default_id) {
3134 $is_selected = "selected=\"1\"";
3135 } else {
3136 $is_selected = "";
3137 }
3138
3139 $title = truncate_string(htmlspecialchars($line["title"]), 40);
3140
3141 printf("<option $is_selected value='%d'>%s</option>",
3142 $line["id"], $title);
3143 }
3144
3145 print "</select>";
3146 }
3147
3148 function print_feed_cat_select($link, $id, $default_id = "",
3149 $attributes = "", $include_all_cats = true) {
3150
3151 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
3152
3153 if ($include_all_cats) {
3154 print "<option value=\"0\">".__('Uncategorized')."</option>";
3155 }
3156
3157 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3158 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3159
3160 if (db_num_rows($result) > 0 && $include_all_cats) {
3161 print "<option disabled=\"1\">--------</option>";
3162 }
3163
3164 while ($line = db_fetch_assoc($result)) {
3165 if ($line["id"] == $default_id) {
3166 $is_selected = "selected=\"1\"";
3167 } else {
3168 $is_selected = "";
3169 }
3170
3171 if ($line["title"])
3172 printf("<option $is_selected value='%d'>%s</option>",
3173 $line["id"], htmlspecialchars($line["title"]));
3174 }
3175
3176 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
3177
3178 print "</select>";
3179 }
3180
3181 function checkbox_to_sql_bool($val) {
3182 return ($val == "on") ? "true" : "false";
3183 }
3184
3185 function getFeedCatTitle($link, $id) {
3186 if ($id == -1) {
3187 return __("Special");
3188 } else if ($id < -10) {
3189 return __("Labels");
3190 } else if ($id > 0) {
3191 $result = db_query($link, "SELECT ttrss_feed_categories.title
3192 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3193 cat_id = ttrss_feed_categories.id");
3194 if (db_num_rows($result) == 1) {
3195 return db_fetch_result($result, 0, "title");
3196 } else {
3197 return __("Uncategorized");
3198 }
3199 } else {
3200 return "getFeedCatTitle($id) failed";
3201 }
3202
3203 }
3204
3205 function getFeedIcon($id) {
3206 switch ($id) {
3207 case 0:
3208 return "images/archive.png";
3209 break;
3210 case -1:
3211 return "images/mark_set.png";
3212 break;
3213 case -2:
3214 return "images/pub_set.png";
3215 break;
3216 case -3:
3217 return "images/fresh.png";
3218 break;
3219 case -4:
3220 return "images/tag.png";
3221 break;
3222 default:
3223 if ($id < -10) {
3224 return "images/label.png";
3225 } else {
3226 if (file_exists(ICONS_DIR . "/$id.ico"))
3227 return ICONS_URL . "/$id.ico";
3228 }
3229 break;
3230 }
3231 }
3232
3233 function getFeedTitle($link, $id) {
3234 if ($id == -1) {
3235 return __("Starred articles");
3236 } else if ($id == -2) {
3237 return __("Published articles");
3238 } else if ($id == -3) {
3239 return __("Fresh articles");
3240 } else if ($id == -4) {
3241 return __("All articles");
3242 } else if ($id === 0 || $id === "0") {
3243 return __("Archived articles");
3244 } else if ($id < -10) {
3245 $label_id = -$id - 11;
3246 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3247 if (db_num_rows($result) == 1) {
3248 return db_fetch_result($result, 0, "caption");
3249 } else {
3250 return "Unknown label ($label_id)";
3251 }
3252
3253 } else if (is_numeric($id) && $id > 0) {
3254 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3255 if (db_num_rows($result) == 1) {
3256 return db_fetch_result($result, 0, "title");
3257 } else {
3258 return "Unknown feed ($id)";
3259 }
3260 } else {
3261 return $id;
3262 }
3263 }
3264
3265 function get_session_cookie_name() {
3266 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
3267 }
3268
3269 function make_init_params($link) {
3270 $params = array();
3271
3272 $params["theme"] = get_user_theme($link);
3273 $params["theme_options"] = get_user_theme_options($link);
3274
3275 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
3276 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
3277 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
3278 $params["sign_info"] = theme_image($link, "images/sign_info.png");
3279
3280 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3281 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3282 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
3283 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
3284
3285 $params[strtolower($param)] = (int) get_pref($link, $param);
3286 }
3287
3288 $params["icons_url"] = ICONS_URL;
3289 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
3290 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
3291 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
3292 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
3293 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
3294
3295 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3296 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3297
3298 $max_feed_id = db_fetch_result($result, 0, "mid");
3299 $num_feeds = db_fetch_result($result, 0, "nf");
3300
3301 $params["max_feed_id"] = (int) $max_feed_id;
3302 $params["num_feeds"] = (int) $num_feeds;
3303
3304 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
3305
3306 return $params;
3307 }
3308
3309 function print_runtime_info($link) {
3310 print "<runtime-info><![CDATA[";
3311 print json_encode(make_runtime_info($link));
3312 print "]]></runtime-info>";
3313 }
3314
3315 function make_runtime_info($link) {
3316 $data = array();
3317
3318 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
3319 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3320
3321 $max_feed_id = db_fetch_result($result, 0, "mid");
3322 $num_feeds = db_fetch_result($result, 0, "nf");
3323
3324 $data["max_feed_id"] = (int) $max_feed_id;
3325 $data["num_feeds"] = (int) $num_feeds;
3326
3327 $data['last_article_id'] = getLastArticleId($link);
3328 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
3329
3330 if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
3331
3332 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
3333
3334 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3335
3336 $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
3337
3338 if ($stamp) {
3339 $stamp_delta = time() - $stamp;
3340
3341 if ($stamp_delta > 1800) {
3342 $stamp_check = 0;
3343 } else {
3344 $stamp_check = 1;
3345 $_SESSION["daemon_stamp_check"] = time();
3346 }
3347
3348 $data['daemon_stamp_ok'] = $stamp_check;
3349
3350 $stamp_fmt = date("Y.m.d, G:i", $stamp);
3351
3352 $data['daemon_stamp'] = $stamp_fmt;
3353 }
3354 }
3355 }
3356
3357 if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
3358 $new_version_details = @check_for_update($link);
3359
3360 $data['new_version_available'] = (int) ($new_version_details != false);
3361
3362 $_SESSION["last_version_check"] = time();
3363 }
3364
3365 return $data;
3366 }
3367
3368 function search_to_sql($link, $search, $match_on) {
3369
3370 $search_query_part = "";
3371
3372 $keywords = explode(" ", $search);
3373 $query_keywords = array();
3374
3375 foreach ($keywords as $k) {
3376 if (strpos($k, "-") === 0) {
3377 $k = substr($k, 1);
3378 $not = "NOT";
3379 } else {
3380 $not = "";
3381 }
3382
3383 $commandpair = explode(":", mb_strtolower($k), 2);
3384
3385 if ($commandpair[0] == "note" && $commandpair[1]) {
3386
3387 if ($commandpair[1] == "true")
3388 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
3389 else
3390 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
3391
3392 } else if ($commandpair[0] == "star" && $commandpair[1]) {
3393
3394 if ($commandpair[1] == "true")
3395 array_push($query_keywords, "($not (marked = true))");
3396 else
3397 array_push($query_keywords, "($not (marked = false))");
3398
3399 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
3400
3401 if ($commandpair[1] == "true")
3402 array_push($query_keywords, "($not (published = true))");
3403 else
3404 array_push($query_keywords, "($not (published = false))");
3405
3406 } else if (strpos($k, "@") === 0) {
3407
3408 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
3409 $orig_ts = strtotime(substr($k, 1));
3410 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
3411
3412 //$k = date("Y-m-d", strtotime(substr($k, 1)));
3413
3414 array_push($query_keywords, "(".SUBSTRING_FOR_DATE."(updated,1,LENGTH('$k')) $not = '$k')");
3415 } else if ($match_on == "both") {
3416 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3417 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3418 } else if ($match_on == "title") {
3419 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3420 } else if ($match_on == "content") {
3421 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3422 }
3423 }
3424
3425 $search_query_part = implode("AND", $query_keywords);
3426
3427 return $search_query_part;
3428 }
3429
3430
3431 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false) {
3432
3433 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3434
3435 $ext_tables_part = "";
3436
3437 if ($search) {
3438
3439 if (SPHINX_ENABLED) {
3440 $ids = join(",", @sphinx_search($search, 0, 500));
3441
3442 if ($ids)
3443 $search_query_part = "ref_id IN ($ids) AND ";
3444 else
3445 $search_query_part = "ref_id = -1 AND ";
3446
3447 } else {
3448 $search_query_part = search_to_sql($link, $search, $match_on);
3449 $search_query_part .= " AND ";
3450 }
3451
3452 } else {
3453 $search_query_part = "";
3454 }
3455
3456 if ($filter) {
3457 $filter_query_part = filter_to_sql($filter);
3458 } else {
3459 $filter_query_part = "";
3460 }
3461
3462 $view_query_part = "";
3463
3464 if ($view_mode == "adaptive" || $view_query_part == "noscores") {
3465 if ($search) {
3466 $view_query_part = " ";
3467 } else if ($feed != -1) {
3468 $unread = getFeedUnread($link, $feed, $cat_view);
3469 if ($unread > 0) {
3470 $view_query_part = " unread = true AND ";
3471 }
3472 }
3473 }
3474
3475 if ($view_mode == "marked") {
3476 $view_query_part = " marked = true AND ";
3477 }
3478
3479 if ($view_mode == "published") {
3480 $view_query_part = " published = true AND ";
3481 }
3482
3483 if ($view_mode == "unread") {
3484 $view_query_part = " unread = true AND ";
3485 }
3486
3487 if ($view_mode == "updated") {
3488 $view_query_part = " (last_read is null and unread = false) AND ";
3489 }
3490
3491 if ($limit > 0) {
3492 $limit_query_part = "LIMIT " . $limit;
3493 }
3494
3495 $vfeed_query_part = "";
3496
3497 // override query strategy and enable feed display when searching globally
3498 if ($search && $search_mode == "all_feeds") {
3499 $query_strategy_part = "ttrss_entries.id > 0";
3500 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3501 /* tags */
3502 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3503 $query_strategy_part = "ttrss_entries.id > 0";
3504 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3505 id = feed_id) as feed_title,";
3506 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3507
3508 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3509
3510 $tmp_result = false;
3511
3512 if ($cat_view) {
3513 $tmp_result = db_query($link, "SELECT id
3514 FROM ttrss_feeds WHERE cat_id = '$feed'");
3515 } else {
3516 $tmp_result = db_query($link, "SELECT id
3517 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
3518 WHERE id = '$feed') AND id != '$feed'");
3519 }
3520
3521 $cat_siblings = array();
3522
3523 if (db_num_rows($tmp_result) > 0) {
3524 while ($p = db_fetch_assoc($tmp_result)) {
3525 array_push($cat_siblings, "feed_id = " . $p["id"]);
3526 }
3527
3528 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
3529 $feed, implode(" OR ", $cat_siblings));
3530
3531 } else {
3532 $query_strategy_part = "ttrss_entries.id > 0";
3533 }
3534
3535 } else if ($feed > 0) {
3536
3537 if ($cat_view) {
3538
3539 if ($feed > 0) {
3540 $query_strategy_part = "cat_id = '$feed'";
3541 } else {
3542 $query_strategy_part = "cat_id IS NULL";
3543 }
3544
3545 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3546
3547 } else {
3548 $query_strategy_part = "feed_id = '$feed'";
3549 }
3550 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3551 $query_strategy_part = "feed_id IS NULL";
3552 } else if ($feed == 0 && $cat_view) { // uncategorized
3553 $query_strategy_part = "cat_id IS NULL";
3554 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3555 } else if ($feed == -1) { // starred virtual feed
3556 $query_strategy_part = "marked = true";
3557 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3558 } else if ($feed == -2) { // published virtual feed OR labels category
3559
3560 if (!$cat_view) {
3561 $query_strategy_part = "published = true";
3562 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3563 } else {
3564 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3565
3566 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3567
3568 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3569 ttrss_user_labels2.article_id = ref_id";
3570
3571 }
3572
3573 } else if ($feed == -3) { // fresh virtual feed
3574 $query_strategy_part = "unread = true AND score >= 0";
3575
3576 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3577
3578 if (DB_TYPE == "pgsql") {
3579 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
3580 } else {
3581 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3582 }
3583
3584 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3585 } else if ($feed == -4) { // all articles virtual feed
3586 $query_strategy_part = "true";
3587 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3588 } else if ($feed <= -10) { // labels
3589 $label_id = -$feed - 11;
3590
3591 $query_strategy_part = "label_id = '$label_id' AND
3592 ttrss_labels2.id = ttrss_user_labels2.label_id AND
3593 ttrss_user_labels2.article_id = ref_id";
3594
3595 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3596 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3597
3598 } else {
3599 $query_strategy_part = "id > 0"; // dumb
3600 }
3601
3602 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3603 $date_sort_field = "updated";
3604 } else {
3605 $date_sort_field = "date_entered";
3606 }
3607
3608 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3609 $order_by = "$date_sort_field";
3610 } else {
3611 $order_by = "$date_sort_field DESC";
3612 }
3613
3614 if ($view_mode != "noscores") {
3615 $order_by = "score DESC, $order_by";
3616 }
3617
3618 if ($override_order) {
3619 $order_by = $override_order;
3620 }
3621
3622 $feed_title = "";
3623
3624 if ($search) {
3625 $feed_title = "Search results";
3626 } else {
3627 if ($cat_view) {
3628 $feed_title = getCategoryTitle($link, $feed);
3629 } else {
3630 if (is_numeric($feed) && $feed > 0) {
3631 $result = db_query($link, "SELECT title,site_url,last_error
3632 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3633
3634 $feed_title = db_fetch_result($result, 0, "title");
3635 $feed_site_url = db_fetch_result($result, 0, "site_url");
3636 $last_error = db_fetch_result($result, 0, "last_error");
3637 } else {
3638 $feed_title = getFeedTitle($link, $feed);
3639 }
3640 }
3641 }
3642
3643 $content_query_part = "content as content_preview,";
3644
3645 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3646
3647 if ($feed >= 0) {
3648 $feed_kind = "Feeds";
3649 } else {
3650 $feed_kind = "Labels";
3651 }
3652
3653 if ($limit_query_part) {
3654 $offset_query_part = "OFFSET $offset";
3655 }
3656
3657 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3658 if (!$override_order) {
3659 $order_by = "ttrss_feeds.title, $order_by";
3660 }
3661 }
3662
3663 if ($feed != "0") {
3664 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3665 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3666
3667 } else {
3668 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3669 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3670 }
3671
3672 $query = "SELECT DISTINCT
3673 date_entered,
3674 guid,
3675 ttrss_entries.id,ttrss_entries.title,
3676 updated,
3677 note,
3678 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3679 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3680 $vfeed_query_part
3681 $content_query_part
3682 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3683 author,score
3684 FROM
3685 $from_qpart
3686 WHERE
3687 $feed_check_qpart
3688 ttrss_user_entries.ref_id = ttrss_entries.id AND
3689 ttrss_user_entries.owner_uid = '$owner_uid' AND
3690 $search_query_part
3691 $filter_query_part
3692 $view_query_part
3693 $query_strategy_part ORDER BY $order_by
3694 $limit_query_part $offset_query_part";
3695
3696 if ($_REQUEST["debug"]) print $query;
3697
3698 $result = db_query($link, $query);
3699
3700 } else {
3701 // browsing by tag
3702
3703 $select_qpart = "SELECT DISTINCT " .
3704 "date_entered," .
3705 "guid," .
3706 "note," .
3707 "ttrss_entries.id as id," .
3708 "title," .
3709 "updated," .
3710 "unread," .
3711 "feed_id," .
3712 "orig_feed_id," .
3713 "marked," .
3714 "link," .
3715 "last_read," .
3716 SUBSTRING_FOR_DATE . "(last_read,1,19) as last_read_noms," .
3717 $vfeed_query_part .
3718 $content_query_part .
3719 SUBSTRING_FOR_DATE . "(updated,1,19) as updated_noms," .
3720 "score ";
3721
3722 $feed_kind = "Tags";
3723 $all_tags = explode(",", $feed);
3724 if ($search_mode == 'any') {
3725 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
3726 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
3727 $where_qpart = " WHERE " .
3728 "ref_id = ttrss_entries.id AND " .
3729 "ttrss_user_entries.owner_uid = $owner_uid AND " .
3730 "post_int_id = int_id AND $tag_sql AND " .
3731 $view_query_part .
3732 $search_query_part .
3733 $query_strategy_part . " ORDER BY $order_by " .
3734 $limit_query_part;
3735
3736 } else {
3737 $i = 1;
3738 $sub_selects = array();
3739 $sub_ands = array();
3740 foreach ($all_tags as $term) {
3741 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
3742 $i++;
3743 }
3744 if ($i > 2) {
3745 $x = 1;
3746 $y = 2;
3747 do {
3748 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
3749 $x++;
3750 $y++;
3751 } while ($y < $i);
3752 }
3753 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
3754 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
3755 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
3756 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
3757 }
3758 // error_log("TAG SQL: " . $tag_sql);
3759 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
3760
3761 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
3762 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
3763 }
3764
3765 return array($result, $feed_title, $feed_site_url, $last_error);
3766
3767 }
3768
3769 function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3770 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3771
3772 require_once "lib/MiniTemplator.class.php";
3773
3774 $note_style = "background-color : #fff7d5;
3775 border-width : 1px; ".
3776 "padding : 5px; border-style : dashed; border-color : #e7d796;".
3777 "margin-bottom : 1em; color : #9a8c59;";
3778
3779 if (!$limit) $limit = 30;
3780
3781 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
3782 $date_sort_field = "updated";
3783 } else {
3784 $date_sort_field = "date_entered";
3785 }
3786
3787 $qfh_ret = queryFeedHeadlines($link, $feed,
3788 $limit, $view_mode, $is_cat, $search, $search_mode,
3789 $match_on, "$date_sort_field DESC", 0, $owner_uid);
3790
3791 $result = $qfh_ret[0];
3792 $feed_title = htmlspecialchars($qfh_ret[1]);
3793 $feed_site_url = $qfh_ret[2];
3794 $last_error = $qfh_ret[3];
3795
3796 $feed_self_url = get_self_url_prefix() .
3797 "/backend.php?op=rss&id=-2&key=" .
3798 get_feed_access_key($link, -2, false);
3799
3800 if (!$feed_site_url) $feed_site_url = get_self_url_prefix();
3801
3802 $tpl = new MiniTemplator;
3803
3804 $tpl->readTemplateFromFile("templates/generated_feed.txt");
3805
3806 $tpl->setVariable('FEED_TITLE', $feed_title);
3807 $tpl->setVariable('VERSION', VERSION);
3808 $tpl->setVariable('FEED_URL', htmlspecialchars($feed_self_url));
3809
3810 if (PUBSUBHUBBUB_HUB && $feed == -2) {
3811 $tpl->setVariable('HUB_URL', htmlspecialchars(PUBSUBHUBBUB_HUB));
3812 $tpl->addBlock('feed_hub');
3813 }
3814
3815 $tpl->setVariable('SELF_URL', htmlspecialchars(get_self_url_prefix()));
3816
3817 while ($line = db_fetch_assoc($result)) {
3818 $tpl->setVariable('ARTICLE_ID', htmlspecialchars($line['link']));
3819 $tpl->setVariable('ARTICLE_LINK', htmlspecialchars($line['link']));
3820 $tpl->setVariable('ARTICLE_TITLE', htmlspecialchars($line['title']));
3821 $tpl->setVariable('ARTICLE_EXCERPT',
3822 truncate_string(strip_tags($line["content_preview"]), 100, '...'));
3823
3824 $content = sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3825
3826 if ($line['note']) {
3827 $content = "<div style=\"$note_style\">Article note: " . $line['note'] . "</div>" .
3828 $content;
3829 }
3830
3831 $tpl->setVariable('ARTICLE_CONTENT', $content);
3832
3833 $tpl->setVariable('ARTICLE_UPDATED', date('c', strtotime($line["updated"])));
3834 $tpl->setVariable('ARTICLE_AUTHOR', htmlspecialchars($line['author']));
3835
3836 $tags = get_article_tags($link, $line["id"], $owner_uid);
3837
3838 foreach ($tags as $tag) {
3839 $tpl->setVariable('ARTICLE_CATEGORY', htmlspecialchars($tag));
3840 $tpl->addBlock('category');
3841 }
3842
3843 $enclosures = get_article_enclosures($link, $line["id"]);
3844
3845 foreach ($enclosures as $e) {
3846 $type = htmlspecialchars($e['content_type']);
3847 $url = htmlspecialchars($e['content_url']);
3848 $length = $e['duration'];
3849
3850 $tpl->setVariable('ARTICLE_ENCLOSURE_URL', $url);
3851 $tpl->setVariable('ARTICLE_ENCLOSURE_TYPE', $type);
3852 $tpl->setVariable('ARTICLE_ENCLOSURE_LENGTH', $length);
3853
3854 $tpl->addBlock('enclosure');
3855 }
3856
3857 $tpl->addBlock('entry');
3858 }
3859
3860 $tmp = "";
3861
3862 $tpl->addBlock('feed');
3863 $tpl->generateOutputToString($tmp);
3864
3865 print $tmp;
3866 }
3867
3868 function getCategoryTitle($link, $cat_id) {
3869
3870 if ($cat_id == -1) {
3871 return __("Special");
3872 } else if ($cat_id == -2) {
3873 return __("Labels");
3874 } else {
3875
3876 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3877 id = '$cat_id'");
3878
3879 if (db_num_rows($result) == 1) {
3880 return db_fetch_result($result, 0, "title");
3881 } else {
3882 return "Uncategorized";
3883 }
3884 }
3885 }
3886
3887 function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
3888 global $purifier;
3889
3890 if (!$owner) $owner = $_SESSION["uid"];
3891
3892 $res = trim($str); if (!$res) return '';
3893
3894 // if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3895 $res = $purifier->purify($res);
3896 // }
3897
3898 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3899 $res = preg_replace('/<img[^>]+>/is', '', $res);
3900 }
3901
3902 if (strpos($res, "href=") === false)
3903 $res = rewrite_urls($res);
3904
3905 $charset_hack = '<head>
3906 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3907 </head>';
3908
3909 $res = trim($res); if (!$res) return '';
3910
3911 libxml_use_internal_errors(true);
3912
3913 $doc = new DOMDocument();
3914 $doc->loadHTML($charset_hack . $res);
3915 $xpath = new DOMXPath($doc);
3916
3917 $entries = $xpath->query('(//a[@href]|//img[@src])');
3918 $br_inserted = 0;
3919
3920 foreach ($entries as $entry) {
3921
3922 if ($site_url) {
3923
3924 if ($entry->hasAttribute('href'))
3925 $entry->setAttribute('href',
3926 rewrite_relative_url($site_url, $entry->getAttribute('href')));
3927
3928 if ($entry->hasAttribute('src'))
3929 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
3930 $entry->setAttribute('src',
3931 rewrite_relative_url($site_url, $entry->getAttribute('src')));
3932 }
3933
3934 if (strtolower($entry->nodeName) == "a") {
3935 $entry->setAttribute("target", "_blank");
3936 }
3937
3938 if (strtolower($entry->nodeName) == "img" && !$br_inserted) {
3939 $br = $doc->createElement("br");
3940
3941 if ($entry->parentNode->nextSibling) {
3942 $entry->parentNode->insertBefore($br, $entry->nextSibling);
3943 $br_inserted = 1;
3944 }
3945
3946 }
3947 }
3948
3949 $node = $doc->getElementsByTagName('body')->item(0);
3950
3951 return $doc->saveXML($node);
3952 }
3953
3954 /**
3955 * Send by mail a digest of last articles.
3956 *
3957 * @param mixed $link The database connection.
3958 * @param integer $limit The maximum number of articles by digest.
3959 * @return boolean Return false if digests are not enabled.
3960 */
3961 function send_headlines_digests($link, $limit = 100) {
3962
3963 if (!DIGEST_ENABLE) return false;
3964
3965 $user_limit = DIGEST_EMAIL_LIMIT;
3966 $days = 1;
3967
3968 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3969
3970 if (DB_TYPE == "pgsql") {
3971 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3972 } else if (DB_TYPE == "mysql") {
3973 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3974 }
3975
3976 $result = db_query($link, "SELECT id,email FROM ttrss_users
3977 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3978
3979 while ($line = db_fetch_assoc($result)) {
3980
3981 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3982 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3983
3984 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3985
3986 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3987 $digest = $tuple[0];
3988 $headlines_count = $tuple[1];
3989 $affected_ids = $tuple[2];
3990 $digest_text = $tuple[3];
3991
3992 if ($headlines_count > 0) {
3993
3994 $mail = new PHPMailer();
3995
3996 $mail->PluginDir = "lib/phpmailer/";
3997 $mail->SetLanguage("en", "lib/phpmailer/language/");
3998
3999 $mail->CharSet = "UTF-8";
4000
4001 $mail->From = DIGEST_FROM_ADDRESS;
4002 $mail->FromName = DIGEST_FROM_NAME;
4003 $mail->AddAddress($line["email"], $line["login"]);
4004
4005 if (DIGEST_SMTP_HOST) {
4006 $mail->Host = DIGEST_SMTP_HOST;
4007 $mail->Mailer = "smtp";
4008 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
4009 $mail->Username = DIGEST_SMTP_LOGIN;
4010 $mail->Password = DIGEST_SMTP_PASSWORD;
4011 }
4012
4013 $mail->IsHTML(true);
4014 $mail->Subject = DIGEST_SUBJECT;
4015 $mail->Body = $digest;
4016 $mail->AltBody = $digest_text;
4017
4018 $rc = $mail->Send();
4019
4020 if (!$rc) print "ERROR: " . $mail->ErrorInfo;
4021
4022 print "RC=$rc\n";
4023
4024 if ($rc && $do_catchup) {
4025 print "Marking affected articles as read...\n";
4026 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
4027 }
4028 } else {
4029 print "No headlines\n";
4030 }
4031
4032 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
4033 WHERE id = " . $line["id"]);
4034 }
4035 }
4036
4037 print "All done.\n";
4038
4039 }
4040
4041 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
4042
4043 require_once "lib/MiniTemplator.class.php";
4044
4045 $tpl = new MiniTemplator;
4046 $tpl_t = new MiniTemplator;
4047
4048 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
4049 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
4050
4051 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
4052 $tpl->setVariable('CUR_TIME', date('G:i'));
4053
4054 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
4055 $tpl_t->setVariable('CUR_TIME', date('G:i'));
4056
4057 $affected_ids = array();
4058
4059 if (DB_TYPE == "pgsql") {
4060 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
4061 } else if (DB_TYPE == "mysql") {
4062 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
4063 }
4064
4065 $result = db_query($link, "SELECT ttrss_entries.title,
4066 ttrss_feeds.title AS feed_title,
4067 date_updated,
4068 ttrss_user_entries.ref_id,
4069 link,
4070 SUBSTRING(content, 1, 120) AS excerpt,
4071 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
4072 FROM
4073 ttrss_user_entries,ttrss_entries,ttrss_feeds
4074 WHERE
4075 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
4076 AND include_in_digest = true
4077 AND $interval_query
4078 AND ttrss_user_entries.owner_uid = $user_id
4079 AND unread = true
4080 ORDER BY ttrss_feeds.title, date_updated DESC
4081 LIMIT $limit");
4082
4083 $cur_feed_title = "";
4084
4085 $headlines_count = db_num_rows($result);
4086
4087 $headlines = array();
4088
4089 while ($line = db_fetch_assoc($result)) {
4090 array_push($headlines, $line);
4091 }
4092
4093 for ($i = 0; $i < sizeof($headlines); $i++) {
4094
4095 $line = $headlines[$i];
4096
4097 array_push($affected_ids, $line["ref_id"]);
4098
4099 $updated = make_local_datetime($link, $line['last_updated'], false,
4100 $user_id);
4101
4102 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
4103 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
4104 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
4105 $tpl->setVariable('ARTICLE_UPDATED', $updated);
4106 $tpl->setVariable('ARTICLE_EXCERPT',
4107 truncate_string(strip_tags($line["excerpt"]), 100));
4108
4109 $tpl->addBlock('article');
4110
4111 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
4112 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
4113 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
4114 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
4115 // $tpl_t->setVariable('ARTICLE_EXCERPT',
4116 // truncate_string(strip_tags($line["excerpt"]), 100));
4117
4118 $tpl_t->addBlock('article');
4119
4120 if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
4121 $tpl->addBlock('feed');
4122 $tpl_t->addBlock('feed');
4123 }
4124
4125 }
4126
4127 $tpl->addBlock('digest');
4128 $tpl->generateOutputToString($tmp);
4129
4130 $tpl_t->addBlock('digest');
4131 $tpl_t->generateOutputToString($tmp_t);
4132
4133 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
4134 }
4135
4136 function check_for_update($link) {
4137 if (CHECK_FOR_NEW_VERSION && $_SESSION['access_level'] >= 10) {
4138 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION;
4139
4140 $version_data = @fetch_file_contents($version_url);
4141
4142 if ($version_data) {
4143 $version_data = json_decode($version_data, true);
4144 if ($version_data && $version_data['version']) {
4145
4146 if (version_compare(VERSION, $version_data['version']) == -1) {
4147 return $version_data;
4148 }
4149 }
4150 }
4151 }
4152 return false;
4153 }
4154
4155 function markArticlesById($link, $ids, $cmode) {
4156
4157 $tmp_ids = array();
4158
4159 foreach ($ids as $id) {
4160 array_push($tmp_ids, "ref_id = '$id'");
4161 }
4162
4163 $ids_qpart = join(" OR ", $tmp_ids);
4164
4165 if ($cmode == 0) {
4166 db_query($link, "UPDATE ttrss_user_entries SET
4167 marked = false,last_read = NOW()
4168 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4169 } else if ($cmode == 1) {
4170 db_query($link, "UPDATE ttrss_user_entries SET
4171 marked = true
4172 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4173 } else {
4174 db_query($link, "UPDATE ttrss_user_entries SET
4175 marked = NOT marked,last_read = NOW()
4176 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4177 }
4178 }
4179
4180 function publishArticlesById($link, $ids, $cmode) {
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 published = false,last_read = NOW()
4193 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4194 } else if ($cmode == 1) {
4195 db_query($link, "UPDATE ttrss_user_entries SET
4196 published = true
4197 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4198 } else {
4199 db_query($link, "UPDATE ttrss_user_entries SET
4200 published = NOT published,last_read = NOW()
4201 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4202 }
4203
4204 if (PUBSUBHUBBUB_HUB) {
4205 $rss_link = get_self_url_prefix() .
4206 "/backend.php?op=rss&id=-2&key=" .
4207 get_feed_access_key($link, -2, false);
4208
4209 $p = new Publisher(PUBSUBHUBBUB_HUB);
4210
4211 $pubsub_result = $p->publish_update($rss_link);
4212 }
4213 }
4214
4215 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4216
4217 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4218 if (count($ids) == 0) return;
4219
4220 $tmp_ids = array();
4221
4222 foreach ($ids as $id) {
4223 array_push($tmp_ids, "ref_id = '$id'");
4224 }
4225
4226 $ids_qpart = join(" OR ", $tmp_ids);
4227
4228 if ($cmode == 0) {
4229 db_query($link, "UPDATE ttrss_user_entries SET
4230 unread = false,last_read = NOW()
4231 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4232 } else if ($cmode == 1) {
4233 db_query($link, "UPDATE ttrss_user_entries SET
4234 unread = true
4235 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4236 } else {
4237 db_query($link, "UPDATE ttrss_user_entries SET
4238 unread = NOT unread,last_read = NOW()
4239 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4240 }
4241
4242 /* update ccache */
4243
4244 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4245 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4246
4247 while ($line = db_fetch_assoc($result)) {
4248 ccache_update($link, $line["feed_id"], $owner_uid);
4249 }
4250 }
4251
4252 function catchupArticleById($link, $id, $cmode) {
4253
4254 if ($cmode == 0) {
4255 db_query($link, "UPDATE ttrss_user_entries SET
4256 unread = false,last_read = NOW()
4257 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4258 } else if ($cmode == 1) {
4259 db_query($link, "UPDATE ttrss_user_entries SET
4260 unread = true
4261 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4262 } else {
4263 db_query($link, "UPDATE ttrss_user_entries SET
4264 unread = NOT unread,last_read = NOW()
4265 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4266 }
4267
4268 $feed_id = getArticleFeed($link, $id);
4269 ccache_update($link, $feed_id, $_SESSION["uid"]);
4270 }
4271
4272 function make_guid_from_title($title) {
4273 return preg_replace("/[ \"\',.:;]/", "-",
4274 mb_strtolower(strip_tags($title), 'utf-8'));
4275 }
4276
4277 function format_headline_subtoolbar($link, $feed_site_url, $feed_title,
4278 $feed_id, $is_cat, $search, $match_on,
4279 $search_mode, $view_mode, $error) {
4280
4281 $page_prev_link = "viewFeedGoPage(-1)";
4282 $page_next_link = "viewFeedGoPage(1)";
4283 $page_first_link = "viewFeedGoPage(0)";
4284
4285 $catchup_page_link = "catchupPage()";
4286 $catchup_feed_link = "catchupCurrentFeed()";
4287 $catchup_sel_link = "catchupSelection()";
4288
4289 $archive_sel_link = "archiveSelection()";
4290 $delete_sel_link = "deleteSelection()";
4291
4292 $sel_all_link = "selectArticles('all')";
4293 $sel_unread_link = "selectArticles('unread')";
4294 $sel_none_link = "selectArticles('none')";
4295 $sel_inv_link = "selectArticles('invert')";
4296
4297 $tog_unread_link = "selectionToggleUnread()";
4298 $tog_marked_link = "selectionToggleMarked()";
4299 $tog_published_link = "selectionTogglePublished()";
4300
4301 $reply = "<div id=\"subtoolbar_main\">";
4302
4303 $reply .= __('Select:')."
4304 <a href=\"#\" onclick=\"$sel_all_link\">".__('All')."</a>,
4305 <a href=\"#\" onclick=\"$sel_unread_link\">".__('Unread')."</a>,
4306 <a href=\"#\" onclick=\"$sel_inv_link\">".__('Invert')."</a>,
4307 <a href=\"#\" onclick=\"$sel_none_link\">".__('None')."</a></li>";
4308
4309 $reply .= " ";
4310
4311 $reply .= "<select dojoType=\"dijit.form.Select\"
4312 onchange=\"headlineActionsChange(this)\">";
4313 $reply .= "<option value=\"false\">".__('Actions...')."</option>";
4314
4315 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection toggle:')."</option>";
4316
4317 $reply .= "<option value=\"$tog_unread_link\">".__('Unread')."</option>
4318 <option value=\"$tog_marked_link\">".__('Starred')."</option>
4319 <option value=\"$tog_published_link\">".__('Published')."</option>";
4320
4321 $reply .= "<option value=\"0\" disabled=\"1\">".__('Selection:')."</option>";
4322
4323 $reply .= "<option value=\"$catchup_sel_link\">".__('Mark as read')."</option>";
4324
4325 if ($feed_id != "0") {
4326 $reply .= "<option value=\"$archive_sel_link\">".__('Archive')."</option>";
4327 } else {
4328 $reply .= "<option value=\"$archive_sel_link\">".__('Move back')."</option>";
4329 $reply .= "<option value=\"$delete_sel_link\">".__('Delete')."</option>";
4330
4331 }
4332
4333 $reply .= "<option value=\"emailArticle(false)\">".__('Forward by email').
4334 "</option>";
4335
4336 if ($is_cat) $cat_q = "&is_cat=$is_cat";
4337
4338 if ($search) {
4339 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4340 } else {
4341 $search_q = "";
4342 }
4343
4344 $rss_link = htmlspecialchars(get_self_url_prefix() .
4345 "/backend.php?op=rss&id=$feed_id$cat_q$search_q");
4346
4347 $reply .= "<option value=\"0\" disabled=\"1\">".__('Feed:')."</option>";
4348
4349 $reply .= "<option value=\"catchupPage()\">".__('Mark as read')."</option>";
4350
4351 $reply .= "<option value=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">".__('View as RSS')."</option>";
4352
4353 $reply .= "</select>";
4354
4355 $reply .= "</div>";
4356
4357 $reply .= "<div id=\"subtoolbar_ftitle\">";
4358
4359 if ($feed_site_url) {
4360 $target = "target=\"_blank\"";
4361 $reply .= "<a title=\"".__("Visit the website")."\" $target href=\"$feed_site_url\">".
4362 truncate_string($feed_title,30)."</a>";
4363
4364 if ($error) {
4365 $reply .= " (<span class=\"error\" title=\"$error\">Error</span>)";
4366 }
4367
4368 } else {
4369 if ($feed_id < -10) {
4370 $label_id = -11-$feed_id;
4371
4372 $result = db_query($link, "SELECT fg_color, bg_color
4373 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4374 $_SESSION["uid"]);
4375
4376 if (db_num_rows($result) != 0) {
4377 $fg_color = db_fetch_result($result, 0, "fg_color");
4378 $bg_color = db_fetch_result($result, 0, "bg_color");
4379
4380 $reply .= "<span style=\"background : $bg_color; color : $fg_color\" >";
4381 $reply .= $feed_title;
4382 $reply .= "</span>";
4383 } else {
4384 $reply .= $feed_title;
4385 }
4386
4387 } else {
4388 $reply .= $feed_title;
4389 }
4390 }
4391
4392 $reply .= "
4393 <a href=\"#\"
4394 title=\"".__("View as RSS feed")."\"
4395 onclick=\"displayDlg('generatedFeed', '$feed_id:$is_cat:$rss_link')\">
4396 <img class=\"noborder\" style=\"vertical-align : middle\" src=\"images/feed-icon-12x12.png\"></a>";
4397
4398 $reply .= "</div>";
4399
4400 return $reply;
4401 }
4402
4403 function outputFeedList($link, $special = true) {
4404
4405 $feedlist = array();
4406
4407 $enable_cats = get_pref($link, 'ENABLE_FEED_CATS');
4408
4409 $feedlist['identifier'] = 'id';
4410 $feedlist['label'] = 'name';
4411 $feedlist['items'] = array();
4412
4413 $owner_uid = $_SESSION["uid"];
4414
4415 /* virtual feeds */
4416
4417 if ($special) {
4418
4419 if ($enable_cats) {
4420 $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4421 $cat = feedlist_init_cat($link, -1, $cat_hidden);
4422 } else {
4423 $cat['items'] = array();
4424 }
4425
4426 foreach (array(-4, -3, -1, -2, 0) as $i) {
4427 array_push($cat['items'], feedlist_init_feed($link, $i));
4428 }
4429
4430 if ($enable_cats) {
4431 array_push($feedlist['items'], $cat);
4432 } else {
4433 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4434 }
4435
4436 $result = db_query($link, "SELECT * FROM
4437 ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4438
4439 if (db_num_rows($result) > 0) {
4440
4441 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4442 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4443 $cat = feedlist_init_cat($link, -2, $cat_hidden);
4444 } else {
4445 $cat['items'] = array();
4446 }
4447
4448 while ($line = db_fetch_assoc($result)) {
4449
4450 $label_id = -$line['id'] - 11;
4451 $count = getFeedUnread($link, $label_id);
4452
4453 $feed = feedlist_init_feed($link, $label_id, false, $count);
4454
4455 $feed['fg_color'] = $line['fg_color'];
4456 $feed['bg_color'] = $line['bg_color'];
4457
4458 array_push($cat['items'], $feed);
4459 }
4460
4461 if ($enable_cats) {
4462 array_push($feedlist['items'], $cat);
4463 } else {
4464 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4465 }
4466 }
4467 }
4468
4469 /* if (get_pref($link, 'ENABLE_FEED_CATS')) {
4470 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4471 $order_by_qpart = "order_id,category,unread DESC,title";
4472 } else {
4473 $order_by_qpart = "order_id,category,title";
4474 }
4475 } else {
4476 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4477 $order_by_qpart = "unread DESC,title";
4478 } else {
4479 $order_by_qpart = "title";
4480 }
4481 } */
4482
4483 /* real feeds */
4484
4485 if ($enable_cats)
4486 $order_by_qpart = "ttrss_feed_categories.order_id,category,
4487 ttrss_feeds.order_id,title";
4488 else
4489 $order_by_qpart = "title";
4490
4491 $age_qpart = getMaxAgeSubquery();
4492
4493 $query = "SELECT ttrss_feeds.id, ttrss_feeds.title,
4494 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4495 cat_id,last_error,
4496 ttrss_feed_categories.title AS category,
4497 ttrss_feed_categories.collapsed,
4498 value AS unread
4499 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4500 ON (ttrss_feed_categories.id = cat_id)
4501 LEFT JOIN ttrss_counters_cache
4502 ON
4503 (ttrss_feeds.id = feed_id)
4504 WHERE
4505 ttrss_feeds.owner_uid = '$owner_uid'
4506 ORDER BY $order_by_qpart";
4507
4508 $result = db_query($link, $query);
4509
4510 $actid = $_REQUEST["actid"];
4511
4512 if (db_num_rows($result) > 0) {
4513
4514 $category = "";
4515
4516 if (!$enable_cats)
4517 $cat['items'] = array();
4518 else
4519 $cat = false;
4520
4521 while ($line = db_fetch_assoc($result)) {
4522
4523 $feed = htmlspecialchars(trim($line["title"]));
4524
4525 if (!$feed) $feed = "[Untitled]";
4526
4527 $feed_id = $line["id"];
4528 $unread = $line["unread"];
4529
4530 $cat_id = $line["cat_id"];
4531 $tmp_category = $line["category"];
4532 if (!$tmp_category) $tmp_category = __("Uncategorized");
4533
4534 if ($category != $tmp_category && $enable_cats) {
4535
4536 $category = $tmp_category;
4537
4538 $collapsed = sql_bool_to_bool($line["collapsed"]);
4539
4540 // workaround for NULL category
4541 if ($category == __("Uncategorized")) {
4542 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4543 }
4544
4545 if ($cat) array_push($feedlist['items'], $cat);
4546
4547 $cat = feedlist_init_cat($link, $cat_id, $collapsed);
4548 }
4549
4550 $updated = make_local_datetime($link, $line["updated_noms"], false);
4551
4552 array_push($cat['items'], feedlist_init_feed($link, $feed_id,
4553 $feed, $unread, $line['last_error'], $updated));
4554 }
4555
4556 if ($enable_cats) {
4557 array_push($feedlist['items'], $cat);
4558 } else {
4559 $feedlist['items'] = array_merge($feedlist['items'], $cat['items']);
4560 }
4561
4562 }
4563
4564 return $feedlist;
4565 }
4566
4567 function get_article_tags($link, $id, $owner_uid = 0) {
4568
4569 global $memcache;
4570
4571 $a_id = db_escape_string($id);
4572
4573 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4574
4575 $query = "SELECT DISTINCT tag_name,
4576 owner_uid as owner FROM
4577 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4578 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4579
4580 $obj_id = md5("TAGS:$owner_uid:$id");
4581 $tags = array();
4582
4583 if ($memcache && $obj = $memcache->get($obj_id)) {
4584 $tags = $obj;
4585 } else {
4586 /* check cache first */
4587
4588 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
4589 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4590
4591 $tag_cache = db_fetch_result($result, 0, "tag_cache");
4592
4593 if ($tag_cache) {
4594 $tags = explode(",", $tag_cache);
4595 } else {
4596
4597 /* do it the hard way */
4598
4599 $tmp_result = db_query($link, $query);
4600
4601 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4602 array_push($tags, $tmp_line["tag_name"]);
4603 }
4604
4605 /* update the cache */
4606
4607 $tags_str = db_escape_string(join(",", $tags));
4608
4609 db_query($link, "UPDATE ttrss_user_entries
4610 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
4611 AND owner_uid = " . $_SESSION["uid"]);
4612 }
4613
4614 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4615 }
4616
4617 return $tags;
4618 }
4619
4620 function trim_value(&$value) {
4621 $value = trim($value);
4622 }
4623
4624 function trim_array($array) {
4625 $tmp = $array;
4626 array_walk($tmp, 'trim_value');
4627 return $tmp;
4628 }
4629
4630 function tag_is_valid($tag) {
4631 if ($tag == '') return false;
4632 if (preg_match("/^[0-9]*$/", $tag)) return false;
4633 if (mb_strlen($tag) > 250) return false;
4634
4635 if (function_exists('iconv')) {
4636 $tag = iconv("utf-8", "utf-8", $tag);
4637 }
4638
4639 if (!$tag) return false;
4640
4641 return true;
4642 }
4643
4644 function render_login_form($link, $mobile = 0) {
4645 switch ($mobile) {
4646 case 0:
4647 require_once "login_form.php";
4648 break;
4649 case 1:
4650 require_once "mobile/login_form.php";
4651 break;
4652 case 2:
4653 require_once "mobile/classic/login_form.php";
4654 }
4655 }
4656
4657 // from http://developer.apple.com/internet/safari/faq.html
4658 function no_cache_incantation() {
4659 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4660 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4661 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4662 header("Cache-Control: post-check=0, pre-check=0", false);
4663 header("Pragma: no-cache"); // HTTP/1.0
4664 }
4665
4666 function format_warning($msg, $id = "") {
4667 global $link;
4668 return "<div class=\"warning\" id=\"$id\">
4669 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4670 }
4671
4672 function format_notice($msg, $id = "") {
4673 global $link;
4674 return "<div class=\"notice\" id=\"$id\">
4675 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4676 }
4677
4678 function format_error($msg, $id = "") {
4679 global $link;
4680 return "<div class=\"error\" id=\"$id\">
4681 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4682 }
4683
4684 function print_notice($msg) {
4685 return print format_notice($msg);
4686 }
4687
4688 function print_warning($msg) {
4689 return print format_warning($msg);
4690 }
4691
4692 function print_error($msg) {
4693 return print format_error($msg);
4694 }
4695
4696
4697 function T_sprintf() {
4698 $args = func_get_args();
4699 return vsprintf(__(array_shift($args)), $args);
4700 }
4701
4702 function format_inline_player($link, $url, $ctype) {
4703
4704 $entry = "";
4705
4706 if (strpos($ctype, "audio/") === 0) {
4707
4708 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
4709 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
4710 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
4711
4712 $id = 'AUDIO-' . uniqid();
4713
4714 $entry .= "<audio id=\"$id\"\">
4715 <source src=\"$url\"></source>
4716 </audio>";
4717
4718 $entry .= "<span onclick=\"player(this)\"
4719 title=\"".__("Click to play")."\" status=\"0\"
4720 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
4721
4722 } else {
4723
4724 $entry .= "<object type=\"application/x-shockwave-flash\"
4725 data=\"lib/button/musicplayer.swf?song_url=$url\"
4726 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
4727 <param name=\"movie\"
4728 value=\"lib/button/musicplayer.swf?song_url=$url\" />
4729 </object>";
4730 }
4731 }
4732
4733 $filename = substr($url, strrpos($url, "/")+1);
4734
4735 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4736 $filename . " (" . $ctype . ")" . "</a>";
4737
4738 return $entry;
4739 }
4740
4741 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
4742
4743 $rv = array();
4744
4745 $rv['id'] = $id;
4746
4747 /* we can figure out feed_id from article id anyway, why do we
4748 * pass feed_id here? let's ignore the argument :( */
4749
4750 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4751 WHERE ref_id = '$id'");
4752
4753 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4754
4755 $rv['feed_id'] = $feed_id;
4756
4757 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4758
4759 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4760 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4761
4762 if (db_num_rows($result) == 1) {
4763 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4764 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4765 } else {
4766 $rtl_content = false;
4767 $always_display_enclosures = false;
4768 }
4769
4770 if ($rtl_content) {
4771 $rtl_tag = "dir=\"RTL\"";
4772 $rtl_class = "RTL";
4773 } else {
4774 $rtl_tag = "";
4775 $rtl_class = "";
4776 }
4777
4778 if ($mark_as_read) {
4779 $result = db_query($link, "UPDATE ttrss_user_entries
4780 SET unread = false,last_read = NOW()
4781 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4782
4783 ccache_update($link, $feed_id, $_SESSION["uid"]);
4784 }
4785
4786 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4787 ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
4788 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4789 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
4790 num_comments,
4791 author,
4792 orig_feed_id,
4793 note
4794 FROM ttrss_entries,ttrss_user_entries
4795 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4796
4797 if ($result) {
4798
4799 $line = db_fetch_assoc($result);
4800
4801 if ($line["icon_url"]) {
4802 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
4803 } else {
4804 $feed_icon = "&nbsp;";
4805 }
4806
4807 $feed_site_url = $line['site_url'];
4808
4809 $num_comments = $line["num_comments"];
4810 $entry_comments = "";
4811
4812 if ($num_comments > 0) {
4813 if ($line["comments"]) {
4814 $comments_url = $line["comments"];
4815 } else {
4816 $comments_url = $line["link"];
4817 }
4818 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4819 } else {
4820 if ($line["comments"] && $line["link"] != $line["comments"]) {
4821 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4822 }
4823 }
4824
4825 if ($zoom_mode) {
4826 header("Content-Type: text/html");
4827 $rv['content'] .= "<html><head>
4828 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4829 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4830 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4831 </head><body>";
4832 }
4833
4834 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
4835 truncate_string(strip_tags($line['title']), 15) . "</div>";
4836
4837 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
4838
4839 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
4840 class=\"postHeader\" id=\"POSTHDR-$id\">";
4841
4842 $entry_author = $line["author"];
4843
4844 if ($entry_author) {
4845 $entry_author = __(" - ") . $entry_author;
4846 }
4847
4848 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4849 false, true);
4850
4851 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4852
4853 if ($line["link"]) {
4854 $rv['content'] .= "<div clear='both'><a target='_blank'
4855 title=\"".htmlspecialchars($line['title'])."\"
4856 href=\"" .
4857 $line["link"] . "\">" .
4858 truncate_string($line["title"], 100) .
4859 "<span class='author'>$entry_author</span></a></div>";
4860 } else {
4861 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4862 }
4863
4864 $tags = get_article_tags($link, $id);
4865 $tags_str = format_tags_string($tags, $id);
4866 $tags_str_full = join(", ", $tags);
4867
4868 if (!$tags_str_full) $tags_str_full = __("no tags");
4869
4870 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4871
4872 $rv['content'] .= "<div style='float : right'>
4873 <img src='".theme_image($link, 'images/tag.png')."'
4874 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
4875
4876 if (!$zoom_mode) {
4877 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
4878 <a title=\"".__('Edit tags for this article')."\"
4879 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4880
4881 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
4882 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
4883 position=\"below\">$tags_str_full</div>";
4884
4885 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4886 class='tagsPic' style=\"cursor : pointer\"
4887 onclick=\"postOpenInNewTab(event, $id)\"
4888 alt='Zoom' title='".__('Open article in new tab')."'>";
4889
4890 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4891
4892 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4893 class='tagsPic' style=\"cursor : pointer\"
4894 onclick=\"editArticleNote($id)\"
4895 alt='PubNote' title='".__('Edit article note')."'>";
4896
4897 if (DIGEST_ENABLE) {
4898 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4899 class='tagsPic' style=\"cursor : pointer\"
4900 onclick=\"emailArticle($id)\"
4901 alt='Zoom' title='".__('Forward by email')."'>";
4902 }
4903
4904 if (ENABLE_TWEET_BUTTON) {
4905 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
4906 class='tagsPic' style=\"cursor : pointer\"
4907 onclick=\"tweetArticle($id)\"
4908 alt='Zoom' title='".__('Share on Twitter')."'>";
4909 }
4910
4911 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4912 class='tagsPic' style=\"cursor : pointer\"
4913 onclick=\"closeArticlePanel($id)\"
4914 alt='Zoom' title='".__('Close this panel')."'>";
4915
4916 } else {
4917 $tags_str = strip_tags($tags_str);
4918 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
4919 }
4920 $rv['content'] .= "</div>";
4921 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
4922
4923 if ($line["orig_feed_id"]) {
4924
4925 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4926 WHERE id = ".$line["orig_feed_id"]);
4927
4928 if (db_num_rows($tmp_result) != 0) {
4929
4930 $rv['content'] .= "<div clear='both'>";
4931 $rv['content'] .= __("Originally from:");
4932
4933 $rv['content'] .= "&nbsp;";
4934
4935 $tmp_line = db_fetch_assoc($tmp_result);
4936
4937 $rv['content'] .= "<a target='_blank'
4938 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4939 $tmp_line['title'] . "</a>";
4940
4941 $rv['content'] .= "&nbsp;";
4942
4943 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4944 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4945
4946 $rv['content'] .= "</div>";
4947 }
4948 }
4949
4950 $rv['content'] .= "</div>";
4951
4952 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
4953 if ($line['note']) {
4954 $rv['content'] .= format_article_note($id, $line['note']);
4955 }
4956 $rv['content'] .= "</div>";
4957
4958 $rv['content'] .= "<div class=\"postIcon\">" .
4959 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4960 href=\"".htmlspecialchars($feed_site_url)."\">".
4961 $feed_icon . "</a></div>";
4962
4963 $rv['content'] .= "<div class=\"postContent\">";
4964
4965 $article_content = sanitize_rss($link, $line["content"], false, false,
4966 $feed_site_url);
4967
4968 $rv['content'] .= $article_content;
4969
4970 $rv['content'] .= format_article_enclosures($link, $id,
4971 $always_display_enclosures, $article_content);
4972
4973 $rv['content'] .= "</div>";
4974
4975 $rv['content'] .= "</div>";
4976
4977 }
4978
4979 if ($zoom_mode) {
4980 $rv['content'] .= "
4981 <div style=\"text-align : center\">
4982 <button onclick=\"return window.close()\">".
4983 __("Close this window")."</button></div>";
4984 $rv['content'] .= "</body></html>";
4985 }
4986
4987 return $rv;
4988
4989 }
4990
4991 function format_headlines_list($link, $feed, $subop, $view_mode, $limit, $cat_view,
4992 $next_unread_feed, $offset, $vgr_last_feed = false,
4993 $override_order = false) {
4994
4995 $disable_cache = false;
4996
4997 $reply = array();
4998
4999 $timing_info = getmicrotime();
5000
5001 $topmost_article_ids = array();
5002
5003 if (!$offset) $offset = 0;
5004 if ($subop == "undefined") $subop = "";
5005
5006 $subop_split = explode(":", $subop);
5007
5008 /* if ($subop == "CatchupSelected") {
5009 $ids = explode(",", db_escape_string($_REQUEST["ids"]));
5010 $cmode = sprintf("%d", $_REQUEST["cmode"]);
5011
5012 catchupArticlesById($link, $ids, $cmode);
5013 } */
5014
5015 if ($subop == "ForceUpdate" && $feed && is_numeric($feed) > 0) {
5016 update_rss_feed($link, $feed, true);
5017 }
5018
5019 if ($subop == "MarkAllRead") {
5020 catchup_feed($link, $feed, $cat_view);
5021
5022 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
5023 if ($next_unread_feed) {
5024 $feed = $next_unread_feed;
5025 }
5026 }
5027 }
5028
5029 if ($subop_split[0] == "MarkAllReadGR") {
5030 catchup_feed($link, $subop_split[1], false);
5031 }
5032
5033 // FIXME: might break tag display?
5034
5035 if (is_numeric($feed) && $feed > 0 && !$cat_view) {
5036 $result = db_query($link,
5037 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
5038
5039 if (db_num_rows($result) == 0) {
5040 $reply['content'] = "<div align='center'>".__('Feed not found.')."</div>";
5041 }
5042 }
5043
5044 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
5045
5046 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
5047 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
5048
5049 if (db_num_rows($result) == 1) {
5050 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
5051 } else {
5052 $rtl_content = false;
5053 }
5054
5055 if ($rtl_content) {
5056 $rtl_tag = "dir=\"RTL\"";
5057 } else {
5058 $rtl_tag = "";
5059 }
5060 } else {
5061 $rtl_tag = "";
5062 $rtl_content = false;
5063 }
5064
5065 @$search = db_escape_string($_REQUEST["query"]);
5066
5067 if ($search) {
5068 $disable_cache = true;
5069 }
5070
5071 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
5072 @$match_on = db_escape_string($_REQUEST["match_on"]);
5073
5074 if (!$match_on) {
5075 $match_on = "both";
5076 }
5077
5078 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
5079
5080 // error_log("format_headlines_list: [" . $feed . "] subop [" . $subop . "]");
5081 if( $search_mode == '' && $subop != '' ){
5082 $search_mode = $subop;
5083 }
5084 // error_log("search_mode: " . $search_mode);
5085 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
5086 $search, $search_mode, $match_on, $override_order, $offset);
5087
5088 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
5089
5090 $result = $qfh_ret[0];
5091 $feed_title = $qfh_ret[1];
5092 $feed_site_url = $qfh_ret[2];
5093 $last_error = $qfh_ret[3];
5094
5095 $vgroup_last_feed = $vgr_last_feed;
5096
5097 if (!$offset) {
5098
5099 if (db_num_rows($result) > 0) {
5100 $reply['toolbar'] = format_headline_subtoolbar($link, $feed_site_url,
5101 $feed_title,
5102 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode,
5103 $last_error);
5104 }
5105 }
5106
5107 $headlines_count = db_num_rows($result);
5108
5109 if (db_num_rows($result) > 0) {
5110
5111 $lnum = $offset;
5112
5113 $num_unread = 0;
5114 $cur_feed_title = '';
5115
5116 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5117
5118 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PS", $timing_info);
5119
5120 while ($line = db_fetch_assoc($result)) {
5121
5122 $class = ($lnum % 2) ? "even" : "odd";
5123
5124 $id = $line["id"];
5125 $feed_id = $line["feed_id"];
5126
5127 $labels = get_article_labels($link, $id);
5128
5129 $labels_str = "<span id=\"HLLCTR-$id\">";
5130 $labels_str .= format_article_labels($labels, $id);
5131 $labels_str .= "</span>";
5132
5133 if (count($topmost_article_ids) < 3) {
5134 array_push($topmost_article_ids, $id);
5135 }
5136
5137 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5138
5139 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5140 theme_image($link, 'images/updated.png')."\"
5141 alt=\"Updated\">";
5142 } else {
5143 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
5144 alt=\"Updated\">";
5145 }
5146
5147 if (sql_bool_to_bool($line["unread"]) &&
5148 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5149
5150 $update_pic = "<img id='FUPDPIC-$id' src=\"".
5151 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5152 }
5153
5154 if ($line["unread"] == "t" || $line["unread"] == "1") {
5155 $class .= " Unread";
5156 ++$num_unread;
5157 $is_unread = true;
5158 } else {
5159 $is_unread = false;
5160 }
5161
5162 if ($line["marked"] == "t" || $line["marked"] == "1") {
5163 $marked_pic = "<img id=\"FMPIC-$id\"
5164 src=\"".theme_image($link, 'images/mark_set.png')."\"
5165 class=\"markedPic\" alt=\"Unstar article\"
5166 onclick='javascript:tMark($id)'>";
5167 } else {
5168 $marked_pic = "<img id=\"FMPIC-$id\"
5169 src=\"".theme_image($link, 'images/mark_unset.png')."\"
5170 class=\"markedPic\" alt=\"Star article\"
5171 onclick='javascript:tMark($id)'>";
5172 }
5173
5174 if ($line["published"] == "t" || $line["published"] == "1") {
5175 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5176 'images/pub_set.png')."\"
5177 class=\"markedPic\"
5178 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5179 } else {
5180 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5181 'images/pub_unset.png')."\"
5182 class=\"markedPic\"
5183 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5184 }
5185
5186 # $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5187 # $line["title"] . "</a>";
5188
5189 # $content_link = "<a
5190 # href=\"" . htmlspecialchars($line["link"]) . "\"
5191 # onclick=\"view($id,$feed_id);\">" .
5192 # $line["title"] . "</a>";
5193
5194 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5195 # $line["title"] . "</a>";
5196
5197 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
5198
5199 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5200 $content_preview = truncate_string(strip_tags($line["content_preview"]),
5201 100);
5202 }
5203
5204 $score = $line["score"];
5205
5206 $score_pic = theme_image($link,
5207 "images/" . get_score_pic($score));
5208
5209 /* $score_title = __("(Click to change)");
5210 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
5211 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5212
5213 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
5214 title=\"$score\">";
5215
5216 if ($score > 500) {
5217 $hlc_suffix = "H";
5218 } else if ($score < -100) {
5219 $hlc_suffix = "L";
5220 } else {
5221 $hlc_suffix = "";
5222 }
5223
5224 $entry_author = $line["author"];
5225
5226 if ($entry_author) {
5227 $entry_author = " - $entry_author";
5228 }
5229
5230 $has_feed_icon = feed_has_icon($feed_id);
5231
5232 if ($has_feed_icon) {
5233 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5234 } else {
5235 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/feed-icon-12x12.png\" alt=\"\">";
5236 }
5237
5238 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5239
5240 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5241 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5242
5243 $cur_feed_title = $line["feed_title"];
5244 $vgroup_last_feed = $feed_id;
5245
5246 $cur_feed_title = htmlspecialchars($cur_feed_title);
5247
5248 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5249
5250 $reply['content'] .= "<div class='cdmFeedTitle'>".
5251 "<div style=\"float : right\">$feed_icon_img</div>".
5252 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5253 $line["feed_title"]."</a> $vf_catchup_link</div>";
5254
5255 }
5256 }
5257
5258 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5259 onmouseout='postMouseOut($id)'";
5260
5261 $reply['content'] .= "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5262
5263 $reply['content'] .= "<div class='hlUpdPic'>$update_pic</div>";
5264
5265 $reply['content'] .= "<div class='hlLeft'>";
5266
5267 $reply['content'] .= "<input type=\"checkbox\" onclick=\"tSR(this)\"
5268 id=\"RCHK-$id\">";
5269
5270 $reply['content'] .= "$marked_pic";
5271 $reply['content'] .= "$published_pic";
5272
5273 $reply['content'] .= "</div>";
5274
5275 $reply['content'] .= "<div onclick='return hlClicked(event, $id)'
5276 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5277 $reply['content'] .= "<a id=\"RTITLE-$id\"
5278 href=\"" . htmlspecialchars($line["link"]) . "\"
5279 onclick=\"\">" .
5280 $line["title"];
5281
5282 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5283 if ($content_preview) {
5284 $reply['content'] .= "<span class=\"contentPreview\"> - $content_preview</span>";
5285 }
5286 }
5287
5288 $reply['content'] .= "</a></span>";
5289
5290 $reply['content'] .= $labels_str;
5291
5292 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5293 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5294 if (@$line["feed_title"]) {
5295 $reply['content'] .= "<span class=\"hlFeed\">
5296 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5297 $line["feed_title"]."</a>)
5298 </span>";
5299 }
5300 }
5301
5302 $reply['content'] .= "</div>";
5303
5304 $reply['content'] .= "<span class=\"hlUpdated\">$updated_fmt</span>";
5305 $reply['content'] .= "<div class=\"hlRight\">";
5306
5307 $reply['content'] .= $score_pic;
5308
5309 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5310
5311 $reply['content'] .= "<span onclick=\"viewfeed($feed_id)\"
5312 style=\"cursor : pointer\"
5313 title=\"".htmlspecialchars($line['feed_title'])."\">
5314 $feed_icon_img<span>";
5315 }
5316
5317 $reply['content'] .= "</div>";
5318 $reply['content'] .= "</div>";
5319
5320 } else {
5321
5322 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5323 if ($feed_id != $vgroup_last_feed) {
5324
5325 $cur_feed_title = $line["feed_title"];
5326 $vgroup_last_feed = $feed_id;
5327
5328 $cur_feed_title = htmlspecialchars($cur_feed_title);
5329
5330 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5331
5332 $has_feed_icon = feed_has_icon($feed_id);
5333
5334 if ($has_feed_icon) {
5335 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5336 } else {
5337 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5338 }
5339
5340 $reply['content'] .= "<div class='cdmFeedTitle'>".
5341 "<div style=\"float : right\">$feed_icon_img</div>".
5342 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5343 $line["feed_title"]."</a> $vf_catchup_link</div>";
5344 }
5345 }
5346
5347 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5348
5349 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5350 onmouseout='postMouseOut($id)'";
5351
5352 $reply['content'] .= "<div class=\"$class\"
5353 id=\"RROW-$id\" $mouseover_attrs'>";
5354
5355 $reply['content'] .= "<div class=\"cdmHeader\">";
5356
5357 $reply['content'] .= "<div style='float : right'>";
5358 $reply['content'] .= "<span class='updated'>$updated_fmt</span>";
5359 $reply['content'] .= "$score_pic";
5360
5361 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5362 $reply['content'] .= "<span style=\"cursor : pointer\"
5363 title=\"".htmlspecialchars($line["feed_title"])."\"
5364 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5365 }
5366 $reply['content'] .= "<div class=\"updPic\">$update_pic</div>";
5367
5368 $reply['content'] .= "</div>";
5369
5370 $reply['content'] .= "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5371 'RROW-$id')\" id=\"RCHK-$id\"/>";
5372
5373 $reply['content'] .= "$marked_pic";
5374 $reply['content'] .= "$published_pic";
5375
5376 $reply['content'] .= "<span id=\"RTITLE-$id\"
5377 onclick=\"return cdmClicked(event, $id);\"
5378 class=\"titleWrap$hlc_suffix\">
5379 <a class=\"title\"
5380 title=\"".htmlspecialchars($line['title'])."\"
5381 target=\"_blank\" href=\"".
5382 htmlspecialchars($line["link"])."\">".
5383 truncate_string($line["title"], 100) .
5384 " $entry_author</a>";
5385
5386 $reply['content'] .= $labels_str;
5387
5388 if (!get_pref($link, 'VFEED_GROUP_BY_FEED') &&
5389 defined('_SHOW_FEED_TITLE_IN_VFEEDS')) {
5390 if (@$line["feed_title"]) {
5391 $reply['content'] .= "<span class=\"hlFeed\">
5392 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5393 $line["feed_title"]."</a>)
5394 </span>";
5395 }
5396 }
5397
5398 if (!$expand_cdm)
5399 $content_hidden = "style=\"display : none\"";
5400 else
5401 $excerpt_hidden = "style=\"display : none\"";
5402
5403 $reply['content'] .= "<span $excerpt_hidden
5404 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5405
5406 $reply['content'] .= "</span>";
5407
5408 $reply['content'] .= "</div>";
5409
5410 $reply['content'] .= "<div class=\"cdmContent\" $content_hidden
5411 onclick=\"return cdmClicked(event, $id);\"
5412 id=\"CICD-$id\">";
5413
5414 $reply['content'] .= "<div class=\"cdmContentInner\">";
5415
5416 if ($line["orig_feed_id"]) {
5417
5418 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5419 WHERE id = ".$line["orig_feed_id"]);
5420
5421 if (db_num_rows($tmp_result) != 0) {
5422
5423 $reply['content'] .= "<div clear='both'>";
5424 $reply['content'] .= __("Originally from:");
5425
5426 $reply['content'] .= "&nbsp;";
5427
5428 $tmp_line = db_fetch_assoc($tmp_result);
5429
5430 $reply['content'] .= "<a target='_blank'
5431 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5432 $tmp_line['title'] . "</a>";
5433
5434 $reply['content'] .= "&nbsp;";
5435
5436 $reply['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5437 $reply['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5438
5439 $reply['content'] .= "</div>";
5440 }
5441 }
5442
5443 // FIXME: make this less of a hack
5444
5445 $feed_site_url = false;
5446
5447 if ($line["feed_id"]) {
5448 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5449 WHERE id = " . $line["feed_id"]);
5450
5451 if (db_num_rows($tmp_result) == 1) {
5452 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5453 }
5454 }
5455
5456 if ($expand_cdm) {
5457 $article_content = sanitize_rss($link, $line["content_preview"],
5458 false, false, $feed_site_url);
5459
5460 if (!$article_content) $article_content = "&nbsp;";
5461 } else {
5462 $article_content = '';
5463 }
5464
5465 $reply['content'] .= "<div id=\"POSTNOTE-$id\">";
5466 if ($line['note']) {
5467 $reply['content'] .= format_article_note($id, $line['note']);
5468 }
5469 $reply['content'] .= "</div>";
5470
5471 $reply['content'] .= "<span id=\"CWRAP-$id\">$article_content</span>";
5472
5473 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5474 ttrss_feeds WHERE id = ".
5475 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
5476 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5477
5478 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5479 0, "always_display_enclosures"));
5480
5481 $reply['content'] .= format_article_enclosures($link, $id, $always_display_enclosures,
5482 $article_content);
5483
5484 $reply['content'] .= "</div>";
5485
5486 $reply['content'] .= "<div class=\"cdmFooter\">";
5487
5488 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5489
5490 $reply['content'] .= "<img src='".theme_image($link,
5491 'images/tag.png')."' alt='Tags' title='Tags'>
5492 <span id=\"ATSTR-$id\">$tags_str</span>
5493 <a title=\"".__('Edit tags for this article')."\"
5494 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5495
5496 $reply['content'] .= "<div style=\"float : right\">";
5497
5498 $reply['content'] .= "<img src=\"images/art-zoom.png\"
5499 onclick=\"zoomToArticle(event, $id)\"
5500 style=\"cursor : pointer\"
5501 alt='Zoom'
5502 title='".__('Open article in new tab')."'>";
5503
5504 //$note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5505
5506 $reply['content'] .= "<img src=\"images/art-pub-note.png\"
5507 style=\"cursor : pointer\" style=\"cursor : pointer\"
5508 onclick=\"editArticleNote($id)\"
5509 alt='PubNote' title='".__('Edit article note')."'>";
5510
5511 if (DIGEST_ENABLE) {
5512 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5513 style=\"cursor : pointer\"
5514 onclick=\"emailArticle($id)\"
5515 alt='Zoom' title='".__('Forward by email')."'>";
5516 }
5517
5518 if (ENABLE_TWEET_BUTTON) {
5519 $reply['content'] .= "<img src=\"".theme_image($link, 'images/art-tweet.png')."\"
5520 class='tagsPic' style=\"cursor : pointer\"
5521 onclick=\"tweetArticle($id)\"
5522 alt='Zoom' title='".__('Share on Twitter')."'>";
5523 }
5524
5525 $reply['content'] .= "<img src=\"images/digest_checkbox.png\"
5526 style=\"cursor : pointer\" style=\"cursor : pointer\"
5527 onclick=\"dismissArticle($id)\"
5528 alt='Dismiss' title='".__('Dismiss article')."'>";
5529
5530 $reply['content'] .= "</div>";
5531 $reply['content'] .= "</div>";
5532
5533 $reply['content'] .= "</div>";
5534
5535 $reply['content'] .= "</div>";
5536
5537 }
5538
5539 ++$lnum;
5540 }
5541
5542 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("PE", $timing_info);
5543
5544 } else {
5545 $message = "";
5546
5547 switch ($view_mode) {
5548 case "unread":
5549 $message = __("No unread articles found to display.");
5550 break;
5551 case "updated":
5552 $message = __("No updated articles found to display.");
5553 break;
5554 case "marked":
5555 $message = __("No starred articles found to display.");
5556 break;
5557 default:
5558 if ($feed < -10) {
5559 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5560 } else {
5561 $message = __("No articles found to display.");
5562 }
5563 }
5564
5565 if (!$offset && $message) {
5566 $reply['content'] .= "<div class='whiteBox'>$message";
5567
5568 $reply['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
5569
5570 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5571 WHERE owner_uid = " . $_SESSION['uid']);
5572
5573 $last_updated = db_fetch_result($result, 0, "last_updated");
5574 $last_updated = make_local_datetime($link, $last_updated, false);
5575
5576 $reply['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
5577
5578 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5579 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5580
5581 $num_errors = db_fetch_result($result, 0, "num_errors");
5582
5583 if ($num_errors > 0) {
5584 $reply['content'] .= "<br/>";
5585 $reply['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5586 __('Some feeds have update errors (click for details)')."</a>";
5587 }
5588 $reply['content'] .= "</span></p></div>";
5589 }
5590 }
5591
5592 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H2", $timing_info);
5593
5594 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache,
5595 $vgroup_last_feed, $reply);
5596 }
5597
5598 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5599
5600 function printTagCloud($link) {
5601
5602 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5603 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5604 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5605
5606 $result = db_query($link, $query);
5607
5608 $tags = array();
5609
5610 while ($line = db_fetch_assoc($result)) {
5611 $tags[$line["tag_name"]] = $line["count"];
5612 }
5613
5614 if( count($tags) == 0 ){ return; }
5615
5616 ksort($tags);
5617
5618 $max_size = 32; // max font size in pixels
5619 $min_size = 11; // min font size in pixels
5620
5621 // largest and smallest array values
5622 $max_qty = max(array_values($tags));
5623 $min_qty = min(array_values($tags));
5624
5625 // find the range of values
5626 $spread = $max_qty - $min_qty;
5627 if ($spread == 0) { // we don't want to divide by zero
5628 $spread = 1;
5629 }
5630
5631 // set the font-size increment
5632 $step = ($max_size - $min_size) / ($spread);
5633
5634 // loop through the tag array
5635 foreach ($tags as $key => $value) {
5636 // calculate font-size
5637 // find the $value in excess of $min_qty
5638 // multiply by the font-size increment ($size)
5639 // and add the $min_size set above
5640 $size = round($min_size + (($value - $min_qty) * $step));
5641
5642 $key_escaped = str_replace("'", "\\'", $key);
5643
5644 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5645 $size . "px\" title=\"$value articles tagged with " .
5646 $key . '">' . $key . '</a> ';
5647 }
5648 }
5649
5650 function print_checkpoint($n, $s) {
5651 $ts = getmicrotime();
5652 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5653 return $ts;
5654 }
5655
5656 function sanitize_tag($tag) {
5657 $tag = trim($tag);
5658
5659 $tag = mb_strtolower($tag, 'utf-8');
5660
5661 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
5662
5663 // $tag = str_replace('"', "", $tag);
5664 // $tag = str_replace("+", " ", $tag);
5665 $tag = str_replace("technorati tag: ", "", $tag);
5666
5667 return $tag;
5668 }
5669
5670 function get_self_url_prefix() {
5671 return SELF_URL_PATH;
5672 }
5673
5674 function opml_publish_url($link){
5675
5676 $url_path = get_self_url_prefix();
5677 $url_path .= "/opml.php?op=publish&key=" .
5678 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5679
5680 return $url_path;
5681 }
5682
5683 /**
5684 * Purge a feed contents, marked articles excepted.
5685 *
5686 * @param mixed $link The database connection.
5687 * @param integer $id The id of the feed to purge.
5688 * @return void
5689 */
5690 function clear_feed_articles($link, $id) {
5691
5692 if ($id != 0) {
5693 $result = db_query($link, "DELETE FROM ttrss_user_entries
5694 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5695 } else {
5696 $result = db_query($link, "DELETE FROM ttrss_user_entries
5697 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5698 }
5699
5700 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5701 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5702
5703 ccache_update($link, $id, $_SESSION['uid']);
5704 } // function clear_feed_articles
5705
5706 /**
5707 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5708 *
5709 * @return string The Mozilla Firefox feed adding URL.
5710 */
5711 function add_feed_url() {
5712 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5713
5714 $url_path = get_self_url_prefix() .
5715 "/backend.php?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5716 return $url_path;
5717 } // function add_feed_url
5718
5719 /**
5720 * Encrypt a password in SHA1.
5721 *
5722 * @param string $pass The password to encrypt.
5723 * @param string $login A optionnal login.
5724 * @return string The encrypted password.
5725 */
5726 function encrypt_password($pass, $login = '') {
5727 if ($login) {
5728 return "SHA1X:" . sha1("$login:$pass");
5729 } else {
5730 return "SHA1:" . sha1($pass);
5731 }
5732 } // function encrypt_password
5733
5734 /**
5735 * Update a feed batch.
5736 * Used by daemons to update n feeds by run.
5737 * Only update feed needing a update, and not being processed
5738 * by another process.
5739 *
5740 * @param mixed $link Database link
5741 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5742 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5743 * @param boolean $debug Set to false to disable debug output. Default to true.
5744 * @return void
5745 */
5746 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5747 // Process all other feeds using last_updated and interval parameters
5748
5749 // Test if the user has loggued in recently. If not, it does not update its feeds.
5750 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5751 if (DB_TYPE == "pgsql") {
5752 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5753 } else {
5754 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5755 }
5756 } else {
5757 $login_thresh_qpart = "";
5758 }
5759
5760 // Test if the feed need a update (update interval exceded).
5761 if (DB_TYPE == "pgsql") {
5762 $update_limit_qpart = "AND ((
5763 ttrss_feeds.update_interval = 0
5764 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5765 ) OR (
5766 ttrss_feeds.update_interval > 0
5767 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5768 ) OR ttrss_feeds.last_updated IS NULL)";
5769 } else {
5770 $update_limit_qpart = "AND ((
5771 ttrss_feeds.update_interval = 0
5772 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5773 ) OR (
5774 ttrss_feeds.update_interval > 0
5775 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5776 ) OR ttrss_feeds.last_updated IS NULL)";
5777 }
5778
5779 // Test if feed is currently being updated by another process.
5780 if (DB_TYPE == "pgsql") {
5781 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5782 } else {
5783 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5784 }
5785
5786 // Test if there is a limit to number of updated feeds
5787 $query_limit = "";
5788 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5789
5790 $random_qpart = sql_random_function();
5791
5792 // We search for feed needing update.
5793 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5794 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5795 ttrss_feeds.update_interval
5796 FROM
5797 ttrss_feeds, ttrss_users, ttrss_user_prefs
5798 WHERE
5799 ttrss_feeds.owner_uid = ttrss_users.id
5800 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5801 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5802 $login_thresh_qpart $update_limit_qpart
5803 $updstart_thresh_qpart
5804 ORDER BY $random_qpart $query_limit");
5805
5806 $user_prefs_cache = array();
5807
5808 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5809
5810 // Here is a little cache magic in order to minimize risk of double feed updates.
5811 $feeds_to_update = array();
5812 while ($line = db_fetch_assoc($result)) {
5813 $feeds_to_update[$line['id']] = $line;
5814 }
5815
5816 // We update the feed last update started date before anything else.
5817 // There is no lag due to feed contents downloads
5818 // It prevent an other process to update the same feed.
5819 $feed_ids = array_keys($feeds_to_update);
5820 if($feed_ids) {
5821 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5822 WHERE id IN (%s)", implode(',', $feed_ids)));
5823 }
5824
5825 // For each feed, we call the feed update function.
5826 while ($line = array_pop($feeds_to_update)) {
5827
5828 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5829
5830 update_rss_feed($link, $line["id"], true);
5831
5832 sleep(1); // prevent flood (FIXME make this an option?)
5833 }
5834
5835 // Send feed digests by email if needed.
5836 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5837
5838 } // function update_daemon_common
5839
5840 function sanitize_article_content($text) {
5841 # we don't support CDATA sections in articles, they break our own escaping
5842 $text = preg_replace("/\[\[CDATA/", "", $text);
5843 $text = preg_replace("/\]\]\>/", "", $text);
5844 return $text;
5845 }
5846
5847 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5848 $filters = array();
5849
5850 global $memcache;
5851
5852 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5853
5854 if ($memcache && $obj = $memcache->get($obj_id)) {
5855
5856 return $obj;
5857
5858 } else {
5859
5860 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5861
5862 $result = db_query($link, "SELECT reg_exp,
5863 ttrss_filter_types.name AS name,
5864 ttrss_filter_actions.name AS action,
5865 inverse,
5866 action_param,
5867 filter_param
5868 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5869 enabled = true AND
5870 $ftype_query_part
5871 owner_uid = $owner_uid AND
5872 ttrss_filter_types.id = filter_type AND
5873 ttrss_filter_actions.id = action_id AND
5874 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5875
5876 while ($line = db_fetch_assoc($result)) {
5877 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5878 $filter["reg_exp"] = $line["reg_exp"];
5879 $filter["action"] = $line["action"];
5880 $filter["action_param"] = $line["action_param"];
5881 $filter["filter_param"] = $line["filter_param"];
5882 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5883
5884 array_push($filters[$line["name"]], $filter);
5885 }
5886
5887 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5888
5889 return $filters;
5890 }
5891 }
5892
5893 function get_score_pic($score) {
5894 if ($score > 100) {
5895 return "score_high.png";
5896 } else if ($score > 0) {
5897 return "score_half_high.png";
5898 } else if ($score < -100) {
5899 return "score_low.png";
5900 } else if ($score < 0) {
5901 return "score_half_low.png";
5902 } else {
5903 return "score_neutral.png";
5904 }
5905 }
5906
5907 function rounded_table_start($classname, $header = "&nbsp;") {
5908 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5909 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5910 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5911 }
5912
5913 function rounded_table_end($footer = "&nbsp;") {
5914 print "</td><td class='right'>&nbsp;</td></tr>";
5915 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5916 print "</table>";
5917 }
5918
5919 function feed_has_icon($id) {
5920 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5921 }
5922
5923 function init_connection($link) {
5924 if (DB_TYPE == "pgsql") {
5925 pg_query($link, "set client_encoding = 'UTF-8'");
5926 pg_set_client_encoding("UNICODE");
5927 pg_query($link, "set datestyle = 'ISO, european'");
5928 pg_query($link, "set TIME ZONE 0");
5929 } else {
5930 db_query($link, "SET time_zone = '+0:0'");
5931
5932 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5933 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5934 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5935 }
5936 }
5937 }
5938
5939 function update_feedbrowser_cache($link) {
5940
5941 $result = db_query($link, "SELECT feed_url, site_url, title, COUNT(id) AS subscribers
5942 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5943 WHERE tf.feed_url = ttrss_feeds.feed_url
5944 AND (private IS true OR auth_login != '' OR auth_pass != '' OR feed_url LIKE '%:%@%/%'))
5945 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT 1000");
5946
5947 db_query($link, "BEGIN");
5948
5949 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5950
5951 $count = 0;
5952
5953 while ($line = db_fetch_assoc($result)) {
5954 $subscribers = db_escape_string($line["subscribers"]);
5955 $feed_url = db_escape_string($line["feed_url"]);
5956 $title = db_escape_string($line["title"]);
5957 $site_url = db_escape_string($line["site_url"]);
5958
5959 $tmp_result = db_query($link, "SELECT subscribers FROM
5960 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5961
5962 if (db_num_rows($tmp_result) == 0) {
5963
5964 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5965 (feed_url, site_url, title, subscribers) VALUES ('$feed_url',
5966 '$site_url', '$title', '$subscribers')");
5967
5968 ++$count;
5969
5970 }
5971
5972 }
5973
5974 db_query($link, "COMMIT");
5975
5976 return $count;
5977
5978 }
5979
5980 function ccache_zero($link, $feed_id, $owner_uid) {
5981 db_query($link, "UPDATE ttrss_counters_cache SET
5982 value = 0, updated = NOW() WHERE
5983 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5984 }
5985
5986 function ccache_zero_all($link, $owner_uid) {
5987 db_query($link, "UPDATE ttrss_counters_cache SET
5988 value = 0 WHERE owner_uid = '$owner_uid'");
5989
5990 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5991 value = 0 WHERE owner_uid = '$owner_uid'");
5992 }
5993
5994 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5995
5996 if (!$is_cat) {
5997 $table = "ttrss_counters_cache";
5998 } else {
5999 $table = "ttrss_cat_counters_cache";
6000 }
6001
6002 db_query($link, "DELETE FROM $table WHERE
6003 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6004
6005 }
6006
6007 function ccache_update_all($link, $owner_uid) {
6008
6009 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
6010
6011 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
6012 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
6013
6014 while ($line = db_fetch_assoc($result)) {
6015 ccache_update($link, $line["feed_id"], $owner_uid, true);
6016 }
6017
6018 /* We have to manually include category 0 */
6019
6020 ccache_update($link, 0, $owner_uid, true);
6021
6022 } else {
6023 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
6024 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
6025
6026 while ($line = db_fetch_assoc($result)) {
6027 print ccache_update($link, $line["feed_id"], $owner_uid);
6028
6029 }
6030
6031 }
6032 }
6033
6034 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
6035 $no_update = false) {
6036
6037 if (!is_numeric($feed_id)) return;
6038
6039 if (!$is_cat) {
6040 $table = "ttrss_counters_cache";
6041 if ($feed_id > 0) {
6042 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
6043 WHERE id = '$feed_id'");
6044 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6045 }
6046 } else {
6047 $table = "ttrss_cat_counters_cache";
6048 }
6049
6050 if (DB_TYPE == "pgsql") {
6051 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
6052 } else if (DB_TYPE == "mysql") {
6053 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
6054 }
6055
6056 $result = db_query($link, "SELECT value FROM $table
6057 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
6058 LIMIT 1");
6059
6060 if (db_num_rows($result) == 1) {
6061 return db_fetch_result($result, 0, "value");
6062 } else {
6063 if ($no_update) {
6064 return -1;
6065 } else {
6066 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
6067 }
6068 }
6069
6070 }
6071
6072 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
6073 $update_pcat = true) {
6074
6075 if (!is_numeric($feed_id)) return;
6076
6077 if (!$is_cat && $feed_id > 0) {
6078 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
6079 WHERE id = '$feed_id'");
6080 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6081 }
6082
6083 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6084
6085 /* When updating a label, all we need to do is recalculate feed counters
6086 * because labels are not cached */
6087
6088 if ($feed_id < 0) {
6089 ccache_update_all($link, $owner_uid);
6090 return;
6091 }
6092
6093 if (!$is_cat) {
6094 $table = "ttrss_counters_cache";
6095 } else {
6096 $table = "ttrss_cat_counters_cache";
6097 }
6098
6099 if ($is_cat && $feed_id >= 0) {
6100 if ($feed_id != 0) {
6101 $cat_qpart = "cat_id = '$feed_id'";
6102 } else {
6103 $cat_qpart = "cat_id IS NULL";
6104 }
6105
6106 /* Recalculate counters for child feeds */
6107
6108 $result = db_query($link, "SELECT id FROM ttrss_feeds
6109 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6110
6111 while ($line = db_fetch_assoc($result)) {
6112 ccache_update($link, $line["id"], $owner_uid, false, false);
6113 }
6114
6115 $result = db_query($link, "SELECT SUM(value) AS sv
6116 FROM ttrss_counters_cache, ttrss_feeds
6117 WHERE id = feed_id AND $cat_qpart AND
6118 ttrss_feeds.owner_uid = '$owner_uid'");
6119
6120 $unread = (int) db_fetch_result($result, 0, "sv");
6121
6122 } else {
6123 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6124 }
6125
6126 db_query($link, "BEGIN");
6127
6128 $result = db_query($link, "SELECT feed_id FROM $table
6129 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6130
6131 if (db_num_rows($result) == 1) {
6132 db_query($link, "UPDATE $table SET
6133 value = '$unread', updated = NOW() WHERE
6134 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6135
6136 } else {
6137 db_query($link, "INSERT INTO $table
6138 (feed_id, value, owner_uid, updated)
6139 VALUES
6140 ($feed_id, $unread, $owner_uid, NOW())");
6141 }
6142
6143 db_query($link, "COMMIT");
6144
6145 if ($feed_id > 0 && $prev_unread != $unread) {
6146
6147 if (!$is_cat) {
6148
6149 /* Update parent category */
6150
6151 if ($update_pcat) {
6152
6153 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6154 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6155
6156 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6157
6158 ccache_update($link, $cat_id, $owner_uid, true);
6159
6160 }
6161 }
6162 } else if ($feed_id < 0) {
6163 ccache_update_all($link, $owner_uid);
6164 }
6165
6166 return $unread;
6167 }
6168
6169 function ccache_cleanup($link, $owner_uid) {
6170
6171 if (DB_TYPE == "pgsql") {
6172 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
6173 (SELECT count(*) FROM ttrss_counters_cache AS c2
6174 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6175 AND owner_uid = '$owner_uid'");
6176
6177 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
6178 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
6179 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
6180 AND owner_uid = '$owner_uid'");
6181 } else {
6182 db_query($link, "DELETE c1 FROM
6183 ttrss_counters_cache AS c1,
6184 ttrss_counters_cache AS c2
6185 WHERE
6186 c1.owner_uid = '$owner_uid' AND
6187 c1.owner_uid = c2.owner_uid AND
6188 c1.feed_id = c2.feed_id");
6189
6190 db_query($link, "DELETE c1 FROM
6191 ttrss_cat_counters_cache AS c1,
6192 ttrss_cat_counters_cache AS c2
6193 WHERE
6194 c1.owner_uid = '$owner_uid' AND
6195 c1.owner_uid = c2.owner_uid AND
6196 c1.feed_id = c2.feed_id");
6197
6198 }
6199 }
6200
6201 function label_find_id($link, $label, $owner_uid) {
6202 $result = db_query($link,
6203 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
6204 AND owner_uid = '$owner_uid' LIMIT 1");
6205
6206 if (db_num_rows($result) == 1) {
6207 return db_fetch_result($result, 0, "id");
6208 } else {
6209 return 0;
6210 }
6211 }
6212
6213 function get_article_labels($link, $id) {
6214 global $memcache;
6215
6216 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6217
6218 $rv = array();
6219
6220 if ($memcache && $obj = $memcache->get($obj_id)) {
6221 return $obj;
6222 } else {
6223
6224 $result = db_query($link, "SELECT label_cache FROM
6225 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
6226 $_SESSION["uid"]);
6227
6228 $label_cache = db_fetch_result($result, 0, "label_cache");
6229
6230 if ($label_cache) {
6231
6232 $label_cache = json_decode($label_cache, true);
6233
6234 if ($label_cache["no-labels"] == 1)
6235 return $rv;
6236 else
6237 return $label_cache;
6238 }
6239
6240 $result = db_query($link,
6241 "SELECT DISTINCT label_id,caption,fg_color,bg_color
6242 FROM ttrss_labels2, ttrss_user_labels2
6243 WHERE id = label_id
6244 AND article_id = '$id'
6245 AND owner_uid = ".$_SESSION["uid"] . "
6246 ORDER BY caption");
6247
6248 while ($line = db_fetch_assoc($result)) {
6249 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6250 $line["bg_color"]);
6251 array_push($rv, $rk);
6252 }
6253 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6254
6255 if (count($rv) > 0)
6256 label_update_cache($link, $id, $rv);
6257 else
6258 label_update_cache($link, $id, array("no-labels" => 1));
6259 }
6260
6261 return $rv;
6262 }
6263
6264
6265 function label_find_caption($link, $label, $owner_uid) {
6266 $result = db_query($link,
6267 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
6268 AND owner_uid = '$owner_uid' LIMIT 1");
6269
6270 if (db_num_rows($result) == 1) {
6271 return db_fetch_result($result, 0, "caption");
6272 } else {
6273 return "";
6274 }
6275 }
6276
6277 function label_update_cache($link, $id, $labels = false, $force = false) {
6278
6279 if ($force)
6280 label_clear_cache($link, $id);
6281
6282 if (!$labels)
6283 $labels = get_article_labels($link, $id);
6284
6285 $labels = db_escape_string(json_encode($labels));
6286
6287 db_query($link, "UPDATE ttrss_user_entries SET
6288 label_cache = '$labels' WHERE ref_id = '$id'");
6289
6290 }
6291
6292 function label_clear_cache($link, $id) {
6293
6294 db_query($link, "UPDATE ttrss_user_entries SET
6295 label_cache = '' WHERE ref_id = '$id'");
6296
6297 }
6298
6299 function label_remove_article($link, $id, $label, $owner_uid) {
6300
6301 $label_id = label_find_id($link, $label, $owner_uid);
6302
6303 if (!$label_id) return;
6304
6305 $result = db_query($link,
6306 "DELETE FROM ttrss_user_labels2
6307 WHERE
6308 label_id = '$label_id' AND
6309 article_id = '$id'");
6310
6311 label_clear_cache($link, $id);
6312 }
6313
6314 function label_add_article($link, $id, $label, $owner_uid) {
6315
6316 global $memcache;
6317
6318 if ($memcache) {
6319 $obj_id = md5("LABELS:$id:$owner_uid");
6320 $memcache->delete($obj_id);
6321 }
6322
6323 $label_id = label_find_id($link, $label, $owner_uid);
6324
6325 if (!$label_id) return;
6326
6327 $result = db_query($link,
6328 "SELECT
6329 article_id FROM ttrss_labels2, ttrss_user_labels2
6330 WHERE
6331 label_id = id AND
6332 label_id = '$label_id' AND
6333 article_id = '$id' AND owner_uid = '$owner_uid'
6334 LIMIT 1");
6335
6336 if (db_num_rows($result) == 0) {
6337 db_query($link, "INSERT INTO ttrss_user_labels2
6338 (label_id, article_id) VALUES ('$label_id', '$id')");
6339 }
6340
6341 label_clear_cache($link, $id);
6342
6343 }
6344
6345 function label_remove($link, $id, $owner_uid) {
6346 global $memcache;
6347
6348 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6349
6350 if ($memcache) {
6351 $obj_id = md5("LABELS:$id:$owner_uid");
6352 $memcache->delete($obj_id);
6353 }
6354
6355 db_query($link, "BEGIN");
6356
6357 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6358 WHERE id = '$id'");
6359
6360 $caption = db_fetch_result($result, 0, "caption");
6361
6362 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6363 AND owner_uid = " . $owner_uid);
6364
6365 if (db_affected_rows($link, $result) != 0 && $caption) {
6366
6367 /* Remove access key for the label */
6368
6369 $ext_id = -11 - $id;
6370
6371 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6372 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6373
6374 /* Disable filters that reference label being removed */
6375
6376 db_query($link, "UPDATE ttrss_filters SET
6377 enabled = false WHERE action_param = '$caption'
6378 AND action_id = 7
6379 AND owner_uid = " . $owner_uid);
6380
6381 /* Remove cached data */
6382
6383 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6384 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6385
6386 }
6387
6388 db_query($link, "COMMIT");
6389 }
6390
6391 function label_create($link, $caption) {
6392
6393 db_query($link, "BEGIN");
6394
6395 $result = false;
6396
6397 $result = db_query($link, "SELECT id FROM ttrss_labels2
6398 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6399
6400 if (db_num_rows($result) == 0) {
6401 $result = db_query($link,
6402 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6403 VALUES ('$caption', '".$_SESSION["uid"]."')");
6404
6405 $result = db_affected_rows($link, $result) != 0;
6406 }
6407
6408 db_query($link, "COMMIT");
6409
6410 return $result;
6411 }
6412
6413 function print_labels_headlines_dropdown($link, $feed_id) {
6414 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6415
6416 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6417 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6418
6419 while ($line = db_fetch_assoc($result)) {
6420
6421 $label_id = $line["id"];
6422 $label_caption = $line["caption"];
6423 $id = $line["id"];
6424
6425 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6426 print "<option id=\"LHDL-$id\"
6427 value=\"selectionRemoveLabel($label_id)\">".
6428 __('Remove:') . " $label_caption</option>";
6429 } else {
6430 print "<option id=\"LHDL-$id\"
6431 value=\"selectionAssignLabel($label_id)\">".
6432 __('Assign:') . " $label_caption</option>";
6433 }
6434 }
6435 }
6436
6437 function format_tags_string($tags, $id) {
6438
6439 $tags_str = "";
6440 $tags_nolinks_str = "";
6441
6442 $num_tags = 0;
6443
6444 $tag_limit = 6;
6445
6446 $formatted_tags = array();
6447
6448 foreach ($tags as $tag) {
6449 $num_tags++;
6450 $tag_escaped = str_replace("'", "\\'", $tag);
6451
6452 if (mb_strlen($tag) > 30) {
6453 $tag = truncate_string($tag, 30);
6454 }
6455
6456 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6457
6458 array_push($formatted_tags, $tag_str);
6459
6460 $tmp_tags_str = implode(", ", $formatted_tags);
6461
6462 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
6463 break;
6464 }
6465 }
6466
6467 $tags_str = implode(", ", $formatted_tags);
6468
6469 if ($num_tags < count($tags)) {
6470 $tags_str .= ", &hellip;";
6471 }
6472
6473 if ($num_tags == 0) {
6474 $tags_str = __("no tags");
6475 }
6476
6477 return $tags_str;
6478
6479 }
6480
6481 function format_article_labels($labels, $id) {
6482
6483 $labels_str = "";
6484
6485 foreach ($labels as $l) {
6486 $labels_str .= sprintf("<span class='hlLabelRef'
6487 style='color : %s; background-color : %s'>%s</span>",
6488 $l[2], $l[3], $l[1]);
6489 }
6490
6491 return $labels_str;
6492
6493 }
6494
6495 function format_article_note($id, $note) {
6496
6497 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
6498 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
6499 __('(edit note)')."</div>$note</div>";
6500
6501 return $str;
6502 }
6503
6504 function toggle_collapse_cat($link, $cat_id, $mode) {
6505 if ($cat_id > 0) {
6506 $mode = bool_to_sql_bool($mode);
6507
6508 db_query($link, "UPDATE ttrss_feed_categories SET
6509 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6510 $_SESSION["uid"]);
6511 } else {
6512 $pref_name = '';
6513
6514 switch ($cat_id) {
6515 case -1:
6516 $pref_name = '_COLLAPSED_SPECIAL';
6517 break;
6518 case -2:
6519 $pref_name = '_COLLAPSED_LABELS';
6520 break;
6521 case 0:
6522 $pref_name = '_COLLAPSED_UNCAT';
6523 break;
6524 }
6525
6526 if ($pref_name) {
6527 if ($mode) {
6528 set_pref($link, $pref_name, 'true');
6529 } else {
6530 set_pref($link, $pref_name, 'false');
6531 }
6532 }
6533 }
6534 }
6535
6536 function remove_feed($link, $id, $owner_uid) {
6537
6538 if ($id > 0) {
6539
6540 /* save starred articles in Archived feed */
6541
6542 db_query($link, "BEGIN");
6543
6544 /* prepare feed if necessary */
6545
6546 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6547 WHERE id = '$id'");
6548
6549 if (db_num_rows($result) == 0) {
6550 db_query($link, "INSERT INTO ttrss_archived_feeds
6551 (id, owner_uid, title, feed_url, site_url)
6552 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6553 WHERE id = '$id'");
6554 }
6555
6556 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6557 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6558 marked = true AND owner_uid = $owner_uid");
6559
6560 /* Remove access key for the feed */
6561
6562 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6563 feed_id = '$id' AND owner_uid = $owner_uid");
6564
6565 /* remove the feed */
6566
6567 db_query($link, "DELETE FROM ttrss_feeds
6568 WHERE id = '$id' AND owner_uid = $owner_uid");
6569
6570 db_query($link, "COMMIT");
6571
6572 /* if (file_exists(ICONS_DIR . "/$id.ico")) {
6573 unlink(ICONS_DIR . "/$id.ico");
6574 } */
6575
6576 ccache_remove($link, $id, $owner_uid);
6577
6578 } else {
6579 label_remove($link, -11-$id, $owner_uid);
6580 ccache_remove($link, -11-$id, $owner_uid);
6581 }
6582 }
6583
6584 function add_feed_category($link, $feed_cat) {
6585
6586 if (!$feed_cat) return false;
6587
6588 db_query($link, "BEGIN");
6589
6590 $result = db_query($link,
6591 "SELECT id FROM ttrss_feed_categories
6592 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6593
6594 if (db_num_rows($result) == 0) {
6595
6596 $result = db_query($link,
6597 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6598 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6599
6600 db_query($link, "COMMIT");
6601
6602 return true;
6603 }
6604
6605 return false;
6606 }
6607
6608 function remove_feed_category($link, $id, $owner_uid) {
6609
6610 db_query($link, "DELETE FROM ttrss_feed_categories
6611 WHERE id = '$id' AND owner_uid = $owner_uid");
6612
6613 ccache_remove($link, $id, $owner_uid, true);
6614 }
6615
6616 function archive_article($link, $id, $owner_uid) {
6617 db_query($link, "BEGIN");
6618
6619 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6620 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6621
6622 if (db_num_rows($result) != 0) {
6623
6624 /* prepare the archived table */
6625
6626 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6627
6628 if ($feed_id) {
6629 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6630 WHERE id = '$feed_id'");
6631
6632 if (db_num_rows($result) == 0) {
6633 db_query($link, "INSERT INTO ttrss_archived_feeds
6634 (id, owner_uid, title, feed_url, site_url)
6635 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6636 WHERE id = '$feed_id'");
6637 }
6638
6639 db_query($link, "UPDATE ttrss_user_entries
6640 SET orig_feed_id = feed_id, feed_id = NULL
6641 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6642 }
6643 }
6644
6645 db_query($link, "COMMIT");
6646 }
6647
6648 function getArticleFeed($link, $id) {
6649 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6650 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6651
6652 if (db_num_rows($result) != 0) {
6653 return db_fetch_result($result, 0, "feed_id");
6654 } else {
6655 return 0;
6656 }
6657 }
6658
6659 function make_url_from_parts($parts) {
6660 $url = $parts['scheme'] . '://' . $parts['host'];
6661
6662 if ($parts['path']) $url .= $parts['path'];
6663 if ($parts['query']) $url .= '?' . $parts['query'];
6664
6665 return $url;
6666 }
6667
6668 /**
6669 * Fixes incomplete URLs by prepending "http://".
6670 * Also replaces feed:// with http://, and
6671 * prepends a trailing slash if the url is a domain name only.
6672 *
6673 * @param string $url Possibly incomplete URL
6674 *
6675 * @return string Fixed URL.
6676 */
6677 function fix_url($url) {
6678 if (strpos($url, '://') === false) {
6679 $url = 'http://' . $url;
6680 } else if (substr($url, 0, 5) == 'feed:') {
6681 $url = 'http:' . substr($url, 5);
6682 }
6683
6684 //prepend slash if the URL has no slash in it
6685 // "http://www.example" -> "http://www.example/"
6686 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
6687 $url .= '/';
6688 }
6689
6690 if ($url != "http:///")
6691 return $url;
6692 else
6693 return '';
6694 }
6695
6696 function validate_feed_url($url) {
6697 $parts = parse_url($url);
6698
6699 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
6700
6701 }
6702
6703 function get_article_enclosures($link, $id) {
6704
6705 global $memcache;
6706
6707 $query = "SELECT * FROM ttrss_enclosures
6708 WHERE post_id = '$id' AND content_url != ''";
6709
6710 $obj_id = md5("ENCLOSURES:$id");
6711
6712 $rv = array();
6713
6714 if ($memcache && $obj = $memcache->get($obj_id)) {
6715 $rv = $obj;
6716 } else {
6717 $result = db_query($link, $query);
6718
6719 if (db_num_rows($result) > 0) {
6720 while ($line = db_fetch_assoc($result)) {
6721 array_push($rv, $line);
6722 }
6723 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6724 }
6725 }
6726
6727 return $rv;
6728 }
6729
6730 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6731
6732 $feeds = array();
6733
6734 /* Labels */
6735
6736 if ($cat_id == -4 || $cat_id == -2) {
6737 $counters = getLabelCounters($link, true);
6738
6739 foreach (array_values($counters) as $cv) {
6740
6741 $unread = $cv["counter"];
6742
6743 if ($unread || !$unread_only) {
6744
6745 $row = array(
6746 "id" => $cv["id"],
6747 "title" => $cv["description"],
6748 "unread" => $cv["counter"],
6749 "cat_id" => -2,
6750 );
6751
6752 array_push($feeds, $row);
6753 }
6754 }
6755 }
6756
6757 /* Virtual feeds */
6758
6759 if ($cat_id == -4 || $cat_id == -1) {
6760 foreach (array(-1, -2, -3, -4, 0) as $i) {
6761 $unread = getFeedUnread($link, $i);
6762
6763 if ($unread || !$unread_only) {
6764 $title = getFeedTitle($link, $i);
6765
6766 $row = array(
6767 "id" => $i,
6768 "title" => $title,
6769 "unread" => $unread,
6770 "cat_id" => -1,
6771 );
6772 array_push($feeds, $row);
6773 }
6774
6775 }
6776 }
6777
6778 /* Real feeds */
6779
6780 if ($limit) {
6781 $limit_qpart = "LIMIT $limit OFFSET $offset";
6782 } else {
6783 $limit_qpart = "";
6784 }
6785
6786 if ($cat_id == -4 || $cat_id == -3) {
6787 $result = db_query($link, "SELECT
6788 id, feed_url, cat_id, title, ".
6789 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6790 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6791 " ORDER BY cat_id, title " . $limit_qpart);
6792 } else {
6793
6794 if ($cat_id)
6795 $cat_qpart = "cat_id = '$cat_id'";
6796 else
6797 $cat_qpart = "cat_id IS NULL";
6798
6799 $result = db_query($link, "SELECT
6800 id, feed_url, cat_id, title, ".
6801 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6802 FROM ttrss_feeds WHERE
6803 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6804 " ORDER BY cat_id, title " . $limit_qpart);
6805 }
6806
6807 while ($line = db_fetch_assoc($result)) {
6808
6809 $unread = getFeedUnread($link, $line["id"]);
6810
6811 $has_icon = feed_has_icon($line['id']);
6812
6813 if ($unread || !$unread_only) {
6814
6815 $row = array(
6816 "feed_url" => $line["feed_url"],
6817 "title" => $line["title"],
6818 "id" => (int)$line["id"],
6819 "unread" => (int)$unread,
6820 "has_icon" => $has_icon,
6821 "cat_id" => (int)$line["cat_id"],
6822 "last_updated" => strtotime($line["last_updated"])
6823 );
6824
6825 array_push($feeds, $row);
6826 }
6827 }
6828
6829 return $feeds;
6830 }
6831
6832 function api_get_headlines($link, $feed_id, $limit, $offset,
6833 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
6834 $include_attachments) {
6835
6836 /* do not rely on params below */
6837
6838 $search = db_escape_string($_REQUEST["search"]);
6839 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6840 $match_on = db_escape_string($_REQUEST["match_on"]);
6841
6842 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6843 $view_mode, $is_cat, $search, $search_mode, $match_on,
6844 $order, $offset);
6845
6846 $result = $qfh_ret[0];
6847 $feed_title = $qfh_ret[1];
6848
6849 $headlines = array();
6850
6851 while ($line = db_fetch_assoc($result)) {
6852 $is_updated = ($line["last_read"] == "" &&
6853 ($line["unread"] != "t" && $line["unread"] != "1"));
6854
6855 $headline_row = array(
6856 "id" => (int)$line["id"],
6857 "unread" => sql_bool_to_bool($line["unread"]),
6858 "marked" => sql_bool_to_bool($line["marked"]),
6859 "published" => sql_bool_to_bool($line["published"]),
6860 "updated" => strtotime($line["updated"]),
6861 "is_updated" => $is_updated,
6862 "title" => $line["title"],
6863 "link" => $line["link"],
6864 "feed_id" => $line["feed_id"],
6865 "tags" => get_article_tags($link, $line["id"]),
6866 );
6867
6868 if ($include_attachments)
6869 $headline_row['attachments'] = get_article_enclosures($link,
6870 $line['id']);
6871
6872 if ($show_excerpt) {
6873 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6874 $headline_row["excerpt"] = $excerpt;
6875 }
6876
6877 if ($show_content) {
6878 $headline_row["content"] = $line["content_preview"];
6879 }
6880
6881 array_push($headlines, $headline_row);
6882 }
6883
6884 return $headlines;
6885 }
6886
6887 function generate_error_feed($link, $error) {
6888 $reply = array();
6889
6890 $reply['headlines']['id'] = -6;
6891 $reply['headlines']['is_cat'] = false;
6892
6893 $reply['headlines']['toolbar'] = '';
6894 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
6895
6896 $reply['headlines-info'] = array("count" => 0,
6897 "vgroup_last_feed" => '',
6898 "unread" => 0,
6899 "disable_cache" => true);
6900
6901 return $reply;
6902 }
6903
6904
6905 function generate_dashboard_feed($link) {
6906 $reply = array();
6907
6908 $reply['headlines']['id'] = -5;
6909 $reply['headlines']['is_cat'] = false;
6910
6911 $reply['headlines']['toolbar'] = '';
6912 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
6913
6914 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
6915
6916 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6917 WHERE owner_uid = " . $_SESSION['uid']);
6918
6919 $last_updated = db_fetch_result($result, 0, "last_updated");
6920 $last_updated = make_local_datetime($link, $last_updated, false);
6921
6922 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
6923
6924 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6925 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6926
6927 $num_errors = db_fetch_result($result, 0, "num_errors");
6928
6929 if ($num_errors > 0) {
6930 $reply['headlines']['content'] .= "<br/>";
6931 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6932 __('Some feeds have update errors (click for details)')."</a>";
6933 }
6934 $reply['headlines']['content'] .= "</span></p>";
6935
6936 $reply['headlines-info'] = array("count" => 0,
6937 "vgroup_last_feed" => '',
6938 "unread" => 0,
6939 "disable_cache" => true);
6940
6941 return $reply;
6942 }
6943
6944 function save_email_address($link, $email) {
6945 // FIXME: implement persistent storage of emails
6946
6947 if (!$_SESSION['stored_emails'])
6948 $_SESSION['stored_emails'] = array();
6949
6950 if (!in_array($email, $_SESSION['stored_emails']))
6951 array_push($_SESSION['stored_emails'], $email);
6952 }
6953
6954 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6955 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6956
6957 $sql_is_cat = bool_to_sql_bool($is_cat);
6958
6959 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6960 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6961 AND owner_uid = " . $owner_uid);
6962
6963 if (db_num_rows($result) == 1) {
6964 $key = db_escape_string(sha1(uniqid(rand(), true)));
6965
6966 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6967 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6968 AND owner_uid = " . $owner_uid);
6969
6970 return $key;
6971
6972 } else {
6973 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6974 }
6975 }
6976
6977 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6978
6979 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6980
6981 $sql_is_cat = bool_to_sql_bool($is_cat);
6982
6983 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6984 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6985 AND owner_uid = " . $owner_uid);
6986
6987 if (db_num_rows($result) == 1) {
6988 return db_fetch_result($result, 0, "access_key");
6989 } else {
6990 $key = db_escape_string(sha1(uniqid(rand(), true)));
6991
6992 $result = db_query($link, "INSERT INTO ttrss_access_keys
6993 (access_key, feed_id, is_cat, owner_uid)
6994 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6995
6996 return $key;
6997 }
6998 return false;
6999 }
7000
7001 /**
7002 * Extracts RSS/Atom feed URLs from the given HTML URL.
7003 *
7004 * @param string $url HTML page URL
7005 *
7006 * @return array Array of feeds. Key is the full URL, value the title
7007 */
7008 function get_feeds_from_html($url, $login = false, $pass = false)
7009 {
7010 $url = fix_url($url);
7011 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
7012
7013 libxml_use_internal_errors(true);
7014
7015 $content = @fetch_file_contents($url, false, $login, $pass);
7016
7017 $doc = new DOMDocument();
7018 $doc->loadHTML($content);
7019 $xpath = new DOMXPath($doc);
7020 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
7021 $feedUrls = array();
7022 foreach ($entries as $entry) {
7023 if ($entry->hasAttribute('href')) {
7024 $title = $entry->getAttribute('title');
7025 if ($title == '') {
7026 $title = $entry->getAttribute('type');
7027 }
7028 $feedUrl = rewrite_relative_url(
7029 $baseUrl, $entry->getAttribute('href')
7030 );
7031 $feedUrls[$feedUrl] = $title;
7032 }
7033 }
7034 return $feedUrls;
7035 }
7036
7037 /**
7038 * Checks if the content behind the given URL is a HTML file
7039 *
7040 * @param string $url URL to check
7041 *
7042 * @return boolean True if the URL contains HTML content
7043 */
7044 function url_is_html($url, $login = false, $pass = false) {
7045 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
7046
7047 if (stripos($content, '<html>') === false
7048 && stripos($content, '<html ') === false
7049 ) {
7050 return false;
7051 }
7052
7053 return true;
7054 }
7055
7056 function print_label_select($link, $name, $value, $attributes = "") {
7057
7058 $result = db_query($link, "SELECT caption FROM ttrss_labels2
7059 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
7060
7061 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
7062 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
7063
7064 while ($line = db_fetch_assoc($result)) {
7065
7066 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
7067
7068 print "<option value=\"".htmlspecialchars($line["caption"])."\"
7069 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
7070
7071 }
7072
7073 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
7074
7075 print "</select>";
7076
7077
7078 }
7079
7080 function format_article_enclosures($link, $id, $always_display_enclosures,
7081 $article_content) {
7082
7083 $result = get_article_enclosures($link, $id);
7084 $rv = '';
7085
7086 if (count($result) > 0) {
7087
7088 $entries_html = array();
7089 $entries = array();
7090
7091 foreach ($result as $line) {
7092
7093 $url = $line["content_url"];
7094 $ctype = $line["content_type"];
7095
7096 if (!$ctype) $ctype = __("unknown type");
7097
7098 # $filename = substr($url, strrpos($url, "/")+1);
7099
7100 $entry = format_inline_player($link, $url, $ctype);
7101
7102 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
7103 # $filename . " (" . $ctype . ")" . "</a>";
7104
7105 array_push($entries_html, $entry);
7106
7107 $entry = array();
7108
7109 $entry["type"] = $ctype;
7110 $entry["filename"] = $filename;
7111 $entry["url"] = $url;
7112
7113 array_push($entries, $entry);
7114 }
7115
7116 $rv .= "<div class=\"postEnclosures\">";
7117
7118 if (!get_pref($link, "STRIP_IMAGES")) {
7119 if ($always_display_enclosures ||
7120 !preg_match("/<img/i", $article_content)) {
7121
7122 foreach ($entries as $entry) {
7123
7124 if (preg_match("/image/", $entry["type"]) ||
7125 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
7126
7127 $rv .= "<p><img
7128 alt=\"".htmlspecialchars($entry["filename"])."\"
7129 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
7130 }
7131 }
7132 }
7133 }
7134
7135 if (count($entries) == 1) {
7136 $rv .= __("Attachment:") . " ";
7137 } else {
7138 $rv .= __("Attachments:") . " ";
7139 }
7140
7141 $rv .= join(", ", $entries_html);
7142
7143 $rv .= "</div>";
7144 }
7145
7146 return $rv;
7147 }
7148
7149 function getLastArticleId($link) {
7150 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
7151 WHERE owner_uid = " . $_SESSION["uid"]);
7152
7153 if (db_num_rows($result) == 1) {
7154 return db_fetch_result($result, 0, "id");
7155 } else {
7156 return -1;
7157 }
7158 }
7159
7160 function build_url($parts) {
7161 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
7162 }
7163
7164 /**
7165 * Converts a (possibly) relative URL to a absolute one.
7166 *
7167 * @param string $url Base URL (i.e. from where the document is)
7168 * @param string $rel_url Possibly relative URL in the document
7169 *
7170 * @return string Absolute URL
7171 */
7172 function rewrite_relative_url($url, $rel_url) {
7173 if (strpos($rel_url, "://") !== false) {
7174 return $rel_url;
7175 } else if (strpos($rel_url, "/") === 0)
7176 {
7177 $parts = parse_url($url);
7178 $parts['path'] = $rel_url;
7179
7180 return build_url($parts);
7181
7182 } else {
7183 $parts = parse_url($url);
7184 if (!isset($parts['path'])) {
7185 $parts['path'] = '/';
7186 }
7187 $dir = $parts['path'];
7188 if (substr($dir, -1) !== '/') {
7189 $dir = dirname($parts['path']);
7190 $dir !== '/' && $dir .= '/';
7191 }
7192 $parts['path'] = $dir . $rel_url;
7193
7194 return build_url($parts);
7195 }
7196 }
7197
7198 function sphinx_search($query, $offset = 0, $limit = 30) {
7199 $sphinxClient = new SphinxClient();
7200
7201 $sphinxClient->SetServer('localhost', 9312);
7202 $sphinxClient->SetConnectTimeout(1);
7203
7204 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
7205 'feed_title' => 20));
7206
7207 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
7208 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
7209 $sphinxClient->SetLimits($offset, $limit, 1000);
7210 $sphinxClient->SetArrayResult(false);
7211 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
7212
7213 $result = $sphinxClient->Query($query, SPHINX_INDEX);
7214
7215 $ids = array();
7216
7217 if (is_array($result['matches'])) {
7218 foreach (array_keys($result['matches']) as $int_id) {
7219 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
7220 array_push($ids, $ref_id);
7221 }
7222 }
7223
7224 return $ids;
7225 }
7226
7227 function cleanup_tags($link, $days = 14, $limit = 1000) {
7228
7229 if (DB_TYPE == "pgsql") {
7230 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
7231 } else if (DB_TYPE == "mysql") {
7232 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
7233 }
7234
7235 $tags_deleted = 0;
7236
7237 while ($limit > 0) {
7238 $limit_part = 500;
7239
7240 $query = "SELECT ttrss_tags.id AS id
7241 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
7242 WHERE post_int_id = int_id AND $interval_query AND
7243 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
7244
7245 $result = db_query($link, $query);
7246
7247 $ids = array();
7248
7249 while ($line = db_fetch_assoc($result)) {
7250 array_push($ids, $line['id']);
7251 }
7252
7253 if (count($ids) > 0) {
7254 $ids = join(",", $ids);
7255 print ".";
7256
7257 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
7258 $tags_deleted += db_affected_rows($link, $tmp_result);
7259 } else {
7260 break;
7261 }
7262
7263 $limit -= $limit_part;
7264 }
7265
7266 print "\n";
7267
7268 return $tags_deleted;
7269 }
7270
7271 function feedlist_init_cat($link, $cat_id, $hidden = false) {
7272 $obj = array();
7273 $cat_id = (int) $cat_id;
7274
7275 if ($cat_id > 0) {
7276 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
7277 } else if ($cat_id == 0 || $cat_id == -2) {
7278 $cat_unread = getCategoryUnread($link, $cat_id);
7279 }
7280
7281 $obj['id'] = 'CAT:' . $cat_id;
7282 $obj['items'] = array();
7283 $obj['name'] = getCategoryTitle($link, $cat_id);
7284 $obj['type'] = 'feed';
7285 $obj['unread'] = (int) $cat_unread;
7286 $obj['hidden'] = $hidden;
7287 $obj['bare_id'] = $cat_id;
7288
7289 return $obj;
7290 }
7291
7292 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
7293 $obj = array();
7294 $feed_id = (int) $feed_id;
7295
7296 if (!$title)
7297 $title = getFeedTitle($link, $feed_id, false);
7298
7299 if ($unread === false)
7300 $unread = getFeedUnread($link, $feed_id, false);
7301
7302 $obj['id'] = 'FEED:' . $feed_id;
7303 $obj['name'] = $title;
7304 $obj['unread'] = (int) $unread;
7305 $obj['type'] = 'feed';
7306 $obj['error'] = $error;
7307 $obj['updated'] = $updated;
7308 $obj['icon'] = getFeedIcon($feed_id);
7309 $obj['bare_id'] = $feed_id;
7310
7311 return $obj;
7312 }
7313
7314
7315 function fetch_twitter_rss($link, $url, $owner_uid) {
7316 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
7317 WHERE id = $owner_uid");
7318
7319 $access_token = json_decode(db_fetch_result($result, 0, 'twitter_oauth'), true);
7320 $url_escaped = db_escape_string($url);
7321
7322 if ($access_token) {
7323
7324 $tmhOAuth = new tmhOAuth(array(
7325 'consumer_key' => CONSUMER_KEY,
7326 'consumer_secret' => CONSUMER_SECRET,
7327 'user_token' => $access_token['oauth_token'],
7328 'user_secret' => $access_token['oauth_token_secret'],
7329 ));
7330
7331 $code = $tmhOAuth->request('GET', $url);
7332
7333 if ($code == 200) {
7334
7335 $content = $tmhOAuth->response['response'];
7336
7337 define('MAGPIE_CACHE_ON', false);
7338
7339 $rss = new MagpieRSS($content, MAGPIE_OUTPUT_ENCODING,
7340 MAGPIE_INPUT_ENCODING, MAGPIE_DETECT_ENCODING );
7341
7342 return $rss;
7343
7344 } else {
7345
7346 db_query($link, "UPDATE ttrss_feeds
7347 SET last_error = 'OAuth authorization failed ($code).'
7348 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7349 }
7350
7351 } else {
7352
7353 db_query($link, "UPDATE ttrss_feeds
7354 SET last_error = 'OAuth information not found.'
7355 WHERE feed_url = '$url_escaped' AND owner_uid = $owner_uid");
7356
7357 return false;
7358 }
7359 }
7360
7361 function print_user_stylesheet($link) {
7362 $value = get_pref($link, 'USER_STYLESHEET');
7363
7364 if ($value) {
7365 print "<style type=\"text/css\">";
7366 print str_replace("<br/>", "\n", $value);
7367 print "</style>";
7368 }
7369
7370 }
7371
7372 function rewrite_urls($line) {
7373 global $url_regex;
7374
7375 $urls = null;
7376
7377 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
7378 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
7379
7380 return $result;
7381 }
7382
7383 function filter_to_sql($filter) {
7384 $query = "";
7385
7386 if (DB_TYPE == "pgsql")
7387 $reg_qpart = "~";
7388 else
7389 $reg_qpart = "REGEXP";
7390
7391 switch ($filter["type"]) {
7392 case "title":
7393 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7394 $filter['reg_exp'] . "')";
7395 break;
7396 case "content":
7397 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
7398 $filter['reg_exp'] . "')";
7399 break;
7400 case "both":
7401 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
7402 $filter['reg_exp'] . "') OR LOWER(" .
7403 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
7404 break;
7405 case "tag":
7406 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
7407 $filter['reg_exp'] . "')";
7408 break;
7409 case "link":
7410 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
7411 $filter['reg_exp'] . "')";
7412 break;
7413 case "date":
7414
7415 if ($filter["filter_param"] == "before")
7416 $cmp_qpart = "<";
7417 else
7418 $cmp_qpart = ">=";
7419
7420 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
7421 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
7422 break;
7423 case "author":
7424 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
7425 $filter['reg_exp'] . "')";
7426 break;
7427 }
7428
7429 if ($filter["inverse"])
7430 $query = "NOT ($query)";
7431
7432 if ($query) {
7433 if (DB_TYPE == "pgsql") {
7434 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
7435 } else {
7436 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
7437 }
7438 $query .= " AND ";
7439 }
7440
7441
7442 return $query;
7443 }
7444
7445 // Status codes:
7446 // -1 - never connected
7447 // 0 - no data received
7448 // 1 - data received successfully
7449 // 2 - did not receive valid data
7450 // >10 - server error, code + 10 (e.g. 16 means server error 6)
7451
7452 function get_linked_feeds($link, $instance_id = false) {
7453 if ($instance_id)
7454 $instance_qpart = "id = '$instance_id' AND ";
7455 else
7456 $instance_qpart = "";
7457
7458 if (DB_TYPE == "pgsql") {
7459 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
7460 } else {
7461 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
7462 }
7463
7464 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
7465 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
7466
7467 while ($line = db_fetch_assoc($result)) {
7468 $id = $line['id'];
7469
7470 _debug("Updating: " . $line['access_url'] . " ($id)");
7471
7472 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
7473 $post_query = 'key=' . $line['access_key'];
7474
7475 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
7476
7477 if ($feeds) {
7478 $feeds = json_decode($feeds, true);
7479
7480 if ($feeds) {
7481 if ($feeds['error']) {
7482 $status = $feeds['error']['code'] + 10;
7483 } else {
7484 $status = 1;
7485
7486 if (count($feeds['feeds']) > 0) {
7487
7488 db_query($link, "DELETE FROM ttrss_linked_feeds
7489 WHERE instance_id = '$id'");
7490
7491 foreach ($feeds['feeds'] as $feed) {
7492 $feed_url = db_escape_string($feed['feed_url']);
7493 $title = db_escape_string($feed['title']);
7494 $subscribers = db_escape_string($feed['subscribers']);
7495 $site_url = db_escape_string($feed['site_url']);
7496
7497 db_query($link, "INSERT INTO ttrss_linked_feeds
7498 (feed_url, site_url, title, subscribers, instance_id, created, updated)
7499 VALUES
7500 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
7501 }
7502 } else {
7503 // received 0 feeds, this might indicate that
7504 // the instance on the other hand is rebuilding feedbrowser cache
7505 // we will try again later
7506
7507 // TODO: maybe perform expiration based on updated here?
7508 }
7509
7510 _debug("Processed " . count($feeds['feeds']) . " feeds.");
7511 }
7512 } else {
7513 $status = 2;
7514 }
7515
7516 } else {
7517 $status = 0;
7518 }
7519
7520 _debug("Status: $status");
7521
7522 db_query($link, "UPDATE ttrss_linked_instances SET
7523 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
7524
7525 }
7526
7527 }
7528 ?>