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