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