]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
update .gitignore (ignore ctags)
[tt-rss.git] / functions.php
1 <?php
2
3         if ($_REQUEST["debug"]) {
4                 define('DEFAULT_ERROR_LEVEL', E_ALL);
5         }
6
7         require_once 'config.php';
8
9         if (DB_TYPE == "pgsql") {
10                 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
11         } else {
12                 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
13         }
14
15         /**
16          * Return available translations names.
17          * 
18          * @access public
19          * @return array A array of available translations.
20          */
21         function get_translations() {
22                 $tr = array(
23                                         "auto"  => "Detect automatically",                                      
24                                         "ca_CA" => "Català",
25                                         "en_US" => "English",
26                                         "es_ES" => "Español",
27                                         "de_DE" => "Deutsch",
28                                         "fr_FR" => "Français",
29                                         "hu_HU" => "Magyar (Hungarian)",
30                                         "it_IT" => "Italiano",
31                                         "ja_JP" => "日本語 (Japanese)",
32                                         "nb_NO" => "Norwegian bokmål",
33                                         "ru_RU" => "Русский",
34                                         "pt_BR" => "Portuguese/Brazil",
35                                         "zh_CN" => "Simplified Chinese");
36
37                 return $tr;
38         }
39
40         if (ENABLE_TRANSLATIONS == true) { // If translations are enabled.
41                 require_once "lib/accept-to-gettext.php";
42                 require_once "lib/gettext/gettext.inc";
43
44                 function startup_gettext() {
45         
46                         # Get locale from Accept-Language header
47                         $lang = al2gt(array_keys(get_translations()), "text/html");
48
49                         if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
50                                 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
51                         }
52
53                         if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {                               
54                                 $lang = $_COOKIE["ttrss_lang"];
55                         }
56
57                         /* In login action of mobile version */
58                         if ($_POST["language"] && defined('MOBILE_VERSION')) {
59                                 $lang = $_POST["language"];
60                                 $_COOKIE["ttrss_lang"] = $lang;
61                         }
62
63                         if ($lang) {
64                                 if (defined('LC_MESSAGES')) {
65                                         _setlocale(LC_MESSAGES, $lang);
66                                 } else if (defined('LC_ALL')) {
67                                         _setlocale(LC_ALL, $lang);
68                                 } else {
69                                         die("can't setlocale(): please set ENABLE_TRANSLATIONS to false in config.php");
70                                 }
71
72                                 if (defined('MOBILE_VERSION')) {
73                                         _bindtextdomain("messages", "../locale");
74                                 } else {
75                                         _bindtextdomain("messages", "locale");
76                                 }
77
78                                 _textdomain("messages");
79                                 _bind_textdomain_codeset("messages", "UTF-8");
80                         }
81                 }
82
83                 startup_gettext();
84
85         } else { // If translations are enabled.
86                 function __($msg) {
87                         return $msg;
88                 }
89                 function startup_gettext() {
90                         // no-op
91                         return true;
92                 }
93         } // If translations are enabled.
94
95         if (defined('MEMCACHE_SERVER')) {
96                 $memcache = new Memcache;
97                 $memcache->connect(MEMCACHE_SERVER, 11211);
98         }
99
100         require_once 'db-prefs.php';
101         require_once 'compat.php';
102         require_once 'errors.php';
103         require_once 'version.php';
104
105         require_once 'lib/phpmailer/class.phpmailer.php';
106
107         define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
108         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
109         define('MAGPIE_CACHE_AGE', 60*15); // 15 minutes
110
111         require_once "lib/simplepie/simplepie.inc";
112         require_once "lib/magpierss/rss_fetch.inc";
113         require_once 'lib/magpierss/rss_utils.inc';
114         require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
115
116         /**
117          * Print a timestamped debug message.
118          * 
119          * @param string $msg The debug message.
120          * @return void
121          */
122         function _debug($msg) {
123                 $ts = strftime("%H:%M:%S", time());
124                 if (function_exists('posix_getpid')) {
125                         $ts = "$ts/" . posix_getpid();
126                 }
127                 print "[$ts] $msg\n";
128         } // function _debug
129
130         /**
131          * Purge a feed old posts.
132          * 
133          * @param mixed $link A database connection.
134          * @param mixed $feed_id The id of the purged feed.
135          * @param mixed $purge_interval Olderness of purged posts.
136          * @param boolean $debug Set to True to enable the debug. False by default.
137          * @access public
138          * @return void
139          */
140         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
141
142                 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
143                 
144                 $rows = -1;
145
146                 $result = db_query($link, 
147                         "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
148
149                 $owner_uid = false;
150
151                 if (db_num_rows($result) == 1) {
152                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
153                 }
154
155                 if ($purge_interval == -1 || !$purge_interval) {
156                         if ($owner_uid) {
157                                 ccache_update($link, $feed_id, $owner_uid);
158                         }
159                         return;
160                 }
161
162                 if (!$owner_uid) return;
163
164                 if (FORCE_ARTICLE_PURGE == 0) {
165                         $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
166                                 $owner_uid, false);
167                 } else {
168                         $purge_unread = true;
169                         $purge_interval = FORCE_ARTICLE_PURGE;
170                 }
171
172                 if (!$purge_unread) $query_limit = " unread = false AND ";
173
174                 if (DB_TYPE == "pgsql") {
175 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
176                                 marked = false AND feed_id = '$feed_id' AND
177                                 (SELECT date_updated FROM ttrss_entries WHERE
178                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
179
180                         $pg_version = get_pgsql_version($link);
181
182                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
183
184                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE 
185                                         ttrss_entries.id = ref_id AND 
186                                         marked = false AND 
187                                         feed_id = '$feed_id' AND 
188                                         $query_limit
189                                         ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
190
191                         } else {
192
193                                 $result = db_query($link, "DELETE FROM ttrss_user_entries 
194                                         USING ttrss_entries 
195                                         WHERE ttrss_entries.id = ref_id AND 
196                                         marked = false AND 
197                                         feed_id = '$feed_id' AND 
198                                         $query_limit
199                                         ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
200                         }
201
202                         $rows = pg_affected_rows($result);
203                         
204                 } else {
205                 
206 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
207                                 marked = false AND feed_id = '$feed_id' AND
208                                 (SELECT date_updated FROM ttrss_entries WHERE 
209                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
210
211                         $result = db_query($link, "DELETE FROM ttrss_user_entries 
212                                 USING ttrss_user_entries, ttrss_entries 
213                                 WHERE ttrss_entries.id = ref_id AND 
214                                 marked = false AND 
215                                 feed_id = '$feed_id' AND 
216                                 $query_limit
217                                 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
218                                         
219                         $rows = mysql_affected_rows($link);
220
221                 }
222
223                 ccache_update($link, $feed_id, $owner_uid);
224
225                 if ($debug) {
226                         _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
227                 }
228         } // function purge_feed
229
230         /**
231          * Purge old posts from old feeds. Not used anymore, purging is done after feed update.
232          * 
233          * @param mixed $link A database connection
234          * @param boolean $do_output Set to true to enable printed output, false by default.
235          * @param integer $limit The maximal number of removed posts.
236          * @access public
237          * @return void
238          */
239         /* function global_purge_old_posts($link, $do_output = false, $limit = false) {
240
241                 $random_qpart = sql_random_function();
242
243                 if ($limit) {
244                         $limit_qpart = "LIMIT $limit";
245                 } else {
246                         $limit_qpart = "";
247                 }
248                 
249                 $result = db_query($link, 
250                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds 
251                                 ORDER BY $random_qpart $limit_qpart");
252
253                 while ($line = db_fetch_assoc($result)) {
254
255                         $feed_id = $line["id"];
256                         $purge_interval = $line["purge_interval"];
257                         $owner_uid = $line["owner_uid"];
258
259                         if ($purge_interval == 0) {
260                         
261                                 $tmp_result = db_query($link, 
262                                         "SELECT value FROM ttrss_user_prefs WHERE
263                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
264
265                                 if (db_num_rows($tmp_result) != 0) {                    
266                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
267                                 }
268                         }
269
270                         if ($do_output) {
271 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
272                         }
273
274                         if ($purge_interval > 0 || FORCE_ARTICLE_PURGE) {
275                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
276                         }
277                 }       
278
279                 purge_orphans($link, $do_output);
280
281         } // function global_purge_old_posts */
282
283         function feed_purge_interval($link, $feed_id) {
284
285                 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds 
286                         WHERE id = '$feed_id'");
287
288                 if (db_num_rows($result) == 1) {
289                         $purge_interval = db_fetch_result($result, 0, "purge_interval");
290                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
291
292                         if ($purge_interval == 0) $purge_interval = get_pref($link, 
293                                 'PURGE_OLD_DAYS', $owner_uid);
294
295                         return $purge_interval;
296
297                 } else {
298                         return -1;
299                 }
300         }
301
302         function purge_old_posts($link) {
303
304                 $user_id = $_SESSION["uid"];
305         
306                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
307                         WHERE owner_uid = '$user_id'");
308
309                 while ($line = db_fetch_assoc($result)) {
310
311                         $feed_id = $line["id"];
312                         $purge_interval = $line["purge_interval"];
313
314                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
315
316                         if ($purge_interval > 0) {
317                                 purge_feed($link, $feed_id, $purge_interval);
318                         }
319                 }       
320
321                 purge_orphans($link);
322         }
323
324         function purge_orphans($link, $do_output = false) {
325
326                 // purge orphaned posts in main content table
327                 $result = db_query($link, "DELETE FROM ttrss_entries WHERE 
328                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
329
330                 if ($do_output) {
331                         $rows = db_affected_rows($link, $result);
332                         _debug("Purged $rows orphaned posts.");
333                 }
334         }
335
336         function get_feed_update_interval($link, $feed_id) {
337                 $result = db_query($link, "SELECT owner_uid, update_interval FROM
338                         ttrss_feeds WHERE id = '$feed_id'");
339
340                 if (db_num_rows($result) == 1) {
341                         $update_interval = db_fetch_result($result, 0, "update_interval");
342                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
343
344                         if ($update_interval != 0) {
345                                 return $update_interval;
346                         } else {
347                                 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
348                         }
349
350                 } else {
351                         return -1;
352                 }
353         }
354
355         function fetch_file_contents($url, $type) {
356                 if (USE_CURL_FOR_ICONS) {
357                         $ch = curl_init($url);
358
359                         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
360                         curl_setopt($ch, CURLOPT_TIMEOUT, 45);
361                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
362                         curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
363                         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
364                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
365
366                         $contents = curl_exec($ch);
367                         if ($contents === false) {
368                                 curl_close($ch);
369                                 return false;
370                         }
371
372                         $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
373                         curl_close($ch);
374
375                         if ($type && strpos($content_type, "$type") === false) {
376                                 return false;
377                         }
378
379                         return $contents;
380                 } else {
381                         return file_get_contents($url);
382                 }
383
384         }
385
386         /**
387          * Try to determine the favicon URL for a feed.
388          * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
389          * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
390          * 
391          * @param string $url A feed or page URL
392          * @access public
393          * @return mixed The favicon URL, or false if none was found.
394          */
395         function get_favicon_url($url) {
396
397                 if ($html = @fetch_file_contents($url)) {
398
399                         if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
400                                 // Attempt to grab a favicon link from their webpage url
401                                 $linkUrl = html_entity_decode($matches[1]);
402
403                                 if (substr($linkUrl, 0, 1) == '/') {
404                                         $urlParts = parse_url($url);
405                                         $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
406                                 } else if (substr($linkUrl, 0, 7) == 'http://') {
407                                         $faviconURL = $linkUrl;
408                                 } else {
409                                         $pos = strrpos($url, "/");
410                                         // no "/" in url or "/" is part of "://"
411                                         if ($pos === false || $pos == (strpos($url, "://")+2)) {
412                                                 $faviconURL = $url.'/'.$linkUrl;
413                                         } else {
414                                                 $faviconURL = substr($url, 0, $pos+1).$linkUrl;
415                                         }
416                                 }
417
418                         } else {
419                                 // If unsuccessful, attempt to "guess" the favicon location
420                                 $urlParts = parse_url($url);
421                                 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
422                         }
423                 }
424
425                 // Run a test to see if what we have attempted to get actually exists.
426                 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
427                         return $faviconURL;
428                 } else {
429                         return false;
430                 }
431         } // function get_favicon_url
432
433         /**
434          * Check if a link is a valid and working URL.
435          * 
436          * @param mixed $link A URL to check
437          * @access public
438          * @return boolean True if the URL is valid, false otherwise.
439          */
440         function url_validate($link) {
441                 
442                 $url_parts = @parse_url($link);
443
444                 if ( empty( $url_parts["host"] ) )
445                                 return false;
446
447                 if ( !empty( $url_parts["path"] ) ) {
448                                 $documentpath = $url_parts["path"];
449                 } else {
450                                 $documentpath = "/";
451                 }
452
453                 if ( !empty( $url_parts["query"] ) )
454                                 $documentpath .= "?" . $url_parts["query"];
455
456                 $host = $url_parts["host"];
457                 $port = $url_parts["port"];
458                 
459                 if ( empty($port) )
460                                 $port = "80";
461
462                 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
463                 
464                 if ( !$socket )
465                                 return false;
466                                 
467                 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
468
469                 $http_response = fgets( $socket, 22 );
470
471                 $responses = "/(200 OK)|(30[123])/";
472                 if ( preg_match($responses, $http_response) ) {
473                                 fclose($socket);
474                                 return true;
475                 } else {
476                                 return false;
477                 }
478
479         } // function url_validate
480
481         function check_feed_favicon($site_url, $feed, $link) {
482                 $favicon_url = get_favicon_url($site_url);
483
484 #               print "FAVICON [$site_url]: $favicon_url\n";
485
486                 error_reporting(0);
487
488                 $icon_file = ICONS_DIR . "/$feed.ico";
489
490                 if ($favicon_url && !file_exists($icon_file)) {
491                         $contents = fetch_file_contents($favicon_url, "image");
492
493                         if ($contents) {
494                                 $fp = fopen($icon_file, "w");
495
496                                 if ($fp) {
497                                         fwrite($fp, $contents);
498                                         fclose($fp);
499                                         chmod($icon_file, 0644);
500                                 }
501                         }
502                 }
503
504                 error_reporting(DEFAULT_ERROR_LEVEL);
505
506         }
507
508         function update_rss_feed($link, $feed, $ignore_daemon = false) {
509
510                 global $memcache;
511
512                 /* Update all feeds with the same URL to utilize memcache */
513
514                 if ($memcache) {
515                         $result = db_query($link, "SELECT f1.id 
516                                 FROM ttrss_feeds AS f1, ttrss_feeds AS f2 
517                                 WHERE   f2.feed_url = f1.feed_url AND f2.id = '$feed'");
518
519                         while ($line = db_fetch_assoc($result)) {
520                                 update_rss_feed_real($link, $line["id"], $ignore_daemon);
521                         }
522                 } else {
523                         update_rss_feed_real($link, $feed, $ignore_daemon);
524                 }
525         }
526
527         function update_rss_feed_real($link, $feed, $ignore_daemon = false) {
528
529                 global $memcache;
530
531                 if (!$_REQUEST["daemon"] && !$ignore_daemon) {
532                         return false;
533                 }
534
535                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
536                         _debug("update_rss_feed: start");
537                 }
538
539                 if (!$ignore_daemon) {
540
541                         if (DB_TYPE == "pgsql") {
542                                         $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
543                                 } else {
544                                         $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
545                                 }                       
546         
547                         $result = db_query($link, "SELECT id,update_interval,auth_login,
548                                 auth_pass,cache_images,update_method
549                                 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
550
551                 } else {
552
553                         $result = db_query($link, "SELECT id,update_interval,auth_login,
554                                 feed_url,auth_pass,cache_images,update_method,last_updated
555                                 FROM ttrss_feeds WHERE id = '$feed'");
556
557                 }
558
559                 if (db_num_rows($result) == 0) {
560                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
561                                 _debug("update_rss_feed: feed $feed NOT FOUND/SKIPPED");
562                         }               
563                         return false;
564                 }
565
566                 $update_method = db_fetch_result($result, 0, "update_method");
567                 $last_updated = db_fetch_result($result, 0, "last_updated");
568
569                 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
570                         WHERE id = '$feed'");
571
572                 $auth_login = db_fetch_result($result, 0, "auth_login");
573                 $auth_pass = db_fetch_result($result, 0, "auth_pass");
574
575                 if (DEFAULT_UPDATE_METHOD == "1") {
576                         $use_simplepie = $update_method != 1;
577                 } else {
578                         $use_simplepie = $update_method == 2;
579                 }
580
581                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
582                         _debug("use simplepie: $use_simplepie (feed setting: $update_method)\n");
583                 }
584
585                 if (!$use_simplepie) {
586                         $auth_login = urlencode($auth_login);
587                         $auth_pass = urlencode($auth_pass);
588                 }
589
590                 $update_interval = db_fetch_result($result, 0, "update_interval");
591                 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
592                 $fetch_url = db_fetch_result($result, 0, "feed_url");
593
594                 if ($update_interval < 0) { return; }
595
596                 $feed = db_escape_string($feed);
597
598                 if ($auth_login && $auth_pass) {
599                         $url_parts = array();
600                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
601
602                         if ($url_parts[1] && $url_parts[2]) {
603                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
604                         }
605
606                 }
607
608                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
609                         _debug("update_rss_feed: fetching [$fetch_url]...");
610                 }
611
612                 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_REQUEST['xdebug']) {
613                         error_reporting(0);
614                 }
615
616                 $obj_id = md5("FDATA:$use_simplepie:$fetch_url");
617
618                 if ($memcache && $obj = $memcache->get($obj_id)) {
619
620                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
621                                 _debug("update_rss_feed: data found in memcache.");
622                         }
623
624                         $rss = $obj;
625
626                 } else {
627
628                         if (!$use_simplepie) {
629                                 $rss = fetch_rss($fetch_url);
630                         } else {
631                                 if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
632                                         mkdir(SIMPLEPIE_CACHE_DIR);
633                                 }
634         
635                                 $rss = new SimplePie();
636                                 $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
637         #                       $rss->set_timeout(10);
638                                 $rss->set_feed_url($fetch_url);
639                                 $rss->set_output_encoding('UTF-8');
640         
641                                 if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
642                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
643                                                 _debug("enabling image cache");
644                                         }
645         
646                                         $rss->set_image_handler('./image.php', 'i');
647                                 }
648         
649                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
650                                         _debug("feed update interval (sec): " .
651                                                 get_feed_update_interval($link, $feed)*60);
652                                 }
653         
654                                 if (is_dir(SIMPLEPIE_CACHE_DIR)) {
655                                         $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
656                                         $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
657                                 }
658         
659                                 $rss->init();
660                         }
661
662                         if ($memcache && $rss) $memcache->add($obj_id, $rss, 0, 300);
663                 }
664
665 //              print_r($rss);
666
667                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
668                         _debug("update_rss_feed: fetch done, parsing...");
669                 } else {
670                         error_reporting (DEFAULT_ERROR_LEVEL);
671                 }
672
673                 $feed = db_escape_string($feed);
674
675                 if ($use_simplepie) {
676                         $fetch_ok = !$rss->error();
677                 } else {
678                         $fetch_ok = !!$rss;
679                 }
680
681                 if ($fetch_ok) {
682
683                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
684                                 _debug("update_rss_feed: processing feed data...");
685                         }
686
687 //                      db_query($link, "BEGIN");
688
689                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
690                                 FROM ttrss_feeds WHERE id = '$feed'");
691
692                         $registered_title = db_fetch_result($result, 0, "title");
693                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
694                         $orig_site_url = db_fetch_result($result, 0, "site_url");
695
696                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
697
698                         if ($use_simplepie) {
699                                 $site_url = $rss->get_link();
700                         } else {
701                                 $site_url = $rss->channel["link"];
702                         }
703
704                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
705                                 _debug("update_rss_feed: checking favicon...");
706                         }
707
708                         check_feed_favicon($site_url, $feed, $link);
709
710                         if (!$registered_title || $registered_title == "[Unknown]") {
711
712                                 if ($use_simplepie) {
713                                         $feed_title = db_escape_string($rss->get_title());
714                                 } else {
715                                         $feed_title = db_escape_string($rss->channel["title"]);
716                                 }
717
718                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
719                                         _debug("update_rss_feed: registering title: $feed_title");
720                                 }
721                                 
722                                 db_query($link, "UPDATE ttrss_feeds SET 
723                                         title = '$feed_title' WHERE id = '$feed'");
724                         }
725
726                         // weird, weird Magpie
727                         if (!$use_simplepie) {
728                                 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
729                         }
730
731                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
732                                 db_query($link, "UPDATE ttrss_feeds SET 
733                                         site_url = '$site_url' WHERE id = '$feed'");
734                         }
735
736 //                      print "I: " . $rss->channel["image"]["url"];
737
738                         if (!$use_simplepie) {
739                                 $icon_url = $rss->image["url"];
740                         } else {
741                                 $icon_url = $rss->get_image_url();
742                         }
743
744                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
745                                 $icon_url = db_escape_string($icon_url);
746                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
747                         }
748
749                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
750                                 _debug("update_rss_feed: loading filters...");
751                         }
752
753                         $filters = load_filters($link, $feed, $owner_uid);
754
755                         if ($use_simplepie) {
756                                 $iterator = $rss->get_items();
757                         } else {
758                                 $iterator = $rss->items;
759                                 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
760                                 if (!$iterator || !is_array($iterator)) $iterator = $rss;
761                         }
762
763                         if (!is_array($iterator)) {
764                                 /* db_query($link, "UPDATE ttrss_feeds 
765                                         SET last_error = 'Parse error: can\'t find any articles.'
766                                         WHERE id = '$feed'"); */
767
768                                 // clear any errors and mark feed as updated if fetched okay
769                                 // even if it's blank
770
771                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
772                                         _debug("update_rss_feed: entry iterator is not an array, no articles?");
773                                 }
774
775                                 db_query($link, "UPDATE ttrss_feeds 
776                                         SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
777
778                                 return; // no articles
779                         }
780
781                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
782                                 _debug("update_rss_feed: processing articles...");
783                         }
784
785                         foreach ($iterator as $item) {
786
787                                 if ($_REQUEST['xdebug'] == 2) {
788                                         print_r($item);
789                                 }
790
791                                 if ($use_simplepie) {
792                                         $entry_guid = $item->get_id();
793                                         if (!$entry_guid) $entry_guid = $item->get_link();
794                                         if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
795
796                                 } else {
797
798                                         $entry_guid = $item["id"];
799
800                                         if (!$entry_guid) $entry_guid = $item["guid"];
801                                         if (!$entry_guid) $entry_guid = $item["link"];
802                                         if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
803                                 }
804
805                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
806                                         _debug("update_rss_feed: guid $entry_guid");
807                                 }
808
809                                 if (!$entry_guid) continue;
810
811                                 $entry_timestamp = "";
812
813                                 if ($use_simplepie) {
814                                         $entry_timestamp = strtotime($item->get_date());
815                                 } else {
816                                         $rss_2_date = $item['pubdate'];
817                                         $rss_1_date = $item['dc']['date'];
818                                         $atom_date = $item['issued'];
819                                         if (!$atom_date) $atom_date = $item['updated'];
820
821                                         if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
822                                         if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
823                                         if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
824
825                                 }
826
827                                 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
828                                         $entry_timestamp = time();
829                                         $no_orig_date = 'true';
830                                 } else {
831                                         $no_orig_date = 'false';
832                                 }
833
834                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
835
836                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
837                                         _debug("update_rss_feed: date $entry_timestamp [$entry_timestamp_fmt]");
838                                 }
839
840                                 if ($use_simplepie) {
841                                         $entry_title = $item->get_title();
842                                 } else {
843                                         $entry_title = trim(strip_tags($item["title"]));
844                                 }
845
846                                 if ($use_simplepie) {
847                                         $entry_link = $item->get_link();
848                                 } else {
849                                         // strange Magpie workaround
850                                         $entry_link = $item["link_"];
851                                         if (!$entry_link) $entry_link = $item["link"];
852                                 }
853
854                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
855                                         _debug("update_rss_feed: title $entry_title");
856                                 }
857
858                                 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
859
860                                 $entry_link = strip_tags($entry_link);
861
862                                 if ($use_simplepie) {
863                                         $entry_content = $item->get_content();
864                                         if (!$entry_content) $entry_content = $item->get_description();
865                                 } else {
866                                         $entry_content = $item["content:escaped"];
867
868                                         if (!$entry_content) $entry_content = $item["content:encoded"];
869                                         if (!$entry_content) $entry_content = $item["content"]["encoded"];
870                                         if (!$entry_content) $entry_content = $item["content"];
871
872                                         // Magpie bugs are getting ridiculous
873                                         if (trim($entry_content) == "Array") $entry_content = false;
874
875                                         if (!$entry_content) $entry_content = $item["atom_content"];
876                                         if (!$entry_content) $entry_content = $item["summary"];
877
878                                         if (!$entry_content || 
879                                                 strlen($entry_content) < strlen($item["description"])) {
880                                                         $entry_content = $item["description"];
881                                         };
882
883                                         // WTF
884                                         if (is_array($entry_content)) {
885                                                 $entry_content = $entry_content["encoded"];
886                                                 if (!$entry_content) $entry_content = $entry_content["escaped"];
887                                         } 
888                                 }
889
890                                 if ($_REQUEST["xdebug"] == 2) {
891                                         print "update_rss_feed: content: ";
892                                         print_r(htmlspecialchars($entry_content));
893                                 }
894
895                                 $entry_content_unescaped = $entry_content;
896
897                                 if ($use_simplepie) {
898                                         $entry_comments = strip_tags($item->data["comments"]);
899                                         if ($item->get_author()) {
900                                                 $entry_author_item = $item->get_author();
901                                                 $entry_author = $entry_author_item->get_name();
902                                                 if (!$entry_author) $entry_author = $entry_author_item->get_email();
903
904                                                 $entry_author = db_escape_string($entry_author);
905                                         }
906                                 } else {
907                                         $entry_comments = strip_tags($item["comments"]);
908                                 
909                                         $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
910
911                                         if ($item['author']) {
912         
913                                                 if (is_array($item['author'])) {
914         
915                                                         if (!$entry_author) {
916                                                                 $entry_author = db_escape_string(strip_tags($item['author']['name']));
917                                                         }
918         
919                                                         if (!$entry_author) {
920                                                                 $entry_author = db_escape_string(strip_tags($item['author']['email']));
921                                                         }
922                                                 }
923         
924                                                 if (!$entry_author) {
925                                                         $entry_author = db_escape_string(strip_tags($item['author']));
926                                                 }
927                                         }
928                                 }
929
930                                 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
931
932                                 $entry_guid = db_escape_string(strip_tags($entry_guid));
933                                 $entry_guid = mb_substr($entry_guid, 0, 250);
934
935                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
936                                         WHERE guid = '$entry_guid'");
937
938                                 $entry_content = db_escape_string($entry_content);
939
940                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
941
942                                 $entry_title = db_escape_string($entry_title);
943                                 $entry_link = db_escape_string($entry_link);
944                                 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
945                                 $entry_author = mb_substr($entry_author, 0, 250);
946
947                                 if ($use_simplepie) {
948                                         $num_comments = 0; #FIXME#
949                                 } else {
950                                         $num_comments = db_escape_string($item["slash"]["comments"]);
951                                 }
952
953                                 if (!$num_comments) $num_comments = 0;
954
955                                 // parse <category> entries into tags
956
957                                 if ($use_simplepie) {
958
959                                         $additional_tags = array();
960                                         $additional_tags_src = $item->get_categories();
961                                         
962                                         if (is_array($additional_tags_src)) {
963                                                 foreach ($additional_tags_src as $tobj) {
964                                                         array_push($additional_tags, $tobj->get_term());
965                                                 }
966                                         }
967
968                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
969                                                 _debug("update_rss_feed: category tags:");
970                                                 print_r($additional_tags);
971                                         }
972
973                                 } else {
974
975                                         $t_ctr = $item['category#'];
976
977                                         $additional_tags = false;
978         
979                                         if ($t_ctr == 0) {
980                                                 $additional_tags = false;
981                                         } else if ($t_ctr > 0) {
982                                                 $additional_tags = array($item['category']);
983
984                                                 if ($item['category@term']) {
985                                                         array_push($additional_tags, $item['category@term']);
986                                                 }
987
988                                                 for ($i = 0; $i <= $t_ctr; $i++ ) {
989                                                         if ($item["category#$i"]) {
990                                                                 array_push($additional_tags, $item["category#$i"]);
991                                                         }
992
993                                                         if ($item["category#$i@term"]) {
994                                                                 array_push($additional_tags, $item["category#$i@term"]);
995                                                         }
996                                                 }
997                                         }
998         
999                                         // parse <dc:subject> elements
1000         
1001                                         $t_ctr = $item['dc']['subject#'];
1002         
1003                                         if ($t_ctr > 0) {
1004                                                 $additional_tags = array($item['dc']['subject']);
1005
1006                                                 for ($i = 0; $i <= $t_ctr; $i++ ) {
1007                                                         if ($item['dc']["subject#$i"]) {
1008                                                                 array_push($additional_tags, $item['dc']["subject#$i"]);
1009                                                         }
1010                                                 }
1011                                         }
1012                                 }
1013
1014                                 // enclosures
1015
1016                                 $enclosures = array();
1017
1018                                 if ($use_simplepie) {
1019                                         $encs = $item->get_enclosures();
1020
1021                                         if (is_array($encs)) {
1022                                                 foreach ($encs as $e) {
1023                                                         $e_item = array(
1024                                                                 $e->link, $e->type, $e->length);
1025         
1026                                                         array_push($enclosures, $e_item);
1027                                                 }
1028                                         }
1029
1030                                 } else {
1031                                         // <enclosure>
1032
1033                                         $e_ctr = $item['enclosure#'];
1034
1035                                         if ($e_ctr > 0) {
1036                                                 $e_item = array($item['enclosure@url'],
1037                                                         $item['enclosure@type'],
1038                                                         $item['enclosure@length']);
1039
1040                                                 array_push($enclosures, $e_item);
1041
1042                                                 for ($i = 0; $i <= $e_ctr; $i++ ) {
1043
1044                                                         if ($item["enclosure#$i@url"]) {
1045                                                                 $e_item = array($item["enclosure#$i@url"],
1046                                                                         $item["enclosure#$i@type"],
1047                                                                         $item["enclosure#$i@length"]);
1048                                                                 array_push($enclosures, $e_item);
1049                                                         }
1050                                                 }
1051                                         }
1052
1053                                         // <media:content>
1054                                         // can there be many of those? yes -fox
1055
1056                                         $m_ctr = $item['media']['content#'];
1057
1058                                         if ($m_ctr > 0) {
1059                                                 $e_item = array($item['media']['content@url'],
1060                                                         $item['media']['content@medium'],
1061                                                         $item['media']['content@length']);
1062
1063                                                 array_push($enclosures, $e_item);
1064
1065                                                 for ($i = 0; $i <= $m_ctr; $i++ ) {
1066
1067                                                         if ($item["media"]["content#$i@url"]) {
1068                                                                 $e_item = array($item["media"]["content#$i@url"],
1069                                                                         $item["media"]["content#$i@medium"],
1070                                                                         $item["media"]["content#$i@length"]);
1071                                                                 array_push($enclosures, $e_item);
1072                                                         }
1073                                                 }
1074
1075                                         }
1076                                 }
1077
1078                                 # sanitize content
1079                                 
1080                                 $entry_content = sanitize_article_content($entry_content);
1081                                 $entry_title = sanitize_article_content($entry_title);
1082
1083                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1084                                         _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
1085                                 }
1086
1087                                 db_query($link, "BEGIN");
1088
1089                                 if (db_num_rows($result) == 0) {
1090
1091                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1092                                                 _debug("update_rss_feed: base guid not found");
1093                                         }
1094
1095                                         // base post entry does not exist, create it
1096
1097                                         $result = db_query($link,
1098                                                 "INSERT INTO ttrss_entries 
1099                                                         (title,
1100                                                         guid,
1101                                                         link,
1102                                                         updated,
1103                                                         content,
1104                                                         content_hash,
1105                                                         no_orig_date,
1106                                                         date_updated,
1107                                                         date_entered,
1108                                                         comments,
1109                                                         num_comments,
1110                                                         author)
1111                                                 VALUES
1112                                                         ('$entry_title', 
1113                                                         '$entry_guid', 
1114                                                         '$entry_link',
1115                                                         '$entry_timestamp_fmt', 
1116                                                         '$entry_content', 
1117                                                         '$content_hash',
1118                                                         $no_orig_date, 
1119                                                         NOW(),
1120                                                         NOW(),
1121                                                         '$entry_comments',
1122                                                         '$num_comments',
1123                                                         '$entry_author')");
1124                                 } else {
1125                                         // we keep encountering the entry in feeds, so we need to
1126                                         // update date_updated column so that we don't get horrible
1127                                         // dupes when the entry gets purged and reinserted again e.g.
1128                                         // in the case of SLOW SLOW OMG SLOW updating feeds
1129
1130                                         $base_entry_id = db_fetch_result($result, 0, "id");
1131
1132                                         db_query($link, "UPDATE ttrss_entries SET date_updated = NOW()
1133                                                 WHERE id = '$base_entry_id'");
1134                                 }
1135
1136                                 // now it should exist, if not - bad luck then
1137
1138                                 $result = db_query($link, "SELECT 
1139                                                 id,content_hash,no_orig_date,title,
1140                                                 ".SUBSTRING_FOR_DATE."(date_updated,1,19) as date_updated,
1141                                                 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated,
1142                                                 num_comments
1143                                         FROM 
1144                                                 ttrss_entries 
1145                                         WHERE guid = '$entry_guid'");
1146
1147                                 $entry_ref_id = 0;
1148                                 $entry_int_id = 0;
1149
1150                                 if (db_num_rows($result) == 1) {
1151
1152                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1153                                                 _debug("update_rss_feed: base guid found, checking for user record");
1154                                         }
1155
1156                                         // this will be used below in update handler
1157                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1158                                         $orig_title = db_fetch_result($result, 0, "title");
1159                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1160                                         $orig_date_updated = strtotime(db_fetch_result($result, 
1161                                                 0, "date_updated"));
1162
1163                                         $ref_id = db_fetch_result($result, 0, "id");
1164                                         $entry_ref_id = $ref_id;
1165
1166                                         // check for user post link to main table
1167
1168                                         // do we allow duplicate posts with same GUID in different feeds?
1169                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1170                                                 $dupcheck_qpart = "AND (feed_id = '$feed' OR feed_id IS NULL)";
1171                                         } else { 
1172                                                 $dupcheck_qpart = "";
1173                                         }
1174
1175 //                                      error_reporting(0);
1176
1177                                         $article_filters = get_article_filters($filters, $entry_title, 
1178                                                         $entry_content, $entry_link, $entry_timestamp, $entry_author);
1179
1180                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1181                                                 _debug("update_rss_feed: article filters: ");
1182                                                 if (count($article_filters) != 0) {
1183                                                         print_r($article_filters);
1184                                                 }
1185                                         }
1186
1187                                         if (find_article_filter($article_filters, "filter")) {
1188                                                 db_query($link, "COMMIT"); // close transaction in progress
1189                                                 continue;
1190                                         }
1191
1192 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
1193
1194                                         $score = calculate_article_score($article_filters);
1195
1196                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1197                                                 _debug("update_rss_feed: initial score: $score");
1198                                         }
1199
1200                                         $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1201                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1202                                                         $dupcheck_qpart";
1203
1204 //                                      if ($_REQUEST["xdebug"]) print "$query\n";
1205
1206                                         $result = db_query($link, $query);
1207
1208                                         // okay it doesn't exist - create user entry
1209                                         if (db_num_rows($result) == 0) {
1210
1211                                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1212                                                         _debug("update_rss_feed: user record not found, creating...");
1213                                                 }
1214
1215                                                 if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
1216                                                         $unread = 'true';
1217                                                         $last_read_qpart = 'NULL';
1218                                                 } else {
1219                                                         $unread = 'false';
1220                                                         $last_read_qpart = 'NOW()';
1221                                                 }                                               
1222
1223                                                 if (find_article_filter($article_filters, 'mark') || $score > 1000) {
1224                                                         $marked = 'true';
1225                                                 } else {
1226                                                         $marked = 'false';
1227                                                 }
1228
1229                                                 if (find_article_filter($article_filters, 'publish')) {
1230                                                         $published = 'true';
1231                                                 } else {
1232                                                         $published = 'false';
1233                                                 }
1234
1235                                                 $result = db_query($link,
1236                                                         "INSERT INTO ttrss_user_entries 
1237                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked, 
1238                                                                         published, score) 
1239                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1240                                                                 $last_read_qpart, $marked, $published, '$score')");
1241
1242                                                 $result = db_query($link, 
1243                                                         "SELECT int_id FROM ttrss_user_entries WHERE
1244                                                                 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1245                                                                 feed_id = '$feed' LIMIT 1");
1246
1247                                                 if (db_num_rows($result) == 1) {
1248                                                         $entry_int_id = db_fetch_result($result, 0, "int_id");
1249                                                 }
1250                                         } else {
1251                                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1252                                                         _debug("update_rss_feed: user record FOUND");
1253                                                 }
1254
1255                                                 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1256                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
1257                                         }
1258
1259                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1260                                                 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1261                                         }
1262
1263                                         $post_needs_update = false;
1264
1265                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1266                                                 ($content_hash != $orig_content_hash)) {
1267 //                                              print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1268                                                 $post_needs_update = true;
1269                                         }
1270
1271                                         if (db_escape_string($orig_title) != $entry_title) {
1272                                                 $post_needs_update = true;
1273                                         }
1274
1275                                         if ($orig_num_comments != $num_comments) {
1276                                                 $post_needs_update = true;
1277                                         }
1278
1279 //                                      this doesn't seem to be very reliable
1280 //
1281 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1282 //                                              $post_needs_update = true;
1283 //                                      }
1284
1285                                         // if post needs update, update it and mark all user entries 
1286                                         // linking to this post as updated                                      
1287                                         if ($post_needs_update) {
1288
1289                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
1290                                                         _debug("update_rss_feed: post $entry_guid needs update...");
1291                                                 }
1292
1293 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
1294
1295                                                 db_query($link, "UPDATE ttrss_entries 
1296                                                         SET title = '$entry_title', content = '$entry_content',
1297                                                                 content_hash = '$content_hash',
1298                                                                 num_comments = '$num_comments'
1299                                                         WHERE id = '$ref_id'");
1300
1301                                                 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1302                                                         db_query($link, "UPDATE ttrss_user_entries 
1303                                                                 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1304                                                 } else {
1305                                                         db_query($link, "UPDATE ttrss_user_entries 
1306                                                                 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1307                                                 }
1308
1309                                         }
1310                                 }
1311
1312                                 db_query($link, "COMMIT");
1313
1314                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1315                                         _debug("update_rss_feed: assigning labels...");
1316                                 }
1317
1318                                 assign_article_to_labels($link, $entry_ref_id, $article_filters,
1319                                         $owner_uid);
1320
1321                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1322                                         _debug("update_rss_feed: looking for enclosures...");
1323                                 }
1324
1325                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1326                                         print_r($enclosures);
1327                                 }
1328
1329                                 db_query($link, "BEGIN");
1330
1331                                 foreach ($enclosures as $enc) {
1332                                         $enc_url = db_escape_string($enc[0]);
1333                                         $enc_type = db_escape_string($enc[1]);
1334                                         $enc_dur = db_escape_string($enc[2]);
1335
1336                                         $result = db_query($link, "SELECT id FROM ttrss_enclosures
1337                                                 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1338
1339                                         if (db_num_rows($result) == 0) {
1340                                                 db_query($link, "INSERT INTO ttrss_enclosures
1341                                                         (content_url, content_type, title, duration, post_id) VALUES
1342                                                         ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1343                                         }
1344                                 }
1345
1346                                 db_query($link, "COMMIT");
1347
1348                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1349                                         _debug("update_rss_feed: looking for tags...");
1350                                 }
1351
1352                                 /* taaaags */
1353                                 // <a href="..." rel="tag">Xorg</a>, //
1354
1355                                 $entry_tags = null;
1356
1357                                 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i", 
1358                                         $entry_content_unescaped, $entry_tags);
1359
1360 /*                              print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1361                                 print_r($entry_tags);
1362                                 print "<br/></p>"; */
1363
1364                                 $entry_tags = $entry_tags[1];
1365
1366                                 # check for manual tags
1367
1368                                 foreach ($article_filters as $f) {
1369                                         if ($f[0] == "tag") {
1370
1371                                                 $manual_tags = trim_array(split(",", $f[1]));
1372
1373                                                 foreach ($manual_tags as $tag) {
1374                                                         if (tag_is_valid($tag)) {
1375                                                                 array_push($entry_tags, $tag);
1376                                                         }
1377                                                 }
1378                                         }
1379                                 }
1380
1381                                 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link, 
1382                                         'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1383
1384                                 if ($additional_tags && is_array($additional_tags)) {
1385                                         foreach ($additional_tags as $tag) {
1386                                                 if (tag_is_valid($tag) && 
1387                                                                 array_search($tag, $boring_tags) === FALSE) {
1388                                                         array_push($entry_tags, $tag);
1389                                                 }
1390                                         }
1391                                 } 
1392
1393 //                              print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1394
1395                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1396                                         print_r($entry_tags);
1397                                 }
1398
1399                                 if (count($entry_tags) > 0) {
1400                                 
1401                                         db_query($link, "BEGIN");
1402                         
1403                                                 foreach ($entry_tags as $tag) {
1404
1405                                                         $tag = sanitize_tag($tag);
1406                                                         $tag = db_escape_string($tag);
1407
1408                                                         if (!tag_is_valid($tag)) continue;
1409                                                         
1410                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
1411                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
1412                                                                 owner_uid = '$owner_uid' LIMIT 1");
1413         
1414         //                                              print db_fetch_result($result, 0, "id");
1415         
1416                                                         if ($result && db_num_rows($result) == 0) {
1417                                                                 
1418                                                                 db_query($link, "INSERT INTO ttrss_tags 
1419                                                                         (owner_uid,tag_name,post_int_id)
1420                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
1421                                                         }                                                       
1422                                                 }
1423
1424                                         db_query($link, "COMMIT");
1425                                 } 
1426
1427                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1428                                         _debug("update_rss_feed: article processed");
1429                                 }
1430                         } 
1431
1432                         if (!$last_updated) {
1433                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1434                                         _debug("update_rss_feed: new feed, catching it up...");
1435                                 }
1436                                 catchup_feed($link, $feed, false, $owner_uid);
1437                         }
1438
1439                         purge_feed($link, $feed, 0);
1440
1441                         db_query($link, "UPDATE ttrss_feeds 
1442                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1443
1444 //                      db_query($link, "COMMIT");
1445
1446                 } else {
1447
1448                         if ($use_simplepie) {
1449                                 $error_msg = mb_substr($rss->error(), 0, 250);
1450                         } else {
1451                                 $error_msg = mb_substr(magpie_error(), 0, 250);
1452                         }
1453
1454                         if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1455                                 _debug("update_rss_feed: error fetching feed: $error_msg");
1456                         }
1457
1458                         $error_msg = db_escape_string($error_msg);
1459
1460                         db_query($link, 
1461                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
1462                                         last_updated = NOW() WHERE id = '$feed'");
1463                 }
1464
1465                 if ($use_simplepie) {
1466                         unset($rss);
1467                 }
1468
1469                 if (defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug']) {
1470                         _debug("update_rss_feed: done");
1471                 }
1472
1473         }
1474
1475         function print_select($id, $default, $values, $attributes = "") {
1476                 print "<select name=\"$id\" id=\"$id\" $attributes>";
1477                 foreach ($values as $v) {
1478                         if ($v == $default)
1479                                 $sel = " selected";
1480                          else
1481                                 $sel = "";
1482                         
1483                         print "<option$sel>$v</option>";
1484                 }
1485                 print "</select>";
1486         }
1487
1488         function print_select_hash($id, $default, $values, $attributes = "") {
1489                 print "<select name=\"$id\" id='$id' $attributes>";
1490                 foreach (array_keys($values) as $v) {
1491                         if ($v == $default)
1492                                 $sel = 'selected="selected"';
1493                          else
1494                                 $sel = "";
1495                         
1496                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
1497                 }
1498
1499                 print "</select>";
1500         }
1501
1502         function get_article_filters($filters, $title, $content, $link, $timestamp, $author) {
1503                 $matches = array();
1504
1505                 if ($filters["title"]) {
1506                         foreach ($filters["title"] as $filter) {
1507                                 $reg_exp = $filter["reg_exp"];          
1508                                 $inverse = $filter["inverse"];  
1509                                 if ((!$inverse && preg_match("/$reg_exp/i", $title)) || 
1510                                                 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1511
1512                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1513                                 }
1514                         }
1515                 }
1516
1517                 if ($filters["content"]) {
1518                         foreach ($filters["content"] as $filter) {
1519                                 $reg_exp = $filter["reg_exp"];
1520                                 $inverse = $filter["inverse"];
1521
1522                                 if ((!$inverse && preg_match("/$reg_exp/i", $content)) || 
1523                                                 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1524
1525                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1526                                 }               
1527                         }
1528                 }
1529
1530                 if ($filters["both"]) {
1531                         foreach ($filters["both"] as $filter) {                 
1532                                 $reg_exp = $filter["reg_exp"];          
1533                                 $inverse = $filter["inverse"];
1534
1535                                 if ($inverse) {
1536                                         if (!preg_match("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
1537                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1538                                         }
1539                                 } else {
1540                                         if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1541                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1542                                         }
1543                                 }
1544                         }
1545                 }
1546
1547                 if ($filters["link"]) {
1548                         $reg_exp = $filter["reg_exp"];
1549                         foreach ($filters["link"] as $filter) {
1550                                 $reg_exp = $filter["reg_exp"];
1551                                 $inverse = $filter["inverse"];
1552
1553                                 if ((!$inverse && preg_match("/$reg_exp/i", $link)) || 
1554                                                 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1555                                                 
1556                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1557                                 }
1558                         }
1559                 }
1560
1561                 if ($filters["date"]) {
1562                         $reg_exp = $filter["reg_exp"];
1563                         foreach ($filters["date"] as $filter) {
1564                                 $date_modifier = $filter["filter_param"];
1565                                 $inverse = $filter["inverse"];
1566                                 $check_timestamp = strtotime($filter["reg_exp"]);
1567
1568                                 # no-op when timestamp doesn't parse to prevent misfires
1569
1570                                 if ($check_timestamp) {
1571                                         $match_ok = false;
1572
1573                                         if ($date_modifier == "before" && $timestamp < $check_timestamp ||
1574                                                 $date_modifier == "after" && $timestamp > $check_timestamp) {
1575                                                         $match_ok = true;
1576                                         }
1577
1578                                         if ($inverse) $match_ok = !$match_ok;
1579
1580                                         if ($match_ok) {
1581                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1582                                         }
1583                                 }
1584                         }
1585                 } 
1586
1587                 if ($filters["author"]) {
1588                         foreach ($filters["author"] as $filter) {
1589                                 $reg_exp = $filter["reg_exp"];          
1590                                 $inverse = $filter["inverse"];  
1591                                 if ((!$inverse && preg_match("/$reg_exp/i", $author)) || 
1592                                                 ($inverse && !preg_match("/$reg_exp/i", $author))) {
1593
1594                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1595                                 }
1596                         }
1597                 }
1598
1599                 return $matches;
1600         }
1601
1602         function find_article_filter($filters, $filter_name) {
1603                 foreach ($filters as $f) {
1604                         if ($f[0] == $filter_name) {
1605                                 return $f;
1606                         };
1607                 }
1608                 return false;
1609         }
1610
1611         function calculate_article_score($filters) {
1612                 $score = 0;
1613
1614                 foreach ($filters as $f) {
1615                         if ($f[0] == "score") {
1616                                 $score += $f[1];
1617                         };
1618                 }
1619                 return $score;
1620         }
1621
1622         function assign_article_to_labels($link, $id, $filters, $owner_uid) {
1623                 foreach ($filters as $f) {
1624                         if ($f[0] == "label") {
1625                                 label_add_article($link, $id, $f[1], $owner_uid);
1626                         };
1627                 }
1628         }
1629
1630         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1631                 $rtl_content = false, $last_updated = false, $last_error = false,
1632                 $fg_content = false, $bg_content = false) {
1633
1634                 if (!$feed_title) $feed_title = getFeedTitle($link, $feed_id, false);
1635                 if (!$unread) $unread = getFeedUnread($link, $feed_id); 
1636
1637                 if ($unread > 0) $class .= "Unread";
1638
1639                 if (!$icon_file) $icon_file = getFeedIcon($feed_id);
1640
1641                 if (strpos($icon_file, "images") !== false) {
1642                         $icon_file = theme_image($link, $icon_file);
1643                 }
1644
1645                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1646                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1647                 } else {
1648                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1649                 }
1650
1651                 if ($rtl_content) {
1652                         $rtl_tag = "dir=\"rtl\"";
1653                 } else {
1654                         $rtl_tag = "dir=\"ltr\"";
1655                 }
1656
1657                 $error_notify_msg = "";
1658                 
1659                 if ($last_error) {
1660                         $link_title = "Error: $last_error ($last_updated)";
1661                         $error_notify_msg = "(Error)";
1662                 } else if ($last_updated) {
1663                         $link_title = "Updated: $last_updated";
1664                 }
1665
1666                 $feed = "<span class='feedlink' title=\"$link_title\" id=\"FEEDL-$feed_id\" href=\"#\"
1667                         onclick=\"viewfeed('$feed_id');\">$feed_title</span>";
1668
1669 /*              if ($feed_id < -10) {
1670                         $bg_color = "#00ccff";
1671                         $fg_color = "white";
1672                 }
1673
1674                 if ($fg_color || $bg_color) {
1675                         $color_str = "<div class='labelColorIndicator'
1676                                 style='color : $fg_color; background-color : $bg_color'>l</div>";
1677                 } 
1678
1679                 print $color_str; */
1680
1681                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1682                 print "$feed_icon";
1683                 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1684
1685                 if ($unread != 0) {
1686                         $fctr_class = "class=\"feedCtrHasUnread\"";
1687                 } else {
1688                         $fctr_class = "class=\"feedCtrNoUnread\"";
1689                 }
1690
1691                 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1692                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1693
1694                 if (get_pref($link, "EXTENDED_FEEDLIST")) {                      
1695                         $total = getFeedArticles($link, $feed_id);
1696                         print "<div class=\"feedExtInfo\">
1697                                 <span id=\"FLUPD-$feed_id\">$last_updated ($total total) $error_notify_msg</span></div>";
1698                 }
1699
1700                 print "</li>";
1701
1702         }
1703
1704         function getmicrotime() {
1705                 list($usec, $sec) = explode(" ",microtime());
1706                 return ((float)$usec + (float)$sec);
1707         }
1708
1709         function print_radio($id, $default, $true_is, $values, $attributes = "") {
1710                 foreach ($values as $v) {
1711                 
1712                         if ($v == $default)
1713                                 $sel = "checked";
1714                          else
1715                                 $sel = "";
1716
1717                         if ($v == $true_is) {
1718                                 $sel .= " value=\"1\"";
1719                         } else {
1720                                 $sel .= " value=\"0\"";
1721                         }
1722                         
1723                         print "<input class=\"noborder\" 
1724                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1725
1726                 }
1727         }
1728
1729         function initialize_user_prefs($link, $uid, $profile = false) {
1730
1731                 $uid = db_escape_string($uid);
1732
1733                 if (!$profile) {
1734                         $profile = "NULL";
1735                         $profile_qpart = "AND profile IS NULL";
1736                 } else {
1737                         $profile_qpart = "AND profile = '$profile'";
1738                 }
1739
1740                 if (get_schema_version($link) < 63) $profile_qpart = "";
1741
1742                 db_query($link, "BEGIN");
1743
1744                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1745                 
1746                 $u_result = db_query($link, "SELECT pref_name 
1747                         FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
1748
1749                 $active_prefs = array();
1750
1751                 while ($line = db_fetch_assoc($u_result)) {
1752                         array_push($active_prefs, $line["pref_name"]);                  
1753                 }
1754
1755                 while ($line = db_fetch_assoc($result)) {
1756                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1757 //                              print "adding " . $line["pref_name"] . "<br>";
1758
1759                                 if (get_schema_version($link) < 63) {
1760                                         db_query($link, "INSERT INTO ttrss_user_prefs
1761                                                 (owner_uid,pref_name,value) VALUES 
1762                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1763
1764                                 } else {
1765                                         db_query($link, "INSERT INTO ttrss_user_prefs
1766                                                 (owner_uid,pref_name,value, profile) VALUES 
1767                                                 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
1768                                 }
1769
1770                         }
1771                 }
1772
1773                 db_query($link, "COMMIT");
1774
1775         }
1776
1777         function lookup_user_id($link, $user) {
1778
1779                 $result = db_query($link, "SELECT id FROM ttrss_users WHERE 
1780                         login = '$login'");
1781
1782                 if (db_num_rows($result) == 1) {
1783                         return db_fetch_result($result, 0, "id");
1784                 } else {
1785                         return false;
1786                 }
1787         }
1788
1789         function http_authenticate_user($link) {
1790
1791 //              error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1792
1793                 if (!$_SERVER["PHP_AUTH_USER"]) {
1794
1795                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1796                         header('HTTP/1.0 401 Unauthorized');
1797                         exit;
1798                                         
1799                 } else {
1800                         $auth_result = authenticate_user($link, 
1801                                 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1802
1803                         if (!$auth_result) {
1804                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1805                                 header('HTTP/1.0 401 Unauthorized');
1806                                 exit;
1807                         }
1808                 }
1809
1810                 return true;
1811         }
1812
1813         function authenticate_user($link, $login, $password, $force_auth = false) {
1814
1815                 if (!SINGLE_USER_MODE) {
1816
1817                         $pwd_hash1 = encrypt_password($password);
1818                         $pwd_hash2 = encrypt_password($password, $login);
1819                         $login = db_escape_string($login);
1820
1821                         if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH 
1822                                         && $_SERVER["REMOTE_USER"] && $login != "admin") {
1823
1824                                 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1825
1826                                 $query = "SELECT id,login,access_level,pwd_hash
1827                     FROM ttrss_users WHERE
1828                                         login = '$login'";
1829
1830                         } else {
1831                                 $query = "SELECT id,login,access_level,pwd_hash
1832                     FROM ttrss_users WHERE
1833                                         login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1834                                                 pwd_hash = '$pwd_hash2')";
1835                         }
1836
1837                         $result = db_query($link, $query);
1838         
1839                         if (db_num_rows($result) == 1) {
1840                                 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1841                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1842                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1843         
1844                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1845                                         $_SESSION["uid"]);
1846         
1847                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1848                                 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1849
1850                                 $_SESSION["last_version_check"] = time();
1851         
1852                                 initialize_user_prefs($link, $_SESSION["uid"]);
1853         
1854                                 return true;
1855                         }
1856         
1857                         return false;
1858
1859                 } else {
1860
1861                         $_SESSION["uid"] = 1;
1862                         $_SESSION["name"] = "admin";
1863
1864                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1865         
1866                         initialize_user_prefs($link, $_SESSION["uid"]);
1867         
1868                         return true;
1869                 }
1870         }
1871
1872         function make_password($length = 8) {
1873
1874                 $password = "";
1875                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
1876                 
1877         $i = 0; 
1878     
1879                 while ($i < $length) { 
1880                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1881         
1882                         if (!strstr($password, $char)) { 
1883                                 $password .= $char;
1884                                 $i++;
1885                         }
1886                 }
1887                 return $password;
1888         }
1889
1890         // this is called after user is created to initialize default feeds, labels
1891         // or whatever else
1892         
1893         // user preferences are checked on every login, not here
1894
1895         function initialize_user($link, $uid) {
1896
1897 /*              db_query($link, "INSERT INTO ttrss_labels2 (owner_uid, caption)
1898                         VALUES ('$uid', 'All Articles')");
1899
1900                 db_query($link, "INSERT INTO ttrss_filters 
1901                         (owner_uid, feed_id, filter_type, reg_exp, enabled, 
1902                                 action_id, action_param, filter_param) 
1903                         VALUES ('$uid', NULL, 1, '.', true, 7, 'All Articles', 'before')"); */
1904
1905                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1906                         values ('$uid', 'Tiny Tiny RSS: New Releases',
1907                         'http://tt-rss.org/releases.rss')");
1908
1909                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1910                         values ('$uid', 'Tiny Tiny RSS: Forum',
1911                         'http://tt-rss.org/forum/rss.php')");
1912         }
1913
1914         function logout_user() {
1915                 session_destroy();
1916                 if (isset($_COOKIE[session_name()])) {
1917                    setcookie(session_name(), '', time()-42000, '/');
1918                 }
1919         }
1920
1921         function get_script_urlpath() {
1922                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1923         }
1924
1925         function validate_session($link) {
1926                 if (SINGLE_USER_MODE) { 
1927                         return true;
1928                 }
1929
1930                 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1931                         if ($_SESSION["ip_address"]) {
1932                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1933                                         $_SESSION["login_error_msg"] = __("Session failed to validate (incorrect IP)");
1934                                         return false;
1935                                 }
1936                         }
1937                 }
1938
1939                 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true)) {
1940                         return false;
1941                 }
1942
1943                 if ($_SESSION["uid"]) {
1944
1945                         $result = db_query($link, 
1946                                 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1947
1948                         $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1949
1950                         if ($pwd_hash != $_SESSION["pwd_hash"]) {
1951                                 return false;
1952                         }
1953                 }
1954
1955 /*              if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1956
1957                         //print_r($_SESSION);
1958
1959                         if (time() > $_SESSION["cookie_lifetime"]) {
1960                                 return false;
1961                         }
1962                 } */
1963
1964                 return true;
1965         }
1966
1967         function login_sequence($link, $mobile = false) {
1968                 if (!SINGLE_USER_MODE) {
1969
1970                         $login_action = $_POST["login_action"];
1971
1972                         # try to authenticate user if called from login form                    
1973                         if ($login_action == "do_login") {
1974                                 $login = $_POST["login"];
1975                                 $password = $_POST["password"];
1976                                 $remember_me = $_POST["remember_me"];
1977
1978                                 if (authenticate_user($link, $login, $password)) {
1979                                         $_POST["password"] = "";
1980
1981                                         $_SESSION["language"] = $_POST["language"];
1982                                         $_SESSION["ref_schema_version"] = get_schema_version($link, true);
1983                                         $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
1984
1985                                         if ($_POST["profile"]) {
1986
1987                                                 $profile = db_escape_string($_POST["profile"]);
1988
1989                                                 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
1990                                                         WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
1991
1992                                                 if (db_num_rows($result) != 0) {
1993                                                         $_SESSION["profile"] = $profile;
1994                                                         $_SESSION["prefs_cache"] = array();
1995                                                 }
1996                                         }
1997
1998                                         header("Location: " . $_SERVER["REQUEST_URI"]);
1999                                         exit;
2000
2001                                         return;
2002                                 } else {
2003                                         $_SESSION["login_error_msg"] = __("Incorrect username or password");
2004                                 }
2005                         }
2006
2007                         if (!$_SESSION["uid"] || !validate_session($link)) {
2008                                 render_login_form($link, $mobile);
2009                                 //header("Location: login.php");
2010                                 exit;
2011                         } else {
2012                                 /* bump login timestamp */
2013                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
2014                                         $_SESSION["uid"]);
2015
2016                                 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
2017                                         setcookie("ttrss_lang", $_SESSION["language"], 
2018                                                 time() + SESSION_COOKIE_LIFETIME);
2019                                 }
2020
2021                                 /* bump counters stamp since we're getting reloaded anyway */
2022
2023                                 $_SESSION["get_all_counters_stamp"] = time();
2024                         }
2025
2026                 } else {
2027                         return authenticate_user($link, "admin", null);
2028                 }
2029         }
2030
2031         function truncate_string($str, $max_len) {
2032                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
2033                         return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
2034                 } else {
2035                         return $str;
2036                 }
2037         }
2038
2039         function theme_image($link, $filename) {
2040                 if ($link) {
2041                         $theme_path = get_user_theme_path($link);
2042
2043                         if ($theme_path && is_file($theme_path.$filename)) {
2044                                 return $theme_path.$filename;
2045                         } else {
2046                                 return $filename;
2047                         }
2048                 } else {
2049                         return $filename;
2050                 }
2051         }
2052
2053         function get_user_theme($link) {
2054
2055                 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2056                         $theme_name = get_pref($link, "_THEME_ID");
2057                         if (is_dir("themes/$theme_name")) {
2058                                 return $theme_name;
2059                         } else {
2060                                 return '';
2061                         }
2062                 } else {
2063                         return '';
2064                 }
2065
2066         }
2067
2068         function get_user_theme_path($link) {
2069                 $theme_path = '';
2070
2071                 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
2072                         $theme_name = get_pref($link, "_THEME_ID");
2073
2074                         if ($theme_name && is_dir("themes/$theme_name")) {
2075                                 $theme_path = "themes/$theme_name/";
2076                         } else {
2077                                 $theme_name = '';
2078                         }
2079                 } else {
2080                         $theme_path = '';
2081                 }
2082
2083                 return $theme_path;
2084         }
2085
2086         function get_user_theme_options($link) {
2087                 $t = get_user_theme_path($link);
2088
2089                 if ($t) {
2090                         if (is_file("$t/theme.ini")) {
2091                                 $ini = parse_ini_file("$t/theme.ini", true);
2092                                 if ($ini['theme']['version']) {
2093                                         return $ini['theme']['options'];
2094                                 }
2095                         }
2096                 }
2097                 return '';
2098         }
2099
2100
2101         function get_all_themes() {
2102                 $themes = glob("themes/*");
2103
2104                 asort($themes);
2105
2106                 $rv = array();
2107
2108                 foreach ($themes as $t) {
2109                         if (is_file("$t/theme.ini")) {
2110                                 $ini = parse_ini_file("$t/theme.ini", true);
2111                                 if ($ini['theme']['version'] && !$ini['theme']['disabled']) {
2112                                         $entry = array();
2113                                         $entry["path"] = $t;
2114                                         $entry["base"] = basename($t);
2115                                         $entry["name"] = $ini['theme']['name'];
2116                                         $entry["version"] = $ini['theme']['version'];
2117                                         $entry["author"] = $ini['theme']['author'];
2118                                         $entry["options"] = $ini['theme']['options'];
2119                                         array_push($rv, $entry);
2120                                 }
2121                         }
2122                 }
2123
2124                 return $rv;
2125         }
2126
2127         function smart_date_time($timestamp) {
2128                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2129                         return date("G:i", $timestamp);
2130                 } else if (date("Y", $timestamp) == date("Y")) {
2131                         return date("M d, G:i", $timestamp);
2132                 } else {
2133                         return date("Y/m/d, G:i", $timestamp);
2134                 }
2135         }
2136
2137         function smart_date($timestamp) {
2138                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
2139                         return "Today";
2140                 } else if (date("Y", $timestamp) == date("Y")) {
2141                         return date("D m", $timestamp);
2142                 } else {
2143                         return date("Y/m/d", $timestamp);
2144                 }
2145         }
2146
2147         function sql_bool_to_string($s) {
2148                 if ($s == "t" || $s == "1") {
2149                         return "true";
2150                 } else {
2151                         return "false";
2152                 }
2153         }
2154
2155         function sql_bool_to_bool($s) {
2156                 if ($s == "t" || $s == "1") {
2157                         return true;
2158                 } else {
2159                         return false;
2160                 }
2161         }
2162         
2163         function bool_to_sql_bool($s) {
2164                 if ($s) {
2165                         return "true";
2166                 } else {
2167                         return "false";
2168                 }
2169         }
2170
2171         function toggleEvenOdd($a) {
2172                 if ($a == "even") 
2173                         return "odd";
2174                 else
2175                         return "even";
2176         }
2177
2178         function get_schema_version($link, $nocache = false) {
2179                 if (!$_SESSION["schema_version"] || $nocache) {
2180                         $result = db_query($link, "SELECT schema_version FROM ttrss_version");
2181                         $version = db_fetch_result($result, 0, "schema_version");
2182                         $_SESSION["schema_version"] = $version;
2183                         return $version;
2184                 } else {
2185                         return $_SESSION["schema_version"];
2186                 }
2187         }
2188
2189         function sanity_check($link) {
2190
2191                 error_reporting(0);
2192
2193                 $error_code = 0;
2194                 $schema_version = get_schema_version($link);
2195
2196                 if ($schema_version != SCHEMA_VERSION) {
2197                         $error_code = 5;
2198                 }
2199
2200                 if (DB_TYPE == "mysql") {
2201                         $result = db_query($link, "SELECT true", false);
2202                         if (db_num_rows($result) != 1) {
2203                                 $error_code = 10;
2204                         }
2205                 }
2206
2207                 if (db_escape_string("testTEST") != "testTEST") {
2208                         $error_code = 12;
2209                 }
2210
2211                 error_reporting (DEFAULT_ERROR_LEVEL);
2212
2213                 if ($error_code != 0) {
2214                         print_error_xml($error_code);
2215                         return false;
2216                 } else {
2217                         return true;
2218                 }
2219         }
2220
2221         function file_is_locked($filename) {
2222                 if (function_exists('flock')) {
2223                         error_reporting(0);
2224                         $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
2225                         error_reporting(DEFAULT_ERROR_LEVEL);
2226                         if ($fp) {
2227                                 if (flock($fp, LOCK_EX | LOCK_NB)) {
2228                                         flock($fp, LOCK_UN);
2229                                         fclose($fp);
2230                                         return false;
2231                                 }
2232                                 fclose($fp);
2233                                 return true;
2234                         } else {
2235                                 return false;
2236                         }
2237                 }
2238                 return true; // consider the file always locked and skip the test
2239         }
2240
2241         function make_lockfile($filename) {
2242                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2243
2244                 if (flock($fp, LOCK_EX | LOCK_NB)) {
2245                         if (function_exists('posix_getpid')) {
2246                                 fwrite($fp, posix_getpid() . "\n");
2247                         }
2248                         return $fp;
2249                 } else {
2250                         return false;
2251                 }
2252         }
2253
2254         function make_stampfile($filename) {
2255                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
2256
2257                 if (flock($fp, LOCK_EX | LOCK_NB)) {
2258                         fwrite($fp, time() . "\n");
2259                         flock($fp, LOCK_UN);
2260                         fclose($fp);
2261                         return true;
2262                 } else {
2263                         return false;
2264                 }
2265         }
2266
2267         function sql_random_function() {
2268                 if (DB_TYPE == "mysql") {
2269                         return "RAND()";
2270                 } else {
2271                         return "RANDOM()";
2272                 }
2273         }
2274
2275         function catchup_feed($link, $feed, $cat_view, $owner_uid) {
2276
2277                         if (!$owner_uid) $owner_uid = $_SESSION['uid'];
2278
2279                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2280
2281                                 if ($cat_view) {
2282
2283                                         if ($feed >= 0) {
2284
2285                                                 if ($feed > 0) {
2286                                                         $cat_qpart = "cat_id = '$feed'";
2287                                                 } else {
2288                                                         $cat_qpart = "cat_id IS NULL";
2289                                                 }
2290                                         
2291                                                 $tmp_result = db_query($link, "SELECT id 
2292                                                         FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
2293
2294                                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2295
2296                                                         $tmp_feed = $tmp_line["id"];
2297
2298                                                         db_query($link, "UPDATE ttrss_user_entries 
2299                                                                 SET unread = false,last_read = NOW() 
2300                                                                 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
2301                                                 }
2302                                         } else if ($feed == -2) {
2303
2304
2305                                                 db_query($link, "UPDATE ttrss_user_entries 
2306                                                         SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*) 
2307                                                                 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0 
2308                                                         AND unread = true AND owner_uid = $owner_uid");
2309                                         }
2310
2311                                 } else if ($feed > 0) {
2312
2313                                         $tmp_result = db_query($link, "SELECT id 
2314                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
2315                                                 ORDER BY cat_id,title");
2316
2317                                         $parent_ids = array();
2318
2319                                         if (db_num_rows($tmp_result) > 0) {
2320                                                 while ($p = db_fetch_assoc($tmp_result)) {
2321                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
2322                                                 }
2323
2324                                                 $children_qpart = implode(" OR ", $parent_ids);
2325                                                 
2326                                                 db_query($link, "UPDATE ttrss_user_entries 
2327                                                         SET unread = false,last_read = NOW() 
2328                                                         WHERE (feed_id = '$feed' OR $children_qpart) 
2329                                                         AND owner_uid = $owner_uid");
2330
2331                                         } else {                                                
2332                                                 db_query($link, "UPDATE ttrss_user_entries 
2333                                                         SET unread = false,last_read = NOW() 
2334                                                         WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
2335                                         }
2336                                                 
2337                                 } else if ($feed < 0 && $feed > -10) { // special, like starred
2338
2339                                         if ($feed == -1) {
2340                                                 db_query($link, "UPDATE ttrss_user_entries 
2341                                                         SET unread = false,last_read = NOW()
2342                                                         WHERE marked = true AND owner_uid = $owner_uid");
2343                                         }
2344
2345                                         if ($feed == -2) {
2346                                                 db_query($link, "UPDATE ttrss_user_entries 
2347                                                         SET unread = false,last_read = NOW()
2348                                                         WHERE published = true AND owner_uid = $owner_uid");
2349                                         }
2350
2351                                         if ($feed == -3) {
2352
2353                                                 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2354
2355                                                 if (DB_TYPE == "pgsql") {
2356                                                         $match_part = "updated > NOW() - INTERVAL '$intl hour' "; 
2357                                                 } else {
2358                                                         $match_part = "updated > DATE_SUB(NOW(), 
2359                                                                 INTERVAL $intl HOUR) ";
2360                                                 }
2361
2362                                                 $result = db_query($link, "SELECT id FROM ttrss_entries, 
2363                                                         ttrss_user_entries WHERE $match_part AND
2364                                                         unread = true AND
2365                                                         ttrss_user_entries.ref_id = ttrss_entries.id AND        
2366                                                         owner_uid = $owner_uid");
2367
2368                                                 $affected_ids = array();
2369
2370                                                 while ($line = db_fetch_assoc($result)) {
2371                                                         array_push($affected_ids, $line["id"]);
2372                                                 }
2373
2374                                                 catchupArticlesById($link, $affected_ids, 0);
2375                                         }
2376
2377                                         if ($feed == -4) {
2378                                                 db_query($link, "UPDATE ttrss_user_entries 
2379                                                         SET unread = false,last_read = NOW()
2380                                                         WHERE owner_uid = $owner_uid");
2381                                         }
2382
2383                                 } else if ($feed < -10) { // label
2384
2385                                         $label_id = -$feed - 11;
2386
2387                                         db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2 
2388                                                 SET unread = false, last_read = NOW() 
2389                                                         WHERE label_id = '$label_id' AND unread = true
2390                                                         AND owner_uid = '$owner_uid' AND ref_id = article_id");
2391
2392                                 }
2393
2394                                 ccache_update($link, $feed, $owner_uid, $cat_view);
2395
2396                         } else { // tag
2397                                 db_query($link, "BEGIN");
2398
2399                                 $tag_name = db_escape_string($feed);
2400
2401                                 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2402                                         WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
2403
2404                                 while ($line = db_fetch_assoc($result)) {
2405                                         db_query($link, "UPDATE ttrss_user_entries SET
2406                                                 unread = false, last_read = NOW() 
2407                                                 WHERE int_id = " . $line["post_int_id"]);
2408                                 }
2409                                 db_query($link, "COMMIT");
2410                         }
2411         }
2412
2413         function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2414                         if ($cat_view) {
2415
2416                                 if ($feed > 0) {
2417                                         $cat_qpart = "cat_id = '$feed'";
2418                                 } else {
2419                                         $cat_qpart = "cat_id IS NULL";
2420                                 }
2421                                 
2422                                 $tmp_result = db_query($link, "SELECT id FROM ttrss_feeds
2423                                         WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2424
2425                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
2426                                         $feed_id = $tmp_line["id"];
2427                                         update_rss_feed($link, $feed_id, $force_update);
2428                                 }
2429
2430                         } else {
2431                                 update_rss_feed($link, $feed, $force_update);
2432                         }
2433         }
2434
2435         function getAllCounters($link, $omode = "flc", $active_feed = false) {
2436
2437                 if (!$omode) $omode = "flc";
2438
2439                 $data = getGlobalCounters($link);
2440                 
2441                 $data = array_merge($data, getVirtCounters($link));
2442
2443                 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
2444                 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
2445                 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
2446                 if (strchr($omode, "c")) {                      
2447                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
2448                                 $data = array_merge($data, getCategoryCounters($link));
2449                         }
2450                 }
2451
2452                 return $data;
2453         }       
2454
2455         function getCategoryCounters($link) {
2456                 $ret_arr = array();
2457
2458                 /* Labels category */
2459
2460                 $cv = array("id" => -2, "kind" => "cat",
2461                         "counter" => getCategoryUnread($link, -2));
2462
2463                 array_push($ret_arr, $cv);
2464
2465                 $age_qpart = getMaxAgeSubquery();
2466
2467                 $result = db_query($link, "SELECT id AS cat_id, value AS unread 
2468                         FROM ttrss_feed_categories, ttrss_cat_counters_cache 
2469                         WHERE ttrss_cat_counters_cache.feed_id = id AND 
2470                         ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
2471
2472                 while ($line = db_fetch_assoc($result)) {
2473                         $line["cat_id"] = (int) $line["cat_id"];
2474
2475                         $cv = array("id" => $line["cat_id"], "kind" => "cat",
2476                                 "counter" => $line["unread"]);
2477
2478                         array_push($ret_arr, $cv);
2479                 }
2480
2481                 /* Special case: NULL category doesn't actually exist in the DB */
2482
2483                 $cv = array("id" => 0, "cat" => true,
2484                         "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
2485
2486                 array_push($ret_arr, $cv);
2487
2488                 return $ret_arr;
2489         }
2490
2491         function getCategoryUnread($link, $cat, $owner_uid = false) {
2492
2493                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2494
2495                 if ($cat >= 0) {
2496
2497                         if ($cat != 0) {
2498                                 $cat_query = "cat_id = '$cat'";
2499                         } else {
2500                                 $cat_query = "cat_id IS NULL";
2501                         }
2502
2503                         $age_qpart = getMaxAgeSubquery();
2504
2505                         $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query 
2506                                         AND owner_uid = " . $owner_uid);
2507         
2508                         $cat_feeds = array();
2509                         while ($line = db_fetch_assoc($result)) {
2510                                 array_push($cat_feeds, "feed_id = " . $line["id"]);
2511                         }
2512         
2513                         if (count($cat_feeds) == 0) return 0;
2514         
2515                         $match_part = implode(" OR ", $cat_feeds);
2516         
2517                         $result = db_query($link, "SELECT COUNT(int_id) AS unread 
2518                                 FROM ttrss_user_entries,ttrss_entries 
2519                                 WHERE   unread = true AND ($match_part) AND id = ref_id 
2520                                 AND $age_qpart AND owner_uid = " . $owner_uid);
2521         
2522                         $unread = 0;
2523         
2524                         # this needs to be rewritten
2525                         while ($line = db_fetch_assoc($result)) {
2526                                 $unread += $line["unread"];
2527                         }
2528         
2529                         return $unread;
2530                 } else if ($cat == -1) {
2531                         return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3) + getFeedUnread($link, 0);
2532                 } else if ($cat == -2) {
2533
2534                         $result = db_query($link, "
2535                                 SELECT COUNT(unread) AS unread FROM 
2536                                         ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds 
2537                                 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND 
2538                                         ttrss_labels2.owner_uid = '$owner_uid'
2539                                         AND unread = true AND feed_id = ttrss_feeds.id
2540                                         AND ttrss_user_entries.owner_uid = '$owner_uid'");
2541
2542                         $unread = db_fetch_result($result, 0, "unread");
2543
2544                         return $unread;
2545
2546                 } 
2547         }
2548
2549         function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2550                 if (DB_TYPE == "pgsql") {
2551                         return "ttrss_entries.date_updated > 
2552                                 NOW() - INTERVAL '$days days'";
2553                 } else {
2554                         return "ttrss_entries.date_updated > 
2555                                 DATE_SUB(NOW(), INTERVAL $days DAY)";
2556                 }
2557         }
2558
2559         function getFeedUnread($link, $feed, $is_cat = false) {
2560                 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
2561         }
2562
2563         function getLabelUnread($link, $label_id, $owner_uid = false) {
2564                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2565
2566                 $result = db_query($link, "
2567                         SELECT COUNT(unread) AS unread FROM 
2568                                 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds 
2569                         WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND 
2570                                 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
2571                                 AND unread = true AND feed_id = ttrss_feeds.id
2572                                 AND ttrss_user_entries.owner_uid = '$owner_uid'");
2573
2574                 if (db_num_rows($result) != 0) {
2575                         return db_fetch_result($result, 0, "unread");
2576                 } else {
2577                         return 0;
2578                 }
2579         }
2580
2581         function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
2582                 $owner_uid = false) {
2583
2584                 $n_feed = (int) $feed;
2585
2586                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2587
2588                 if ($unread_only) {
2589                         $unread_qpart = "unread = true";
2590                 } else {
2591                         $unread_qpart = "true";
2592                 }
2593
2594                 $age_qpart = getMaxAgeSubquery();
2595
2596                 if ($is_cat) {
2597                         return getCategoryUnread($link, $n_feed, $owner_uid);           
2598                 } if ($feed != "0" && $n_feed == 0) {
2599
2600                         $feed = db_escape_string($feed);
2601
2602                         $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
2603                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
2604                                         AND ref_id = id AND $age_qpart
2605                                         AND $unread_qpart)) AS count FROM ttrss_tags 
2606                                 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
2607                         return db_fetch_result($result, 0, "count");
2608
2609                 } else if ($n_feed == -1) {
2610                         $match_part = "marked = true";
2611                 } else if ($n_feed == -2) {
2612                         $match_part = "published = true";
2613                 } else if ($n_feed == -3) {
2614                         $match_part = "unread = true";
2615
2616                         $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2617
2618                         if (DB_TYPE == "pgsql") {
2619                                 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' "; 
2620                         } else {
2621                                 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2622                         }
2623                 } else if ($n_feed == -4) {
2624                         $match_part = "true";
2625                 } else if ($n_feed >= 0) {
2626
2627                         $result = db_query($link, "SELECT id FROM ttrss_feeds 
2628                                         WHERE parent_feed = '$n_feed'
2629                                         AND owner_uid = " . $owner_uid);
2630
2631                         if (db_num_rows($result) > 0) {
2632
2633                                 $linked_feeds = array();
2634                                 while ($line = db_fetch_assoc($result)) {
2635                                         array_push($linked_feeds, "feed_id = " . $line["id"]);
2636                                 }
2637
2638                                 array_push($linked_feeds, "feed_id = $n_feed");
2639                                 
2640                                 $match_part = implode(" OR ", $linked_feeds);
2641
2642                                 $tmp_result = db_query($link, "SELECT COUNT(int_id) AS unread 
2643                                         FROM ttrss_user_entries,ttrss_entries
2644                                         WHERE   $unread_qpart AND
2645                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
2646                                         $age_qpart AND
2647                                         ($match_part) AND
2648                                         owner_uid = " . $owner_uid);
2649
2650                                 $unread = 0;
2651
2652                                 # this needs to be rewritten
2653                                 while ($line = db_fetch_assoc($tmp_result)) {
2654                                         $unread += $line["unread"];
2655                                 }
2656
2657                                 return $unread;
2658
2659                         } else {
2660                                 if ($n_feed != 0) {
2661                                         $match_part = "feed_id = '$n_feed'";
2662                                 } else {
2663                                         $match_part = "feed_id IS NULL";
2664                                 }
2665                         }
2666                 } else if ($feed < -10) {
2667
2668                         $label_id = -$feed - 11;
2669
2670                         return getLabelUnread($link, $label_id, $owner_uid);
2671
2672                 }
2673
2674                 if ($match_part) {
2675
2676                         if ($n_feed != 0) {
2677                                 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
2678                                 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2679                         } else {
2680                                 $from_qpart = "ttrss_user_entries,ttrss_entries";
2681                                 $feeds_qpart = '';
2682                         }
2683
2684                         $query = "SELECT count(int_id) AS unread 
2685                                 FROM $from_qpart WHERE
2686                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
2687                                 $age_qpart AND
2688                                 $feeds_qpart
2689                                 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
2690
2691                         $result = db_query($link, $query);
2692                                 
2693                 } else {
2694                 
2695                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2696                                 FROM ttrss_tags,ttrss_user_entries,ttrss_entries 
2697                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id 
2698                                 AND $unread_qpart AND $age_qpart AND
2699                                         ttrss_tags.owner_uid = " . $owner_uid);
2700                 }
2701                 
2702                 $unread = db_fetch_result($result, 0, "unread");
2703
2704                 return $unread;
2705         }
2706
2707         function getGlobalUnread($link, $user_id = false) {
2708
2709                 if (!$user_id) {
2710                         $user_id = $_SESSION["uid"];
2711                 }
2712
2713                 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
2714                         WHERE owner_uid = '$user_id' AND feed_id > 0");
2715
2716                 $c_id = db_fetch_result($result, 0, "c_id"); 
2717
2718                 return $c_id;
2719         }
2720
2721         function getGlobalCounters($link, $global_unread = -1) {
2722                 $ret_arr = array();
2723
2724                 if ($global_unread == -1) {     
2725                         $global_unread = getGlobalUnread($link);
2726                 }
2727
2728                 $cv = array("id" => "global-unread", 
2729                         "counter" => $global_unread);
2730
2731                 array_push($ret_arr, $cv);
2732
2733                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM 
2734                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2735
2736                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2737
2738                 $cv = array("id" => "subscribed-feeds", 
2739                         "counter" => $subscribed_feeds);
2740
2741                 array_push($ret_arr, $cv);
2742
2743                 return $ret_arr;
2744         }
2745
2746         function getSubscribedFeeds($link) {
2747                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM 
2748                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2749
2750                 return db_fetch_result($result, 0, "fn");
2751         }
2752
2753         function getTagCounters($link) {
2754                 
2755                 $ret_arr = array();
2756
2757                 $age_qpart = getMaxAgeSubquery();
2758
2759                 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
2760                         FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
2761                                 AND ref_id = id AND $age_qpart
2762                                 AND unread = true)) AS count FROM ttrss_tags 
2763                                 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name 
2764                                 ORDER BY count DESC LIMIT 55");
2765                         
2766                 $tags = array();
2767
2768                 while ($line = db_fetch_assoc($result)) {
2769                         $tags[$line["tag_name"]] += $line["count"];
2770                 }
2771
2772                 foreach (array_keys($tags) as $tag) {
2773                         $unread = $tags[$tag];                  
2774                         $tag = htmlspecialchars($tag);
2775
2776                         $cv = array("id" => $tag,
2777                                 "kind" => "tag",
2778                                 "counter" => $unread);
2779
2780                         array_push($ret_arr, $cv);
2781                 }
2782
2783                 return $ret_arr;        
2784         }
2785
2786         function getVirtCounters($link) {
2787
2788                 $ret_arr = array();
2789
2790                 for ($i = 0; $i >= -4; $i--) {
2791
2792                         $count = getFeedUnread($link, $i);
2793
2794                         $cv = array("id" => $i,
2795                                 "counter" => $count);
2796         
2797                         if (get_pref($link, 'EXTENDED_FEEDLIST'))
2798                                 $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
2799
2800                         array_push($ret_arr, $cv);
2801                 } 
2802
2803                 return $ret_arr;
2804         }
2805
2806         function getLabelCounters($link, $descriptions = false) {
2807
2808                 $ret_arr = array();
2809
2810                 $age_qpart = getMaxAgeSubquery();
2811
2812                 $owner_uid = $_SESSION["uid"];
2813
2814                 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
2815                         WHERE owner_uid = '$owner_uid'");
2816         
2817                 while ($line = db_fetch_assoc($result)) {
2818
2819                         $id = -$line["id"] - 11;
2820
2821                         $label_name = $line["caption"];
2822                         $count = getFeedUnread($link, $id);
2823
2824                         $cv = array("id" => $id,
2825                                 "counter" => $count);
2826
2827                         if ($descriptions)
2828                                 $cv["description"] = $label_name;
2829
2830                         if (get_pref($link, 'EXTENDED_FEEDLIST'))
2831                                 $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2832
2833                         array_push($ret_arr, $cv);
2834                 }
2835         
2836                 return $ret_arr;
2837         }
2838
2839         function getFeedCounters($link, $active_feed = false) {
2840
2841                 $ret_arr = array();
2842
2843                 $age_qpart = getMaxAgeSubquery();
2844
2845                 $query = "SELECT ttrss_feeds.id,
2846                                 ttrss_feeds.title,
2847                                 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated, 
2848                                 last_error, value AS count
2849                         FROM ttrss_feeds, ttrss_counters_cache
2850                         WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."  
2851                                 AND parent_feed IS NULL 
2852                                 AND ttrss_counters_cache.feed_id = id";
2853
2854                 $result = db_query($link, $query);
2855                 $fctrs_modified = false;
2856
2857                 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2858
2859                 while ($line = db_fetch_assoc($result)) {
2860                 
2861                         $id = $line["id"];
2862                         $count = $line["count"];
2863                         $last_error = htmlspecialchars($line["last_error"]);
2864
2865                         if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2866                                 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2867                         } else {
2868                                 $last_updated = date($short_date, strtotime($line["last_updated"]));
2869                         }                               
2870
2871                         $has_img = feed_has_icon($id);
2872
2873                         $tmp_result = db_query($link,
2874                                 "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache 
2875                                         WHERE parent_feed = '$id' AND feed_id = id");
2876
2877                         $count += db_fetch_result($tmp_result, 0, "unread");
2878
2879                         $cv = array("id" => $id,
2880                                 "updated" => $last_updated,
2881                                 "counter" => $count,
2882                                 "has_img" => (int) $has_img);
2883
2884                         if ($last_error)
2885                                 $cv["error"] = $last_error;
2886
2887                         if (get_pref($link, 'EXTENDED_FEEDLIST'))
2888                                 $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
2889
2890                         if ($active_feed && $id == $active_feed)
2891                                 $cv["title"] = $line["title"];
2892
2893                         array_push($ret_arr, $cv);
2894
2895                 }
2896
2897                 return $ret_arr;
2898         }
2899
2900         function get_script_dt_add() {
2901                 return time();
2902         }
2903
2904         function get_pgsql_version($link) {
2905                 $result = db_query($link, "SELECT version() AS version");
2906                 $version = split(" ", db_fetch_result($result, 0, "version"));
2907                 return $version[1];
2908         }
2909
2910         function print_error_xml($code, $add_msg = "") {
2911                 global $ERRORS;
2912
2913                 $error_msg = $ERRORS[$code];
2914                 
2915                 if ($add_msg) {
2916                         $error_msg = "$error_msg; $add_msg";
2917                 }
2918                 
2919                 print "<rpc-reply>";
2920                 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2921                 print "</rpc-reply>";
2922         }
2923
2924         function subscribe_to_feed($link, $url, $cat_id = 0, 
2925                         $auth_login = '', $auth_pass = '') {
2926
2927                 $parts = parse_url($url);
2928
2929                 if (!validate_feed_url($url)) return 2;
2930
2931                 if ($parts['scheme'] == 'feed') $parts['scheme'] = 'http';
2932
2933                 $url = make_url_from_parts($parts);
2934
2935                 if ($cat_id == "0" || !$cat_id) {
2936                         $cat_qpart = "NULL";
2937                 } else {
2938                         $cat_qpart = "'$cat_id'";
2939                 }
2940         
2941                 $result = db_query($link,
2942                         "SELECT id FROM ttrss_feeds 
2943                         WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
2944         
2945                 if (db_num_rows($result) == 0) {
2946                         
2947                         $result = db_query($link,
2948                                 "INSERT INTO ttrss_feeds 
2949                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass) 
2950                                 VALUES ('".$_SESSION["uid"]."', '$url', 
2951                                 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2952         
2953                         $result = db_query($link,
2954                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url' 
2955                                         AND owner_uid = " . $_SESSION["uid"]);
2956         
2957                         $feed_id = db_fetch_result($result, 0, "id");
2958         
2959                         if ($feed_id) {
2960                                 update_rss_feed($link, $feed_id, true);
2961                         }
2962
2963                         return 1;
2964                 } else {
2965                         return 0;
2966                 }
2967         }
2968
2969         function print_feed_select($link, $id, $default_id = "", 
2970                 $attributes = "", $include_all_feeds = true) {
2971
2972                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2973                 if ($include_all_feeds) { 
2974                         print "<option value=\"0\">".__('All feeds')."</option>";
2975                 }
2976         
2977                 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2978                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2979
2980                 if (db_num_rows($result) > 0 && $include_all_feeds) {
2981                         print "<option disabled>--------</option>";
2982                 }
2983
2984                 while ($line = db_fetch_assoc($result)) {
2985                         if ($line["id"] == $default_id) {
2986                                 $is_selected = "selected";
2987                         } else {
2988                                 $is_selected = "";
2989                         }
2990
2991                         $title = truncate_string(htmlspecialchars($line["title"]), 40);
2992
2993                         printf("<option $is_selected value='%d'>%s</option>", 
2994                                 $line["id"], $title);
2995                 }
2996         
2997                 print "</select>";
2998         }
2999
3000         function print_feed_cat_select($link, $id, $default_id = "", 
3001                 $attributes = "", $include_all_cats = true) {
3002                 
3003                 print "<select id=\"$id\" name=\"$id\" $attributes>";
3004
3005                 if ($include_all_cats) {
3006                         print "<option value=\"0\">".__('Uncategorized')."</option>";
3007                 }
3008
3009                 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
3010                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
3011
3012                 if (db_num_rows($result) > 0 && $include_all_cats) {
3013                         print "<option disabled>--------</option>";
3014                 }
3015
3016                 while ($line = db_fetch_assoc($result)) {
3017                         if ($line["id"] == $default_id) {
3018                                 $is_selected = "selected";
3019                         } else {
3020                                 $is_selected = "";
3021                         }
3022                         printf("<option $is_selected value='%d'>%s</option>", 
3023                                 $line["id"], htmlspecialchars($line["title"]));
3024                 }
3025
3026                 print "</select>";
3027         }
3028         
3029         function checkbox_to_sql_bool($val) {
3030                 return ($val == "on") ? "true" : "false";
3031         }
3032
3033         function getFeedCatTitle($link, $id) {
3034                 if ($id == -1) {
3035                         return __("Special");
3036                 } else if ($id < -10) {
3037                         return __("Labels");
3038                 } else if ($id > 0) {
3039                         $result = db_query($link, "SELECT ttrss_feed_categories.title 
3040                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
3041                                         cat_id = ttrss_feed_categories.id");
3042                         if (db_num_rows($result) == 1) {
3043                                 return db_fetch_result($result, 0, "title");
3044                         } else {
3045                                 return __("Uncategorized");
3046                         }
3047                 } else {
3048                         return "getFeedCatTitle($id) failed";
3049                 }
3050
3051         }
3052
3053         function getFeedIcon($id) {
3054                 switch ($id) {
3055                 case 0:
3056                         return "images/archive.png";
3057                         break;
3058                 case -1:
3059                         return "images/mark_set.png";
3060                         break;
3061                 case -2:
3062                         return "images/pub_set.png";
3063                         break;
3064                 case -3:
3065                         return "images/fresh.png";
3066                         break;
3067                 case -4:
3068                         return "images/tag.png";
3069                         break;
3070                 default:
3071                         if ($id < -10) {
3072                                 return "images/label.png";
3073                         } else {
3074                                 return ICONS_URL . "/$id.ico";
3075                         }
3076                         break;
3077                 }
3078         }
3079
3080         function getFeedTitle($link, $id) {
3081                 if ($id == -1) {
3082                         return __("Starred articles");
3083                 } else if ($id == -2) {
3084                         return __("Published articles");
3085                 } else if ($id == -3) {
3086                         return __("Fresh articles");
3087                 } else if ($id == -4) {
3088                         return __("All articles");
3089                 } else if ($id === 0 || $id === "0") {
3090                         return __("Archived articles");
3091                 } else if ($id < -10) {
3092                         $label_id = -$id - 11;
3093                         $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
3094                         if (db_num_rows($result) == 1) {
3095                                 return db_fetch_result($result, 0, "caption");
3096                         } else {
3097                                 return "Unknown label ($label_id)";
3098                         }
3099
3100                 } else if ($id > 0) {
3101                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
3102                         if (db_num_rows($result) == 1) {
3103                                 return db_fetch_result($result, 0, "title");
3104                         } else {
3105                                 return "Unknown feed ($id)";
3106                         }
3107                 } else {
3108                         return $id;
3109                 }
3110         }
3111
3112         function get_session_cookie_name() {
3113                 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
3114         }
3115
3116         function make_init_param($param, $value) {
3117                 return array("param" => $param, "value" => $value);
3118         }
3119
3120         function make_init_params($link) {
3121                 $params = array();
3122
3123                 array_push($params, make_init_param("theme", get_user_theme($link)));
3124                 array_push($params, make_init_param("theme_options", get_user_theme_options($link)));
3125                 array_push($params, make_init_param("daemon_enabled", ENABLE_UPDATE_DAEMON));
3126                 array_push($params, make_init_param("feeds_frame_refresh", FEEDS_FRAME_REFRESH));
3127                 array_push($params, make_init_param("daemon_refresh_only", true));
3128
3129                 array_push($params, make_init_param("sign_progress", 
3130                         theme_image($link, "images/indicator_white.gif")));
3131
3132                 array_push($params, make_init_param("sign_progress_tiny", 
3133                         theme_image($link, "images/indicator_tiny.gif")));
3134
3135                 array_push($params, make_init_param("sign_excl", 
3136                         theme_image($link, "images/sign_excl.png")));
3137
3138                 array_push($params, make_init_param("sign_info", 
3139                         theme_image($link, "images/sign_info.png")));
3140
3141                 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
3142                         "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
3143                         "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", 
3144                         "HIDE_READ_SHOWS_SPECIAL", "HIDE_FEEDLIST") as $param) {
3145
3146                                  array_push($params, make_init_param(strtolower($param), 
3147                                          (int) get_pref($link, $param)));
3148                  }
3149
3150                 array_push($params, make_init_param("icons_url", ICONS_URL));
3151
3152                 array_push($params, make_init_param("cookie_lifetime", SESSION_COOKIE_LIFETIME));
3153
3154                 array_push($params, make_init_param("default_view_mode", 
3155                         get_pref($link, "_DEFAULT_VIEW_MODE")));
3156
3157                 array_push($params, make_init_param("default_view_limit", 
3158                         (int) get_pref($link, "_DEFAULT_VIEW_LIMIT")));
3159
3160                 array_push($params, make_init_param("default_view_order_by", 
3161                         get_pref($link, "_DEFAULT_VIEW_ORDER_BY")));
3162
3163                 array_push($params, make_init_param("prefs_active_tab", 
3164                         get_pref($link, "_PREFS_ACTIVE_TAB")));
3165
3166                 array_push($params, make_init_param("infobox_disable_overlay", 
3167                         get_pref($link, "_INFOBOX_DISABLE_OVERLAY")));
3168
3169                 array_push($params, make_init_param("bw_limit", 
3170                         (int) $_SESSION["bw_limit"]));
3171
3172                 array_push($params, make_init_param("sync_counters", 1));
3173
3174                 array_push($params, make_init_param("offline_enabled", 
3175                         (int) get_pref($link, "ENABLE_OFFLINE_READING")));
3176
3177                 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3178                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3179
3180                 $num_feeds = db_fetch_result($result, 0, "cf");
3181
3182                 array_push($params, make_init_param("num_feeds", 
3183                         (int) $num_feeds));
3184
3185                 array_push($params, make_init_param("collapsed_feedlist", 
3186                         (int) get_pref($link, "_COLLAPSED_FEEDLIST")));
3187
3188                 return $params;
3189         }
3190
3191         function print_runtime_info($link) {
3192                 print "<runtime-info>";
3193
3194                 $result = db_query($link, "SELECT COUNT(*) AS cf FROM
3195                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
3196
3197                 $num_feeds = db_fetch_result($result, 0, "cf");
3198
3199                 print "<param key=\"num_feeds\" value=\"".
3200                         (int)$num_feeds. "\"/>";
3201
3202                 if (ENABLE_UPDATE_DAEMON) {
3203                         print "<param key=\"daemon_is_running\" value=\"".
3204                                 (int) file_is_locked("update_daemon.lock") . "\"/>";
3205
3206                         if (time() - $_SESSION["daemon_stamp_check"] > 30) {
3207
3208                                 $stamp = (int) file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
3209
3210                                 if ($stamp) {
3211                                         $stamp_delta = time() - $stamp;
3212
3213                                         if ($stamp_delta > 1800) {
3214                                                 $stamp_check = 0;
3215                                         } else {
3216                                                 $stamp_check = 1;
3217                                                 $_SESSION["daemon_stamp_check"] = time();
3218                                         }
3219
3220                                         print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
3221
3222                                         $stamp_fmt = date("Y.m.d, G:i", $stamp);
3223
3224                                         print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
3225                                 }
3226                         }
3227                 }
3228
3229                 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
3230                         
3231                         if ($_SESSION["last_version_check"] + 86400 + rand(-1000, 1000) < time()) {
3232                                 $new_version_details = check_for_update($link);
3233
3234                                 print "<param key=\"new_version_available\" value=\"".
3235                                         sprintf("%d", $new_version_details != ""). "\"/>";
3236
3237                                 $_SESSION["last_version_check"] = time();
3238                         }
3239                 }
3240
3241 //              print "<param key=\"new_version_available\" value=\"1\"/>";
3242
3243                 print "</runtime-info>";
3244         }
3245
3246         function getSearchSql($search, $match_on) {
3247
3248                 $search_query_part = "";
3249
3250                 $keywords = split(" ", $search);
3251                 $query_keywords = array();
3252
3253                 if ($match_on == "both") {
3254
3255                         foreach ($keywords as $k) {
3256                                 if (strpos($k, "-") === 0) {
3257                                         $k = substr($k, 1);
3258                                         $not = "NOT";
3259                                 } else {
3260                                         $not = "";
3261                                 }
3262
3263                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
3264                                         OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3265                         }
3266
3267                         $search_query_part = implode("AND", $query_keywords) . " AND ";
3268
3269                 } else if ($match_on == "title") {
3270
3271                         foreach ($keywords as $k) {
3272                                 if (strpos($k, "-") === 0) {
3273                                         $k = substr($k, 1);
3274                                         $not = "NOT";
3275                                 } else {
3276                                         $not = "";
3277                                 }
3278
3279                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
3280                         }
3281
3282                         $search_query_part = implode("AND", $query_keywords) . " AND ";
3283
3284                 } else if ($match_on == "content") {
3285
3286                         foreach ($keywords as $k) {
3287                                 if (strpos($k, "-") === 0) {
3288                                         $k = substr($k, 1);
3289                                         $not = "NOT";
3290                                 } else {
3291                                         $not = "";
3292                                 }
3293
3294                                 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
3295                         }
3296                 }
3297
3298                 $search_query_part = implode("AND", $query_keywords);
3299
3300                 return $search_query_part;
3301         }
3302
3303         function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
3304
3305                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3306
3307                 $ext_tables_part = "";
3308
3309                         if ($search) {
3310                         
3311                                 $search_query_part = getSearchSql($search, $match_on);
3312                                 $search_query_part .= " AND ";
3313
3314                         } else {
3315                                 $search_query_part = "";
3316                         }
3317
3318                         $view_query_part = "";
3319         
3320                         if ($view_mode == "adaptive" || $view_query_part == "noscores") {
3321                                 if ($search) {
3322                                         $view_query_part = " ";
3323                                 } else if ($feed != -1) {
3324                                         $unread = getFeedUnread($link, $feed, $cat_view);
3325                                         if ($unread > 0) {
3326                                                 $view_query_part = " unread = true AND ";
3327                                         }
3328                                 }
3329                         }
3330         
3331                         if ($view_mode == "marked") {
3332                                 $view_query_part = " marked = true AND ";
3333                         }
3334
3335                         if ($view_mode == "published") {
3336                                 $view_query_part = " published = true AND ";
3337                         }
3338
3339                         if ($view_mode == "unread") {
3340                                 $view_query_part = " unread = true AND ";
3341                         }
3342
3343                         if ($view_mode == "updated") {
3344                                 $view_query_part = " (last_read is null and unread = false) AND ";
3345                         }
3346
3347                         if ($limit > 0) {
3348                                 $limit_query_part = "LIMIT " . $limit;
3349                         } 
3350
3351                         $vfeed_query_part = "";
3352         
3353                         // override query strategy and enable feed display when searching globally
3354                         if ($search && $search_mode == "all_feeds") {
3355                                 $query_strategy_part = "ttrss_entries.id > 0";
3356                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
3357                         /* tags */
3358                         } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3359                                 $query_strategy_part = "ttrss_entries.id > 0";
3360                                 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3361                                         id = feed_id) as feed_title,";
3362                         } else if ($feed > 0 && $search && $search_mode == "this_cat") {
3363         
3364                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
3365
3366                                 $tmp_result = false;
3367
3368                                 if ($cat_view) {
3369                                         $tmp_result = db_query($link, "SELECT id 
3370                                                 FROM ttrss_feeds WHERE cat_id = '$feed'");
3371                                 } else {
3372                                         $tmp_result = db_query($link, "SELECT id
3373                                                 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds 
3374                                                         WHERE id = '$feed') AND id != '$feed'");
3375                                 }
3376         
3377                                 $cat_siblings = array();
3378         
3379                                 if (db_num_rows($tmp_result) > 0) {
3380                                         while ($p = db_fetch_assoc($tmp_result)) {
3381                                                 array_push($cat_siblings, "feed_id = " . $p["id"]);
3382                                         }
3383         
3384                                         $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
3385                                                 $feed, implode(" OR ", $cat_siblings));
3386         
3387                                 } else {
3388                                         $query_strategy_part = "ttrss_entries.id > 0";
3389                                 }
3390                                 
3391                         } else if ($feed > 0) {
3392         
3393                                 if ($cat_view) {
3394
3395                                         if ($feed > 0) {
3396                                                 $query_strategy_part = "cat_id = '$feed'";
3397                                         } else {
3398                                                 $query_strategy_part = "cat_id IS NULL";
3399                                         }
3400         
3401                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3402
3403                                 } else {                
3404                                         $tmp_result = db_query($link, "SELECT id 
3405                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
3406                                                 ORDER BY cat_id,title");
3407                 
3408                                         $parent_ids = array();
3409                 
3410                                         if (db_num_rows($tmp_result) > 0) {
3411                                                 while ($p = db_fetch_assoc($tmp_result)) {
3412                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
3413                                                 }
3414                 
3415                                                 $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
3416                                                         $feed, implode(" OR ", $parent_ids));
3417                 
3418                                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3419                                         } else {
3420                                                 $query_strategy_part = "feed_id = '$feed'";
3421                                         }
3422                                 }
3423                         } else if ($feed == 0 && !$cat_view) { // archive virtual feed
3424                                 $query_strategy_part = "feed_id IS NULL";
3425                         } else if ($feed == 0 && $cat_view) { // uncategorized
3426                                 $query_strategy_part = "cat_id IS NULL";
3427                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3428                         } else if ($feed == -1) { // starred virtual feed
3429                                 $query_strategy_part = "marked = true";
3430                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3431                         } else if ($feed == -2) { // published virtual feed OR labels category
3432
3433                                 if (!$cat_view) {
3434                                         $query_strategy_part = "published = true";
3435                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3436                                 } else {
3437                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3438
3439                                         $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3440         
3441                                         $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
3442                                                 ttrss_user_labels2.article_id = ref_id";
3443
3444                                 }
3445
3446                         } else if ($feed == -3) { // fresh virtual feed
3447                                 $query_strategy_part = "unread = true";
3448
3449                                 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
3450
3451                                 if (DB_TYPE == "pgsql") {
3452                                         $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' "; 
3453                                 } else {
3454                                         $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3455                                 }
3456
3457                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3458                         } else if ($feed == -4) { // all articles virtual feed
3459                                 $query_strategy_part = "true";
3460                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3461                         } else if ($feed <= -10) { // labels
3462                                 $label_id = -$feed - 11;
3463
3464                                 $query_strategy_part = "label_id = '$label_id' AND
3465                                         ttrss_labels2.id = ttrss_user_labels2.label_id AND
3466                                         ttrss_user_labels2.article_id = ref_id";
3467
3468                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3469                                 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
3470  
3471                         } else {
3472                                 $query_strategy_part = "id > 0"; // dumb
3473                         }
3474
3475                         if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
3476                                 $order_by = "date_entered";
3477                         } else {        
3478                                 $order_by = "date_entered DESC";
3479                         }
3480
3481                         if ($view_mode != "noscores") {
3482                                 $order_by = "score DESC, $order_by";
3483                         }
3484
3485                         if ($override_order) {
3486                                 $order_by = $override_order;
3487                         }
3488         
3489                         $feed_title = "";
3490
3491                         if ($search) {
3492                                 $feed_title = "Search results";
3493                         } else {
3494                                 if ($cat_view) {
3495                                         $feed_title = getCategoryTitle($link, $feed);
3496                                 } else {
3497                                         if ((int)$feed == $feed && $feed > 0) {
3498                                                 $result = db_query($link, "SELECT title,site_url,last_error 
3499                                                         FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
3500                 
3501                                                 $feed_title = db_fetch_result($result, 0, "title");
3502                                                 $feed_site_url = db_fetch_result($result, 0, "site_url");
3503                                                 $last_error = db_fetch_result($result, 0, "last_error");
3504                                         } else {
3505                                                 $feed_title = getFeedTitle($link, $feed);
3506                                         } 
3507                                 }
3508                         }
3509
3510                         $content_query_part = "content as content_preview,";
3511
3512                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3513         
3514                                 if ($feed >= 0) {
3515                                         $feed_kind = "Feeds";
3516                                 } else {
3517                                         $feed_kind = "Labels";
3518                                 }
3519         
3520                                 if ($limit_query_part) {
3521                                         $offset_query_part = "OFFSET $offset";
3522                                 }
3523
3524                                 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
3525                                         if (!$override_order) {
3526                                                 $order_by = "ttrss_feeds.title, $order_by";     
3527                                         }
3528                                 }
3529
3530                                 if ($feed != "0") {
3531                                         $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
3532                                         $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
3533
3534                                 } else {
3535                                         $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
3536                                                 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
3537                                 }
3538
3539                                 $query = "SELECT DISTINCT 
3540                                                 date_entered,
3541                                                 guid,
3542                                                 ttrss_entries.id,ttrss_entries.title,
3543                                                 updated,
3544                                                 note,
3545                                                 unread,feed_id,marked,published,link,last_read,orig_feed_id,
3546                                                 ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3547                                                 $vfeed_query_part
3548                                                 $content_query_part
3549                                                 ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3550                                                 author,score
3551                                         FROM
3552                                                 $from_qpart
3553                                         WHERE
3554                                         $feed_check_qpart
3555                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
3556                                         ttrss_user_entries.owner_uid = '$owner_uid' AND
3557                                         $search_query_part
3558                                         $view_query_part
3559                                         $query_strategy_part ORDER BY $order_by
3560                                         $limit_query_part $offset_query_part";
3561
3562                                 if ($_REQUEST["debug"]) print $query;
3563
3564                                 $result = db_query($link, $query);
3565         
3566                         } else {
3567                                 // browsing by tag
3568         
3569                                 $feed_kind = "Tags";
3570         
3571                                 $result = db_query($link, "SELECT
3572                                         guid,
3573                                         note,
3574                                         ttrss_entries.id as id,title,
3575                                         updated,
3576                                         unread,feed_id,orig_feed_id,
3577                                         marked,link,last_read,                          
3578                                         ".SUBSTRING_FOR_DATE."(last_read,1,19) as last_read_noms,
3579                                         $vfeed_query_part
3580                                         $content_query_part
3581                                         ".SUBSTRING_FOR_DATE."(updated,1,19) as updated_noms,
3582                                         score
3583                                         FROM
3584                                                 ttrss_entries,ttrss_user_entries,ttrss_tags
3585                                         WHERE
3586                                                 ref_id = ttrss_entries.id AND 
3587                                                 ttrss_user_entries.owner_uid = '$owner_uid' AND
3588                                                 post_int_id = int_id AND tag_name = '$feed' AND
3589                                                 $view_query_part
3590                                                 $search_query_part
3591                                                 $query_strategy_part ORDER BY $order_by
3592                                         $limit_query_part");    
3593                         }
3594
3595                         return array($result, $feed_title, $feed_site_url, $last_error);
3596                 
3597         }
3598
3599         function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3600                 $limit, $search, $search_mode, $match_on, $view_mode = false) {
3601
3602                 $note_style =   "float : right; background-color : #fff7d5; border-width : 1px; ".
3603                         "padding : 5px; border-style : dashed; border-color : #e7d796;".
3604                         "margin-bottom : 1em; color : #9a8c59;";
3605
3606                 if (!$limit) $limit = 30;
3607
3608                 $qfh_ret = queryFeedHeadlines($link, $feed, 
3609                         $limit, $view_mode, $is_cat, $search, $search_mode, 
3610                         $match_on, "date_entered DESC", 0, $owner_uid);
3611
3612                 $result = $qfh_ret[0];
3613                 $feed_title = htmlspecialchars($qfh_ret[1]);
3614                 $feed_site_url = $qfh_ret[2];
3615                 $last_error = $qfh_ret[3];
3616
3617 //              if (!$feed_site_url) $feed_site_url = "http://localhost/";
3618
3619                 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3620                         <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3621                         <rss version=\"2.0\">
3622                         <channel>
3623                         <title>$feed_title</title>
3624                         <link>$feed_site_url</link>
3625                         <description>Feed generated by Tiny Tiny RSS</description>";
3626  
3627                 while ($line = db_fetch_assoc($result)) {
3628                         print "<item>";
3629                         print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3630                         print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3631
3632                         $tags = get_article_tags($link, $line["id"], $owner_uid);
3633
3634                         foreach ($tags as $tag) {
3635                                 print "<category>" . htmlspecialchars($tag) . "</category>";
3636                         }
3637
3638                         $rfc822_date = date('r', strtotime($line["updated"]));
3639   
3640                         print "<pubDate>$rfc822_date</pubDate>";
3641
3642                         if ($line["author"]) {
3643                                 print "<author>" . htmlspecialchars($line["author"]) . "</author>";
3644                         }
3645  
3646                         print "<title>" . 
3647                                 htmlspecialchars($line["title"]) . "</title>";
3648   
3649                         print "<description><![CDATA[";
3650
3651                         if ($line["note"]) {
3652                                 print "<div style='$note_style'>";
3653                                 print $line["note"];
3654                                 print "</div>";
3655                         }
3656
3657                         print sanitize_rss($link, $line["content_preview"], false, $owner_uid);
3658                         print "]]></description>";
3659         
3660                         $enclosures = get_article_enclosures($link, $line["id"]);
3661
3662                         foreach ($enclosures as $e) {
3663                                 $type = htmlspecialchars($e['content_type']);
3664                                 $url = htmlspecialchars($e['content_url']);
3665                                 $length = $e['duration'];
3666                                 print "<enclosure url=\"$url\" type=\"$type\" length=\"$length\"/>";
3667                         }
3668
3669                         print "</item>";
3670                 }
3671   
3672                 print "</channel></rss>";
3673
3674         }
3675
3676         function getCategoryTitle($link, $cat_id) {
3677
3678                 if ($cat_id == -1) {
3679                         return __("Special");
3680                 } else if ($cat_id == -2) {
3681                         return __("Labels");
3682                 } else {
3683
3684                         $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3685                                 id = '$cat_id'");
3686
3687                         if (db_num_rows($result) == 1) {
3688                                 return db_fetch_result($result, 0, "title");
3689                         } else {
3690                                 return "Uncategorized";
3691                         }
3692                 }
3693         }
3694
3695         function strip_tags_long($string, $allowed) {
3696
3697                 $config = HTMLPurifier_Config::createDefault();
3698
3699                 $config->set('HTML', 'Allowed', $allowed);
3700                 $purifier = new HTMLPurifier($config);
3701
3702                 return $purifier->purify($string);              
3703
3704         }
3705
3706         // http://ru2.php.net/strip-tags
3707
3708 /*      function strip_tags_long($textstring, $allowed){
3709         while($textstring != strip_tags($textstring, $allowed))
3710     {
3711     while (strlen($textstring) != 0)
3712          {
3713          if (strlen($textstring) > 1024) {
3714               $otherlen = 1024;
3715          } else {
3716               $otherlen = strlen($textstring);
3717          }
3718          $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3719          $safetext .= $temptext;
3720          $textstring = substr_replace($textstring,'',0,$otherlen);
3721          }  
3722     $textstring = $safetext;
3723     }
3724         return $textstring;
3725 } */
3726
3727
3728         function sanitize_rss($link, $str, $force_strip_tags = false, $owner = false) {
3729                 $res = $str;
3730
3731                 if (!$owner) $owner = $_SESSION["uid"];
3732
3733                 if (get_pref($link, "STRIP_UNSAFE_TAGS", $owner) || $force_strip_tags) {
3734
3735 //                      $res = strip_tags_long($res, 
3736 //                              "<p><a><i><em><b><strong><code><pre><blockquote><br><img><ul><ol><li>");
3737
3738                         $res = strip_tags_long($res, 
3739                                 "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4");
3740
3741                 }
3742
3743                 if (get_pref($link, "STRIP_IMAGES", $owner)) {
3744                         $res = preg_replace('/<img[^>]+>/is', '', $res);
3745                 }
3746
3747                 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW', $owner)) {
3748                         $res = preg_replace("/href=/i", "target=\"_blank\" href=", $res);
3749                 }
3750
3751                 return $res;
3752         }
3753
3754         /**
3755          * Send by mail a digest of last articles.
3756          * 
3757          * @param mixed $link The database connection.
3758          * @param integer $limit The maximum number of articles by digest.
3759          * @return boolean Return false if digests are not enabled.
3760          */
3761         function send_headlines_digests($link, $limit = 100) {
3762
3763                 if (!DIGEST_ENABLE) return false;
3764
3765                 $user_limit = DIGEST_EMAIL_LIMIT;
3766                 $days = 1;
3767
3768                 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3769
3770                 if (DB_TYPE == "pgsql") {
3771                         $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3772                 } else if (DB_TYPE == "mysql") {
3773                         $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3774                 }
3775
3776                 $result = db_query($link, "SELECT id,email FROM ttrss_users 
3777                                 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3778
3779                 while ($line = db_fetch_assoc($result)) {
3780
3781                         if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3782                                 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3783
3784                                 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3785
3786                                 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3787                                 $digest = $tuple[0];
3788                                 $headlines_count = $tuple[1];
3789                                 $affected_ids = $tuple[2];
3790                                 $digest_text = $tuple[3];
3791
3792                                 if ($headlines_count > 0) {
3793
3794                                         $mail = new PHPMailer();
3795
3796                                         $mail->PluginDir = "lib/phpmailer/";
3797                                         $mail->SetLanguage("en", "lib/phpmailer/language/");
3798
3799                                         $mail->CharSet = "UTF-8";
3800
3801                                         $mail->From = DIGEST_FROM_ADDRESS;
3802                                         $mail->FromName = DIGEST_FROM_NAME;
3803                                         $mail->AddAddress($line["email"], $line["login"]);
3804
3805                                         if (DIGEST_SMTP_HOST) {
3806                                                 $mail->Host = DIGEST_SMTP_HOST;
3807                                                 $mail->Mailer = "smtp";
3808                                                 $mail->SMTPAuth = DIGEST_SMTP_LOGIN != '';
3809                                                 $mail->Username = DIGEST_SMTP_LOGIN;
3810                                                 $mail->Password = DIGEST_SMTP_PASSWORD;
3811                                         }
3812
3813                                         $mail->IsHTML(true);
3814                                         $mail->Subject = DIGEST_SUBJECT;
3815                                         $mail->Body = $digest;
3816                                         $mail->AltBody = $digest_text;
3817
3818                                         $rc = $mail->Send();
3819
3820                                         if (!$rc) print "ERROR: " . $mail->ErrorInfo;
3821
3822                                         print "RC=$rc\n";
3823
3824                                         if ($rc && $do_catchup) {
3825                                                 print "Marking affected articles as read...\n";
3826                                                 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3827                                         }
3828
3829                                         db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
3830                                                         WHERE id = " . $line["id"]);
3831                                 } else {
3832                                         print "No headlines\n";
3833                                 }
3834                         }
3835                 }
3836
3837                 print "All done.\n";
3838
3839         }
3840
3841         function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3842
3843                 require_once "lib/MiniTemplator.class.php";
3844
3845                 $tpl = new MiniTemplator;
3846                 $tpl_t = new MiniTemplator;
3847
3848                 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3849                 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3850
3851                 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3852                 $tpl->setVariable('CUR_TIME', date('G:i'));
3853
3854                 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3855                 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3856
3857                 $affected_ids = array();
3858
3859                 if (DB_TYPE == "pgsql") {
3860                         $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
3861                 } else if (DB_TYPE == "mysql") {
3862                         $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
3863                 }
3864
3865                 $result = db_query($link, "SELECT ttrss_entries.title,
3866                                 ttrss_feeds.title AS feed_title,
3867                                 date_updated,
3868                                 ttrss_user_entries.ref_id,
3869                                 link,
3870                                 SUBSTRING(content, 1, 120) AS excerpt,
3871                                 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
3872                         FROM 
3873                                 ttrss_user_entries,ttrss_entries,ttrss_feeds 
3874                         WHERE 
3875                                 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id 
3876                                 AND include_in_digest = true
3877                                 AND $interval_query
3878                                 AND ttrss_user_entries.owner_uid = $user_id
3879                                 AND unread = true 
3880                         ORDER BY ttrss_feeds.title, date_updated DESC
3881                         LIMIT $limit");
3882
3883                 $cur_feed_title = "";
3884
3885                 $headlines_count = db_num_rows($result);
3886
3887                 $headlines = array();
3888
3889                 while ($line = db_fetch_assoc($result)) {
3890                         array_push($headlines, $line);
3891                 }
3892
3893                 for ($i = 0; $i < sizeof($headlines); $i++) {   
3894
3895                         $line = $headlines[$i];
3896
3897                         array_push($affected_ids, $line["ref_id"]);
3898
3899                         $updated = smart_date_time(strtotime($line["last_updated"]));
3900
3901                         $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3902                         $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3903                         $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3904                         $tpl->setVariable('ARTICLE_UPDATED', $updated);
3905                         $tpl->setVariable('ARTICLE_EXCERPT', 
3906                                 truncate_string(strip_tags($line["excerpt"]), 100));
3907
3908                         $tpl->addBlock('article');
3909
3910                         $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3911                         $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3912                         $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3913                         $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3914 //                      $tpl_t->setVariable('ARTICLE_EXCERPT', 
3915 //                              truncate_string(strip_tags($line["excerpt"]), 100));
3916
3917                         $tpl_t->addBlock('article');
3918
3919                         if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3920                                 $tpl->addBlock('feed');
3921                                 $tpl_t->addBlock('feed');
3922                         }
3923
3924                 }
3925
3926                 $tpl->addBlock('digest');
3927                 $tpl->generateOutputToString($tmp);
3928
3929                 $tpl_t->addBlock('digest');
3930                 $tpl_t->generateOutputToString($tmp_t);
3931
3932                 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3933         }
3934
3935         function check_for_update($link) {
3936                 $releases_feed = "http://tt-rss.org/releases.rss";
3937
3938                 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
3939                         return;
3940                 }
3941
3942                 error_reporting(0);
3943                 if (DEFAULT_UPDATE_METHOD == "1") {
3944                         $rss = new SimplePie();
3945                         $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
3946 //                      $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3947                         $rss->set_feed_url($fetch_url);
3948                         $rss->set_output_encoding('UTF-8');
3949                         $rss->init();
3950                 } else {
3951                         $rss = fetch_rss($releases_feed);
3952                 }
3953                 error_reporting (DEFAULT_ERROR_LEVEL);
3954
3955                 if ($rss) {
3956
3957                         if (DEFAULT_UPDATE_METHOD == "1") {
3958                                 $items = $rss->get_items();
3959                         } else {
3960                                 $items = $rss->items;
3961
3962                                 if (!$items || !is_array($items)) $items = $rss->entries;
3963                                 if (!$items || !is_array($items)) $items = $rss;
3964                         }
3965
3966                         if (!is_array($items) || count($items) == 0) {
3967                                 return;
3968                         }                       
3969
3970                         $latest_item = $items[0];
3971
3972                         if (DEFAULT_UPDATE_METHOD == "1") {
3973                                 $last_title = $latest_item->get_title();
3974                         } else {
3975                                 $last_title = $latest_item["title"];
3976                         }
3977
3978                         $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3979
3980                         if (DEFAULT_UPDATE_METHOD == "1") {
3981                                 $release_url = sanitize_rss($link, $latest_item->get_link());
3982                                 $content = sanitize_rss($link, $latest_item->get_description());
3983                         } else {
3984                                 $release_url = sanitize_rss($link, $latest_item["link"]);
3985                                 $content = sanitize_rss($link, $latest_item["description"]);
3986                         }
3987
3988                         if (version_compare(VERSION, $latest_version) == -1) {
3989                                 return sprintf("New version of Tiny-Tiny RSS (%s) is available:", 
3990                                         $latest_version)."<div class='milestoneDetails'>$content</div>";
3991                         } else {
3992                                 return false;
3993                         }       
3994                 }
3995         }
3996
3997         function markArticlesById($link, $ids, $cmode) {
3998
3999                 $tmp_ids = array();
4000
4001                 foreach ($ids as $id) {
4002                         array_push($tmp_ids, "ref_id = '$id'");
4003                 }
4004
4005                 $ids_qpart = join(" OR ", $tmp_ids);
4006
4007                 if ($cmode == 0) {
4008                         db_query($link, "UPDATE ttrss_user_entries SET 
4009                         marked = false,last_read = NOW()
4010                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4011                 } else if ($cmode == 1) {
4012                         db_query($link, "UPDATE ttrss_user_entries SET 
4013                         marked = true
4014                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4015                 } else {
4016                         db_query($link, "UPDATE ttrss_user_entries SET 
4017                         marked = NOT marked,last_read = NOW()
4018                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4019                 }
4020         }
4021
4022         function publishArticlesById($link, $ids, $cmode) {
4023
4024                 $tmp_ids = array();
4025
4026                 foreach ($ids as $id) {
4027                         array_push($tmp_ids, "ref_id = '$id'");
4028                 }
4029
4030                 $ids_qpart = join(" OR ", $tmp_ids);
4031
4032                 if ($cmode == 0) {
4033                         db_query($link, "UPDATE ttrss_user_entries SET 
4034                         published = false,last_read = NOW()
4035                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4036                 } else if ($cmode == 1) {
4037                         db_query($link, "UPDATE ttrss_user_entries SET 
4038                         published = true
4039                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4040                 } else {
4041                         db_query($link, "UPDATE ttrss_user_entries SET 
4042                         published = NOT published,last_read = NOW()
4043                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
4044                 }
4045         }
4046
4047         function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
4048
4049                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4050                 if (count($ids) == 0) return;
4051
4052                 $tmp_ids = array();
4053
4054                 foreach ($ids as $id) {
4055                         array_push($tmp_ids, "ref_id = '$id'");
4056                 }
4057
4058                 $ids_qpart = join(" OR ", $tmp_ids);
4059
4060                 if ($cmode == 0) {
4061                         db_query($link, "UPDATE ttrss_user_entries SET 
4062                         unread = false,last_read = NOW()
4063                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4064                 } else if ($cmode == 1) {
4065                         db_query($link, "UPDATE ttrss_user_entries SET 
4066                         unread = true
4067                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4068                 } else {
4069                         db_query($link, "UPDATE ttrss_user_entries SET 
4070                         unread = NOT unread,last_read = NOW()
4071                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4072                 }
4073
4074                 /* update ccache */
4075
4076                 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
4077                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
4078
4079                 while ($line = db_fetch_assoc($result)) {
4080                         ccache_update($link, $line["feed_id"], $owner_uid);
4081                 }
4082         }
4083
4084         function catchupArticleById($link, $id, $cmode) {
4085
4086                 if ($cmode == 0) {
4087                         db_query($link, "UPDATE ttrss_user_entries SET 
4088                         unread = false,last_read = NOW()
4089                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4090                 } else if ($cmode == 1) {
4091                         db_query($link, "UPDATE ttrss_user_entries SET 
4092                         unread = true
4093                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4094                 } else {
4095                         db_query($link, "UPDATE ttrss_user_entries SET 
4096                         unread = NOT unread,last_read = NOW()
4097                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4098                 }
4099
4100                 $feed_id = getArticleFeed($link, $id);
4101                 ccache_update($link, $feed_id, $_SESSION["uid"]);
4102         }
4103
4104         function make_guid_from_title($title) {
4105                 return preg_replace("/[ \"\',.:;]/", "-", 
4106                         mb_strtolower(strip_tags($title), 'utf-8'));
4107         }
4108
4109         function print_headline_subtoolbar($link, $feed_site_url, $feed_title, 
4110                         $feed_id, $is_cat, $search, $match_on,
4111                         $search_mode, $view_mode) {
4112
4113                         print "<div class=\"headlinesSubToolbar\">";
4114
4115                         $page_prev_link = "javascript:viewFeedGoPage(-1)";
4116                         $page_next_link = "javascript:viewFeedGoPage(1)";
4117                         $page_first_link = "javascript:viewFeedGoPage(0)";
4118
4119                         $catchup_page_link = "javascript:catchupPage()";
4120                         $catchup_feed_link = "javascript:catchupCurrentFeed()";
4121                         $catchup_sel_link = "javascript:catchupSelection()";
4122
4123                         $archive_sel_link = "javascript:archiveSelection()";
4124                         $delete_sel_link = "javascript:deleteSelection()";
4125
4126                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4127
4128                                 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
4129                                 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
4130                                 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
4131                                 $sel_inv_link = "javascript:invertHeadlineSelection()";
4132
4133                                 $tog_unread_link = "javascript:selectionToggleUnread()";
4134                                 $tog_marked_link = "javascript:selectionToggleMarked()";
4135                                 $tog_published_link = "javascript:selectionTogglePublished()";
4136
4137                         } else {
4138
4139                                 $sel_all_link = "javascript:cdmSelectArticles('all')";
4140                                 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
4141                                 $sel_none_link = "javascript:cdmSelectArticles('none')";
4142
4143                                 $sel_inv_link = "javascript:invertHeadlineSelection()";
4144
4145                                 $tog_unread_link = "javascript:selectionToggleUnread(true)";
4146                                 $tog_marked_link = "javascript:selectionToggleMarked(true)";
4147                                 $tog_published_link = "javascript:selectionTogglePublished(true)";
4148
4149                         }
4150
4151                         print "<div id=\"subtoolbar_ftitle\">";
4152
4153                         if ($feed_site_url) {
4154                                 $target = "target=\"_blank\"";
4155                                 print "<a title=\"".__("Visit the website")."\"$target href=\"$feed_site_url\">".
4156                                         truncate_string($feed_title,30)."</a>";
4157                         } else {
4158                                 if ($feed_id < -10) {
4159                                         $label_id = -11-$feed_id;
4160
4161                                         $result = db_query($link, "SELECT fg_color, bg_color
4162                                                 FROM ttrss_labels2 WHERE id = '$label_id' AND owner_uid = " .
4163                                                 $_SESSION["uid"]);
4164
4165                                         if (db_num_rows($result) != 0) {
4166                                                 $fg_color = db_fetch_result($result, 0, "fg_color");
4167                                                 $bg_color = db_fetch_result($result, 0, "bg_color");
4168
4169                                                 print "<span style='background : $bg_color; color : $fg_color'>";
4170                                                 print $feed_title;
4171                                                 print "</span>";
4172                                         } else {
4173                                                 print $feed_title;
4174                                         }
4175
4176                                 } else {
4177                                         print $feed_title;
4178                                 }
4179                         }
4180
4181                         if ($search) {
4182                                 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
4183                         } else {
4184                                 $search_q = "";
4185                         }
4186
4187                         $rss_link = "backend.php?op=rss&id=$feed_id&is_cat=$is_cat&view-mode=$view_mode$search_q";
4188
4189                         print "
4190                                 <a target=\"_blank\"
4191                                         title=\"".__("View as RSS feed")."\"
4192                                         href=\"$rss_link\">
4193                                         <img class=\"noborder\" src=\"images/feed-icon-12x12.png\"></a>";
4194
4195                         print "</div>";
4196
4197                         print __('Select:')."
4198                                 <a href=\"$sel_all_link\">".__('All')."</a>,
4199                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
4200                                 <a href=\"$sel_inv_link\">".__('Invert')."</a>,
4201                                 <a href=\"$sel_none_link\">".__('None')."</a></li>";
4202
4203                         print "&nbsp;&nbsp;";
4204
4205                         print "<span 
4206                                 onmouseover=\"enable_selection(false)\" 
4207             onmouseout=\"enable_selection(true)\"
4208                                 onclick=\"toggleHeadlineActions()\" id=\"headlineActionsDrop\">".
4209                                 __("Actions...") . "&nbsp;&nbsp;<img width='11' height'7' 
4210                                 src=\"images/down_arrow.png\">
4211                                 </span>";
4212
4213                         print "<ul id=\"headlineActionsBody\" style=\"display : none\">";
4214
4215                         print "<li class=\"insensitive\">".__('Selection toggle:')."</li>
4216                                 <li onclick=\"$tog_unread_link\">&nbsp;&nbsp;".__('Unread')."</li>
4217                                 <li onclick=\"$tog_marked_link\">&nbsp;&nbsp;".__('Starred')."</li>
4218                                 <li onclick=\"$tog_published_link\">&nbsp;&nbsp;".__('Published')."</li>
4219                                 <li class=\"insensitive\">".__('Selection:')."</li>
4220                                 <li onclick=\"$catchup_sel_link\">&nbsp;&nbsp;".__('Mark as read')."</li>";
4221
4222 //                      print "<li onclick=\"$catchup_feed_link\">&nbsp;&nbsp;".__('Entire feed').
4223 //                              "</li>";
4224
4225                         if ($feed_id != "0") {
4226                                 print "<li onclick=\"$archive_sel_link\">&nbsp;&nbsp;".__('Archive')."</li>";
4227                         } else {
4228                                 print "<li onclick=\"$archive_sel_link\">&nbsp;&nbsp;".__('Move back')."</li>";
4229                                 print "<li onclick=\"$delete_sel_link\">&nbsp;&nbsp;".__('Delete')."</li>";
4230
4231                         } 
4232
4233                         //print "<li><span class=\"insensitive\">--------</span></li>";
4234                         print "<li class=\"insensitive\">".__('Assign label:')."</li>";
4235
4236                         print_labels_headlines_dropdown($link, $feed_id);
4237
4238                         print "<li class=\"insensitive\">".__('Feed:')."</li>";
4239                         print "<li onclick=\"window.open('$rss_link')\">&nbsp;&nbsp;".__('View as RSS')."</li>";
4240
4241                         print "</ul>";
4242
4243                         print "</div>";
4244                 }
4245
4246         function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
4247
4248                         $tmp_category = getCategoryTitle($link, $cat_id);
4249
4250                         if ($cat_id > 0) {
4251                                 $cat_unread = ccache_find($link, $cat_id, $_SESSION["uid"], true);
4252                         } else if ($cat_id == 0 || $cat_id == -2) {
4253                                 $cat_unread = getCategoryUnread($link, $cat_id);
4254                         }
4255
4256                         if ($hidden) {
4257                                 $holder_style = "display:none;";
4258                                 $ellipsis = "…";
4259                         } else {
4260                                 $holder_style = "";
4261                                 $ellipsis = "";
4262                         }
4263
4264                         $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4265
4266                         if ($can_browse) {
4267                                 $browse_cat_link = "onclick=\"javascript:viewCategory($cat_id)\"";
4268                                 $inner_title_class = "catTitle";
4269                         } else {
4270                                 $browse_cat_link = "";
4271                                 $inner_title_class = "catTitleNL";
4272                         }
4273
4274                         $cat_class = "feedCat";
4275
4276                         print "<li class=\"$cat_class\" id=\"FCAT-$cat_id\">
4277                                 <img onclick=\"toggleCollapseCat($cat_id)\" class=\"catCollapse\"
4278                                         title=\"".__('Click to collapse category')."\"
4279                                         src=\"images/cat-collapse.png\"><span class=\"$inner_title_class\" 
4280                                         id=\"FCATN-$cat_id\" $browse_cat_link/>$tmp_category</span>";
4281
4282                         print "<span id=\"FCAP-$cat_id\">";
4283
4284                         print " <span id=\"FCATCTR-$cat_id\" 
4285                                 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
4286
4287                         print "</span>";
4288
4289                         //print "</li>";
4290
4291                         print "<ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4292
4293         }
4294         
4295         function outputFeedList($link, $tags = false) {
4296
4297                 print "<ul class=\"feedList\" id=\"feedList\">";
4298
4299                 $owner_uid = $_SESSION["uid"];
4300
4301                 /* virtual feeds */
4302
4303                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4304
4305                         $cat_hidden = get_pref($link, "_COLLAPSED_SPECIAL");
4306
4307                         printCategoryHeader($link, -1, $cat_hidden, false);
4308                 }
4309
4310                 foreach (array(-4, -3, -1, -2, 0) as $i) {
4311                         printFeedEntry($i, "virt", false, false, 
4312                                 false, $link);
4313                 }
4314
4315                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
4316                         print "</ul></li>";
4317                 }
4318
4319                 if (!$tags) {
4320
4321
4322                                 $result = db_query($link, "SELECT * FROM
4323                                         ttrss_labels2 WHERE owner_uid = '$owner_uid' ORDER by caption");
4324                 
4325                                 if (db_num_rows($result) > 0) {
4326                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4327
4328                                                 $cat_hidden = get_pref($link, "_COLLAPSED_LABELS");
4329
4330                                                 printCategoryHeader($link, -2, $cat_hidden, true);
4331
4332                                         } else {
4333                                                 print "<li><hr></li>";
4334                                         }
4335                                 }
4336                 
4337                                 while ($line = db_fetch_assoc($result)) {
4338         
4339                                         $label_id = -$line['id'] - 11;
4340                                         $count = getFeedUnread($link, $label_id);
4341         
4342                                         printFeedEntry($label_id, 
4343                                                 "label", $line["caption"], 
4344                                                 $count, false, $link, 
4345                                                 false, false, false,
4346                                                 $line['fg_color'], $line['bg_color']);
4347                 
4348                                 }
4349
4350                                 if (db_num_rows($result) > 0) {
4351                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4352                                                 print "</ul>";
4353                                         }
4354                                 } 
4355
4356
4357                         if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4358                                 print "<li><hr></li>";
4359                         }
4360
4361                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4362                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4363                                         $order_by_qpart = "order_id,category,unread DESC,title";
4364                                 } else {
4365                                         $order_by_qpart = "order_id,category,title";
4366                                 }
4367                         } else {
4368                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4369                                         $order_by_qpart = "unread DESC,title";
4370                                 } else {                
4371                                         $order_by_qpart = "title";
4372                                 }
4373                         }
4374
4375                         $age_qpart = getMaxAgeSubquery();
4376
4377                         $query = "SELECT ttrss_feeds.*,
4378                                 ".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated_noms,
4379                                 cat_id,last_error,
4380                                 ttrss_feed_categories.title AS category,
4381                                 ttrss_feed_categories.collapsed,
4382                                 value AS unread 
4383                                 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
4384                                         ON (ttrss_feed_categories.id = cat_id)                  
4385                                 LEFT JOIN ttrss_counters_cache 
4386                                         ON
4387                                                 (ttrss_feeds.id = feed_id)
4388                                 WHERE 
4389                                         ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4390                                 ORDER BY $order_by_qpart"; 
4391
4392                         $result = db_query($link, $query);
4393
4394                         $actid = $_REQUEST["actid"];
4395         
4396                         /* real feeds */
4397         
4398                         $lnum = 0;
4399         
4400                         $total_unread = 0;
4401
4402                         $category = "";
4403
4404                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4405         
4406                         while ($line = db_fetch_assoc($result)) {
4407                         
4408                                 $feed = htmlspecialchars(trim($line["title"]));
4409
4410                                 if (!$feed) $feed = "[Untitled]";
4411
4412                                 $feed_id = $line["id"];   
4413                                 $unread = $line["unread"];
4414         
4415                                 $subop = $_REQUEST["subop"];
4416
4417                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4418                                         $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4419                                 } else {
4420                                         $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4421                                 }
4422
4423                                 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4424
4425                                 if ($rtl_content) {
4426                                         $rtl_tag = "dir=\"RTL\"";
4427                                 } else {
4428                                         $rtl_tag = "";
4429                                 }
4430
4431                                 $tmp_result = db_query($link,
4432                                         "SELECT SUM(value) AS unread FROM ttrss_feeds, ttrss_counters_cache 
4433                                                 WHERE parent_feed = '$feed_id' AND feed_id = id");
4434
4435                                 $unread += db_fetch_result($tmp_result, 0, "unread");
4436         
4437                                 $cat_id = $line["cat_id"];
4438
4439                                 $tmp_category = $line["category"];
4440
4441                                 if (!$tmp_category) {
4442                                         $tmp_category = __("Uncategorized");
4443                                 }
4444                                 
4445         //                      $class = ($lnum % 2) ? "even" : "odd";
4446
4447                                 if ($line["last_error"]) {
4448                                         $class = "error";
4449                                 } else {
4450                                         $class = "feed";
4451                                 }
4452         
4453                                 if ($actid == $feed_id) {
4454                                         $class .= "Selected";
4455                                 }
4456         
4457                                 $total_unread += $unread;
4458
4459                                 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4460                                 
4461                                         if ($category) {
4462                                                 print "</ul></li>";
4463                                         }
4464                                 
4465                                         $category = $tmp_category;
4466
4467                                         $collapsed = sql_bool_to_bool($line["collapsed"]);
4468
4469                                         // workaround for NULL category
4470                                         if ($category == __("Uncategorized")) {
4471                                                 $collapsed = get_pref($link, "_COLLAPSED_UNCAT");
4472                                         }
4473
4474                                         $cat_id = (int) $cat_id;
4475
4476                                         printCategoryHeader($link, $cat_id, $collapsed, true);
4477
4478                                 }
4479         
4480                                 printFeedEntry($feed_id, $class, $feed, $unread, 
4481                                         false, $link, $rtl_content, 
4482                                         $last_updated, $line["last_error"]);
4483         
4484                                 ++$lnum;
4485                         }
4486
4487                         if (db_num_rows($result) == 0) {
4488                                 print "<li>".__('No feeds to display.')."</li>";
4489                         }
4490
4491                 } else {
4492
4493                         // tags
4494
4495 /*                      $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4496                                 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4497                                 post_int_id = ttrss_user_entries.int_id AND 
4498                                 unread = true AND ref_id = ttrss_entries.id
4499                                 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name       
4500                         UNION
4501                                 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4502                         ORDER BY tag_name"); */
4503
4504                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4505                                 print "<li class=\"feedCat\">".__('Tags')."</li>";
4506                                 print "<ul class=\"feedCatList\">";
4507                         }
4508
4509                         $age_qpart = getMaxAgeSubquery();
4510
4511                         $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
4512                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
4513                                         AND ref_id = id AND $age_qpart
4514                                         AND unread = true)) AS count FROM ttrss_tags 
4515                                         WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name 
4516                                         ORDER BY count DESC LIMIT 50");
4517
4518                         $tags = array();
4519         
4520                         while ($line = db_fetch_assoc($result)) {
4521                                 $tags[$line["tag_name"]] += $line["count"];
4522                         }
4523         
4524                         foreach (array_keys($tags) as $tag) {
4525         
4526                                 $unread = $tags[$tag];
4527                                 $class = "tag";
4528
4529                                 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4530         
4531                         } 
4532
4533                         if (db_num_rows($result) == 0) {
4534                                 print "<li>No tags to display.</li>";
4535                         }
4536
4537                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4538                                 print "</ul>";
4539                         }
4540
4541                 }
4542
4543                 print "</ul>";
4544
4545         }
4546
4547         function get_article_tags($link, $id, $owner_uid = 0) {
4548
4549                 global $memcache;
4550
4551                 $a_id = db_escape_string($id);
4552
4553                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4554
4555                 $query = "SELECT DISTINCT tag_name, 
4556                         owner_uid as owner FROM
4557                         ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4558                         ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
4559
4560                 $obj_id = md5("TAGS:$owner_uid:$id");
4561                 $tags = array();        
4562
4563                 if ($memcache && $obj = $memcache->get($obj_id)) {
4564                         $tags = $obj;
4565                 } else {
4566                         $tmp_result = db_query($link, $query);
4567
4568                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
4569                                 array_push($tags, $tmp_line["tag_name"]);                               
4570                         }
4571
4572                         if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
4573                 }
4574
4575                 return $tags;
4576         }
4577
4578         function trim_value(&$value) {
4579                 $value = trim($value);
4580         }       
4581
4582         function trim_array($array) {
4583                 $tmp = $array;
4584                 array_walk($tmp, 'trim_value');
4585                 return $tmp;
4586         }
4587
4588         function tag_is_valid($tag) {
4589                 if ($tag == '') return false;
4590                 if (preg_match("/^[0-9]*$/", $tag)) return false;
4591                 if (mb_strlen($tag) > 250) return false;
4592
4593                 if (function_exists('iconv')) {
4594                         $tag = iconv("utf-8", "utf-8", $tag);
4595                 }
4596
4597                 if (!$tag) return false;
4598
4599                 return true;
4600         }
4601
4602         function render_login_form($link, $mobile = 0) {
4603                 switch ($mobile) {
4604                 case 0:
4605                         require_once "login_form.php";
4606                         break;
4607                 case 1:
4608                         require_once "mobile/login_form.php";
4609                         break;
4610                 case 2:
4611                         require_once "mobile/classic/login_form.php";
4612                 }
4613         }
4614
4615         // from http://developer.apple.com/internet/safari/faq.html
4616         function no_cache_incantation() {
4617                 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4618                 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4619                 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4620                 header("Cache-Control: post-check=0, pre-check=0", false);
4621                 header("Pragma: no-cache"); // HTTP/1.0
4622         }
4623
4624         function format_warning($msg, $id = "") {
4625                 global $link;
4626                 return "<div class=\"warning\" id=\"$id\"> 
4627                         <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4628         }
4629
4630         function format_notice($msg) {
4631                 global $link;
4632                 return "<div class=\"notice\" id=\"$id\"> 
4633                         <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
4634         }
4635
4636         function format_error($msg) {
4637                 global $link;
4638                 return "<div class=\"error\" id=\"$id\"> 
4639                         <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
4640         }
4641
4642         function print_notice($msg) {
4643                 return print format_notice($msg);
4644         }
4645
4646         function print_warning($msg) {
4647                 return print format_warning($msg);
4648         }
4649
4650         function print_error($msg) {
4651                 return print format_error($msg);
4652         }
4653
4654
4655         function T_sprintf() {
4656                 $args = func_get_args();
4657                 return vsprintf(__(array_shift($args)), $args);
4658         }
4659
4660         function format_inline_player($link, $url, $ctype) {
4661
4662                 $entry = "";
4663
4664                 if (($ctype == __("audio/mpeg")) &&  (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {  
4665                      
4666                         $entry .= "<object type=\"application/x-shockwave-flash\" 
4667                                 data=\"extras/button/musicplayer.swf?song_url=$url\" 
4668                                 width=\"17\" height=\"17\"> 
4669                                         <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object>";  
4670                 }
4671
4672                 /*
4673
4674                 if (substr($ctype,0,6)=="audio/" || $ctype=="application/ogg" || $ctype=="application/x-ogg") {
4675                         $entry .= "<audio controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4676                         if (($ctype == __("audio/mpeg")) && 
4677                                 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) { 
4678                                 $entry .= "<span><object type=\"application/x-shockwave-flash\" data=\"extras/button/musicplayer.swf?song_url=$url\" width=\"17\" height=\"17\"> <param name=\"movie\" value=\"extras/button/musicplayer.swf?song_url=$url\" /> </object></span>";
4679                         }
4680                         $entry .= "</audio> ";
4681                         if (($ctype == __("audio/mpeg")) && 
4682                                 (get_pref($link, "ENABLE_FLASH_PLAYER")) ) {
4683                                 $entry .= "<a id='switchToFlashLink' href='#' onclick='return switchToFlash(this)'>".__('Switch to Flash Player')."</a>";       
4684                                 $entry .= "<script type='text/javascript'>html5AudioOrFlash('$ctype');</script>"; 
4685                         }
4686                 } elseif (substr($ctype,0,6)=="video/") {
4687                         $entry .= "<video controls=\"controls\"><source src=\"$url\" type=\"$ctype\" />";
4688                         $entry .= "</video>";
4689                 } */
4690
4691
4692
4693                 return $entry;
4694         }
4695
4696         function outputArticleXML($link, $id, $feed_id, $mark_as_read = true,
4697                 $zoom_mode = false) {
4698
4699                 /* we can figure out feed_id from article id anyway, why do we
4700                  * pass feed_id here? let's ignore the argument :( */
4701
4702                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4703                         WHERE ref_id = '$id'");
4704
4705                 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4706
4707                 if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
4708
4709                 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
4710                         WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4711
4712                 if (db_num_rows($result) == 1) {
4713                         $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4714                         $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
4715                 } else {
4716                         $rtl_content = false;
4717                         $always_display_enclosures = false;
4718                 }
4719
4720                 if ($rtl_content) {
4721                         $rtl_tag = "dir=\"RTL\"";
4722                         $rtl_class = "RTL";
4723                 } else {
4724                         $rtl_tag = "";
4725                         $rtl_class = "";
4726                 }
4727
4728                 if ($mark_as_read) {
4729                         $result = db_query($link, "UPDATE ttrss_user_entries 
4730                                 SET unread = false,last_read = NOW() 
4731                                 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4732
4733                         ccache_update($link, $feed_id, $_SESSION["uid"]);
4734                 }
4735
4736                 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4737                         ".SUBSTRING_FOR_DATE."(updated,1,16) as updated,
4738                         (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4739                         num_comments,
4740                         author,
4741                         orig_feed_id,
4742                         note
4743                         FROM ttrss_entries,ttrss_user_entries
4744                         WHERE   id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4745
4746                 if ($result) {
4747
4748                         $line = db_fetch_assoc($result);
4749
4750                         if ($line["icon_url"]) {
4751                                 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4752                         } else {
4753                                 $feed_icon = "&nbsp;";
4754                         }
4755
4756                         $num_comments = $line["num_comments"];
4757                         $entry_comments = "";
4758
4759                         if ($num_comments > 0) {
4760                                 if ($line["comments"]) {
4761                                         $comments_url = $line["comments"];
4762                                 } else {
4763                                         $comments_url = $line["link"];
4764                                 }
4765                                 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
4766                         } else {
4767                                 if ($line["comments"] && $line["link"] != $line["comments"]) {
4768                                         $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
4769                                 }                               
4770                         }
4771
4772                         if ($zoom_mode) {
4773                                 header("Content-Type: text/html");
4774                                 print "<html><head>
4775                                                 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
4776                                                 <title>Tiny Tiny RSS - ".$line["title"]."</title>
4777                                                 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
4778                                         </head><body>";
4779                         }
4780
4781
4782                         print "<div class=\"postReply\">";
4783
4784                         print "<div class=\"postHeader\" onmouseover=\"enable_resize(true)\" 
4785                                 onmouseout=\"enable_resize(false)\">";
4786
4787                         $entry_author = $line["author"];
4788
4789                         if ($entry_author) {
4790                                 $entry_author = __(" - ") . $entry_author;
4791                         }
4792
4793                         $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'), 
4794                                 strtotime($line["updated"]));
4795                 
4796                         print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4797
4798                         if ($line["link"]) {
4799                                 print "<div clear='both'><a target='_blank' href=\"" . $line["link"] . "\">" . 
4800                                         $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4801                         } else {
4802                                 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4803                         }
4804
4805                         $tags_str = format_tags_string(get_article_tags($link, $id), $id);
4806
4807                         if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4808
4809                         print "<div style='float : right'>
4810                                 <img src='".theme_image($link, 'images/tag.png')."' 
4811                                 class='tagsPic' alt='Tags' title='Tags'>&nbsp;";
4812
4813                         if (!$zoom_mode) {
4814                                 print "<span id=\"ATSTR-$id\">$tags_str</span>
4815                                         <a title=\"".__('Edit tags for this article')."\" 
4816                                         href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a>";
4817
4818                                 print "<img src=\"".theme_image($link, 'images/art-zoom.png')."\" 
4819                                                 class='tagsPic' style=\"cursor : pointer\" style=\"cursor : pointer\"
4820                                                 onclick=\"zoomToArticle($id)\"
4821                                                 alt='Zoom' title='".__('Show article summary in new window')."'>";
4822
4823                                 $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
4824
4825                                 print "<img src=\"".theme_image($link, 'images/art-pub-note.png')."\" 
4826                                                 class='tagsPic' style=\"cursor : pointer\" style=\"cursor : pointer\"
4827                                                 onclick=\"publishWithNote($id, '$note_escaped')\"
4828                                                 alt='PubNote' title='".__('Publish article with a note')."'>";
4829
4830                         } else {
4831                                 $tags_str = strip_tags($tags_str);
4832                                 print "<span id=\"ATSTR-$id\">$tags_str</span>";
4833                         }
4834                         print "</div>";
4835                         print "<div clear='both'>$entry_comments</div>";
4836
4837                         if ($line["orig_feed_id"]) {
4838
4839                                 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
4840                                         WHERE id = ".$line["orig_feed_id"]);
4841
4842                                 if (db_num_rows($tmp_result) != 0) {
4843
4844                                         print "<div clear='both'>";
4845                                         print __("Originally from:");
4846
4847                                         print "&nbsp;";
4848
4849                                         $tmp_line = db_fetch_assoc($tmp_result);
4850
4851                                         print "<a target='_blank' 
4852                                                 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
4853                                                 $tmp_line['title'] . "</a>";
4854
4855                                         print "&nbsp;";
4856
4857                                         print "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
4858                                         print "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
4859
4860                                         print "</div>";
4861                                 }
4862                         }
4863
4864                         print "</div>";
4865
4866                         print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4867
4868                         print "<div class=\"postContent\">";
4869
4870                         $article_content = sanitize_rss($link, $line["content"]);
4871
4872                         print "<div id=\"POSTNOTE-$id\">";
4873                                 if ($line['note']) {
4874                                         print format_article_note($id, $line['note']);
4875                                 }
4876                         print "</div>";
4877
4878                         print $article_content;
4879
4880 //                      $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4881 //                              post_id = '$id' AND content_url != ''");
4882
4883                         $result = get_article_enclosures($link, $id);
4884
4885 //                      if (db_num_rows($result) > 0) {
4886
4887                         if (count($result) > 0) {
4888
4889                                 $entries_html = array();
4890                                 $entries = array();
4891
4892                                 //while ($line = db_fetch_assoc($result)) {
4893                                 foreach ($result as $line) {
4894
4895                                         $url = $line["content_url"];
4896                                         $ctype = $line["content_type"];
4897
4898                                         if (!$ctype) $ctype = __("unknown type");
4899
4900                                         $filename = substr($url, strrpos($url, "/")+1);
4901
4902                                         $entry = format_inline_player($link, $url, $ctype);
4903
4904                                         $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4905                                                 $filename . " (" . $ctype . ")" . "</a>";
4906
4907                                         array_push($entries_html, $entry);
4908
4909                                         $entry = array();
4910
4911                                         $entry["type"] = $ctype;
4912                                         $entry["filename"] = $filename;
4913                                         $entry["url"] = $url;
4914
4915                                         array_push($entries, $entry);
4916                                 }
4917
4918                                 print "<div class=\"postEnclosures\">";
4919
4920                                 if (!get_pref($link, "STRIP_IMAGES")) {
4921                                         if ($always_display_enclosures ||
4922                                                                 !preg_match("/<img/i", $article_content)) {
4923                                                                         
4924                                                 foreach ($entries as $entry) {
4925
4926                                                         if (preg_match("/image/", $entry["type"]) ||
4927                                                                         preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4928
4929                                                                         print "<p><img
4930                                                                         alt=\"".htmlspecialchars($entry["filename"])."\"
4931                                                                         src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4932                                                         }
4933                                                 }
4934                                         }
4935                                 }
4936
4937                                 if (db_num_rows($result) == 1) {
4938                                         print __("Attachment:") . " ";
4939                                 } else {
4940                                         print __("Attachments:") . " ";
4941                                 }
4942
4943                                 print join(", ", $entries_html);
4944
4945                                 print "</div>";
4946                         }
4947                 
4948                         print "</div>";
4949                         
4950                         print "</div>";
4951
4952                 }
4953
4954                 if (!$zoom_mode) { 
4955                         print "]]></article>"; 
4956                 } else {
4957                         print "
4958                                 <div style=\"text-align : center\">
4959                                 <button onclick=\"return window.close()\">".
4960                                         __("Close this window")."</button></div>";
4961                         print "</body></html>";
4962
4963                 }
4964
4965         }
4966
4967         function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4968                                         $next_unread_feed, $offset, $vgr_last_feed = false, 
4969                                         $override_order = false) {
4970
4971                 $disable_cache = false;
4972
4973                 $timing_info = getmicrotime();
4974
4975                 $topmost_article_ids = array();
4976
4977                 if (!$offset) {
4978                         $offset = 0;
4979                 }
4980
4981                 if ($subop == "undefined") $subop = "";
4982
4983                 $subop_split = split(":", $subop);
4984
4985                 if ($subop == "CatchupSelected") {
4986                         $ids = split(",", db_escape_string($_REQUEST["ids"]));
4987                         $cmode = sprintf("%d", $_REQUEST["cmode"]);
4988
4989                         catchupArticlesById($link, $ids, $cmode);
4990                 }
4991
4992                 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4993                         update_generic_feed($link, $feed, $cat_view, true);
4994                 }
4995
4996                 if ($subop == "MarkAllRead")  {
4997                         catchup_feed($link, $feed, $cat_view);
4998
4999                         if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
5000                                 if ($next_unread_feed) {
5001                                         $feed = $next_unread_feed;
5002                                 }
5003                         }
5004                 }
5005
5006                 if ($subop_split[0] == "MarkAllReadGR")  {
5007                         catchup_feed($link, $subop_split[1], false);
5008                 }
5009
5010                 // FIXME: might break tag display?
5011
5012                 if ($feed > 0) {                
5013                         $result = db_query($link,
5014                                 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
5015                 
5016                         if (db_num_rows($result) == 0) {
5017                                 print "<div align='center'>".__('Feed not found.')."</div>";                            
5018                                 return;
5019                         }
5020                 }
5021
5022                 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
5023
5024                         $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
5025                                 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
5026
5027                         if (db_num_rows($result) == 1) {
5028                                 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
5029                         } else {
5030                                 $rtl_content = false;
5031                         }
5032         
5033                         if ($rtl_content) {
5034                                 $rtl_tag = "dir=\"RTL\"";
5035                         } else {
5036                                 $rtl_tag = "";
5037                         }
5038                 } else {
5039                         $rtl_tag = "";
5040                         $rtl_content = false;
5041                 }
5042
5043                 $script_dt_add = get_script_dt_add();
5044
5045                 /// START /////////////////////////////////////////////////////////////////////////////////
5046
5047                 @$search = db_escape_string($_REQUEST["query"]);
5048
5049                 if ($search) { 
5050                         $disable_cache = true;
5051                 }
5052
5053                 @$search_mode = db_escape_string($_REQUEST["search_mode"]);
5054                 @$match_on = db_escape_string($_REQUEST["match_on"]);
5055
5056                 if (!$match_on) {
5057                         $match_on = "both";
5058                 }
5059
5060                 $real_offset = $offset * $limit;
5061
5062                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
5063
5064                 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, 
5065                         $search, $search_mode, $match_on, $override_order, $real_offset);
5066
5067                 if ($_REQUEST["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
5068
5069                 $result = $qfh_ret[0];
5070                 $feed_title = $qfh_ret[1];
5071                 $feed_site_url = $qfh_ret[2];
5072                 $last_error = $qfh_ret[3];
5073
5074                 $vgroup_last_feed = $vgr_last_feed;
5075
5076                 if ($feed == -2) {
5077                         $feed_site_url = article_publish_url($link);
5078                 }
5079
5080                 /// STOP //////////////////////////////////////////////////////////////////////////////////
5081
5082                 if (!$offset) {
5083                         print "<div id=\"headlinesContainer\" $rtl_tag>";
5084
5085                         if (!$result) {
5086                                 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
5087                                 return;
5088                         }
5089
5090                         print_headline_subtoolbar($link, $feed_site_url, $feed_title,
5091                                 $feed, $cat_view, $search, $match_on, $search_mode, $view_mode);
5092
5093                         print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
5094                 }
5095
5096                 $headlines_count = db_num_rows($result);
5097
5098                 if (db_num_rows($result) > 0) {
5099
5100 #                       print "\{$offset}";
5101
5102                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
5103                                 print "<table class=\"headlinesList\" id=\"headlinesList\" 
5104                                         cellspacing=\"0\">";
5105                         }
5106
5107                         $lnum = $limit*$offset;
5108
5109                         error_reporting (DEFAULT_ERROR_LEVEL);
5110         
5111                         $num_unread = 0;
5112                         $cur_feed_title = '';
5113
5114                         $fresh_intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE") * 60 * 60;
5115
5116                         while ($line = db_fetch_assoc($result)) {
5117
5118                                 $class = ($lnum % 2) ? "even" : "odd";
5119         
5120                                 $id = $line["id"];
5121                                 $feed_id = $line["feed_id"];
5122
5123                                 $labels = get_article_labels($link, $id);
5124
5125                                 $labels_str = "<span id=\"HLLCTR-$id\">";
5126                                 $labels_str .= format_article_labels($labels, $id);
5127                                 $labels_str .= "</span>";
5128         
5129                                 if (count($topmost_article_ids) < 5) {
5130                                         array_push($topmost_article_ids, $id);
5131                                 }
5132
5133                                 if ($line["last_read"] == "" && !sql_bool_to_bool($line["unread"])) {
5134         
5135                                         $update_pic = "<img id='FUPDPIC-$id' src=\"".
5136                                                 theme_image($link, 'images/updated.png')."\" 
5137                                                 alt=\"Updated\">";
5138                                 } else {
5139                                         $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\" 
5140                                                 alt=\"Updated\">";
5141                                 }
5142
5143                                 if (sql_bool_to_bool($line["unread"]) && 
5144                                         time() - strtotime($line["updated_noms"]) < $fresh_intl) {
5145
5146                                         $update_pic = "<img id='FUPDPIC-$id' src=\"".
5147                                                 theme_image($link, 'images/fresh_sign.png')."\" alt=\"Fresh\">";
5148                                 }
5149         
5150                                 if ($line["unread"] == "t" || $line["unread"] == "1") {
5151                                         $class .= "Unread";
5152                                         ++$num_unread;
5153                                         $is_unread = true;
5154                                 } else {
5155                                         $is_unread = false;
5156                                 }
5157
5158                                 if ($line["marked"] == "t" || $line["marked"] == "1") {
5159                                         $marked_pic = "<img id=\"FMPIC-$id\" 
5160                                                 src=\"".theme_image($link, 'images/mark_set.png')."\" 
5161                                                 class=\"markedPic\" alt=\"Unstar article\" 
5162                                                 onclick='javascript:tMark($id)'>";
5163                                 } else {
5164                                         $marked_pic = "<img id=\"FMPIC-$id\" 
5165                                                 src=\"".theme_image($link, 'images/mark_unset.png')."\" 
5166                                                 class=\"markedPic\" alt=\"Star article\" 
5167                                                 onclick='javascript:tMark($id)'>";
5168                                 }
5169
5170                                 if ($line["published"] == "t" || $line["published"] == "1") {
5171                                         $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link, 
5172                                                 'images/pub_set.png')."\" 
5173                                                 class=\"markedPic\"
5174                                                 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
5175                                 } else {
5176                                         $published_pic = "<img id=\"FPPIC-$id\" src=\"".theme_image($link,
5177                                                 'images/pub_unset.png')."\" 
5178                                                 class=\"markedPic\"
5179                                                 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
5180                                 }
5181
5182 #                               $content_link = "<a target=\"_blank\" href=\"".$line["link"]."\">" .
5183 #                                       $line["title"] . "</a>";
5184
5185 #                               $content_link = "<a 
5186 #                                       href=\"" . htmlspecialchars($line["link"]) . "\"
5187 #                                       onclick=\"view($id,$feed_id);\">" .
5188 #                                       $line["title"] . "</a>";
5189
5190 #                               $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
5191 #                                       $line["title"] . "</a>";
5192
5193                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
5194                                         $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
5195                                 } else {
5196                                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
5197                                         $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
5198                                 }                               
5199
5200                                 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5201                                         $content_preview = truncate_string(strip_tags($line["content_preview"]), 
5202                                                 100);
5203                                 }
5204
5205                                 $score = $line["score"];
5206
5207                                 $score_pic = theme_image($link, 
5208                                         "images/" . get_score_pic($score));
5209
5210 /*                              $score_title = __("(Click to change)");
5211                                 $score_pic = "<img class='hlScorePic' src=\"images/$score_pic\" 
5212                                         onclick=\"adjustArticleScore($id, $score)\" title=\"$score $score_title\">"; */
5213
5214                                 $score_pic = "<img class='hlScorePic' src=\"$score_pic\" 
5215                                         title=\"$score\">";
5216
5217                                 if ($score > 500) {
5218                                         $hlc_suffix = "H";
5219                                 } else if ($score < -100) {
5220                                         $hlc_suffix = "L";
5221                                 } else {
5222                                         $hlc_suffix = "";
5223                                 }
5224
5225                                 $entry_author = $line["author"];
5226
5227                                 if ($entry_author) {
5228                                         $entry_author = " - $entry_author";
5229                                 }
5230
5231                                 $has_feed_icon = feed_has_icon($feed_id);
5232
5233                                 if ($has_feed_icon) {
5234                                         $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5235                                 } else {
5236                                         //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5237                                         $feed_icon_img = "";
5238                                 }
5239
5240                                 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
5241
5242                                         if (get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5243                                                 if ($feed_id != $vgroup_last_feed && $line["feed_title"]) {
5244
5245                                                         $cur_feed_title = $line["feed_title"];
5246                                                         $vgroup_last_feed = $feed_id;
5247
5248                                                         $cur_feed_title = htmlspecialchars($cur_feed_title);
5249
5250                                                         $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5251
5252                                                         print "<tr class='feedTitle'><td colspan='7'>".
5253                                                                 "<div style=\"float : right\">$feed_icon_img</div>".
5254                                                                 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5255                                                                 $line["feed_title"]."</a> $vf_catchup_link</td></tr>";
5256                                                 }
5257                                         }
5258
5259                                         $mouseover_attrs = "onmouseover='postMouseIn($id)' 
5260                                                 onmouseout='postMouseOut($id)'";
5261
5262                                         print "<tr class='$class' id='RROW-$id' $mouseover_attrs>";
5263                 
5264                                         print "<td class='hlUpdPic'>$update_pic</td>";
5265                 
5266                                         print "<td class='hlSelectRow'>
5267                                                 <input type=\"checkbox\" onclick=\"tSR(this)\"
5268                                                         id=\"RCHK-$id\">
5269                                                 </td>";
5270                 
5271                                         print "<td class='hlMarkedPic'>$marked_pic</td>";
5272                                         print "<td class='hlMarkedPic'>$published_pic</td>";
5273
5274 #                                       if ($line["feed_title"]) {                      
5275 #                                               print "<td class='hlContent'>$content_link</td>";
5276 #                                               print "<td class='hlFeed'>
5277 #                                                       <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5278 #                                                               truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
5279 #                                       } else {                        
5280
5281                                         print "<td onclick='view($id)' class='hlContent$hlc_suffix' valign='middle' id='HLC-$id'>";
5282
5283                                         print "<a id=\"RTITLE-$id\" 
5284                                                 href=\"" . htmlspecialchars($line["link"]) . "\"
5285                                                 onclick=\"return false\">" .
5286                                                 $line["title"];
5287
5288                                         if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
5289                                                 if ($content_preview) {
5290                                                         print "<span class=\"contentPreview\"> - $content_preview</span>";
5291                                                 }
5292                                         }
5293
5294                                         print "</a>";
5295
5296                                         print $labels_str;
5297
5298 #                                                       <a href=\"javascript:viewfeed($feed_id, '', false)\">".
5299 #                                                       $line["feed_title"]."</a>       
5300
5301                                         if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5302                                                 if (@$line["feed_title"]) {                     
5303                                                         print "<span class=\"hlFeed\">
5304                                                                 (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5305                                                                 $line["feed_title"]."</a>)
5306                                                         </span>";
5307                                                 }
5308                                         }
5309
5310 //                                      print "<img id='HLL-$id' class='hlLoading' 
5311 //                                              src='images/indicator_tiny.gif' style='display : none'>";
5312
5313                                         print "</td>";
5314
5315 #                                       }
5316                                         
5317                                         print "<td class=\"hlUpdated\" onclick='view($id)'><nobr>$updated_fmt&nbsp;</nobr></td>";
5318
5319                                         print "<td class='hlMarkedPic'>$score_pic</td>";
5320
5321                                         if (@$line["feed_title"] && !get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5322                                                 print "<td onclick=\"viewfeed($feed_id)\" class=\"hlFeedIcon\">$feed_icon_img</td>";
5323                                         }
5324
5325                                         print "</tr>";
5326
5327                                 } else {
5328
5329                                         if (get_pref($link, 'VFEED_GROUP_BY_FEED') && $line["feed_title"]) {
5330                                                 if ($feed_id != $vgroup_last_feed) {
5331
5332                                                         $cur_feed_title = $line["feed_title"];
5333                                                         $vgroup_last_feed = $feed_id;
5334
5335                                                         $cur_feed_title = htmlspecialchars($cur_feed_title);
5336
5337                                                         $vf_catchup_link = "(<a onclick='javascript:catchupFeedInGroup($feed_id);' href='#'>".__('mark as read')."</a>)";
5338
5339                                                         $has_feed_icon = feed_has_icon($feed_id);
5340
5341                                                         if ($has_feed_icon) {
5342                                                                 $feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"".ICONS_URL."/$feed_id.ico\" alt=\"\">";
5343                                                         } else {
5344                                                                 //$feed_icon_img = "<img class=\"tinyFeedIcon\" src=\"images/blank_icon.gif\" alt=\"\">";
5345                                                         }
5346
5347                                                         print "<div class='cdmFeedTitle'>".
5348                                                                 "<div style=\"float : right\">$feed_icon_img</div>".
5349                                                                 "<a href=\"javascript:viewfeed($feed_id, '', false)\">".
5350                                                                 $line["feed_title"]."</a> $vf_catchup_link</div>";
5351                                                 }
5352                                         }
5353
5354                                         if ($is_unread) {
5355                                                 $add_class = "Unread";
5356                                         } else {
5357                                                 $add_class = "";
5358                                         }       
5359
5360                                         $expand_cdm = get_pref($link, 'CDM_EXPANDED');
5361                                         $show_excerpt = false;
5362
5363                                         if ($expand_cdm && $score >= -100) {
5364                                                 $cdm_cstyle = "";
5365                                                 $show_excerpt = false;
5366                                         } else {
5367                                                 $cdm_cstyle = "style=\"display : none\"";
5368                                                 $show_excerpt = true;
5369                                         }
5370
5371                                         $mouseover_attrs = "onmouseover='postMouseIn($id)' 
5372                                                 onmouseout='postMouseOut($id)'";
5373
5374                                         print "<div class=\"cdmArticle$add_class\" 
5375                                                 id=\"RROW-$id\"                                         
5376                                                 $mouseover_attrs'>";
5377
5378                                         print "<div class=\"cdmHeader\">";
5379
5380                                         if (!get_pref($link, "VFEED_GROUP_BY_FEED") || !$line["feed_title"]) {
5381                                                 $cdm_feed_icon = "<span style=\"cursor : pointer\" onclick=\"viewfeed($feed_id)\">$feed_icon_img</span>";
5382                                         }
5383
5384                                         print "<div class=\"articleUpdated\">$updated_fmt $score_pic $cdm_feed_icon
5385                                                 </div>";
5386
5387                                         print "<span id=\"RTITLE-$id\" class=\"titleWrap$hlc_suffix\"><a class=\"title\" 
5388                                                 onclick=\"javascript:toggleUnread($id, 0)\"
5389                                                 target=\"_blank\" href=\"".$line["link"]."\">".$line["title"]."</a>
5390                                                 ";
5391
5392                                         print $entry_author;
5393
5394 /*                                      if (!$expand_cdm || $score < -100) {
5395                                                 print "&nbsp;<a id=\"CICH-$id\" 
5396                                                         href=\"javascript:cdmExpandArticle($id)\">
5397                                                         (".__('Show article').")</a>";
5398                                         } */
5399
5400                                         print $labels_str;
5401
5402                                         if (!get_pref($link, 'VFEED_GROUP_BY_FEED')) {
5403                                                 if ($line["feed_title"]) {      
5404                                                         print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
5405                                                 }
5406                                         }
5407
5408                                         print "</span></div>";
5409
5410                                         if ($show_excerpt) {
5411                                                 print "<div class=\"cdmExcerpt\" id=\"CEXC-$id\"
5412                                                         onclick=\"cdmExpandArticle($id)\"
5413                                                         title=\"".__('Click to expand article')."\">";
5414
5415                                                 $content_preview = trim(truncate_string(strip_tags($line["content_preview"]), 100));
5416
5417                                                 if (strlen($content_preview) != 0) {
5418                                                         print $content_preview;
5419                                                 } else {
5420                                                         print __('Click to expand article');
5421                                                 }
5422                                                 print "</div>";
5423                                         }
5424         
5425                                         print "<div class=\"cdmContent\" 
5426                                                 onclick=\"cdmClicked($id)\"
5427                                                 id=\"CICD-$id\" $cdm_cstyle>";
5428
5429                                         if ($line["orig_feed_id"]) {
5430
5431                                                 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
5432                                                 WHERE id = ".$line["orig_feed_id"]);
5433
5434                                                 if (db_num_rows($tmp_result) != 0) {
5435
5436                                                 print "<div clear='both'>";
5437                                                 print __("Originally from:");
5438
5439                                                 print "&nbsp;";
5440
5441                                                 $tmp_line = db_fetch_assoc($tmp_result);
5442
5443                                                 print "<a target='_blank' 
5444                                                         href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
5445                                                         $tmp_line['title'] . "</a>";
5446
5447                                                 print "&nbsp;";
5448
5449                                                 print "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
5450                                                 print "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
5451
5452                                                 print "</div>";
5453                                         }
5454                                 }
5455
5456 //                                      print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
5457
5458                                         print "<div id=\"POSTNOTE-$id\">";
5459                                         if ($line['note']) {
5460                                                 print format_article_note($id, $line['note']);
5461                                         }
5462                                         print "</div>";
5463
5464                                         print sanitize_rss($link, $line["content_preview"]);
5465
5466                                         $article_content = $line["content_preview"];
5467
5468                                         $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
5469                                                 post_id = '$id' AND content_url != ''");
5470
5471                                         if (db_num_rows($e_result) > 0) {
5472
5473                                 $entries_html = array();
5474                                 $entries = array();
5475
5476                                 while ($e_line = db_fetch_assoc($e_result)) {
5477
5478                                         $url = $e_line["content_url"];
5479                                         $ctype = $e_line["content_type"];
5480                                         if (!$ctype) $ctype = __("unknown type");
5481
5482                                         $filename = substr($url, strrpos($url, "/")+1);
5483
5484                                         $entry = format_inline_player($link, $url, $ctype);
5485
5486                                         $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
5487                                                 $filename . " (" . $ctype . ")" . "</a>";
5488
5489                                         array_push($entries_html, $entry);
5490
5491                                         $entry = array();
5492
5493                                         $entry["type"] = $ctype;
5494                                         $entry["filename"] = $filename;
5495                                         $entry["url"] = $url;
5496
5497                                         array_push($entries, $entry);
5498                                 }
5499
5500                                 $tmp_result = db_query($link, "SELECT always_display_enclosures FROM
5501                                         ttrss_feeds WHERE id = ".
5502                                                 (($line['feed_id'] == null) ? $line['orig_feed_id'] : 
5503                                                                 $line['feed_id'])." AND owner_uid = ".$_SESSION["uid"]);
5504
5505                                 $always_display_enclosures = db_fetch_result($tmp_result, 0, "always_display_enclosures");
5506
5507                                 if (!get_pref($link, "STRIP_IMAGES")) {
5508                                         if ($always_display_enclosures || 
5509                                                                         !preg_match("/img/i", $article_content)) {
5510
5511                                                 foreach ($entries as $entry) {
5512                                                         if (preg_match("/image/", $entry["type"]) || 
5513                                                                 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
5514                                                                 print "<p><img 
5515                                                                         alt=\"".htmlspecialchars($entry["filename"])."\"
5516                                                                         src=\"" .htmlspecialchars($entry["url"]) . "\"></p>";
5517                                                         }
5518                                                 }
5519                                         }
5520                                 }
5521
5522                                 print "<div class=\"cdmEnclosures\">";
5523
5524                                 if (db_num_rows($e_result) == 1) {
5525                                         print __("Attachment:") . " ";
5526                                 } else {
5527                                         print __("Attachments:") . " ";
5528                                 }
5529
5530                                 print join(", ", $entries_html);
5531
5532                                 print "</div>";
5533                         }
5534
5535
5536                                         print "<br clear='both'>";
5537 //                                      print "</div>";
5538
5539 /*                                      if (!$expand_cdm) {
5540                                                 print "<a id=\"CICH-$id\" 
5541                                                         href=\"javascript:cdmExpandArticle($id)\">
5542                                                         Show article</a>";
5543                                         } */
5544
5545                                         print "</div>";
5546
5547                                         print "<div class=\"cdmFooter\"><span class='s0'>";
5548
5549                                         /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
5550
5551                                         print __("Select:").
5552                                                         " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this, 
5553                                                         'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
5554
5555                                         print "</span><span class='s1'>$marked_pic&nbsp;";
5556                                         print "$published_pic&nbsp;";
5557                                         print "<img src=\"images/art-zoom.png\" class='tagsPic' 
5558                                                 onclick=\"zoomToArticle($id)\"
5559                                                 style=\"cursor : pointer\"
5560                                                 alt='Zoom' 
5561                                                 title='".__('Show article summary in new window')."'>&nbsp;";
5562
5563                                         $note_escaped = htmlspecialchars($line['note'], ENT_QUOTES);
5564
5565                                         print "<img src=\"images/art-pub-note.png\" class='tagsPic' 
5566                                                 style=\"cursor : pointer\" style=\"cursor : pointer\"
5567                                                 onclick=\"publishWithNote($id, '$note_escaped')\"
5568                                                 alt='PubNote' title='".__('Publish article with a note')."'>";
5569
5570                                         print "</span>";
5571
5572                                         $tags_str = format_tags_string(get_article_tags($link, $id), $id);
5573
5574                                         print "<span class='s1'>
5575                                                 <img class='tagsPic' src='".theme_image($link,
5576                                                         'images/tag.png')."' alt='Tags' title='Tags'>
5577                                                 <span id=\"ATSTR-$id\">$tags_str</span>
5578                                                 <a title=\"".__('Edit tags for this article')."\" 
5579                                                 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
5580
5581                                         print "</span>";
5582
5583                                         print "<span class='s2'><a class=\"cdmToggleLink\"
5584                                                         href=\"javascript:toggleUnread($id)\">
5585                                                         ".__('toggle unread')."</a></span>";
5586
5587                                         print "</div>";
5588                                         print "</div>"; 
5589
5590                                 }                               
5591         
5592                                 ++$lnum;
5593                         }
5594
5595                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {                    
5596                                 print "</table>";
5597                         }
5598
5599                 } else {
5600                         $message = "";
5601
5602                         switch ($view_mode) {
5603                                 case "unread":
5604                                         $message = __("No unread articles found to display.");
5605                                         break;
5606                                 case "updated":
5607                                         $message = __("No updated articles found to display.");
5608                                         break;
5609                                 case "marked":
5610                                         $message = __("No starred articles found to display.");
5611                                         break;
5612                                 default:
5613                                         if ($feed < -10) {
5614                                                 $message = __("No articles found to display. You can assign articles to labels manually (see the Actions menu above) or use a filter.");
5615                                         } else {
5616                                                 $message = __("No articles found to display.");
5617                                         }
5618                         }
5619
5620                         if (!$offset) print "<div class='whiteBox'>$message</div>";
5621                 }
5622
5623                 if (!$offset) {
5624                         print "</div>";
5625                         print "</div>";
5626                 }
5627
5628                 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache, $vgroup_last_feed);
5629         }
5630
5631 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
5632
5633         function printTagCloud($link) {
5634
5635                 $query = "SELECT tag_name, COUNT(post_int_id) AS count 
5636                         FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]." 
5637                         GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5638
5639                 $result = db_query($link, $query);
5640
5641                 $tags = array();
5642
5643                 while ($line = db_fetch_assoc($result)) {
5644                         $tags[$line["tag_name"]] = $line["count"];
5645                 }
5646
5647                 ksort($tags);
5648
5649                 $max_size = 32; // max font size in pixels
5650                 $min_size = 11; // min font size in pixels
5651                    
5652                 // largest and smallest array values
5653                 $max_qty = max(array_values($tags));
5654                 $min_qty = min(array_values($tags));
5655                    
5656                 // find the range of values
5657                 $spread = $max_qty - $min_qty;
5658                 if ($spread == 0) { // we don't want to divide by zero
5659                                 $spread = 1;
5660                 }
5661                    
5662                 // set the font-size increment
5663                 $step = ($max_size - $min_size) / ($spread);
5664                    
5665                 // loop through the tag array
5666                 foreach ($tags as $key => $value) {
5667                         // calculate font-size
5668                         // find the $value in excess of $min_qty
5669                         // multiply by the font-size increment ($size)
5670                         // and add the $min_size set above
5671                         $size = round($min_size + (($value - $min_qty) * $step));
5672
5673                         $key_escaped = str_replace("'", "\\'", $key);
5674
5675                         echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " . 
5676                                 $size . "px\" title=\"$value articles tagged with " . 
5677                                 $key . '">' . $key . '</a> ';
5678                 }
5679         }
5680
5681         function print_checkpoint($n, $s) {
5682                 $ts = getmicrotime();   
5683                 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5684                 return $ts;
5685         }
5686
5687         function sanitize_tag($tag) {
5688                 $tag = trim($tag);
5689
5690                 $tag = mb_strtolower($tag, 'utf-8');
5691
5692                 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);  
5693
5694 //              $tag = str_replace('"', "", $tag);      
5695 //              $tag = str_replace("+", " ", $tag);     
5696                 $tag = str_replace("technorati tag: ", "", $tag);
5697
5698                 return $tag;
5699         }
5700
5701         function generate_publish_key() {
5702                 return sha1(uniqid(rand(), true));
5703         }
5704
5705         function article_publish_url($link) {
5706
5707                 $url_path = "";
5708                 
5709
5710                 if ($_SERVER['HTTPS'] != "on") {
5711                         $url_path = "http://";
5712                 } else {
5713                         $url_path = "https://";
5714                 }
5715
5716                 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5717                 $url_path .= "/backend.php?op=publish&key=" . 
5718                         get_pref($link, "_PREFS_PUBLISH_KEY", $_SESSION["uid"]);
5719
5720                 return $url_path;
5721         }
5722         function opml_publish_url($link){
5723                 $url_path = "";
5724                 
5725
5726                 if ($_SERVER['HTTPS'] != "on") {
5727                         $url_path = "http://";
5728                 } else {
5729                         $url_path = "https://";
5730                 }
5731
5732                 $url_path .= $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
5733                 $url_path .= "/opml.php?op=publish&key=" . 
5734                         get_pref($link, "_PREFS_PUBLISH_KEY", $_SESSION["uid"]);
5735
5736                 return $url_path;
5737         }
5738
5739         /**
5740          * Purge a feed contents, marked articles excepted.
5741          * 
5742          * @param mixed $link The database connection.
5743          * @param integer $id The id of the feed to purge.
5744          * @return void
5745          */
5746         function clear_feed_articles($link, $id) {
5747
5748                 if ($id != 0) {
5749                         $result = db_query($link, "DELETE FROM ttrss_user_entries
5750                         WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5751                 } else {
5752                         $result = db_query($link, "DELETE FROM ttrss_user_entries
5753                         WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5754                 }
5755
5756                 $result = db_query($link, "DELETE FROM ttrss_entries WHERE 
5757                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5758
5759                 ccache_update($link, $id, $_SESSION['uid']);
5760         } // function clear_feed_articles
5761
5762         /**
5763          * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
5764          *
5765          * @return string The Mozilla Firefox feed adding URL.
5766          */
5767         function add_feed_url() {
5768                 $url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' :  'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5769                 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5770                 return $url_path;
5771         } // function add_feed_url
5772
5773         /**
5774          * Encrypt a password in SHA1.
5775          * 
5776          * @param string $pass The password to encrypt.
5777          * @param string $login A optionnal login.
5778          * @return string The encrypted password.
5779          */
5780         function encrypt_password($pass, $login = '') {
5781                 if ($login) {
5782                         return "SHA1X:" . sha1("$login:$pass");
5783                 } else {
5784                         return "SHA1:" . sha1($pass);
5785                 }
5786         } // function encrypt_password
5787
5788         /**
5789          * Update a feed batch.
5790          * Used by daemons to update n feeds by run.
5791          * Only update feed needing a update, and not being processed
5792          * by another process.
5793          * 
5794          * @param mixed $link Database link
5795          * @param integer $limit Maximum number of feeds in update batch. Default to DAEMON_FEED_LIMIT.
5796          * @param boolean $from_http Set to true if you call this function from http to disable cli specific code.
5797          * @param boolean $debug Set to false to disable debug output. Default to true.
5798          * @return void
5799          */
5800         function update_daemon_common($link, $limit = DAEMON_FEED_LIMIT, $from_http = false, $debug = true) {
5801                 // Process all other feeds using last_updated and interval parameters
5802
5803                 // Test if the user has loggued in recently. If not, it does not update its feeds.
5804                 if (DAEMON_UPDATE_LOGIN_LIMIT > 0) {
5805                         if (DB_TYPE == "pgsql") {
5806                                 $login_thresh_qpart = "AND ttrss_users.last_login >= NOW() - INTERVAL '".DAEMON_UPDATE_LOGIN_LIMIT." days'";
5807                         } else {
5808                                 $login_thresh_qpart = "AND ttrss_users.last_login >= DATE_SUB(NOW(), INTERVAL ".DAEMON_UPDATE_LOGIN_LIMIT." DAY)";
5809                         }                       
5810                 } else {
5811                         $login_thresh_qpart = "";
5812                 }
5813
5814                 // Test if the feed need a update (update interval exceded).
5815                 if (DB_TYPE == "pgsql") {
5816                         $update_limit_qpart = "AND ((
5817                                         ttrss_feeds.update_interval = 0
5818                                         AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
5819                                 ) OR (
5820                                         ttrss_feeds.update_interval > 0
5821                                         AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
5822                                 ) OR ttrss_feeds.last_updated IS NULL)";
5823                 } else {
5824                         $update_limit_qpart = "AND ((
5825                                         ttrss_feeds.update_interval = 0
5826                                         AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
5827                                 ) OR (
5828                                         ttrss_feeds.update_interval > 0
5829                                         AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
5830                                 ) OR ttrss_feeds.last_updated IS NULL)";
5831                 }
5832
5833                 // Test if feed is currently being updated by another process.
5834                 if (DB_TYPE == "pgsql") {
5835                         $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
5836                 } else {
5837                         $updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
5838                 }
5839
5840                 // Test if there is a limit to number of updated feeds
5841                 $query_limit = "";
5842                 if($limit) $query_limit = sprintf("LIMIT %d", $limit);
5843
5844                 $random_qpart = sql_random_function();
5845
5846                 // We search for feed needing update.
5847                 $result = db_query($link, "SELECT ttrss_feeds.feed_url,ttrss_feeds.id, ttrss_feeds.owner_uid,
5848                                 ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated,
5849                                 ttrss_feeds.update_interval 
5850                         FROM 
5851                                 ttrss_feeds, ttrss_users, ttrss_user_prefs
5852                         WHERE
5853                                 ttrss_feeds.owner_uid = ttrss_users.id
5854                                 AND ttrss_users.id = ttrss_user_prefs.owner_uid
5855                                 AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
5856                                 $login_thresh_qpart $update_limit_qpart
5857                          $updstart_thresh_qpart
5858                         ORDER BY $random_qpart $query_limit");
5859
5860                 $user_prefs_cache = array();
5861
5862                 if($debug) _debug(sprintf("Scheduled %d feeds to update...\n", db_num_rows($result)));
5863
5864                 // Here is a little cache magic in order to minimize risk of double feed updates.
5865                 $feeds_to_update = array();
5866                 while ($line = db_fetch_assoc($result)) {
5867                         $feeds_to_update[$line['id']] = $line;
5868                 }
5869
5870                 // We update the feed last update started date before anything else.
5871                 // There is no lag due to feed contents downloads
5872                 // It prevent an other process to update the same feed.
5873                 $feed_ids = array_keys($feeds_to_update);
5874                 if($feed_ids) {
5875                         db_query($link, sprintf("UPDATE ttrss_feeds SET last_update_started = NOW()
5876                                 WHERE id IN (%s)", implode(',', $feed_ids)));
5877                 }
5878
5879                 // For each feed, we call the feed update function.
5880                 while ($line = array_pop($feeds_to_update)) {
5881
5882                         if($debug) _debug("Feed: " . $line["feed_url"] . ", " . $line["last_updated"]);
5883
5884                         update_rss_feed($link, $line["id"], true);
5885
5886                         sleep(1); // prevent flood (FIXME make this an option?)
5887                 }
5888
5889                 // Send feed digests by email if needed.
5890                 if (DAEMON_SENDS_DIGESTS) send_headlines_digests($link);
5891
5892                 purge_orphans($link);
5893
5894         } // function update_daemon_common
5895
5896         function sanitize_article_content($text) {
5897                 # we don't support CDATA sections in articles, they break our own escaping
5898                 $text = preg_replace("/\[\[CDATA/", "", $text);
5899                 $text = preg_replace("/\]\]\>/", "", $text);
5900                 return $text;
5901         }
5902
5903         function load_filters($link, $feed, $owner_uid, $action_id = false) {
5904                 $filters = array();
5905
5906                 global $memcache;
5907
5908                 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
5909
5910                 if ($memcache && $obj = $memcache->get($obj_id)) {
5911
5912                         return $obj;
5913
5914                 } else {
5915
5916                         if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
5917         
5918                         $result = db_query($link, "SELECT reg_exp,
5919                                 ttrss_filter_types.name AS name,
5920                                 ttrss_filter_actions.name AS action,
5921                                 inverse,
5922                                 action_param,
5923                                 filter_param
5924                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
5925                                         enabled = true AND
5926                                         $ftype_query_part
5927                                         owner_uid = $owner_uid AND
5928                                         ttrss_filter_types.id = filter_type AND
5929                                         ttrss_filter_actions.id = action_id AND
5930                                         (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
5931         
5932                         while ($line = db_fetch_assoc($result)) {
5933                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
5934                                         $filter["reg_exp"] = $line["reg_exp"];
5935                                         $filter["action"] = $line["action"];
5936                                         $filter["action_param"] = $line["action_param"];
5937                                         $filter["filter_param"] = $line["filter_param"];
5938                                         $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
5939                                 
5940                                         array_push($filters[$line["name"]], $filter);
5941                                 }
5942
5943                         if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
5944
5945                         return $filters;
5946                 }
5947         }
5948
5949         function get_score_pic($score) {
5950                 if ($score > 100) { 
5951                         return "score_high.png"; 
5952                 } else if ($score > 0) { 
5953                         return "score_half_high.png";
5954                 } else if ($score < -100) {
5955                         return "score_low.png";
5956                 } else if ($score < 0) {
5957                         return "score_half_low.png";
5958                 } else { 
5959                         return "score_neutral.png";
5960                 }
5961         }
5962
5963         function rounded_table_start($classname, $header = "&nbsp;") {
5964                 print "<table width='100%' class='$classname' cellspacing='0' cellpadding='0'>";
5965                 print "<tr><td class='c1'>&nbsp;</td><td class='top'>$header</td><td class='c2'>&nbsp;</td></tr>";
5966                 print "<tr><td class='left'>&nbsp;</td><td class='content'>";
5967         }
5968
5969         function rounded_table_end($footer = "&nbsp;") {
5970                 print "</td><td class='right'>&nbsp;</td></tr>";
5971                 print "<tr><td class='c4'>&nbsp;</td><td class='bottom'>$footer</td><td class='c3'>&nbsp;</td></tr>";
5972                 print "</table>";
5973         }
5974
5975         function feed_has_icon($id) {
5976                 return is_file(ICONS_DIR . "/$id.ico") && filesize(ICONS_DIR . "/$id.ico") > 0;
5977         }
5978
5979         function init_connection($link) {
5980                 if (DB_TYPE == "pgsql") {
5981                         pg_query($link, "set client_encoding = 'UTF-8'");
5982                         pg_set_client_encoding("UNICODE");
5983                         pg_query($link, "set datestyle = 'ISO, european'");
5984                 } else {
5985                         if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
5986                                 db_query($link, "SET NAMES " . MYSQL_CHARSET);
5987         //                      db_query($link, "SET CHARACTER SET " . MYSQL_CHARSET);
5988                         }
5989                 }
5990         }
5991
5992         function update_feedbrowser_cache($link) {
5993
5994                 $result = db_query($link, "SELECT feed_url,title, COUNT(id) AS subscribers
5995                         FROM ttrss_feeds WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf 
5996                                 WHERE tf.feed_url = ttrss_feeds.feed_url 
5997                                 AND (private IS true OR feed_url LIKE '%:%@%/%')) 
5998                                 GROUP BY feed_url, title ORDER BY subscribers DESC LIMIT 1000");
5999         
6000                 db_query($link, "BEGIN");
6001         
6002                 db_query($link, "DELETE FROM ttrss_feedbrowser_cache");
6003         
6004                 $count = 0;
6005         
6006                 while ($line = db_fetch_assoc($result)) {
6007                         $subscribers = db_escape_string($line["subscribers"]);
6008                         $feed_url = db_escape_string($line["feed_url"]);
6009                         $title = db_escape_string($line["title"]);
6010
6011                         $tmp_result = db_query($link, "SELECT subscribers FROM
6012                                 ttrss_feedbrowser_cache WHERE feed_url = '$feed_url'");
6013
6014                         if (db_num_rows($tmp_result) == 0) {
6015
6016                                 db_query($link, "INSERT INTO ttrss_feedbrowser_cache 
6017                                         (feed_url, title, subscribers) VALUES ('$feed_url', 
6018                                                 '$title', '$subscribers')");
6019
6020                                 ++$count;
6021
6022                         }
6023         
6024                 }
6025         
6026                 db_query($link, "COMMIT");
6027
6028                 return $count;
6029
6030         }
6031
6032         function ccache_zero($link, $feed_id, $owner_uid) {
6033                 db_query($link, "UPDATE ttrss_counters_cache SET
6034                         value = 0, updated = NOW() WHERE
6035                         feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6036         }
6037
6038         function ccache_zero_all($link, $owner_uid) {
6039                 db_query($link, "UPDATE ttrss_counters_cache SET
6040                         value = 0 WHERE owner_uid = '$owner_uid'");
6041
6042                 db_query($link, "UPDATE ttrss_cat_counters_cache SET
6043                         value = 0 WHERE owner_uid = '$owner_uid'");
6044         }
6045
6046         function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
6047
6048                 if (!$is_cat) {
6049                         $table = "ttrss_counters_cache";
6050                 } else {
6051                         $table = "ttrss_cat_counters_cache";
6052                 }
6053
6054                 db_query($link, "DELETE FROM $table WHERE
6055                         feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6056
6057         }
6058
6059         function ccache_update_all($link, $owner_uid) {
6060
6061                 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
6062
6063                         $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
6064                                 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
6065
6066                         while ($line = db_fetch_assoc($result)) {
6067                                 ccache_update($link, $line["feed_id"], $owner_uid, true);
6068                         }
6069
6070                         /* We have to manually include category 0 */
6071
6072                         ccache_update($link, 0, $owner_uid, true);
6073
6074                 } else {
6075                         $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
6076                                 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
6077
6078                         while ($line = db_fetch_assoc($result)) {
6079                                 print ccache_update($link, $line["feed_id"], $owner_uid);
6080
6081                         }
6082
6083                 }
6084         }
6085
6086         function ccache_find($link, $feed_id, $owner_uid, $is_cat = false, 
6087                 $no_update = false) {
6088
6089                 if (!is_numeric($feed_id)) return;
6090
6091                 if (!$is_cat) {
6092                         $table = "ttrss_counters_cache";
6093                         if ($feed_id > 0) {
6094                                 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds 
6095                                         WHERE id = '$feed_id'");
6096                                 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6097                         }
6098                 } else {
6099                         $table = "ttrss_cat_counters_cache";
6100                 }
6101
6102                 if (DB_TYPE == "pgsql") {
6103                         $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
6104                 } else if (DB_TYPE == "mysql") {
6105                         $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
6106                 }
6107
6108                 $result = db_query($link, "SELECT value FROM $table
6109                         WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' 
6110                         LIMIT 1");
6111
6112                 if (db_num_rows($result) == 1) {
6113                         return db_fetch_result($result, 0, "value");
6114                 } else {
6115                         if ($no_update) {
6116                                 return -1;
6117                         } else {
6118                                 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
6119                         }
6120                 }
6121
6122         }
6123
6124         function ccache_update($link, $feed_id, $owner_uid, $is_cat = false, 
6125                 $update_pcat = true) {
6126
6127                 if (!is_numeric($feed_id)) return;
6128
6129                 if (!$is_cat && $feed_id > 0) {
6130                         $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds 
6131                                 WHERE id = '$feed_id'");
6132                         $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
6133                 }
6134
6135                 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
6136
6137                 /* When updating a label, all we need to do is recalculate feed counters
6138                  * because labels are not cached */
6139
6140                 if ($feed_id < 0) {
6141                         ccache_update_all($link, $owner_uid);
6142                         return;
6143                 }
6144
6145                 if (!$is_cat) {
6146                         $table = "ttrss_counters_cache";
6147                 } else {
6148                         $table = "ttrss_cat_counters_cache";
6149                 }
6150
6151                 if ($is_cat && $feed_id >= 0) {
6152                         if ($feed_id != 0) {
6153                                 $cat_qpart = "cat_id = '$feed_id'";
6154                         } else {
6155                                 $cat_qpart = "cat_id IS NULL";
6156                         }
6157
6158                         /* Recalculate counters for child feeds */
6159
6160                         $result = db_query($link, "SELECT id FROM ttrss_feeds
6161                                                 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
6162
6163                         while ($line = db_fetch_assoc($result)) {
6164                                 ccache_update($link, $line["id"], $owner_uid, false, false);
6165                         }
6166
6167                         $result = db_query($link, "SELECT SUM(value) AS sv 
6168                                 FROM ttrss_counters_cache, ttrss_feeds 
6169                                 WHERE id = feed_id AND $cat_qpart AND 
6170                                 ttrss_feeds.owner_uid = '$owner_uid'");
6171
6172                         $unread = (int) db_fetch_result($result, 0, "sv");
6173
6174                 } else {
6175                         $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
6176                 }
6177
6178                 db_query($link, "BEGIN");
6179
6180                 $result = db_query($link, "SELECT feed_id FROM $table
6181                         WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
6182
6183                 if (db_num_rows($result) == 1) {
6184                         db_query($link, "UPDATE $table SET
6185                                 value = '$unread', updated = NOW() WHERE
6186                                 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
6187
6188                 } else {
6189                         db_query($link, "INSERT INTO $table
6190                                 (feed_id, value, owner_uid, updated) 
6191                                 VALUES 
6192                                 ($feed_id, $unread, $owner_uid, NOW())");
6193                 }
6194
6195                 db_query($link, "COMMIT");
6196
6197                 if ($feed_id > 0 && $prev_unread != $unread) {
6198
6199                         if (!$is_cat) {
6200
6201                                 /* Update parent category */
6202
6203                                 if ($update_pcat) {
6204
6205                                         $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
6206                                                 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
6207
6208                                         $cat_id = (int) db_fetch_result($result, 0, "cat_id");
6209
6210                                         ccache_update($link, $cat_id, $owner_uid, true);
6211
6212                                 }
6213                         }
6214                 } else if ($feed_id < 0) {
6215                         ccache_update_all($link, $owner_uid);
6216                 }
6217
6218                 return $unread;
6219         }
6220
6221         function label_find_id($link, $label, $owner_uid) {
6222                 $result = db_query($link, 
6223                         "SELECT id FROM ttrss_labels2 WHERE caption = '$label' 
6224                                 AND owner_uid = '$owner_uid' LIMIT 1");
6225
6226                 if (db_num_rows($result) == 1) {
6227                         return db_fetch_result($result, 0, "id");
6228                 } else {
6229                         return 0;
6230                 }
6231         }
6232
6233         function get_article_labels($link, $id) {
6234                 global $memcache;
6235
6236                 $result = db_query($link, 
6237                         "SELECT DISTINCT label_id,caption,fg_color,bg_color 
6238                                 FROM ttrss_labels2, ttrss_user_labels2 
6239                         WHERE id = label_id 
6240                                 AND article_id = '$id' 
6241                                 AND owner_uid = ".$_SESSION["uid"] . "
6242                         ORDER BY caption");
6243
6244                 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
6245
6246                 $rv = array();
6247
6248                 if ($memcache && $obj = $memcache->get($obj_id)) {
6249                         return $obj;
6250                 } else {
6251                         while ($line = db_fetch_assoc($result)) {
6252                                 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
6253                                         $line["bg_color"]);
6254                                 array_push($rv, $rk);
6255                         }
6256                         if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6257                 }
6258
6259                 return $rv;
6260         }
6261
6262
6263         function label_find_caption($link, $label, $owner_uid) {
6264                 $result = db_query($link, 
6265                         "SELECT caption FROM ttrss_labels2 WHERE id = '$label' 
6266                                 AND owner_uid = '$owner_uid' LIMIT 1");
6267
6268                 if (db_num_rows($result) == 1) {
6269                         return db_fetch_result($result, 0, "caption");
6270                 } else {
6271                         return "";
6272                 }
6273         }
6274
6275         function label_remove_article($link, $id, $label, $owner_uid) {
6276
6277                 $label_id = label_find_id($link, $label, $owner_uid);
6278
6279                 if (!$label_id) return;
6280
6281                 $result = db_query($link, 
6282                         "DELETE FROM ttrss_user_labels2
6283                         WHERE 
6284                                 label_id = '$label_id' AND
6285                                 article_id = '$id'");
6286         }
6287
6288         function label_add_article($link, $id, $label, $owner_uid) {
6289
6290                 global $memcache;
6291
6292                 if ($memcache) {
6293                         $obj_id = md5("LABELS:$id:$owner_uid");
6294                         $memcache->delete($obj_id);
6295                 }
6296
6297                 $label_id = label_find_id($link, $label, $owner_uid);
6298
6299                 if (!$label_id) return;
6300
6301                 $result = db_query($link, 
6302                         "SELECT 
6303                                 article_id FROM ttrss_labels2, ttrss_user_labels2
6304                         WHERE 
6305                                 label_id = id AND 
6306                                 label_id = '$label_id' AND
6307                                 article_id = '$id' AND owner_uid = '$owner_uid'
6308                         LIMIT 1");
6309
6310                 if (db_num_rows($result) == 0) {
6311                         db_query($link, "INSERT INTO ttrss_user_labels2 
6312                                 (label_id, article_id) VALUES ('$label_id', '$id')");
6313                 }
6314         }
6315
6316         function label_remove($link, $id, $owner_uid) {
6317                 global $memcache;
6318
6319                 if ($memcache) {
6320                         $obj_id = md5("LABELS:$id:$owner_uid");
6321                         $memcache->delete($obj_id);
6322                 }
6323
6324                 db_query($link, "BEGIN");
6325
6326                 $result = db_query($link, "SELECT caption FROM ttrss_labels2
6327                         WHERE id = '$id'");
6328
6329                 $caption = db_fetch_result($result, 0, "caption");
6330
6331                 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
6332                         AND owner_uid = " . $_SESSION["uid"]);
6333
6334                 if (db_affected_rows($link, $result) != 0 && $caption) {
6335
6336                         /* Disable filters that reference label being removed */
6337         
6338                         db_query($link, "UPDATE ttrss_filters SET
6339                                 enabled = false WHERE action_param = '$caption'
6340                                         AND action_id = 7
6341                                         AND owner_uid = " . $_SESSION["uid"]);
6342                         }
6343
6344                 db_query($link, "COMMIT");
6345         }
6346
6347         function label_create($link, $caption) {
6348
6349                 db_query($link, "BEGIN");
6350
6351                 $result = false;
6352
6353                 $result = db_query($link, "SELECT id FROM ttrss_labels2
6354                         WHERE caption = '$caption' AND owner_uid =  ". $_SESSION["uid"]);
6355
6356                 if (db_num_rows($result) == 0) {
6357                         $result = db_query($link,
6358                                 "INSERT INTO ttrss_labels2 (caption,owner_uid) 
6359                                         VALUES ('$caption', '".$_SESSION["uid"]."')");
6360
6361                         $result = db_affected_rows($link, $result) != 0;
6362                 }
6363
6364                 db_query($link, "COMMIT");
6365
6366                 return $result;
6367         }
6368
6369         function print_labels_headlines_dropdown($link, $feed_id) {
6370                 print "<li onclick=\"javascript:addLabel()\">
6371                         &nbsp;&nbsp;".__("Create label...")."</li>";
6372
6373                 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2 WHERE
6374                         owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
6375
6376                 while ($line = db_fetch_assoc($result)) {
6377
6378                         $label_id = $line["id"];
6379                         $label_caption = $line["caption"];
6380                         $id = $line["id"];
6381
6382                         if ($feed_id < -10 && $feed_id == -11-$label_id) {
6383                                 print "<li id=\"LHDL-$id\" 
6384                                         onclick=\"javascript:selectionRemoveLabel($label_id)\">
6385                                         &nbsp;&nbsp;$label_caption ".__('(remove)')."</li>";
6386                         } else {                                        
6387                                 print "<li id=\"LHDL-$id\" 
6388                                         onclick=\"javascript:selectionAssignLabel($label_id)\">
6389                                         &nbsp;&nbsp;$label_caption</li>";
6390                         }
6391                 }
6392         }
6393
6394         function format_tags_string($tags, $id) {
6395
6396                 $tags_str = "";
6397                 $tags_nolinks_str = "";
6398
6399                 $num_tags = 0;
6400
6401 /*              if (get_user_theme($link) == "3pane") {
6402                         $tag_limit = 3;
6403                 } else {
6404                         $tag_limit = 6;
6405                 } */
6406
6407                 $tag_limit = 6;
6408
6409                 $formatted_tags = array();
6410
6411                 foreach ($tags as $tag) {
6412                         $num_tags++;
6413                         $tag_escaped = str_replace("'", "\\'", $tag);
6414
6415                         if (mb_strlen($tag) > 30) {
6416                                 $tag = truncate_string($tag, 30);
6417                         }
6418
6419                         $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
6420
6421                         array_push($formatted_tags, $tag_str);
6422
6423                         $tmp_tags_str = implode(", ", $formatted_tags);
6424                                 
6425                         if ($num_tags == $tag_limit || mb_strlen($tmp_tags_str) > 150) {
6426                                 break;
6427                         }
6428                 }
6429
6430                 $tags_str = implode(", ", $formatted_tags);
6431
6432                 if ($num_tags < count($tags)) {
6433                         $tags_str .= ", &hellip;";
6434                 }
6435
6436                 if ($num_tags == 0) {
6437                         $tags_str = __("no tags");
6438                 }
6439
6440                 return $tags_str;
6441
6442         }
6443
6444         function format_article_labels($labels, $id) {
6445
6446                 $labels_str = "";
6447
6448                 foreach ($labels as $l) {
6449                         $labels_str .= sprintf("<span class='hlLabelRef' 
6450                                 style='color : %s; background-color : %s'>%s</span>",
6451                                         $l[2], $l[3], $l[1]);
6452                         }
6453
6454                 return $labels_str;
6455
6456         }
6457
6458         function format_article_note($id, $note) {
6459
6460                 $note_escaped = htmlspecialchars($note, ENT_QUOTES);
6461
6462                 $str = "<div class='articleNote'>";
6463                 $str .= $note;
6464                 $str .= "<div class='articleNoteOps'>";
6465                 $str .= "<a href=\"javascript:publishWithNote($id, '$note_escaped')\">".
6466                         __('edit note')."</a>";
6467                 $str .= "</div>";
6468                 $str .= "</div>";
6469
6470                 return $str;
6471         }
6472
6473         function toggle_collapse_cat($link, $cat_id) {
6474                 if ($cat_id > 0) {
6475                         db_query($link, "UPDATE ttrss_feed_categories SET
6476                                 collapsed = NOT collapsed WHERE id = '$cat_id' AND owner_uid = " . 
6477                                 $_SESSION["uid"]);
6478                 } else {
6479                         $pref_name = '';
6480
6481                         switch ($cat_id) {
6482                         case -1:
6483                                 $pref_name = '_COLLAPSED_SPECIAL';
6484                                 break;
6485                         case -2:
6486                                 $pref_name = '_COLLAPSED_LABELS';
6487                                 break;
6488                         case 0:
6489                                 $pref_name = '_COLLAPSED_UNCAT';
6490                                 break;
6491                         }
6492
6493                         if ($pref_name) {
6494                                 if (get_pref($link, $pref_name)) {
6495                                         set_pref($link, $pref_name, 'false');
6496                                 } else {
6497                                         set_pref($link, $pref_name, 'true');
6498                                 }
6499                         }
6500                 }
6501         }
6502
6503         function remove_feed($link, $id, $owner_uid) {
6504
6505                 if ($id > 0) {
6506
6507                         /* save starred articles in Archived feed */
6508
6509                         db_query($link, "BEGIN");
6510
6511                         /* prepare feed if necessary */
6512
6513                         $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6514                                 WHERE id = '$id'");
6515
6516                         if (db_num_rows($result) == 0) {
6517                                 db_query($link, "INSERT INTO ttrss_archived_feeds 
6518                                         (id, owner_uid, title, feed_url, site_url)
6519                                 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6520                                 WHERE id = '$id'");
6521                         }
6522
6523                         db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
6524                                 orig_feed_id = '$id' WHERE feed_id = '$id' AND 
6525                                         marked = true AND owner_uid = $owner_uid");
6526
6527                         /* remove the feed */
6528
6529                         db_query($link, "DELETE FROM ttrss_feeds 
6530                                         WHERE id = '$id' AND owner_uid = $owner_uid");
6531
6532                         db_query($link, "COMMIT");
6533
6534 /*                      if (file_exists(ICONS_DIR . "/$id.ico")) {
6535                                 unlink(ICONS_DIR . "/$id.ico");
6536                         } */
6537
6538                         ccache_remove($link, $id, $owner_uid);
6539
6540                 } else {
6541                         label_remove($link, -11-$id, $owner_uid);
6542                         ccache_remove($link, -11-$id, $owner_uid);
6543                 }
6544         }
6545
6546         function remove_feed_category($link, $id, $owner_uid) {
6547
6548                 db_query($link, "DELETE FROM ttrss_feed_categories
6549                         WHERE id = '$id' AND owner_uid = $owner_uid");
6550
6551                 ccache_remove($link, $id, $owner_uid, true);
6552         }
6553
6554         function archive_article($link, $id, $owner_uid) {
6555                 db_query($link, "BEGIN");
6556
6557                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
6558                         WHERE ref_id = '$id' AND owner_uid = $owner_uid");
6559
6560                 if (db_num_rows($result) != 0) {
6561
6562                         /* prepare the archived table */
6563
6564                         $feed_id = (int) db_fetch_result($result, 0, "feed_id");
6565
6566                         if ($feed_id) {
6567                                 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
6568                                         WHERE id = '$feed_id'");
6569
6570                                 if (db_num_rows($result) == 0) {
6571                                         db_query($link, "INSERT INTO ttrss_archived_feeds 
6572                                                 (id, owner_uid, title, feed_url, site_url)
6573                                         SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
6574                                         WHERE id = '$feed_id'");
6575                                 }
6576
6577                                 db_query($link, "UPDATE ttrss_user_entries 
6578                                         SET orig_feed_id = feed_id, feed_id = NULL
6579                                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6580                         }
6581                 }
6582
6583                 db_query($link, "COMMIT");
6584         }
6585
6586         function getArticleFeed($link, $id) {
6587                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries 
6588                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
6589
6590                 if (db_num_rows($result) != 0) {
6591                         return db_fetch_result($result, 0, "feed_id");
6592                 } else {
6593                         return 0;
6594                 }
6595         }
6596
6597         function make_url_from_parts($parts) {
6598                 $url = $parts['scheme'] . '://' . $parts['host'];
6599
6600                 if ($parts['path']) $url .= $parts['path'];
6601                 if ($parts['query']) $url .= '?' . $parts['query'];
6602
6603                 return $url;
6604         }
6605
6606         function validate_feed_url($url) {
6607                 $parts = parse_url($url);
6608
6609                 return ($parts['scheme'] == 'http' || $parts['scheme'] == 'feed' || $parts['scheme'] == 'https');
6610
6611         }
6612
6613         function get_article_enclosures($link, $id) {
6614
6615                 global $memcache;
6616
6617                 $query = "SELECT * FROM ttrss_enclosures 
6618                         WHERE post_id = '$id' AND content_url != ''";
6619
6620                 $obj_id = md5("ENCLOSURES:$id");
6621
6622                 $rv = array();
6623
6624                 if ($memcache && $obj = $memcache->get($obj_id)) {
6625                         $rv = $obj;
6626                 } else {
6627                         $result = db_query($link, $query);
6628
6629                         if (db_num_rows($result) > 0) {
6630                                 while ($line = db_fetch_assoc($result)) {
6631                                         array_push($rv, $line);
6632                                 }
6633                                 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
6634                         }
6635                 }
6636
6637                 return $rv;
6638         }
6639
6640         function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
6641
6642                         $feeds = array();
6643
6644                         /* Labels */
6645
6646                         if ($cat_id == -4 || $cat_id == -2) {
6647                                 $counters = getLabelCounters($link, true);
6648
6649                                 foreach (array_values($counters) as $cv) {
6650
6651                                         $unread = $cv["counter"];
6652         
6653                                         if ($unread || !$unread_only) {
6654         
6655                                                 $row = array(
6656                                                                 "id" => $cv["id"],
6657                                                                 "title" => $cv["description"],
6658                                                                 "unread" => $cv["counter"],
6659                                                                 "cat_id" => -2,
6660                                                         );
6661         
6662                                                 array_push($feeds, $row);
6663                                         }
6664                                 }
6665                         }
6666
6667                         /* Virtual feeds */
6668
6669                         if ($cat_id == -4 || $cat_id == -1) {
6670                                 foreach (array(-1, -2, -3, -4, 0) as $i) {
6671                                         $unread = getFeedUnread($link, $i);
6672
6673                                         if ($unread || !$unread_only) {
6674                                                 $title = getFeedTitle($link, $i);
6675
6676                                                 $row = array(
6677                                                                 "id" => $i,
6678                                                                 "title" => $title,
6679                                                                 "unread" => $unread,
6680                                                                 "cat_id" => -1,
6681                                                         );
6682                                                 array_push($feeds, $row);
6683                                         }
6684
6685                                 }                       
6686                         }
6687
6688                         /* Real feeds */
6689
6690                         if ($limit) {
6691                                 $limit_qpart = "LIMIT $limit OFFSET $offset";
6692                         } else {
6693                                 $limit_qpart = "";
6694                         }
6695
6696                         if ($cat_id == -4 || $cat_id == -3) {
6697                                 $result = db_query($link, "SELECT 
6698                                         id, feed_url, cat_id, title, ".
6699                                                 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6700                                                 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] . 
6701                                                 " ORDER BY cat_id, title " . $limit_qpart);
6702                         } else {
6703
6704                                 if ($cat_id)
6705                                         $cat_qpart = "cat_id = '$cat_id'";
6706                                 else
6707                                         $cat_qpart = "cat_id IS NULL";
6708
6709                                 $result = db_query($link, "SELECT 
6710                                         id, feed_url, cat_id, title, ".
6711                                                 SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated
6712                                                 FROM ttrss_feeds WHERE 
6713                                                 $cat_qpart AND owner_uid = " . $_SESSION["uid"] . 
6714                                                 " ORDER BY cat_id, title " . $limit_qpart);
6715                         }
6716
6717                         while ($line = db_fetch_assoc($result)) {
6718
6719                                 $unread = getFeedUnread($link, $line["id"]);
6720
6721                                 $has_icon = feed_has_icon($line['id']);
6722
6723                                 if ($unread || !$unread_only) {
6724
6725                                         $row = array(
6726                                                         "feed_url" => $line["feed_url"],
6727                                                         "title" => $line["title"],
6728                                                         "id" => (int)$line["id"],
6729                                                         "unread" => (int)$unread,
6730                                                         "has_icon" => $has_icon,
6731                                                         "cat_id" => (int)$line["cat_id"],
6732                                                         "last_updated" => strtotime($line["last_updated"])
6733                                                 );
6734         
6735                                         array_push($feeds, $row);
6736                                 }
6737                         }
6738
6739                 return $feeds;
6740         }
6741
6742         function api_get_headlines($link, $feed_id, $limit, $offset,
6743                                         $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order) {
6744
6745                         /* do not rely on params below */
6746
6747                         $search = db_escape_string($_REQUEST["search"]);
6748                         $search_mode = db_escape_string($_REQUEST["search_mode"]);
6749                         $match_on = db_escape_string($_REQUEST["match_on"]);
6750                         
6751                         $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit, 
6752                                 $view_mode, $is_cat, $search, $search_mode, $match_on,
6753                                 $order, $offset);
6754
6755                         $result = $qfh_ret[0];
6756                         $feed_title = $qfh_ret[1];
6757
6758                         $headlines = array();
6759
6760                         while ($line = db_fetch_assoc($result)) {
6761                                 $is_updated = ($line["last_read"] == "" && 
6762                                         ($line["unread"] != "t" && $line["unread"] != "1"));
6763
6764                                 $headline_row = array(
6765                                                 "id" => (int)$line["id"],
6766                                                 "unread" => sql_bool_to_bool($line["unread"]),
6767                                                 "marked" => sql_bool_to_bool($line["marked"]),
6768                                                 "published" => sql_bool_to_bool($line["published"]),
6769                                                 "updated" => strtotime($line["updated"]),
6770                                                 "is_updated" => $is_updated,
6771                                                 "title" => $line["title"],
6772                                                 "link" => $line["link"],
6773                                                 "feed_id" => $line["feed_id"],
6774                                                 "tags" => get_article_tags($link, $line["id"]),
6775                                         );
6776
6777                                 if ($show_excerpt) {
6778                                         $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
6779                                         $headline_row["excerpt"] = $excerpt;
6780                                 }
6781
6782                                 if ($show_content) {
6783                                         $headline_row["content"] = $line["content_preview"];
6784                                 }
6785
6786                                 array_push($headlines, $headline_row);
6787                         }
6788
6789                         return $headlines;
6790         }
6791
6792         function generate_dashboard_feed($link) {
6793                 print "<headlines id=\"-5\" is_cat=\"\">";
6794
6795                 print '<![CDATA[<div id="headlinesContainer">';
6796
6797                 print "<div class='whiteBox'>".__('No feed selected.');
6798
6799                 print "<p class=\"small\"><span class=\"insensitive\">";
6800
6801                 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
6802                         WHERE owner_uid = " . $_SESSION['uid']);
6803
6804                 $last_updated = db_fetch_result($result, 0, "last_updated");
6805
6806                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
6807                         $last_updated = smart_date_time(strtotime($last_updated));
6808                 } else {
6809                         $last_updated = date($short_date, strtotime($last_updated));
6810                 }                               
6811
6812                 printf(__("Feeds last updated at %s"), $last_updated);
6813
6814                 $result = db_query($link, "SELECT COUNT(id) AS num_errors
6815                         FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
6816
6817                 $num_errors = db_fetch_result($result, 0, "num_errors");
6818
6819                 if ($num_errors > 0) {
6820                         print "<br/>";
6821                         print "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
6822                                 __('Some feeds have update errors (click for details)')."</a>";
6823                 }
6824                 print "</span></p>";
6825
6826                 print "</div>]]>";
6827                 print "</headlines>";
6828
6829                 print "<headlines-count value=\"0\"/>";
6830                 print "<vgroup-last-feed value=\"0\"/>";
6831                 print "<headlines-unread value=\"0\"/>";
6832                 print "<disable-cache value=\"1\"/>";
6833
6834         }
6835 ?>