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