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