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