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