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