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