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