]> git.wh0rd.org - tt-rss.git/blame_incremental - functions.php
js: misc code cleanup, handle ctrl-clicking on postContent
[tt-rss.git] / functions.php
... / ...
CommitLineData
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
4603 onclick=\"return postClicked(event, $id)\"
4604 class=\"postHeader\">";
4605
4606 $entry_author = $line["author"];
4607
4608 if ($entry_author) {
4609 $entry_author = __(" - ") . $entry_author;
4610 }
4611
4612 $parsed_updated = make_local_datetime($link, $line["updated"], true,
4613 false, true);
4614
4615 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4616
4617 if ($line["link"]) {
4618 print "<div clear='both'><a target='_blank' href=\"" .
4619 $line["link"] . "\">" .
4620 $line["title"] . "<span class='author'>$entry_author</span></a></div>";
4621 } else {
4622 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4623 }
4624
4625 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4626
4627 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4628
4629 print "<div style='float : right'>
4630 <img src='".theme_image($link, 'images/tag.png')."'
4631 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
4632
4633 if (!$zoom_mode) {
4634 print "<span id=\"ATSTR-$id\">$tags_str</span>
4635 <a title=\"".__('Edit tags for this article')."\"
4636 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
4637
4638 print "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
4639 class='tagsPic' style=\"cursor : pointer\"
4640 onclick=\"zoomToArticle(event, $id)\"
4641 alt='Zoom' title='".__('Open article in new tab')."'>";
4642
4643 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4644
4645 print "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\"
4646 class='tagsPic' style=\"cursor : pointer\"
4647 onclick=\"publishWithNote($id, '$note_escaped')\"
4648 alt='PubNote' title='".__('Publish article with a note')."'>";
4649
4650 if (DIGEST_ENABLE) {
4651 print "<img src=\"".theme_image($link, 'images/art-email.png')."\"
4652 class='tagsPic' style=\"cursor : pointer\"
4653 onclick=\"emailArticle($id)\"
4654 alt='Zoom' title='".__('Forward by email')."'>";
4655 }
4656
4657 print "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
4658 class='tagsPic' style=\"cursor : pointer\"
4659 onclick=\"closeArticlePanel($id)\"
4660 alt='Zoom' title='".__('Close this panel')."'>";
4661
4662 } else {
4663 $tags_str = strip_tags($tags_str);
4664 print "<span id=\"ATSTR-$id\">$tags_str</span>";
4665 }
4666 print "</div>";
4667 print "<div clear='both'>$entry_comments</div>";
4668
4669 if ($line["orig_feed_id"]) {
4670
4671 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4672 WHERE id = ".$line["orig_feed_id"]);
4673
4674 if (db_num_rows($tmp_result) != 0) {
4675
4676 print "<div clear='both'>";
4677 print __("Originally from:");
4678
4679 print "&nbsp;";
4680
4681 $tmp_line = db_fetch_assoc($tmp_result);
4682
4683 print "<a target='_blank'
4684 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4685 $tmp_line['title'] . "</a>";
4686
4687 print "&nbsp;";
4688
4689 print "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4690 print "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4691
4692 print "</div>";
4693 }
4694 }
4695
4696 print "</div>";
4697
4698 print "<div class=\"postIcon\">" .
4699 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
4700 href=\"".htmlspecialchars($feed_site_url)."\">".
4701 $feed_icon . "</a></div>";
4702
4703 print "<div class=\"postContent\">";
4704
4705 $article_content = sanitize_rss($link, $line["content"], false, false,
4706 $feed_site_url);
4707
4708 print "<div id=\"POSTNOTE-$id\">";
4709 if ($line['note']) {
4710 print format_article_note($id, $line['note']);
4711 }
4712 print "</div>";
4713
4714 print $article_content;
4715
4716 print_article_enclosures($link, $id, $always_display_enclosures,
4717 $article_content);
4718
4719 print "</div>";
4720
4721 print "</div>";
4722
4723 }
4724
4725 if (!$zoom_mode) {
4726 print "]]></article>";
4727 } else {
4728 print "
4729 <div style=\"text-align : center\">
4730 <button onclick=\"return window.close()\">".
4731 __("Close this window")."</button></div>";
4732 print "</body></html>";
4733
4734 }
4735
4736 }
4737
4738 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4739 $next_unread_feed, $offset, $vgr_last_feed = false,
4740 $override_order = false) {
4741
4742 $disable_cache = false;
4743
4744 $timing_info = getmicrotime();
4745
4746 $topmost_article_ids = array();
4747
4748 if (!$offset) {
4749 $offset = 0;
4750 }
4751
4752 if ($subop == "undefined") $subop = "";
4753
4754 $subop_split = split(":", $subop);
4755
4756 if ($subop == "CatchupSelected") {
4757 $ids = split(",", db_escape_string($_REQUEST["ids"]));
4758 $cmode = sprintf("%d", $_REQUEST["cmode"]);
4759
4760 catchupArticlesById($link, $ids, $cmode);
4761 }
4762
4763 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0 && !$cat_view) {
4764 update_generic_feed($link, $feed, $cat_view, true);
4765 }
4766
4767 if ($subop == "MarkAllRead") {
4768 catchup_feed($link, $feed, $cat_view);
4769
4770 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4771 if ($next_unread_feed) {
4772 $feed = $next_unread_feed;
4773 }
4774 }
4775 }
4776
4777 if ($subop_split[0] == "MarkAllReadGR") {
4778 catchup_feed($link, $subop_split[1], false);
4779 }
4780
4781 // FIXME: might break tag display?
4782
4783 if ($feed > 0 && !$cat_view) {
4784 $result = db_query($link,
4785 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4786
4787 if (db_num_rows($result) == 0) {
4788 print "<div align='center'>".__('Feed not found.')."</div>";
4789 return;
4790 }
4791 }
4792
4793 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4794
4795 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4796 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4797
4798 if (db_num_rows($result) == 1) {
4799 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4800 } else {
4801 $rtl_content = false;
4802 }
4803
4804 if ($rtl_content) {
4805 $rtl_tag = "dir=\"RTL\"";
4806 } else {
4807 $rtl_tag = "";
4808 }
4809 } else {
4810 $rtl_tag = "";
4811 $rtl_content = false;
4812 }
4813
4814 /// START /////////////////////////////////////////////////////////////////////////////////
4815
4816 @$search = db_escape_string($_REQUEST["query"]);
4817
4818 if ($search) {
4819 $disable_cache = true;
4820 }
4821
4822 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
4823 @$match_on = db_escape_string($_REQUEST["match_on"]);
4824
4825 if (!$match_on) {
4826 $match_on = "both";
4827 }
4828
4829 $real_offset = $offset * $limit;
4830
4831 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4832
4833 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
4834 $search, $search_mode, $match_on, $override_order, $real_offset);
4835
4836 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4837
4838 $result = $qfh_ret[0];
4839 $feed_title = $qfh_ret[1];
4840 $feed_site_url = $qfh_ret[2];
4841 $last_error = $qfh_ret[3];
4842
4843 $vgroup_last_feed = $vgr_last_feed;
4844
4845/* if ($feed == -2) {
4846 $feed_site_url = article_publish_url($link);
4847 } */
4848
4849 /// STOP //////////////////////////////////////////////////////////////////////////////////
4850
4851 print "<toolbar><![CDATA[";
4852
4853 if (!$offset) {
4854// print "<div id=\"headlinesContainer\" $rtl_tag>";
4855
4856 if (!$result) {
4857 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4858 return;
4859 }
4860
4861 if (db_num_rows($result) > 0) {
4862 print_headline_subtoolbar($link, $feed_site_url, $feed_title,
4863 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode);
4864
4865// print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4866
4867 }
4868 }
4869
4870 print "]]></toolbar><content><![CDATA[";
4871
4872 $headlines_count = db_num_rows($result);
4873
4874 if (db_num_rows($result) > 0) {
4875
4876 $lnum = $limit*$offset;
4877
4878 $num_unread = 0;
4879 $cur_feed_title = '';
4880
4881 $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
4882
4883 while ($line = db_fetch_assoc($result)) {
4884
4885 $class = ($lnum % 2) ? "even" : "odd";
4886
4887 $id = $line["id"];
4888 $feed_id = $line["feed_id"];
4889
4890 $labels = get_article_labels($link, $id);
4891
4892 $labels_str = "<span id=\"HLLCTR-$id\">";
4893 $labels_str .= format_article_labels($labels, $id);
4894 $labels_str .= "</span>";
4895
4896 if (count($topmost_article_ids) < 3) {
4897 array_push($topmost_article_ids, $id);
4898 }
4899
4900 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
4901
4902 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4903 theme_image($link, 'images/updated.png')."\"
4904 alt=\"Updated\">";
4905 } else {
4906 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
4907 alt=\"Updated\">";
4908 }
4909
4910 if (sql_bool_to_bool($line["unread"]) &&
4911 time() - strtotime($line["updated_noms"]) < $fresh_intl) {
4912
4913 $update_pic = "<img id='FUPDPIC-$id' src=\"".
4914 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
4915 }
4916
4917 if ($line["unread"] == "t" || $line["unread"] == "1") {
4918 $class .= " Unread";
4919 ++$num_unread;
4920 $is_unread = true;
4921 } else {
4922 $is_unread = false;
4923 }
4924
4925 if ($line["marked"] == "t" || $line["marked"] == "1") {
4926 $marked_pic = "<img id=\"FMPIC-$id\"
4927 src=\"".theme_image($link, 'images/mark_set.png')."\"
4928 class=\"markedPic\" alt=\"Unstar article\"
4929 onclick='javascript:tMark($id)'>";
4930 } else {
4931 $marked_pic = "<img id=\"FMPIC-$id\"
4932 src=\"".theme_image($link, 'images/mark_unset.png')."\"
4933 class=\"markedPic\" alt=\"Star article\"
4934 onclick='javascript:tMark($id)'>";
4935 }
4936
4937 if ($line["published"] == "t" || $line["published"] == "1") {
4938 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4939 'images/pub_set.png')."\"
4940 class=\"markedPic\"
4941 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4942 } else {
4943 $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
4944 'images/pub_unset.png')."\"
4945 class=\"markedPic\"
4946 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4947 }
4948
4949# $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
4950# $line["title"] . "</a>";
4951
4952# $content_link = "<a
4953# href=\"" . htmlspecialchars($line["link"]) . "\"
4954# onclick=\"view($id,$feed_id);\">" .
4955# $line["title"] . "</a>";
4956
4957# $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4958# $line["title"] . "</a>";
4959
4960 $updated_fmt = make_local_datetime($link, $line["updated_noms"], false);
4961
4962 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4963 $content_preview = truncate_string(strip_tags($line["content_preview"]),
4964 100);
4965 }
4966
4967 $score = $line["score"];
4968
4969 $score_pic = theme_image($link,
4970 "images/" . get_score_pic($score));
4971
4972/* $score_title = __("(Click to change)");
4973 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\"
4974 onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
4975
4976 $score_pic = "<img class='hlScorePic' src=\"$score_pic\"
4977 title=\"$score\">";
4978
4979 if ($score > 500) {
4980 $hlc_suffix = "H";
4981 } else if ($score < -100) {
4982 $hlc_suffix = "L";
4983 } else {
4984 $hlc_suffix = "";
4985 }
4986
4987 $entry_author = $line["author"];
4988
4989 if ($entry_author) {
4990 $entry_author = " - $entry_author";
4991 }
4992
4993 $has_feed_icon = feed_has_icon($feed_id);
4994
4995 if ($has_feed_icon) {
4996 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
4997 } else {
4998 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
4999 $feed_icon_img = "";
5000 }
5001
5002 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5003
5004 if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5005 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5006
5007 $cur_feed_title = $line["feed_title"];
5008 $vgroup_last_feed = $feed_id;
5009
5010 $cur_feed_title = htmlspecialchars($cur_feed_title);
5011
5012 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5013
5014 print "<div class='cdmFeedTitle'>".
5015 "<div style=\"float : right\">$feed_icon_img</div>".
5016 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5017 $line["feed_title"]."</a> $vf_catchup_link</div>";
5018
5019 }
5020 }
5021
5022 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5023 onmouseout='postMouseOut($id)'";
5024
5025 print "<div class='$class' id='RROW-$id' $mouseover_attrs>";
5026
5027 print "<div class='hlUpdPic'>$update_pic</div>";
5028
5029 print "<div class='hlLeft'>";
5030
5031 print "<input type=\"checkbox\" onclick=\"tSR(this)\"
5032 id=\"RCHK-$id\">";
5033
5034 print "$marked_pic";
5035 print "$published_pic";
5036
5037 print "</div>";
5038
5039 print "<div onclick='return hlClicked(event, $id)'
5040 class=\"hlTitle\"><span class='hlContent$hlc_suffix'>";
5041 print "<a id=\"RTITLE-$id\"
5042 href=\"" . htmlspecialchars($line["link"]) . "\"
5043 onclick=\"return false;\">" .
5044 $line["title"];
5045
5046 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5047 if ($content_preview) {
5048 print "<span class=\"contentPreview\"> - $content_preview</span>";
5049 }
5050 }
5051
5052 print "</a></span>";
5053
5054 print $labels_str;
5055
5056 /* if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5057 if (@$line["feed_title"]) {
5058 print "<span class=\"hlFeed\">
5059 (<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5060 $line["feed_title"]."</a>)
5061 </span>";
5062 }
5063 } */
5064
5065 print "</div>";
5066
5067 print "<div class=\"hlRight\">";
5068 print "<span class=\"hlUpdated\">$updated_fmt</span>";
5069 print $score_pic;
5070
5071 if ($line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5072
5073 print "<span onclick=\"viewfeed($feed_id)\"
5074 title=\"".htmlspecialchars($line['feed_title'])."\">
5075 $feed_icon_img<span>";
5076 }
5077
5078 print "</div>";
5079 print "</div>";
5080
5081 } else {
5082
5083 if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5084 if ($feed_id != $vgroup_last_feed) {
5085
5086 $cur_feed_title = $line["feed_title"];
5087 $vgroup_last_feed = $feed_id;
5088
5089 $cur_feed_title = htmlspecialchars($cur_feed_title);
5090
5091 $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5092
5093 $has_feed_icon = feed_has_icon($feed_id);
5094
5095 if ($has_feed_icon) {
5096 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5097 } else {
5098 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5099 }
5100
5101 print "<div class='cdmFeedTitle'>".
5102 "<div style=\"float : right\">$feed_icon_img</div>".
5103 "<a href=\"#\" onclick=\"viewfeed($feed_id)\">".
5104 $line["feed_title"]."</a> $vf_catchup_link</div>";
5105 }
5106 }
5107
5108 $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5109
5110 $mouseover_attrs = "onmouseover='postMouseIn($id)'
5111 onmouseout='postMouseOut($id)'";
5112
5113 print "<div class=\"$class\"
5114 id=\"RROW-$id\" $mouseover_attrs'>";
5115
5116 print "<div class=\"cdmHeader\">";
5117
5118 print "<div style='float : right'>";
5119 print "<span class='updated'>$updated_fmt</span>";
5120 print "$score_pic";
5121
5122 if (!get_pref($link, "VFEED_GROUP_BY_FEED") && $line["feed_title"]) {
5123 print "<span style=\"cursor : pointer\"
5124 title=\"".htmlspecialchars($line["feed_title"])."\"
5125 onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5126 }
5127 print "<div class=\"updPic\">$update_pic</div>";
5128
5129 print "</div>";
5130
5131 print "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
5132 'RROW-$id')\" id=\"RCHK-$id\"/>";
5133
5134 print "$marked_pic";
5135 print "$published_pic";
5136
5137 print "<span id=\"RTITLE-$id\"
5138 onclick=\"return cdmClicked(event, $id);\"
5139 class=\"titleWrap$hlc_suffix\">
5140 <a class=\"title\"
5141 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5142 $entry_author";
5143
5144 print $labels_str;
5145
5146 if (!$expand_cdm)
5147 $content_hidden = "style=\"display : none\"";
5148 else
5149 $excerpt_hidden = "style=\"display : none\"";
5150
5151 print "<span $excerpt_hidden
5152 id=\"CEXC-$id\" class=\"cdmExcerpt\"> - $content_preview</span>";
5153
5154 print "</span>";
5155
5156 print "</div>";
5157
5158 print "<div class=\"cdmContent\" $content_hidden
5159 onclick=\"return cdmClicked(event, $id);\"
5160 id=\"CICD-$id\">";
5161
5162 print "<div class=\"cdmContentInner\">";
5163
5164 if ($line["orig_feed_id"]) {
5165
5166 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5167 WHERE id = ".$line["orig_feed_id"]);
5168
5169 if (db_num_rows($tmp_result) != 0) {
5170
5171 print "<div clear='both'>";
5172 print __("Originally from:");
5173
5174 print "&nbsp;";
5175
5176 $tmp_line = db_fetch_assoc($tmp_result);
5177
5178 print "<a target='_blank'
5179 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5180 $tmp_line['title'] . "</a>";
5181
5182 print "&nbsp;";
5183
5184 print "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5185 print "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5186
5187 print "</div>";
5188 }
5189 }
5190
5191 // FIXME: make this less of a hack
5192
5193 $feed_site_url = false;
5194
5195 if ($line["feed_id"]) {
5196 $tmp_result = db_query($link, "SELECT site_url FROM ttrss_feeds
5197 WHERE id = " . $line["feed_id"]);
5198
5199 if (db_num_rows($tmp_result) == 1) {
5200 $feed_site_url = db_fetch_result($tmp_result, 0, "site_url");
5201 }
5202 }
5203
5204 if ($expand_cdm) {
5205 $article_content = sanitize_rss($link, $line["content_preview"],
5206 false, false, $feed_site_url);
5207
5208 if (!$article_content) $article_content = "&nbsp;";
5209 } else {
5210 $article_content = '';
5211 }
5212
5213 print "<div id=\"POSTNOTE-$id\">";
5214 if ($line['note']) {
5215 print format_article_note($id, $line['note']);
5216 }
5217 print "</div>";
5218
5219 print "<span id=\"CWRAP-$id\">$article_content</span>";
5220
5221 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5222 ttrss_feeds WHERE id = ".
5223 (($line['feed_id'] == null) ? $line['orig_feed_id'] :
5224 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5225
5226 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($tmp_result,
5227 0, "always_display_enclosures"));
5228
5229 print_article_enclosures($link, $id, $always_display_enclosures,
5230 $article_content);
5231
5232 print "</div>";
5233
5234 print "<div class=\"cdmFooter\">";
5235
5236 $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5237
5238 print "<img src='".theme_image($link,
5239 'images/tag.png')."' alt='Tags' title='Tags'>
5240 <span id=\"ATSTR-$id\">$tags_str</span>
5241 <a title=\"".__('Edit tags for this article')."\"
5242 href=\"#\" onclick=\"editArticleTags($id, $feed_id, true)\">(+)</a>";
5243
5244 print "<div style=\"float : right\">";
5245
5246 print "<img src=\"images/art-zoom.png\"
5247 onclick=\"zoomToArticle(event, $id)\"
5248 style=\"cursor : pointer\"
5249 alt='Zoom'
5250 title='".__('Open article in new tab')."'>";
5251
5252 if (DIGEST_ENABLE) {
5253 print "<img src=\"".theme_image($link, 'images/art-email.png')."\"
5254 style=\"cursor : pointer\"
5255 onclick=\"emailArticle($id)\"
5256 alt='Zoom' title='".__('Forward by email')."'>";
5257 }
5258
5259 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5260
5261 print "<img src=\"images/art-pub-note.png\"
5262 style=\"cursor : pointer\" style=\"cursor : pointer\"
5263 onclick=\"publishWithNote($id, '$note_escaped')\"
5264 alt='PubNote' title='".__('Publish article with a note')."'>";
5265
5266 print "<img src=\"images/digest_checkbox.png\"
5267 style=\"cursor : pointer\" style=\"cursor : pointer\"
5268 onclick=\"dismissArticle($id)\"
5269 alt='Dismiss' title='".__('Dismiss article')."'>";
5270
5271 print "</div>";
5272 print "</div>";
5273
5274 print "</div>";
5275
5276 print "</div>";
5277
5278 }
5279
5280 ++$lnum;
5281 }
5282
5283 } else {
5284 $message = "";
5285
5286 switch ($view_mode) {
5287 case "unread":
5288 $message = __("No unread articles found to display.");
5289 break;
5290 case "updated":
5291 $message = __("No updated articles found to display.");
5292 break;
5293 case "marked":
5294 $message = __("No starred articles found to display.");
5295 break;
5296 default:
5297 if ($feed < -10) {
5298 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5299 } else {
5300 $message = __("No articles found to display.");
5301 }
5302 }
5303
5304 if (!$offset && $message) {
5305 print "<div class='whiteBox'>$message";
5306
5307 print "<p class=\"small\"><span class=\"insensitive\">";
5308
5309 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
5310 WHERE owner_uid = " . $_SESSION['uid']);
5311
5312 $last_updated = db_fetch_result($result, 0, "last_updated");
5313 $last_updated = make_local_datetime($link, $last_updated, false);
5314
5315 printf(__("Feeds last updated at %s"), $last_updated);
5316
5317 $result = db_query($link, "SELECT COUNT(id) AS num_errors
5318 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
5319
5320 $num_errors = db_fetch_result($result, 0, "num_errors");
5321
5322 if ($num_errors > 0) {
5323 print "<br/>";
5324 print "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
5325 __('Some feeds have update errors (click for details)')."</a>";
5326 }
5327 print "</span></p></div>";
5328 }
5329 }
5330
5331# if (!$offset) {
5332# if ($headlines_count > 0) print "</div>";
5333# print "</div>";
5334# }
5335
5336 print "]]></content>";
5337
5338 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5339 }
5340
5341// from here: http://www.roscripts.com/Create_tag_cloud-71.html
5342
5343 function printTagCloud($link) {
5344
5345 $query = "SELECT tag_name, COUNT(post_int_id) AS count
5346 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
5347 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5348
5349 $result = db_query($link, $query);
5350
5351 $tags = array();
5352
5353 while ($line = db_fetch_assoc($result)) {
5354 $tags[$line["tag_name"]] = $line["count"];
5355 }
5356
5357 ksort($tags);
5358
5359 $max_size = 32; // max font size in pixels
5360 $min_size = 11; // min font size in pixels
5361
5362 // largest and smallest array values
5363 $max_qty = max(array_values($tags));
5364 $min_qty = min(array_values($tags));
5365
5366 // find the range of values
5367 $spread = $max_qty - $min_qty;
5368 if ($spread == 0) { // we don't want to divide by zero
5369 $spread = 1;
5370 }
5371
5372 // set the font-size increment
5373 $step = ($max_size - $min_size) / ($spread);
5374
5375 // loop through the tag array
5376 foreach ($tags as $key => $value) {
5377 // calculate font-size
5378 // find the $value in excess of $min_qty
5379 // multiply by the font-size increment ($size)
5380 // and add the $min_size set above
5381 $size = round($min_size + (($value - $min_qty) * $step));
5382
5383 $key_escaped = str_replace("'", "\\'", $key);
5384
5385 echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " .
5386 $size . "px\" title=\"$value articles tagged with " .
5387 $key . '">' . $key . '</a> ';
5388 }
5389 }
5390
5391 function print_checkpoint($n, $s) {
5392 $ts = getmicrotime();
5393 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5394 return $ts;
5395 }
5396
5397 function sanitize_tag($tag) {
5398 $tag = trim($tag);
5399
5400 $tag = mb_strtolower($tag, 'utf-8');
5401
5402 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);
5403
5404// $tag = str_replace('"', "", $tag);
5405// $tag = str_replace("+", " ", $tag);
5406 $tag = str_replace("technorati tag: ", "", $tag);
5407
5408 return $tag;
5409 }
5410
5411 function get_self_url_prefix() {
5412
5413 $url_path = "";
5414
5415 if ($_SERVER['HTTPS'] != "on") {
5416 $url_path = "http://";
5417 } else {
5418 $url_path = "https://";
5419 }
5420
5421 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5422
5423 return $url_path;
5424
5425 }
5426 function opml_publish_url($link){
5427
5428 $url_path = get_self_url_prefix();
5429 $url_path .= "/opml.php?op=publish&key=" .
5430 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
5431
5432 return $url_path;
5433 }
5434
5435 /**
5436 * Purge a feed contents, marked articles excepted.
5437 *
5438 * @param mixed $link The database connection.
5439 * @param integer $id The id of the feed to purge.
5440 * @return void
5441 */
5442 function clear_feed_articles($link, $id) {
5443
5444 if ($id != 0) {
5445 $result = db_query($link, "DELETE FROM ttrss_user_entries
5446 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5447 } else {
5448 $result = db_query($link, "DELETE FROM ttrss_user_entries
5449 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5450 }
5451
5452 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
5453 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5454
5455 ccache_update($link, $id, $_SESSION['uid']);
5456 } // function clear_feed_articles
5457
5458 /**
5459 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5460 *
5461 * @return string The Mozilla Firefox feed adding URL.
5462 */
5463 function add_feed_url() {
5464 $url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5465 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5466 return $url_path;
5467 } // function add_feed_url
5468
5469 /**
5470 * Encrypt a password in SHA1.
5471 *
5472 * @param string $pass The password to encrypt.
5473 * @param string $login A optionnal login.
5474 * @return string The encrypted password.
5475 */
5476 function encrypt_password($pass, $login = '') {
5477 if ($login) {
5478 return "SHA1X:" . sha1("$login:$pass");
5479 } else {
5480 return "SHA1:" . sha1($pass);
5481 }
5482 } // function encrypt_password
5483
5484 /**
5485 * Update a feed batch.
5486 * Used by daemons to update n feeds by run.
5487 * Only update feed needing a update, and not being processed
5488 * by another process.
5489 *
5490 * @param mixed $link Database link
5491 * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5492 * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5493 * @param boolean $debug Set to false to disable debug output. Default to true.
5494 * @return void
5495 */
5496 function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5497 // Process all other feeds using last_updated and interval parameters
5498
5499 // Test if the user has loggued in recently. If not, it does not update its feeds.
5500 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5501 if (DB_TYPE == "pgsql") {
5502 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5503 } else {
5504 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5505 }
5506 } else {
5507 $login_thresh_qpart = "";
5508 }
5509
5510 // Test if the feed need a update (update interval exceded).
5511 if (DB_TYPE == "pgsql") {
5512 $update_limit_qpart = "AND ((
5513 ttrss_feeds.update_interval = 0
5514 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5515 ) OR (
5516 ttrss_feeds.update_interval > 0
5517 AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5518 ) OR ttrss_feeds.last_updated IS NULL)";
5519 } else {
5520 $update_limit_qpart = "AND ((
5521 ttrss_feeds.update_interval = 0
5522 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5523 ) OR (
5524 ttrss_feeds.update_interval > 0
5525 AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5526 ) OR ttrss_feeds.last_updated IS NULL)";
5527 }
5528
5529 // Test if feed is currently being updated by another process.
5530 if (DB_TYPE == "pgsql") {
5531 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5532 } else {
5533 $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5534 }
5535
5536 // Test if there is a limit to number of updated feeds
5537 $query_limit = "";
5538 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5539
5540 $random_qpart = sql_random_function();
5541
5542 // We search for feed needing update.
5543 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5544 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5545 ttrss_feeds.update_interval
5546 FROM
5547 ttrss_feeds, ttrss_users, ttrss_user_prefs
5548 WHERE
5549 ttrss_feeds.owner_uid = ttrss_users.id
5550 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5551 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5552 $login_thresh_qpart $update_limit_qpart
5553 $updstart_thresh_qpart
5554 ORDER BY $random_qpart $query_limit");
5555
5556 $user_prefs_cache = array();
5557
5558 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5559
5560 // Here is a little cache magic in order to minimize risk of double feed updates.
5561 $feeds_to_update = array();
5562 while ($line = db_fetch_assoc($result)) {
5563 $feeds_to_update[$line['id']] = $line;
5564 }
5565
5566 // We update the feed last update started date before anything else.
5567 // There is no lag due to feed contents downloads
5568 // It prevent an other process to update the same feed.
5569 $feed_ids = array_keys($feeds_to_update);
5570 if($feed_ids) {
5571 db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5572 WHERE id IN (%s)", implode(',', $feed_ids)));
5573 }
5574
5575 // For each feed, we call the feed update function.
5576 while ($line = array_pop($feeds_to_update)) {
5577
5578 if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5579
5580 update_rss_feed($link, $line["id"], true);
5581
5582 sleep(1); // prevent flood (FIXME make this an option?)
5583 }
5584
5585 // Send feed digests by email if needed.
5586 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5587
5588 } // function update_daemon_common
5589
5590 function sanitize_article_content($text) {
5591 # we don't support CDATA sections in articles, they break our own escaping
5592 $text = preg_replace("/\[\[CDATA/", "", $text);
5593 $text = preg_replace("/\]\]\>/", "", $text);
5594 return $text;
5595 }
5596
5597 function load_filters($link, $feed, $owner_uid, $action_id = false) {
5598 $filters = array();
5599
5600 global $memcache;
5601
5602 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5603
5604 if ($memcache && $obj = $memcache->get($obj_id)) {
5605
5606 return $obj;
5607
5608 } else {
5609
5610 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5611
5612 $result = db_query($link, "SELECT reg_exp,
5613 ttrss_filter_types.name AS name,
5614 ttrss_filter_actions.name AS action,
5615 inverse,
5616 action_param,
5617 filter_param
5618 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
5619 enabled = true AND
5620 $ftype_query_part
5621 owner_uid = $owner_uid AND
5622 ttrss_filter_types.id = filter_type AND
5623 ttrss_filter_actions.id = action_id AND
5624 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5625
5626 while ($line = db_fetch_assoc($result)) {
5627 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5628 $filter["reg_exp"] = $line["reg_exp"];
5629 $filter["action"] = $line["action"];
5630 $filter["action_param"] = $line["action_param"];
5631 $filter["filter_param"] = $line["filter_param"];
5632 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5633
5634 array_push($filters[$line["name"]], $filter);
5635 }
5636
5637 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5638
5639 return $filters;
5640 }
5641 }
5642
5643 function get_score_pic($score) {
5644 if ($score > 100) {
5645 return "score_high.png";
5646 } else if ($score > 0) {
5647 return "score_half_high.png";
5648 } else if ($score < -100) {
5649 return "score_low.png";
5650 } else if ($score < 0) {
5651 return "score_half_low.png";
5652 } else {
5653 return "score_neutral.png";
5654 }
5655 }
5656
5657 function rounded_table_start($classname, $header = "&nbsp;") {
5658 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5659 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5660 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5661 }
5662
5663 function rounded_table_end($footer = "&nbsp;") {
5664 print "</td><td class='right'>&nbsp;</td></tr>";
5665 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5666 print "</table>";
5667 }
5668
5669 function feed_has_icon($id) {
5670 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5671 }
5672
5673 function init_connection($link) {
5674 if (DB_TYPE == "pgsql") {
5675 pg_query($link, "set client_encoding = 'UTF-8'");
5676 pg_set_client_encoding("UNICODE");
5677 pg_query($link, "set datestyle = 'ISO, european'");
5678 pg_query($link, "set TIME ZONE 0");
5679 } else {
5680 db_query($link, "SET time_zone = '+0:0'");
5681
5682 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5683 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5684 // db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5685 }
5686 }
5687 }
5688
5689 function update_feedbrowser_cache($link) {
5690
5691 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5692 FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5693 WHERE tf.feed_url = ttrss_feeds.feed_url
5694 AND (private IS true OR feed_url LIKE '%:%@%/%'))
5695 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5696
5697 db_query($link, "BEGIN");
5698
5699 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
5700
5701 $count = 0;
5702
5703 while ($line = db_fetch_assoc($result)) {
5704 $subscribers = db_escape_string($line["subscribers"]);
5705 $feed_url = db_escape_string($line["feed_url"]);
5706 $title = db_escape_string($line["title"]);
5707
5708 $tmp_result = db_query($link, "SELECT subscribers FROM
5709 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
5710
5711 if (db_num_rows($tmp_result) == 0) {
5712
5713 db_query($link, "INSERT INTO ttrss_feedbrowser_cache
5714 (feed_url, title, subscribers) VALUES ('$feed_url',
5715 '$title', '$subscribers')");
5716
5717 ++$count;
5718
5719 }
5720
5721 }
5722
5723 db_query($link, "COMMIT");
5724
5725 return $count;
5726
5727 }
5728
5729 function ccache_zero($link, $feed_id, $owner_uid) {
5730 db_query($link, "UPDATE ttrss_counters_cache SET
5731 value = 0, updated = NOW() WHERE
5732 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5733 }
5734
5735 function ccache_zero_all($link, $owner_uid) {
5736 db_query($link, "UPDATE ttrss_counters_cache SET
5737 value = 0 WHERE owner_uid = '$owner_uid'");
5738
5739 db_query($link, "UPDATE ttrss_cat_counters_cache SET
5740 value = 0 WHERE owner_uid = '$owner_uid'");
5741 }
5742
5743 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
5744
5745 if (!$is_cat) {
5746 $table = "ttrss_counters_cache";
5747 } else {
5748 $table = "ttrss_cat_counters_cache";
5749 }
5750
5751 db_query($link, "DELETE FROM $table WHERE
5752 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5753
5754 }
5755
5756 function ccache_update_all($link, $owner_uid) {
5757
5758 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
5759
5760 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
5761 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5762
5763 while ($line = db_fetch_assoc($result)) {
5764 ccache_update($link, $line["feed_id"], $owner_uid, true);
5765 }
5766
5767 /* We have to manually include category 0 */
5768
5769 ccache_update($link, 0, $owner_uid, true);
5770
5771 } else {
5772 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
5773 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
5774
5775 while ($line = db_fetch_assoc($result)) {
5776 print ccache_update($link, $line["feed_id"], $owner_uid);
5777
5778 }
5779
5780 }
5781 }
5782
5783 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
5784 $no_update = false) {
5785
5786 if (!is_numeric($feed_id)) return;
5787
5788 if (!$is_cat) {
5789 $table = "ttrss_counters_cache";
5790 if ($feed_id > 0) {
5791 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5792 WHERE id = '$feed_id'");
5793 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5794 }
5795 } else {
5796 $table = "ttrss_cat_counters_cache";
5797 }
5798
5799 if (DB_TYPE == "pgsql") {
5800 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
5801 } else if (DB_TYPE == "mysql") {
5802 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
5803 }
5804
5805 $result = db_query($link, "SELECT value FROM $table
5806 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
5807 LIMIT 1");
5808
5809 if (db_num_rows($result) == 1) {
5810 return db_fetch_result($result, 0, "value");
5811 } else {
5812 if ($no_update) {
5813 return -1;
5814 } else {
5815 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
5816 }
5817 }
5818
5819 }
5820
5821 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
5822 $update_pcat = true) {
5823
5824 if (!is_numeric($feed_id)) return;
5825
5826 if (!$is_cat && $feed_id > 0) {
5827 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
5828 WHERE id = '$feed_id'");
5829 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
5830 }
5831
5832 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
5833
5834 /* When updating a label, all we need to do is recalculate feed counters
5835 * because labels are not cached */
5836
5837 if ($feed_id < 0) {
5838 ccache_update_all($link, $owner_uid);
5839 return;
5840 }
5841
5842 if (!$is_cat) {
5843 $table = "ttrss_counters_cache";
5844 } else {
5845 $table = "ttrss_cat_counters_cache";
5846 }
5847
5848 if ($is_cat && $feed_id >= 0) {
5849 if ($feed_id != 0) {
5850 $cat_qpart = "cat_id = '$feed_id'";
5851 } else {
5852 $cat_qpart = "cat_id IS NULL";
5853 }
5854
5855 /* Recalculate counters for child feeds */
5856
5857 $result = db_query($link, "SELECT id FROM ttrss_feeds
5858 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
5859
5860 while ($line = db_fetch_assoc($result)) {
5861 ccache_update($link, $line["id"], $owner_uid, false, false);
5862 }
5863
5864 $result = db_query($link, "SELECT SUM(value) AS sv
5865 FROM ttrss_counters_cache, ttrss_feeds
5866 WHERE id = feed_id AND $cat_qpart AND
5867 ttrss_feeds.owner_uid = '$owner_uid'");
5868
5869 $unread = (int) db_fetch_result($result, 0, "sv");
5870
5871 } else {
5872 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
5873 }
5874
5875 db_query($link, "BEGIN");
5876
5877 $result = db_query($link, "SELECT feed_id FROM $table
5878 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
5879
5880 if (db_num_rows($result) == 1) {
5881 db_query($link, "UPDATE $table SET
5882 value = '$unread', updated = NOW() WHERE
5883 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
5884
5885 } else {
5886 db_query($link, "INSERT INTO $table
5887 (feed_id, value, owner_uid, updated)
5888 VALUES
5889 ($feed_id, $unread, $owner_uid, NOW())");
5890 }
5891
5892 db_query($link, "COMMIT");
5893
5894 if ($feed_id > 0 && $prev_unread != $unread) {
5895
5896 if (!$is_cat) {
5897
5898 /* Update parent category */
5899
5900 if ($update_pcat) {
5901
5902 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
5903 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
5904
5905 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
5906
5907 ccache_update($link, $cat_id, $owner_uid, true);
5908
5909 }
5910 }
5911 } else if ($feed_id < 0) {
5912 ccache_update_all($link, $owner_uid);
5913 }
5914
5915 return $unread;
5916 }
5917
5918 function label_find_id($link, $label, $owner_uid) {
5919 $result = db_query($link,
5920 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
5921 AND owner_uid = '$owner_uid' LIMIT 1");
5922
5923 if (db_num_rows($result) == 1) {
5924 return db_fetch_result($result, 0, "id");
5925 } else {
5926 return 0;
5927 }
5928 }
5929
5930 function get_article_labels($link, $id) {
5931 global $memcache;
5932
5933 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
5934
5935 $rv = array();
5936
5937 if ($memcache && $obj = $memcache->get($obj_id)) {
5938 return $obj;
5939 } else {
5940
5941 $result = db_query($link, "SELECT label_cache FROM
5942 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
5943 $_SESSION["uid"]);
5944
5945 $label_cache = db_fetch_result($result, 0, "label_cache");
5946
5947 if ($label_cache) {
5948
5949 $label_cache = json_decode($label_cache, true);
5950
5951 if ($label_cache["no-labels"] == 1)
5952 return $rv;
5953 else
5954 return $label_cache;
5955 }
5956
5957 $result = db_query($link,
5958 "SELECT DISTINCT label_id,caption,fg_color,bg_color
5959 FROM ttrss_labels2, ttrss_user_labels2
5960 WHERE id = label_id
5961 AND article_id = '$id'
5962 AND owner_uid = ".$_SESSION["uid"] . "
5963 ORDER BY caption");
5964
5965 while ($line = db_fetch_assoc($result)) {
5966 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
5967 $line["bg_color"]);
5968 array_push($rv, $rk);
5969 }
5970 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
5971
5972 if (count($rv) > 0)
5973 label_update_cache($link, $id, $rv);
5974 else
5975 label_update_cache($link, $id, array("no-labels" => 1));
5976 }
5977
5978 return $rv;
5979 }
5980
5981
5982 function label_find_caption($link, $label, $owner_uid) {
5983 $result = db_query($link,
5984 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
5985 AND owner_uid = '$owner_uid' LIMIT 1");
5986
5987 if (db_num_rows($result) == 1) {
5988 return db_fetch_result($result, 0, "caption");
5989 } else {
5990 return "";
5991 }
5992 }
5993
5994 function label_update_cache($link, $id, $labels = false, $force = false) {
5995
5996 if ($force)
5997 label_clear_cache($link, $id);
5998
5999 if (!$labels)
6000 $labels = get_article_labels($link, $id);
6001
6002 $labels = db_escape_string(json_encode($labels));
6003
6004 db_query($link, "UPDATE ttrss_user_entries SET
6005 label_cache = '$labels' WHERE ref_id = '$id'");
6006
6007 }
6008
6009 function label_clear_cache($link, $id) {
6010
6011 db_query($link, "UPDATE ttrss_user_entries SET
6012 label_cache = '' WHERE ref_id = '$id'");
6013
6014 }
6015
6016 function label_remove_article($link, $id, $label, $owner_uid) {
6017
6018 $label_id = label_find_id($link, $label, $owner_uid);
6019
6020 if (!$label_id) return;
6021
6022 $result = db_query($link,
6023 "DELETE FROM ttrss_user_labels2
6024 WHERE
6025 label_id = '$label_id' AND
6026 article_id = '$id'");
6027
6028 label_clear_cache($link, $id);
6029 }
6030
6031 function label_add_article($link, $id, $label, $owner_uid) {
6032
6033 global $memcache;
6034
6035 if ($memcache) {
6036 $obj_id = md5("LABELS:$id:$owner_uid");
6037 $memcache->delete($obj_id);
6038 }
6039
6040 $label_id = label_find_id($link, $label, $owner_uid);
6041
6042 if (!$label_id) return;
6043
6044 $result = db_query($link,
6045 "SELECT
6046 article_id FROM ttrss_labels2, ttrss_user_labels2
6047 WHERE
6048 label_id = id AND
6049 label_id = '$label_id' AND
6050 article_id = '$id' AND owner_uid = '$owner_uid'
6051 LIMIT 1");
6052
6053 if (db_num_rows($result) == 0) {
6054 db_query($link, "INSERT INTO ttrss_user_labels2
6055 (label_id, article_id) VALUES ('$label_id', '$id')");
6056 }
6057
6058 label_clear_cache($link, $id);
6059
6060 }
6061
6062 function label_remove($link, $id, $owner_uid) {
6063 global $memcache;
6064
6065 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6066
6067 if ($memcache) {
6068 $obj_id = md5("LABELS:$id:$owner_uid");
6069 $memcache->delete($obj_id);
6070 }
6071
6072 db_query($link, "BEGIN");
6073
6074 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6075 WHERE id = '$id'");
6076
6077 $caption = db_fetch_result($result, 0, "caption");
6078
6079 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6080 AND owner_uid = " . $owner_uid);
6081
6082 if (db_affected_rows($link, $result) != 0 && $caption) {
6083
6084 /* Remove access key for the label */
6085
6086 $ext_id = -11 - $id;
6087
6088 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6089 feed_id = '$ext_id' AND owner_uid = $owner_uid");
6090
6091 /* Disable filters that reference label being removed */
6092
6093 db_query($link, "UPDATE ttrss_filters SET
6094 enabled = false WHERE action_param = '$caption'
6095 AND action_id = 7
6096 AND owner_uid = " . $owner_uid);
6097
6098 /* Remove cached data */
6099
6100 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
6101 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
6102
6103 }
6104
6105 db_query($link, "COMMIT");
6106 }
6107
6108 function label_create($link, $caption) {
6109
6110 db_query($link, "BEGIN");
6111
6112 $result = false;
6113
6114 $result = db_query($link, "SELECT id FROM ttrss_labels2
6115 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
6116
6117 if (db_num_rows($result) == 0) {
6118 $result = db_query($link,
6119 "INSERT INTO ttrss_labels2 (caption,owner_uid)
6120 VALUES ('$caption', '".$_SESSION["uid"]."')");
6121
6122 $result = db_affected_rows($link, $result) != 0;
6123 }
6124
6125 db_query($link, "COMMIT");
6126
6127 return $result;
6128 }
6129
6130 function print_labels_headlines_dropdown($link, $feed_id) {
6131 print "<option value=\"addLabel()\">".__("Create label...")."</option>";
6132
6133 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6134 owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6135
6136 while ($line = db_fetch_assoc($result)) {
6137
6138 $label_id = $line["id"];
6139 $label_caption = $line["caption"];
6140 $id = $line["id"];
6141
6142 if ($feed_id < -10 && $feed_id == -11-$label_id) {
6143 print "<option id=\"LHDL-$id\"
6144 value=\"selectionRemoveLabel($label_id)\">".
6145 __('Remove:') . " $label_caption</option>";
6146 } else {
6147 print "<option id=\"LHDL-$id\"
6148 value=\"selectionAssignLabel($label_id)\">".
6149 __('Assign:') . " $label_caption</option>";
6150 }
6151 }
6152 }
6153
6154 function format_tags_string($tags, $id) {
6155
6156 $tags_str = "";
6157 $tags_nolinks_str = "";
6158
6159 $num_tags = 0;
6160
6161/* if (get_user_theme($link) == "3pane") {
6162 $tag_limit = 3;
6163 } else {
6164 $tag_limit = 6;
6165 } */
6166
6167 $tag_limit = 6;
6168
6169 $formatted_tags = array();
6170
6171 foreach ($tags as $tag) {
6172 $num_tags++;
6173 $tag_escaped = str_replace("'", "\\'", $tag);
6174
6175 if (mb_strlen($tag) > 30) {
6176 $tag = truncate_string($tag, 30);
6177 }
6178
6179 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6180
6181 array_push($formatted_tags, $tag_str);
6182
6183 $tmp_tags_str = implode(", ", $formatted_tags);
6184
6185 if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
6186 break;
6187 }
6188 }
6189
6190 $tags_str = implode(", ", $formatted_tags);
6191
6192 if ($num_tags < count($tags)) {
6193 $tags_str .= ", &hellip;";
6194 }
6195
6196 if ($num_tags == 0) {
6197 $tags_str = __("no tags");
6198 }
6199
6200 return $tags_str;
6201
6202 }
6203
6204 function format_article_labels($labels, $id) {
6205
6206 $labels_str = "";
6207
6208 foreach ($labels as $l) {
6209 $labels_str .= sprintf("<span class='hlLabelRef'
6210 style='color : %s; background-color : %s'>%s</span>",
6211 $l[2], $l[3], $l[1]);
6212 }
6213
6214 return $labels_str;
6215
6216 }
6217
6218 function format_article_note($id, $note) {
6219
6220 $note_escaped = htmlspecialchars($note, ENT_QUOTES);
6221
6222 $str = "<div class='articleNote'>";
6223 $str .= $note;
6224 $str .= "<div class='articleNoteOps'>";
6225 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6226 __('edit note')."</a>";
6227 $str .= "</div>";
6228 $str .= "</div>";
6229
6230 return $str;
6231 }
6232
6233 function toggle_collapse_cat($link, $cat_id, $mode) {
6234 if ($cat_id > 0) {
6235 $mode = bool_to_sql_bool($mode);
6236
6237 db_query($link, "UPDATE ttrss_feed_categories SET
6238 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
6239 $_SESSION["uid"]);
6240 } else {
6241 $pref_name = '';
6242
6243 switch ($cat_id) {
6244 case -1:
6245 $pref_name = '_COLLAPSED_SPECIAL';
6246 break;
6247 case -2:
6248 $pref_name = '_COLLAPSED_LABELS';
6249 break;
6250 case 0:
6251 $pref_name = '_COLLAPSED_UNCAT';
6252 break;
6253 }
6254
6255 if ($pref_name) {
6256 if ($mode) {
6257 set_pref($link, $pref_name, 'true');
6258 } else {
6259 set_pref($link, $pref_name, 'false');
6260 }
6261 }
6262 }
6263 }
6264
6265 function remove_feed($link, $id, $owner_uid) {
6266
6267 if ($id > 0) {
6268
6269 /* save starred articles in Archived feed */
6270
6271 db_query($link, "BEGIN");
6272
6273 /* prepare feed if necessary */
6274
6275 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6276 WHERE id = '$id'");
6277
6278 if (db_num_rows($result) == 0) {
6279 db_query($link, "INSERT INTO ttrss_archived_feeds
6280 (id, owner_uid, title, feed_url, site_url)
6281 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6282 WHERE id = '$id'");
6283 }
6284
6285 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6286 orig_feed_id = '$id' WHERE feed_id = '$id' AND
6287 marked = true AND owner_uid = $owner_uid");
6288
6289 /* Remove access key for the feed */
6290
6291 db_query($link, "DELETE FROM ttrss_access_keys WHERE
6292 feed_id = '$id' AND owner_uid = $owner_uid");
6293
6294 /* remove the feed */
6295
6296 db_query($link, "DELETE FROM ttrss_feeds
6297 WHERE id = '$id' AND owner_uid = $owner_uid");
6298
6299 db_query($link, "COMMIT");
6300
6301/* if (file_exists(ICONS_DIR . "/$id.ico")) {
6302 unlink(ICONS_DIR . "/$id.ico");
6303 } */
6304
6305 ccache_remove($link, $id, $owner_uid);
6306
6307 } else {
6308 label_remove($link, -11-$id, $owner_uid);
6309 ccache_remove($link, -11-$id, $owner_uid);
6310 }
6311 }
6312
6313 function add_feed_category($link, $feed_cat) {
6314
6315 if (!$feed_cat) return false;
6316
6317 db_query($link, "BEGIN");
6318
6319 $result = db_query($link,
6320 "SELECT id FROM ttrss_feed_categories
6321 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
6322
6323 if (db_num_rows($result) == 0) {
6324
6325 $result = db_query($link,
6326 "INSERT INTO ttrss_feed_categories (owner_uid,title)
6327 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
6328
6329 db_query($link, "COMMIT");
6330
6331 return true;
6332 }
6333
6334 return false;
6335 }
6336
6337 function remove_feed_category($link, $id, $owner_uid) {
6338
6339 db_query($link, "DELETE FROM ttrss_feed_categories
6340 WHERE id = '$id' AND owner_uid = $owner_uid");
6341
6342 ccache_remove($link, $id, $owner_uid, true);
6343 }
6344
6345 function archive_article($link, $id, $owner_uid) {
6346 db_query($link, "BEGIN");
6347
6348 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6349 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6350
6351 if (db_num_rows($result) != 0) {
6352
6353 /* prepare the archived table */
6354
6355 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6356
6357 if ($feed_id) {
6358 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6359 WHERE id = '$feed_id'");
6360
6361 if (db_num_rows($result) == 0) {
6362 db_query($link, "INSERT INTO ttrss_archived_feeds
6363 (id, owner_uid, title, feed_url, site_url)
6364 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6365 WHERE id = '$feed_id'");
6366 }
6367
6368 db_query($link, "UPDATE ttrss_user_entries
6369 SET orig_feed_id = feed_id, feed_id = NULL
6370 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6371 }
6372 }
6373
6374 db_query($link, "COMMIT");
6375 }
6376
6377 function getArticleFeed($link, $id) {
6378 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6379 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6380
6381 if (db_num_rows($result) != 0) {
6382 return db_fetch_result($result, 0, "feed_id");
6383 } else {
6384 return 0;
6385 }
6386 }
6387
6388 function make_url_from_parts($parts) {
6389 $url = $parts['scheme'] . '://' . $parts['host'];
6390
6391 if ($parts['path']) $url .= $parts['path'];
6392 if ($parts['query']) $url .= '?' . $parts['query'];
6393
6394 return $url;
6395 }
6396
6397 /**
6398 * Fixes incomplete URLs by prepending "http://".
6399 * Also replaces feed:// with http://, and
6400 * prepends a trailing slash if the url is a domain name only.
6401 *
6402 * @param string $url Possibly incomplete URL
6403 *
6404 * @return string Fixed URL.
6405 */
6406 function fix_url($url) {
6407 if (strpos($url, '://') === false) {
6408 $url = 'http://' . $url;
6409 } else if (substr($url, 0, 5) == 'feed:') {
6410 $url = 'http:' . substr($url, 5);
6411 }
6412
6413 //prepend slash if the URL has no slash in it
6414 // "http://www.example" -> "http://www.example/"
6415 if (strpos($url, '/', strpos($url, ':') + 3) === false) {
6416 $url .= '/';
6417 }
6418 return $url;
6419 }
6420
6421 function validate_feed_url($url) {
6422 $parts = parse_url($url);
6423
6424 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
6425
6426 }
6427
6428 function get_article_enclosures($link, $id) {
6429
6430 global $memcache;
6431
6432 $query = "SELECT * FROM ttrss_enclosures
6433 WHERE post_id = '$id' AND content_url != ''";
6434
6435 $obj_id = md5("ENCLOSURES:$id");
6436
6437 $rv = array();
6438
6439 if ($memcache && $obj = $memcache->get($obj_id)) {
6440 $rv = $obj;
6441 } else {
6442 $result = db_query($link, $query);
6443
6444 if (db_num_rows($result) > 0) {
6445 while ($line = db_fetch_assoc($result)) {
6446 array_push($rv, $line);
6447 }
6448 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6449 }
6450 }
6451
6452 return $rv;
6453 }
6454
6455 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6456
6457 $feeds = array();
6458
6459 /* Labels */
6460
6461 if ($cat_id == -4 || $cat_id == -2) {
6462 $counters = getLabelCounters($link, true);
6463
6464 foreach (array_values($counters) as $cv) {
6465
6466 $unread = $cv["counter"];
6467
6468 if ($unread || !$unread_only) {
6469
6470 $row = array(
6471 "id" => $cv["id"],
6472 "title" => $cv["description"],
6473 "unread" => $cv["counter"],
6474 "cat_id" => -2,
6475 );
6476
6477 array_push($feeds, $row);
6478 }
6479 }
6480 }
6481
6482 /* Virtual feeds */
6483
6484 if ($cat_id == -4 || $cat_id == -1) {
6485 foreach (array(-1, -2, -3, -4, 0) as $i) {
6486 $unread = getFeedUnread($link, $i);
6487
6488 if ($unread || !$unread_only) {
6489 $title = getFeedTitle($link, $i);
6490
6491 $row = array(
6492 "id" => $i,
6493 "title" => $title,
6494 "unread" => $unread,
6495 "cat_id" => -1,
6496 );
6497 array_push($feeds, $row);
6498 }
6499
6500 }
6501 }
6502
6503 /* Real feeds */
6504
6505 if ($limit) {
6506 $limit_qpart = "LIMIT $limit OFFSET $offset";
6507 } else {
6508 $limit_qpart = "";
6509 }
6510
6511 if ($cat_id == -4 || $cat_id == -3) {
6512 $result = db_query($link, "SELECT
6513 id, feed_url, cat_id, title, ".
6514 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6515 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
6516 " ORDER BY cat_id, title " . $limit_qpart);
6517 } else {
6518
6519 if ($cat_id)
6520 $cat_qpart = "cat_id = '$cat_id'";
6521 else
6522 $cat_qpart = "cat_id IS NULL";
6523
6524 $result = db_query($link, "SELECT
6525 id, feed_url, cat_id, title, ".
6526 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6527 FROM ttrss_feeds WHERE
6528 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
6529 " ORDER BY cat_id, title " . $limit_qpart);
6530 }
6531
6532 while ($line = db_fetch_assoc($result)) {
6533
6534 $unread = getFeedUnread($link, $line["id"]);
6535
6536 $has_icon = feed_has_icon($line['id']);
6537
6538 if ($unread || !$unread_only) {
6539
6540 $row = array(
6541 "feed_url" => $line["feed_url"],
6542 "title" => $line["title"],
6543 "id" => (int)$line["id"],
6544 "unread" => (int)$unread,
6545 "has_icon" => $has_icon,
6546 "cat_id" => (int)$line["cat_id"],
6547 "last_updated" => strtotime($line["last_updated"])
6548 );
6549
6550 array_push($feeds, $row);
6551 }
6552 }
6553
6554 return $feeds;
6555 }
6556
6557 function api_get_headlines($link, $feed_id, $limit, $offset,
6558 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order) {
6559
6560 /* do not rely on params below */
6561
6562 $search = db_escape_string($_REQUEST["search"]);
6563 $search_mode = db_escape_string($_REQUEST["search_mode"]);
6564 $match_on = db_escape_string($_REQUEST["match_on"]);
6565
6566 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
6567 $view_mode, $is_cat, $search, $search_mode, $match_on,
6568 $order, $offset);
6569
6570 $result = $qfh_ret[0];
6571 $feed_title = $qfh_ret[1];
6572
6573 $headlines = array();
6574
6575 while ($line = db_fetch_assoc($result)) {
6576 $is_updated = ($line["last_read"] == "" &&
6577 ($line["unread"] != "t" && $line["unread"] != "1"));
6578
6579 $headline_row = array(
6580 "id" => (int)$line["id"],
6581 "unread" => sql_bool_to_bool($line["unread"]),
6582 "marked" => sql_bool_to_bool($line["marked"]),
6583 "published" => sql_bool_to_bool($line["published"]),
6584 "updated" => strtotime($line["updated"]),
6585 "is_updated" => $is_updated,
6586 "title" => $line["title"],
6587 "link" => $line["link"],
6588 "feed_id" => $line["feed_id"],
6589 "tags" => get_article_tags($link, $line["id"]),
6590 );
6591
6592 if ($show_excerpt) {
6593 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6594 $headline_row["excerpt"] = $excerpt;
6595 }
6596
6597 if ($show_content) {
6598 $headline_row["content"] = $line["content_preview"];
6599 }
6600
6601 array_push($headlines, $headline_row);
6602 }
6603
6604 return $headlines;
6605 }
6606
6607 function generate_dashboard_feed($link) {
6608 print "<headlines id=\"-5\" is_cat=\"\">";
6609
6610 print "<toolbar><![CDATA[]]></toolbar>";
6611
6612 print '<content><![CDATA[';
6613
6614 print "<div class='whiteBox'>".__('No feed selected.');
6615
6616 print "<p class=\"small\"><span class=\"insensitive\">";
6617
6618 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6619 WHERE owner_uid = " . $_SESSION['uid']);
6620
6621 $last_updated = db_fetch_result($result, 0, "last_updated");
6622 $last_updated = make_local_datetime($link, $last_updated, false);
6623
6624 printf(__("Feeds last updated at %s"), $last_updated);
6625
6626 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6627 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6628
6629 $num_errors = db_fetch_result($result, 0, "num_errors");
6630
6631 if ($num_errors > 0) {
6632 print "<br/>";
6633 print "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6634 __('Some feeds have update errors (click for details)')."</a>";
6635 }
6636 print "</span></p>";
6637
6638 print "]]></content>";
6639 print "</headlines>";
6640
6641 print "<headlines-info><![CDATA[";
6642
6643 $info = array("count" => 0,
6644 "vgroup_last_feed" => '',
6645 "unread" => 0,
6646 "disable_cache" => true);
6647
6648 print json_encode($info);
6649
6650 print "]]></headlines-info>";
6651
6652 }
6653
6654 function save_email_address($link, $email) {
6655 // FIXME: implement persistent storage of emails
6656
6657 if (!$_SESSION['stored_emails'])
6658 $_SESSION['stored_emails'] = array();
6659
6660 if (!in_array($email, $_SESSION['stored_emails']))
6661 array_push($_SESSION['stored_emails'], $email);
6662 }
6663
6664 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6665 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6666
6667 $sql_is_cat = bool_to_sql_bool($is_cat);
6668
6669 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6670 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6671 AND owner_uid = " . $owner_uid);
6672
6673 if (db_num_rows($result) == 1) {
6674 $key = db_escape_string(sha1(uniqid(rand(), true)));
6675
6676 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
6677 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6678 AND owner_uid = " . $owner_uid);
6679
6680 return $key;
6681
6682 } else {
6683 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
6684 }
6685 }
6686
6687 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
6688
6689 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
6690
6691 $sql_is_cat = bool_to_sql_bool($is_cat);
6692
6693 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
6694 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
6695 AND owner_uid = " . $owner_uid);
6696
6697 if (db_num_rows($result) == 1) {
6698 return db_fetch_result($result, 0, "access_key");
6699 } else {
6700 $key = db_escape_string(sha1(uniqid(rand(), true)));
6701
6702 $result = db_query($link, "INSERT INTO ttrss_access_keys
6703 (access_key, feed_id, is_cat, owner_uid)
6704 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
6705
6706 return $key;
6707 }
6708 return false;
6709 }
6710
6711 /**
6712 * Extracts RSS/Atom feed URLs from the given HTML URL.
6713 *
6714 * @param string $url HTML page URL
6715 *
6716 * @return array Array of feeds. Key is the full URL, value the title
6717 */
6718 function get_feeds_from_html($url)
6719 {
6720 $url = fix_url($url);
6721 $baseUrl = substr($url, 0, strrpos($url, '/') + 1);
6722
6723 libxml_use_internal_errors(true);
6724
6725 $doc = new DOMDocument();
6726 $doc->loadHTMLFile($url);
6727 $xpath = new DOMXPath($doc);
6728 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
6729 $feedUrls = array();
6730 foreach ($entries as $entry) {
6731 if ($entry->hasAttribute('href')) {
6732 $title = $entry->getAttribute('title');
6733 if ($title == '') {
6734 $title = $entry->getAttribute('type');
6735 }
6736 $feedUrl = rewrite_relative_url(
6737 $baseUrl, $entry->getAttribute('href')
6738 );
6739 $feedUrls[$feedUrl] = $title;
6740 }
6741 }
6742 return $feedUrls;
6743 }
6744
6745 /**
6746 * Checks if the content behind the given URL is a HTML file
6747 *
6748 * @param string $url URL to check
6749 *
6750 * @return boolean True if the URL contains HTML content
6751 */
6752 function url_is_html($url) {
6753 $content = substr(fetch_file_contents($url, false), 0, 1000);
6754 if (stripos($content, '<html>') === false
6755 && stripos($content, '<html ') === false
6756 ) {
6757 return false;
6758 }
6759
6760 return true;
6761 }
6762
6763 function print_label_select($link, $name, $value, $style = "") {
6764
6765 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6766 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6767
6768 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
6769 "\" style=\"$style\" onchange=\"labelSelectOnChange(this)\" >";
6770
6771 while ($line = db_fetch_assoc($result)) {
6772
6773 $issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
6774
6775 print "<option $issel>" . htmlspecialchars($line["caption"]) . "</option>";
6776
6777 }
6778
6779 print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
6780
6781 print "</select>";
6782
6783
6784 }
6785
6786 function print_article_enclosures($link, $id, $always_display_enclosures,
6787 $article_content) {
6788
6789 $result = get_article_enclosures($link, $id);
6790
6791 if (count($result) > 0) {
6792
6793 $entries_html = array();
6794 $entries = array();
6795
6796 foreach ($result as $line) {
6797
6798 $url = $line["content_url"];
6799 $ctype = $line["content_type"];
6800
6801 if (!$ctype) $ctype = __("unknown type");
6802
6803 $filename = substr($url, strrpos($url, "/")+1);
6804
6805 $entry = format_inline_player($link, $url, $ctype);
6806
6807 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
6808 $filename . " (" . $ctype . ")" . "</a>";
6809
6810 array_push($entries_html, $entry);
6811
6812 $entry = array();
6813
6814 $entry["type"] = $ctype;
6815 $entry["filename"] = $filename;
6816 $entry["url"] = $url;
6817
6818 array_push($entries, $entry);
6819 }
6820
6821 print "<div class=\"postEnclosures\">";
6822
6823 if (!get_pref($link, "STRIP_IMAGES")) {
6824 if ($always_display_enclosures ||
6825 !preg_match("/<img/i", $article_content)) {
6826
6827 foreach ($entries as $entry) {
6828
6829 if (preg_match("/image/", $entry["type"]) ||
6830 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
6831
6832 print "<p><img
6833 alt=\"".htmlspecialchars($entry["filename"])."\"
6834 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
6835 }
6836 }
6837 }
6838 }
6839
6840 if (count($entries) == 1) {
6841 print __("Attachment:") . " ";
6842 } else {
6843 print __("Attachments:") . " ";
6844 }
6845
6846 print join(", ", $entries_html);
6847
6848 print "</div>";
6849 }
6850 }
6851
6852 function getLastArticleId($link) {
6853 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
6854 WHERE owner_uid = " . $_SESSION["uid"]);
6855
6856 if (db_num_rows($result) == 1) {
6857 return db_fetch_result($result, 0, "id");
6858 } else {
6859 return -1;
6860 }
6861 }
6862
6863 function build_url($parts) {
6864 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
6865 }
6866
6867 /**
6868 * Converts a (possibly) relative URL to a absolute one.
6869 *
6870 * @param string $url Base URL (i.e. from where the document is)
6871 * @param string $rel_url Possibly relative URL in the document
6872 *
6873 * @return string Absolute URL
6874 */
6875 function rewrite_relative_url($url, $rel_url) {
6876 if (strpos($rel_url, "://") !== false) {
6877 return $rel_url;
6878 } else if (strpos($rel_url, "/") === 0)
6879 {
6880 $parts = parse_url($url);
6881 $parts['path'] = $rel_url;
6882
6883 return build_url($parts);
6884
6885 } else {
6886 $parts = parse_url($url);
6887 if (!isset($parts['path'])) {
6888 $parts['path'] = '/';
6889 }
6890 $dir = $parts['path'];
6891 if (substr($dir, -1) !== '/') {
6892 $dir = dirname($parts['path']);
6893 $dir !== '/' && $dir .= '/';
6894 }
6895 $parts['path'] = $dir . $rel_url;
6896
6897 return build_url($parts);
6898 }
6899 }
6900
6901 function sphinx_search($query, $offset = 0, $limit = 30) {
6902 $sphinxClient = new SphinxClient();
6903
6904 $sphinxClient->SetServer('localhost', 9312);
6905 $sphinxClient->SetConnectTimeout(1);
6906
6907 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
6908 'feed_title' => 20));
6909
6910 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2);
6911 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
6912 $sphinxClient->SetLimits($offset, $limit, 1000);
6913 $sphinxClient->SetArrayResult(false);
6914 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
6915
6916 $result = $sphinxClient->Query($query, SPHINX_INDEX);
6917
6918 $ids = array();
6919
6920 if (is_array($result['matches'])) {
6921 foreach (array_keys($result['matches']) as $int_id) {
6922 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
6923 array_push($ids, $ref_id);
6924 }
6925 }
6926
6927 return $ids;
6928 }
6929
6930 function cleanup_tags($link, $days = 14, $limit = 1000) {
6931
6932 if (DB_TYPE == "pgsql") {
6933 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
6934 } else if (DB_TYPE == "mysql") {
6935 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
6936 }
6937
6938 $tags_deleted = 0;
6939
6940 while ($limit > 0) {
6941 $limit_part = 500;
6942
6943 $query = "SELECT ttrss_tags.id AS id
6944 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
6945 WHERE post_int_id = int_id AND $interval_query AND
6946 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
6947
6948 $result = db_query($link, $query);
6949
6950 $ids = array();
6951
6952 while ($line = db_fetch_assoc($result)) {
6953 array_push($ids, $line['id']);
6954 }
6955
6956 if (count($ids) > 0) {
6957 $ids = join(",", $ids);
6958 print ".";
6959
6960 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
6961 $tags_deleted += db_affected_rows($link, $tmp_result);
6962 } else {
6963 break;
6964 }
6965
6966 $limit -= $limit_part;
6967 }
6968
6969 print "\n";
6970
6971 return $tags_deleted;
6972 }
6973
6974 function feedlist_init_cat($link, $cat_id, $hidden = false) {
6975 $obj = array();
6976 $cat_id = (int) $cat_id;
6977
6978 if ($cat_id > 0) {
6979 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
6980 } else if ($cat_id == 0 || $cat_id == -2) {
6981 $cat_unread = getCategoryUnread($link, $cat_id);
6982 }
6983
6984 $obj['id'] = 'CAT:' . ((int)$cat_id);
6985 $obj['items'] = array();
6986 $obj['name'] = getCategoryTitle($link, $cat_id);
6987 $obj['type'] = 'feed';
6988 $obj['unread'] = (int) $cat_unread;
6989 $obj['hidden'] = $hidden;
6990
6991 return $obj;
6992 }
6993
6994 function feedlist_init_feed($link, $feed_id, $title = false, $unread = false, $error = '', $updated = '') {
6995 $obj = array();
6996
6997 if (!$title)
6998 $title = getFeedTitle($link, $feed_id, false);
6999
7000 if (!$unread)
7001 $unread = getFeedUnread($link, $feed_id, false);
7002
7003 $obj['id'] = 'FEED:' . $feed_id;
7004 $obj['name'] = $title;
7005 $obj['unread'] = (int) $unread;
7006 $obj['type'] = 'feed';
7007 $obj['error'] = $error;
7008 $obj['updated'] = $updated;
7009 $obj['icon'] = getFeedIcon($feed_id);
7010
7011 return $obj;
7012 }
7013
7014?>