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