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