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