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