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