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