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