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