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