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