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