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