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