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