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