]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
update_daemon2: fix the never-update bug
[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         function get_translations() {
12                 $tr = array(
13                                         "auto"  => "Detect automatically",
14                                         "en_US" => "English",
15                                         "fr_FR" => "Français",
16                                         "nb_NO" => "Norsk Bokmål",
17                                         "ru_RU" => "Русский",
18                                         "pt_BR" => "Portuguese/Brazil",
19                                         "zh_CN" => "Simplified Chinese");
20
21                 return $tr;
22         }
23
24         if (ENABLE_TRANSLATIONS == true) { 
25                 require_once "accept-to-gettext.php";
26                 require_once "gettext/gettext.inc";
27
28                 function startup_gettext() {
29         
30                         # Get locale from Accept-Language header
31                         $lang = al2gt(array_keys(get_translations()), "text/html");
32
33                         if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
34                                 $lang = _TRANSLATION_OVERRIDE_DEFAULT;
35                         }
36
37                         if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {                               
38                                 $lang = $_COOKIE["ttrss_lang"];
39                         }
40
41                         if ($lang) {
42                                 _setlocale(LC_MESSAGES, $lang);
43                                 _bindtextdomain("messages", "locale");
44                                 _textdomain("messages");
45                                 _bind_textdomain_codeset("messages", "UTF-8");
46                         }
47                 }
48
49                 startup_gettext();
50
51         } else {
52                 function __($msg) {
53                         return $msg;
54                 }
55                 function startup_gettext() {
56                         // no-op
57                         return true;
58                 }
59         }
60
61         require_once 'db-prefs.php';
62         require_once 'compat.php';
63         require_once 'errors.php';
64         require_once 'version.php';
65
66         require_once 'phpmailer/class.phpmailer.php';
67
68         define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
69         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
70
71         if (ENABLE_SIMPLEPIE) {
72                 require_once "simplepie/simplepie.inc";
73         } else {
74                 require_once "magpierss/rss_fetch.inc";
75                 require_once 'magpierss/rss_utils.inc';
76         }
77
78         function _debug($msg) {
79                 $ts = strftime("%H:%M:%S", time());
80                 $ts = "$ts/" . posix_getpid();
81                 print "[$ts] $msg\n";
82         }
83
84         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
85
86                 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
87
88                 $rows = -1;
89
90                 $result = db_query($link, 
91                         "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
92
93                 $owner_uid = false;
94
95                 if (db_num_rows($result) == 1) {
96                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
97                 }
98
99                 if (!$owner_uid) return;
100
101                 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
102                         $owner_uid, false);
103
104                 if (!$purge_unread) $query_limit = " unread = false AND ";
105
106                 if (DB_TYPE == "pgsql") {
107 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
108                                 marked = false AND feed_id = '$feed_id' AND
109                                 (SELECT date_entered FROM ttrss_entries WHERE
110                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
111
112                         $pg_version = get_pgsql_version($link);
113
114                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
115
116                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE 
117                                         ttrss_entries.id = ref_id AND 
118                                         marked = false AND 
119                                         feed_id = '$feed_id' AND 
120                                         $query_limit
121                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
122
123                         } else {
124
125                                 $result = db_query($link, "DELETE FROM ttrss_user_entries 
126                                         USING ttrss_entries 
127                                         WHERE ttrss_entries.id = ref_id AND 
128                                         marked = false AND 
129                                         feed_id = '$feed_id' AND 
130                                         $query_limit
131                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
132                         }
133
134                         $rows = pg_affected_rows($result);
135                         
136                 } else {
137                 
138 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
139                                 marked = false AND feed_id = '$feed_id' AND
140                                 (SELECT date_entered FROM ttrss_entries WHERE 
141                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
142
143                         $result = db_query($link, "DELETE FROM ttrss_user_entries 
144                                 USING ttrss_user_entries, ttrss_entries 
145                                 WHERE ttrss_entries.id = ref_id AND 
146                                 marked = false AND 
147                                 feed_id = '$feed_id' AND 
148                                 $query_limit
149                                 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
150                                         
151                         $rows = mysql_affected_rows($link);
152
153                 }
154
155                 if ($debug) {
156                         _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
157                 }
158         }
159
160         function global_purge_old_posts($link, $do_output = false, $limit = false) {
161
162                 $random_qpart = sql_random_function();
163
164                 if ($limit) {
165                         $limit_qpart = "LIMIT $limit";
166                 } else {
167                         $limit_qpart = "";
168                 }
169                 
170                 $result = db_query($link, 
171                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds 
172                                 ORDER BY $random_qpart $limit_qpart");
173
174                 while ($line = db_fetch_assoc($result)) {
175
176                         $feed_id = $line["id"];
177                         $purge_interval = $line["purge_interval"];
178                         $owner_uid = $line["owner_uid"];
179
180                         if ($purge_interval == 0) {
181                         
182                                 $tmp_result = db_query($link, 
183                                         "SELECT value FROM ttrss_user_prefs WHERE
184                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
185
186                                 if (db_num_rows($tmp_result) != 0) {                    
187                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
188                                 }
189                         }
190
191                         if ($do_output) {
192 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
193                         }
194
195                         if ($purge_interval > 0) {
196                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
197                         }
198                 }       
199
200                 // purge orphaned posts in main content table
201                 $result = db_query($link, "DELETE FROM ttrss_entries WHERE 
202                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
203
204                 if ($do_output) {
205                         $rows = db_affected_rows($link, $result);
206                         _debug("Purged $rows orphaned posts.");
207                 }
208
209         }
210
211         function feed_purge_interval($link, $feed_id) {
212
213                 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds 
214                         WHERE id = '$feed_id'");
215
216                 if (db_num_rows($result) == 1) {
217                         $purge_interval = db_fetch_result($result, 0, "purge_interval");
218                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
219
220                         if ($purge_interval == 0) $purge_interval = get_pref($link, 
221                                 'PURGE_OLD_DAYS', $user_id);
222
223                         return $purge_interval;
224
225                 } else {
226                         return -1;
227                 }
228         }
229
230         function purge_old_posts($link) {
231
232                 $user_id = $_SESSION["uid"];
233         
234                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
235                         WHERE owner_uid = '$user_id'");
236
237                 while ($line = db_fetch_assoc($result)) {
238
239                         $feed_id = $line["id"];
240                         $purge_interval = $line["purge_interval"];
241
242                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
243
244                         if ($purge_interval > 0) {
245                                 purge_feed($link, $feed_id, $purge_interval);
246                         }
247                 }       
248
249                 // purge orphaned posts in main content table
250                 db_query($link, "DELETE FROM ttrss_entries WHERE 
251                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
252         }
253
254         function get_feed_update_interval($link, $feed_id) {
255                 $result = db_query($link, "SELECT owner_uid, update_interval FROM
256                         ttrss_feeds WHERE id = '$feed_id'");
257
258                 if (db_num_rows($result) == 1) {
259                         $update_interval = db_fetch_result($result, 0, "update_interval");
260                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
261
262                         if ($update_interval != 0) {
263                                 return $update_interval;
264                         } else {
265                                 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
266                         }
267
268                 } else {
269                         return -1;
270                 }
271         }
272
273         function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
274
275                 if (WEB_DEMO_MODE) return;
276
277                 if (!$user_id) {
278                         $user_id = $_SESSION["uid"];
279                         purge_old_posts($link);
280                 }
281
282 //              db_query($link, "BEGIN");
283
284                 if (MAX_UPDATE_TIME > 0) {
285                         if (DB_TYPE == "mysql") {
286                                 $q_order = "RAND()";
287                         } else {
288                                 $q_order = "RANDOM()";
289                         }
290                 } else {
291                         $q_order = "last_updated DESC";
292                 }
293
294                 $result = db_query($link, "SELECT feed_url,id,
295                         SUBSTRING(last_updated,1,19) AS last_updated,
296                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
297                         ORDER BY $q_order");
298
299                 $upd_start = time();
300
301                 while ($line = db_fetch_assoc($result)) {
302                         $upd_intl = $line["update_interval"];
303
304                         if (!$upd_intl || $upd_intl == 0) {
305                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
306                         }
307
308                         if ($upd_intl < 0) { 
309                                 // Updates for this feed are disabled
310                                 continue; 
311                         }
312
313                         if ($fetch || (!$line["last_updated"] || 
314                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
315
316 //                              print "<!-- feed: ".$line["feed_url"]." -->";
317
318                                 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
319
320                                 $upd_elapsed = time() - $upd_start;
321
322                                 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
323                                         return;
324                                 }
325                         }
326                 }
327
328 //              db_query($link, "COMMIT");
329
330         }
331
332         function fetch_file_contents($url) {
333                 if (USE_CURL_FOR_ICONS) {
334                         $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
335
336                         $ch = curl_init($url);
337                         $fp = fopen($tmpfile, "w");
338
339                         if ($fp) {
340                                 curl_setopt($ch, CURLOPT_FILE, $fp);
341                                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
342                                 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
343                                 curl_exec($ch);
344                                 curl_close($ch);
345                                 fclose($fp);                                    
346                         }
347
348                         $contents =  file_get_contents($tmpfile);
349                         unlink($tmpfile);
350
351                         return $contents;
352
353                 } else {
354                         return file_get_contents($url);
355                 }
356
357         }
358
359         // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
360         // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
361
362         function get_favicon_url($url) {
363
364                 if ($html = @fetch_file_contents($url)) {
365
366                         if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
367                                 // Attempt to grab a favicon link from their webpage url
368                                 $linkUrl = html_entity_decode($matches[1]);
369
370                                 if (substr($linkUrl, 0, 1) == '/') {
371                                         $urlParts = parse_url($url);
372                                         $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
373                                 } else if (substr($linkUrl, 0, 7) == 'http://') {
374                                         $faviconURL = $linkUrl;
375                                 } else if (substr($url, -1, 1) == '/') {
376                                         $faviconURL = $url.$linkUrl;
377                                 } else {
378                                         $faviconURL = $url.'/'.$linkUrl;
379                                 }
380
381                         } else {
382                                 // If unsuccessful, attempt to "guess" the favicon location
383                                 $urlParts = parse_url($url);
384                                 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
385                         }
386                 }
387
388                 // Run a test to see if what we have attempted to get actually exists.
389                 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
390                         return $faviconURL;
391                 } else {
392                         return false;
393                 }
394         }
395
396         function url_validate($link) {
397                 
398                 $url_parts = @parse_url($link);
399
400                 if ( empty( $url_parts["host"] ) )
401                                 return false;
402
403                 if ( !empty( $url_parts["path"] ) ) {
404                                 $documentpath = $url_parts["path"];
405                 } else {
406                                 $documentpath = "/";
407                 }
408
409                 if ( !empty( $url_parts["query"] ) )
410                                 $documentpath .= "?" . $url_parts["query"];
411
412                 $host = $url_parts["host"];
413                 $port = $url_parts["port"];
414                 
415                 if ( empty($port) )
416                                 $port = "80";
417
418                 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
419                 
420                 if ( !$socket )
421                                 return false;
422                                 
423                 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
424
425                 $http_response = fgets( $socket, 22 );
426
427                 $responses = "/(200 OK)|(30[0-9] Moved)/";
428                 if ( preg_match($responses, $http_response) ) {
429                                 fclose($socket);
430                                 return true;
431                 } else {
432                                 return false;
433                 }
434
435         } 
436
437         function check_feed_favicon($site_url, $feed, $link) {
438                 $favicon_url = get_favicon_url($site_url);
439
440 #               print "FAVICON [$site_url]: $favicon_url\n";
441
442                 error_reporting(0);
443
444                 $icon_file = ICONS_DIR . "/$feed.ico";
445
446                 if ($favicon_url && !file_exists($icon_file)) {
447                         $contents = fetch_file_contents($favicon_url);
448
449                         $fp = fopen($icon_file, "w");
450
451                         if ($fp) {
452                                 fwrite($fp, $contents);
453                                 fclose($fp);
454                                 chmod($icon_file, 0644);
455                         }
456                 }
457
458                 error_reporting(DEFAULT_ERROR_LEVEL);
459
460         }
461
462         function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
463
464                 if (!$_GET["daemon"] && !$ignore_daemon) {
465                         return;                 
466                 }
467
468                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
469                         _debug("update_rss_feed: start");
470                 }
471
472                 if (!$ignore_daemon) {
473
474                         if (DB_TYPE == "pgsql") {
475                                         $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
476                                 } else {
477                                         $updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
478                                 }                       
479         
480                         $result = db_query($link, "SELECT id,update_interval,auth_login,
481                                 auth_pass,cache_images
482                                 FROM ttrss_feeds WHERE id = '$feed' AND $updstart_thresh_qpart");
483
484                 } else {
485
486                         $result = db_query($link, "SELECT id,update_interval,auth_login,
487                                 auth_pass,cache_images
488                                 FROM ttrss_feeds WHERE id = '$feed'");
489
490                 }
491
492                 if (db_num_rows($result) == 0) {
493                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
494                                 _debug("update_rss_feed: feed $feed [$feed_url] NOT FOUND/SKIPPED");
495                         }               
496                         return;
497                 }
498
499                 db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()
500                         WHERE id = '$feed'");
501
502                 $auth_login = db_fetch_result($result, 0, "auth_login");
503                 $auth_pass = db_fetch_result($result, 0, "auth_pass");
504
505                 if (!ENABLE_SIMPLEPIE) {
506                         $auth_login = urlencode($auth_login);
507                         $auth_pass = urlencode($auth_pass);
508                 }
509
510                 $update_interval = db_fetch_result($result, 0, "update_interval");
511                 $cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
512
513                 if ($update_interval < 0) { return; }
514
515                 $feed = db_escape_string($feed);
516
517                 $fetch_url = $feed_url;
518
519                 if ($auth_login && $auth_pass) {
520                         $url_parts = array();
521                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
522
523                         if ($url_parts[1] && $url_parts[2]) {
524                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
525                         }
526
527                 }
528
529                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
530                         _debug("update_rss_feed: fetching [$fetch_url]...");
531                 }
532
533                 if (!defined('DAEMON_EXTENDED_DEBUG') && !$_GET['xdebug']) {
534                         error_reporting(0);
535                 }
536
537                 if (!ENABLE_SIMPLEPIE) {
538                         $rss = fetch_rss($fetch_url);
539                 } else {
540                         if (!is_dir(SIMPLEPIE_CACHE_DIR)) {
541                                 mkdir(SIMPLEPIE_CACHE_DIR);
542                         }
543
544                         $rss = new SimplePie();
545                         $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
546 //                      $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
547                         $rss->set_feed_url($fetch_url);
548                         $rss->set_output_encoding('UTF-8');
549
550                         if (SIMPLEPIE_CACHE_IMAGES && $cache_images) {
551                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
552                                         _debug("enabling image cache");
553                                 }
554
555                                 $rss->set_image_handler('./image.php', 'i');
556                         }
557
558                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
559                                 _debug("feed update interval (sec): " .
560                                         get_feed_update_interval($link, $feed)*60);
561                         }
562
563                         if (is_dir(SIMPLEPIE_CACHE_DIR)) {
564                                 $rss->set_cache_location(SIMPLEPIE_CACHE_DIR);
565                                 $rss->set_cache_duration(get_feed_update_interval($link, $feed) * 60);
566                         }
567
568                         $rss->init();
569                 }
570
571 //              print_r($rss);
572
573                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
574                         _debug("update_rss_feed: fetch done, parsing...");
575                 } else {
576                         error_reporting (DEFAULT_ERROR_LEVEL);
577                 }
578
579                 $feed = db_escape_string($feed);
580
581                 if (ENABLE_SIMPLEPIE) {
582                         $fetch_ok = !$rss->error();
583                 } else {
584                         $fetch_ok = !!$rss;
585                 }
586
587                 if ($fetch_ok) {
588
589                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
590                                 _debug("update_rss_feed: processing feed data...");
591                         }
592
593 //                      db_query($link, "BEGIN");
594
595                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
596                                 FROM ttrss_feeds WHERE id = '$feed'");
597
598                         $registered_title = db_fetch_result($result, 0, "title");
599                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
600                         $orig_site_url = db_fetch_result($result, 0, "site_url");
601
602                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
603
604                         if (ENABLE_SIMPLEPIE) {
605                                 $site_url = $rss->get_link();
606                         } else {
607                                 $site_url = $rss->channel["link"];
608                         }
609
610                         if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {  
611                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
612                                         _debug("update_rss_feed: checking favicon...");
613                                 }
614
615                                 check_feed_favicon($site_url, $feed, $link);
616                         }
617
618                         if (!$registered_title || $registered_title == "[Unknown]") {
619
620                                 if (ENABLE_SIMPLEPIE) {
621                                         $feed_title = db_escape_string($rss->get_title());
622                                 } else {
623                                         $feed_title = db_escape_string($rss->channel["title"]);
624                                 }
625
626                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
627                                         _debug("update_rss_feed: registering title: $feed_title");
628                                 }
629                                 
630                                 db_query($link, "UPDATE ttrss_feeds SET 
631                                         title = '$feed_title' WHERE id = '$feed'");
632                         }
633
634                         // weird, weird Magpie
635                         if (!ENABLE_SIMPLEPIE) {
636                                 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
637                         }
638
639                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
640                                 db_query($link, "UPDATE ttrss_feeds SET 
641                                         site_url = '$site_url' WHERE id = '$feed'");
642                         }
643
644 //                      print "I: " . $rss->channel["image"]["url"];
645
646                         if (!ENABLE_SIMPLEPIE) {
647                                 $icon_url = $rss->image["url"];
648                         } else {
649                                 $icon_url = $rss->get_image_url();
650                         }
651
652                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
653                                 $icon_url = db_escape_string($icon_url);
654                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
655                         }
656
657                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
658                                 _debug("update_rss_feed: loading filters...");
659                         }
660
661                         $filters = array();
662
663                         $result = db_query($link, "SELECT reg_exp,
664                                 ttrss_filter_types.name AS name,
665                                 ttrss_filter_actions.name AS action,
666                                 inverse,
667                                 action_param
668                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
669                                         enabled = true AND
670                                         owner_uid = $owner_uid AND
671                                         ttrss_filter_types.id = filter_type AND
672                                         ttrss_filter_actions.id = action_id AND
673                                 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
674
675                         while ($line = db_fetch_assoc($result)) {
676                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
677
678                                 $filter["reg_exp"] = $line["reg_exp"];
679                                 $filter["action"] = $line["action"];
680                                 $filter["action_param"] = $line["action_param"];
681                                 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
682                         
683                                 array_push($filters[$line["name"]], $filter);
684                         }
685
686                         if (ENABLE_SIMPLEPIE) {
687                                 $iterator = $rss->get_items();
688                         } else {
689                                 $iterator = $rss->items;
690                                 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
691                                 if (!$iterator || !is_array($iterator)) $iterator = $rss;
692                         }
693
694                         if (!is_array($iterator)) {
695                                 /* db_query($link, "UPDATE ttrss_feeds 
696                                         SET last_error = 'Parse error: can\'t find any articles.'
697                                         WHERE id = '$feed'"); */
698
699                                 // clear any errors and mark feed as updated if fetched okay
700                                 // even if it's blank
701
702                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
703                                         _debug("update_rss_feed: entry iterator is not an array, no articles?");
704                                 }
705
706                                 db_query($link, "UPDATE ttrss_feeds 
707                                         SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
708
709                                 return; // no articles
710                         }
711
712                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
713                                 _debug("update_rss_feed: processing articles...");
714                         }
715
716                         foreach ($iterator as $item) {
717
718                                 if ($_GET['xdebug']) {
719                                         print_r($item);
720
721                                 }
722
723                                 if (ENABLE_SIMPLEPIE) {
724                                         $entry_guid = $item->get_id();
725                                         if (!$entry_guid) $entry_guid = $item->get_link();
726                                         if (!$entry_guid) $entry_guid = make_guid_from_title($item->get_title());
727
728                                 } else {
729
730                                         $entry_guid = $item["id"];
731
732                                         if (!$entry_guid) $entry_guid = $item["guid"];
733                                         if (!$entry_guid) $entry_guid = $item["link"];
734                                         if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
735                                 }
736
737                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
738                                         _debug("update_rss_feed: guid $entry_guid");
739                                 }
740
741                                 if (!$entry_guid) continue;
742
743                                 $entry_timestamp = "";
744
745                                 if (ENABLE_SIMPLEPIE) {
746                                         $entry_timestamp = strtotime($item->get_date());
747                                 } else {
748                                         $rss_2_date = $item['pubdate'];
749                                         $rss_1_date = $item['dc']['date'];
750                                         $atom_date = $item['issued'];
751                                         if (!$atom_date) $atom_date = $item['updated'];
752                         
753                                         if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
754                                         if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
755                                         if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
756                                 }
757
758                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
759                                         _debug("update_rss_feed: date $entry_timestamp");
760                                 }
761
762                                 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
763                                         $entry_timestamp = time();
764                                         $no_orig_date = 'true';
765                                 } else {
766                                         $no_orig_date = 'false';
767                                 }
768
769                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
770
771                                 if (ENABLE_SIMPLEPIE) {
772                                         $entry_title = $item->get_title();
773                                 } else {
774                                         $entry_title = trim(strip_tags($item["title"]));
775                                 }
776
777                                 if (ENABLE_SIMPLEPIE) {
778                                         $entry_link = $item->get_link();
779                                 } else {
780                                         // strange Magpie workaround
781                                         $entry_link = $item["link_"];
782                                         if (!$entry_link) $entry_link = $item["link"];
783                                 }
784
785                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
786                                         _debug("update_rss_feed: title $entry_title");
787                                 }
788
789                                 if (!$entry_title) $entry_title = date("Y-m-d H:i:s", $entry_timestamp);;
790
791                                 $entry_link = strip_tags($entry_link);
792
793                                 if (ENABLE_SIMPLEPIE) {
794                                         $entry_content = $item->get_description();
795                                 } else {
796                                         $entry_content = $item["content:escaped"];
797
798                                         if (!$entry_content) $entry_content = $item["content:encoded"];
799                                         if (!$entry_content) $entry_content = $item["content"];
800
801                                         // Magpie bugs are getting ridiculous
802                                         if (trim($entry_content) == "Array") $entry_content = false;
803
804                                         if (!$entry_content) $entry_content = $item["atom_content"];
805                                         if (!$entry_content) $entry_content = $item["summary"];
806                                         if (!$entry_content) $entry_content = $item["description"];
807
808                                         // WTF
809                                         if (is_array($entry_content)) {
810                                                 $entry_content = $entry_content["encoded"];
811                                                 if (!$entry_content) $entry_content = $entry_content["escaped"];
812                                         } 
813                                 }
814
815                                 if ($_GET["xdebug"]) {
816                                         print "update_rss_feed: content: ";
817                                         print_r(htmlspecialchars($entry_content));
818                                 }
819
820                                 $entry_content_unescaped = $entry_content;
821
822                                 if (ENABLE_SIMPLEPIE) {
823                                         $entry_comments = strip_tags($item->data["comments"]);
824                                         if ($item->get_author()) {
825                                                 $entry_author_item = $item->get_author();
826                                                 $entry_author = $entry_author_item->get_name();                                                 
827                                         }
828                                 } else {
829                                         $entry_comments = strip_tags($item["comments"]);
830                                 
831                                         $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
832
833                                         if ($item['author']) {
834         
835                                                 if (is_array($item['author'])) {
836         
837                                                         if (!$entry_author) {
838                                                                 $entry_author = db_escape_string(strip_tags($item['author']['name']));
839                                                         }
840         
841                                                         if (!$entry_author) {
842                                                                 $entry_author = db_escape_string(strip_tags($item['author']['email']));
843                                                         }
844                                                 }
845         
846                                                 if (!$entry_author) {
847                                                         $entry_author = db_escape_string(strip_tags($item['author']));
848                                                 }
849                                         }
850                                 }
851
852                                 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
853
854                                 $entry_guid = db_escape_string(strip_tags($entry_guid));
855                                 $entry_guid = mb_substr($entry_guid, 0, 250);
856
857                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
858                                         WHERE guid = '$entry_guid'");
859
860                                 $entry_content = db_escape_string($entry_content);
861
862                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
863
864                                 $entry_title = db_escape_string($entry_title);
865                                 $entry_link = db_escape_string($entry_link);
866                                 $entry_comments = mb_substr(db_escape_string($entry_comments), 0, 250);
867                                 $entry_author = mb_substr($entry_author, 0, 250);
868
869                                 if (ENABLE_SIMPLEPIE) {
870                                         $num_comments = 0; #FIXME#
871                                 } else {
872                                         $num_comments = db_escape_string($item["slash"]["comments"]);
873                                 }
874
875                                 if (!$num_comments) $num_comments = 0;
876
877                                 // parse <category> entries into tags
878
879                                 if (ENABLE_SIMPLEPIE) {
880
881                                         $additional_tags = array();
882                                         $additional_tags_src = $item->get_categories();
883                                         
884                                         if (is_array($additional_tags_src)) {
885                                                 foreach ($additional_tags_src as $tobj) {
886                                                         array_push($additional_tags, $tobj->get_term());
887                                                 }
888                                         }
889
890                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
891                                                 _debug("update_rss_feed: category tags:");
892                                                 print_r($additional_tags);
893                                         }
894
895                                 } else {
896
897                                         $t_ctr = $item['category#'];
898
899                                         $additional_tags = false;
900         
901                                         if ($t_ctr == 0) {
902                                                 $additional_tags = false;
903                                         } else if ($t_ctr > 0) {
904                                                 $additional_tags = array($item['category']);
905
906                                                 if ($item['category@term']) {
907                                                         array_push($additional_tags, $item['category@term']);
908                                                 }
909
910                                                 for ($i = 0; $i <= $t_ctr; $i++ ) {
911                                                         if ($item["category#$i"]) {
912                                                                 array_push($additional_tags, $item["category#$i"]);
913                                                         }
914
915                                                         if ($item["category#$i@term"]) {
916                                                                 array_push($additional_tags, $item["category#$i@term"]);
917                                                         }
918                                                 }
919                                         }
920         
921                                         // parse <dc:subject> elements
922         
923                                         $t_ctr = $item['dc']['subject#'];
924         
925                                         if ($t_ctr > 0) {
926                                                 $additional_tags = array($item['dc']['subject']);
927
928                                                 for ($i = 0; $i <= $t_ctr; $i++ ) {
929                                                         if ($item['dc']["subject#$i"]) {
930                                                                 array_push($additional_tags, $item['dc']["subject#$i"]);
931                                                         }
932                                                 }
933                                         }
934                                 }
935
936                                 // enclosures
937
938                                 $enclosures = array();
939
940                                 if (ENABLE_SIMPLEPIE) {
941                                         $encs = $item->get_enclosures();
942
943                                         if (is_array($encs)) {
944                                                 foreach ($encs as $e) {
945                                                         $e_item = array(
946                                                                 $e->link, $e->type, $e->length);
947         
948                                                         array_push($enclosures, $e_item);
949                                                 }
950                                         }
951
952                                 } else {
953                                         $e_ctr = $item['enclosure#'];
954
955                                         if ($e_ctr > 0) {
956                                                 $e_item = array($item['enclosure@url'],
957                                                         $item['enclosure@type'],
958                                                         $item['enclosure@length']);
959
960                                                 array_push($enclosures, $e_item);
961
962                                                 for ($i = 0; $i <= $e_ctr; $i++ ) {
963
964                                                         if ($item["enclosure#$i@url"]) {
965                                                                 $e_item = array($item["enclosure#$i@url"],
966                                                                         $item["enclosure#$i@type"],
967                                                                         $item["enclosure#$i@length"]);
968                                                                 array_push($enclosures, $e_item);
969                                                         }
970                                                 }
971                                         }
972
973                                 }
974
975                                 # sanitize content
976                                 
977 //                              $entry_content = sanitize_rss($entry_content);
978
979                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
980                                         _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
981                                 }
982
983                                 db_query($link, "BEGIN");
984
985                                 if (db_num_rows($result) == 0) {
986
987                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
988                                                 _debug("update_rss_feed: base guid not found");
989                                         }
990
991                                         // base post entry does not exist, create it
992
993                                         $result = db_query($link,
994                                                 "INSERT INTO ttrss_entries 
995                                                         (title,
996                                                         guid,
997                                                         link,
998                                                         updated,
999                                                         content,
1000                                                         content_hash,
1001                                                         no_orig_date,
1002                                                         date_entered,
1003                                                         comments,
1004                                                         num_comments,
1005                                                         author)
1006                                                 VALUES
1007                                                         ('$entry_title', 
1008                                                         '$entry_guid', 
1009                                                         '$entry_link',
1010                                                         '$entry_timestamp_fmt', 
1011                                                         '$entry_content', 
1012                                                         '$content_hash',
1013                                                         $no_orig_date, 
1014                                                         NOW(), 
1015                                                         '$entry_comments',
1016                                                         '$num_comments',
1017                                                         '$entry_author')");
1018                                 } else {
1019                                         // we keep encountering the entry in feeds, so we need to
1020                                         // update date_entered column so that we don't get horrible
1021                                         // dupes when the entry gets purged and reinserted again e.g.
1022                                         // in the case of SLOW SLOW OMG SLOW updating feeds
1023
1024                                         $base_entry_id = db_fetch_result($result, 0, "id");
1025
1026                                         db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
1027                                                 WHERE id = '$base_entry_id'");
1028                                 }
1029
1030                                 // now it should exist, if not - bad luck then
1031
1032                                 $result = db_query($link, "SELECT 
1033                                                 id,content_hash,no_orig_date,title,
1034                                                 substring(date_entered,1,19) as date_entered,
1035                                                 substring(updated,1,19) as updated,
1036                                                 num_comments
1037                                         FROM 
1038                                                 ttrss_entries 
1039                                         WHERE guid = '$entry_guid'");
1040
1041                                 $entry_ref_id = 0;
1042                                 $entry_int_id = 0;
1043
1044                                 if (db_num_rows($result) == 1) {
1045
1046                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1047                                                 _debug("update_rss_feed: base guid found, checking for user record");
1048                                         }
1049
1050                                         // this will be used below in update handler
1051                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
1052                                         $orig_title = db_fetch_result($result, 0, "title");
1053                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
1054                                         $orig_date_entered = strtotime(db_fetch_result($result, 
1055                                                 0, "date_entered"));
1056
1057                                         $ref_id = db_fetch_result($result, 0, "id");
1058                                         $entry_ref_id = $ref_id;
1059
1060                                         // check for user post link to main table
1061
1062                                         // do we allow duplicate posts with same GUID in different feeds?
1063                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
1064                                                 $dupcheck_qpart = "AND feed_id = '$feed'";
1065                                         } else { 
1066                                                 $dupcheck_qpart = "";
1067                                         }
1068
1069 //                                      error_reporting(0);
1070
1071                                         $article_filters = get_article_filters($filters, $entry_title, 
1072                                                         $entry_content, $entry_link);
1073
1074                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1075                                                 _debug("update_rss_feed: article filters: ");
1076                                                 if (count($article_filters) != 0) {
1077                                                         print_r($article_filters);
1078                                                 }
1079                                         }
1080
1081                                         if (find_article_filter($article_filters, "filter")) {
1082                                                 continue;
1083                                         }
1084
1085 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
1086
1087                                         $result = db_query($link,
1088                                                 "SELECT ref_id, int_id FROM ttrss_user_entries WHERE
1089                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
1090                                                         $dupcheck_qpart");
1091
1092                                         // okay it doesn't exist - create user entry
1093                                         if (db_num_rows($result) == 0) {
1094
1095                                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1096                                                         _debug("update_rss_feed: user record not found, creating...");
1097                                                 }
1098
1099                                                 if (!find_article_filter($article_filters, 'catchup')) {
1100                                                         $unread = 'true';
1101                                                         $last_read_qpart = 'NULL';
1102                                                 } else {
1103                                                         $unread = 'false';
1104                                                         $last_read_qpart = 'NOW()';
1105                                                 }                                               
1106
1107                                                 if (find_article_filter($article_filters, 'mark')) {
1108                                                         $marked = 'true';
1109                                                 } else {
1110                                                         $marked = 'false';
1111                                                 }
1112
1113                                                 if (find_article_filter($article_filters, 'publish')) {
1114                                                         $published = 'true';
1115                                                 } else {
1116                                                         $published = 'false';
1117                                                 }
1118
1119                                                 $result = db_query($link,
1120                                                         "INSERT INTO ttrss_user_entries 
1121                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked, published) 
1122                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
1123                                                                 $last_read_qpart, $marked, $published)");
1124
1125                                                 $result = db_query($link, 
1126                                                         "SELECT int_id FROM ttrss_user_entries WHERE
1127                                                                 ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND
1128                                                                 feed_id = '$feed' LIMIT 1");
1129
1130                                                 if (db_num_rows($result) == 1) {
1131                                                         $entry_int_id = db_fetch_result($result, 0, "int_id");
1132                                                 }
1133                                         } else {
1134                                                 $entry_ref_id = db_fetch_result($result, 0, "ref_id");
1135                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
1136                                         }
1137
1138                                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1139                                                 _debug("update_rss_feed: RID: $entry_ref_id, IID: $entry_int_id");
1140                                         }
1141
1142                                         $post_needs_update = false;
1143
1144                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
1145                                                 ($content_hash != $orig_content_hash)) {
1146 //                                              print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
1147                                                 $post_needs_update = true;
1148                                         }
1149
1150                                         if (db_escape_string($orig_title) != $entry_title) {
1151                                                 $post_needs_update = true;
1152                                         }
1153
1154                                         if ($orig_num_comments != $num_comments) {
1155                                                 $post_needs_update = true;
1156                                         }
1157
1158 //                                      this doesn't seem to be very reliable
1159 //
1160 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
1161 //                                              $post_needs_update = true;
1162 //                                      }
1163
1164                                         // if post needs update, update it and mark all user entries 
1165                                         // linking to this post as updated                                      
1166                                         if ($post_needs_update) {
1167
1168                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
1169                                                         _debug("update_rss_feed: post $entry_guid needs update...");
1170                                                 }
1171
1172 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
1173
1174                                                 db_query($link, "UPDATE ttrss_entries 
1175                                                         SET title = '$entry_title', content = '$entry_content',
1176                                                                 content_hash = '$content_hash',
1177                                                                 num_comments = '$num_comments'
1178                                                         WHERE id = '$ref_id'");
1179
1180                                                 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
1181                                                         db_query($link, "UPDATE ttrss_user_entries 
1182                                                                 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
1183                                                 } else {
1184                                                         db_query($link, "UPDATE ttrss_user_entries 
1185                                                                 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
1186                                                 }
1187
1188                                         }
1189                                 }
1190
1191                                 db_query($link, "COMMIT");
1192
1193                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1194                                         _debug("update_rss_feed: looking for enclosures...");
1195                                 }
1196
1197                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1198                                         print_r($enclosures);
1199                                 }
1200
1201                                 db_query($link, "BEGIN");
1202
1203                                 foreach ($enclosures as $enc) {
1204                                         $enc_url = db_escape_string($enc[0]);
1205                                         $enc_type = db_escape_string($enc[1]);
1206                                         $enc_dur = db_escape_string($enc[2]);
1207
1208                                         $result = db_query($link, "SELECT id FROM ttrss_enclosures
1209                                                 WHERE content_url = '$enc_url' AND post_id = '$entry_ref_id'");
1210
1211                                         if (db_num_rows($result) == 0) {
1212                                                 db_query($link, "INSERT INTO ttrss_enclosures
1213                                                         (content_url, content_type, title, duration, post_id) VALUES
1214                                                         ('$enc_url', '$enc_type', '', '$enc_dur', '$entry_ref_id')");
1215                                         }
1216                                 }
1217
1218                                 db_query($link, "COMMIT");
1219
1220                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1221                                         _debug("update_rss_feed: looking for tags...");
1222                                 }
1223
1224                                 /* taaaags */
1225                                 // <a href="..." rel="tag">Xorg</a>, //
1226
1227                                 $entry_tags = null;
1228
1229                                 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i", 
1230                                         $entry_content_unescaped, $entry_tags);
1231
1232 /*                              print "<p><br/>$entry_title : $entry_content_unescaped<br>";
1233                                 print_r($entry_tags);
1234                                 print "<br/></p>"; */
1235
1236                                 $entry_tags = $entry_tags[1];
1237
1238                                 # check for manual tags
1239
1240                                 $tag_filter = find_article_filter($article_filters, "tag"); 
1241
1242                                 if ($tag_filter) {
1243
1244                                         $manual_tags = trim_array(split(",", $tag_filter[1]));
1245
1246                                         foreach ($manual_tags as $tag) {
1247                                                 if (tag_is_valid($tag)) {
1248                                                         array_push($entry_tags, $tag);
1249                                                 }
1250                                         }
1251                                 }
1252
1253                                 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link, 
1254                                         'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
1255
1256                                 if ($additional_tags && is_array($additional_tags)) {
1257                                         foreach ($additional_tags as $tag) {
1258                                                 if (tag_is_valid($tag) && 
1259                                                                 array_search($tag, $boring_tags) === FALSE) {
1260                                                         array_push($entry_tags, $tag);
1261                                                 }
1262                                         }
1263                                 } 
1264
1265 //                              print "<p>TAGS: "; print_r($entry_tags); print "</p>";
1266
1267                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1268                                         print_r($entry_tags);
1269                                 }
1270
1271                                 if (count($entry_tags) > 0) {
1272                                 
1273                                         db_query($link, "BEGIN");
1274                         
1275                                                 foreach ($entry_tags as $tag) {
1276
1277                                                         $tag = sanitize_tag($tag);
1278                                                         $tag = db_escape_string($tag);
1279
1280                                                         if (!tag_is_valid($tag)) continue;
1281                                                         
1282                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
1283                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
1284                                                                 owner_uid = '$owner_uid' LIMIT 1");
1285         
1286         //                                              print db_fetch_result($result, 0, "id");
1287         
1288                                                         if ($result && db_num_rows($result) == 0) {
1289                                                                 
1290                                                                 db_query($link, "INSERT INTO ttrss_tags 
1291                                                                         (owner_uid,tag_name,post_int_id)
1292                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
1293                                                         }                                                       
1294                                                 }
1295
1296                                         db_query($link, "COMMIT");
1297                                 } 
1298
1299                                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1300                                         _debug("update_rss_feed: article processed");
1301                                 }
1302                         } 
1303
1304                         db_query($link, "UPDATE ttrss_feeds 
1305                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
1306
1307 //                      db_query($link, "COMMIT");
1308
1309                 } else {
1310
1311                         if (ENABLE_SIMPLEPIE) {
1312                                 $error_msg = mb_substr($rss->error(), 0, 250);
1313                         } else {
1314                                 $error_msg = mb_substr(magpie_error(), 0, 250);
1315                         }
1316
1317                         if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1318                                 _debug("update_rss_feed: error fetching feed: $error_msg");
1319                         }
1320
1321                         $error_msg = db_escape_string($error_msg);
1322
1323                         db_query($link, 
1324                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
1325                                         last_updated = NOW() WHERE id = '$feed'");
1326                 }
1327
1328                 if (ENABLE_SIMPLEPIE) {
1329                         unset($rss);
1330                 }
1331
1332                 if (defined('DAEMON_EXTENDED_DEBUG') || $_GET['xdebug']) {
1333                         _debug("update_rss_feed: done");
1334                 }
1335
1336         }
1337
1338         function print_select($id, $default, $values, $attributes = "") {
1339                 print "<select name=\"$id\" id=\"$id\" $attributes>";
1340                 foreach ($values as $v) {
1341                         if ($v == $default)
1342                                 $sel = " selected";
1343                          else
1344                                 $sel = "";
1345                         
1346                         print "<option$sel>$v</option>";
1347                 }
1348                 print "</select>";
1349         }
1350
1351         function print_select_hash($id, $default, $values, $attributes = "") {
1352                 print "<select name=\"$id\" id='$id' $attributes>";
1353                 foreach (array_keys($values) as $v) {
1354                         if ($v == $default)
1355                                 $sel = "selected";
1356                          else
1357                                 $sel = "";
1358                         
1359                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
1360                 }
1361
1362                 print "</select>";
1363         }
1364
1365         function get_article_filters($filters, $title, $content, $link) {
1366                 $matches = array();
1367
1368                 if ($filters["title"]) {
1369                         foreach ($filters["title"] as $filter) {
1370                                 $reg_exp = $filter["reg_exp"];          
1371                                 $inverse = $filter["inverse"];  
1372                                 if ((!$inverse && preg_match("/$reg_exp/i", $title)) || 
1373                                                 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1374
1375                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1376                                 }
1377                         }
1378                 }
1379
1380                 if ($filters["content"]) {
1381                         foreach ($filters["content"] as $filter) {
1382                                 $reg_exp = $filter["reg_exp"];
1383                                 $inverse = $filter["inverse"];
1384
1385                                 if ((!$inverse && preg_match("/$reg_exp/i", $content)) || 
1386                                                 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1387
1388                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1389                                 }               
1390                         }
1391                 }
1392
1393                 if ($filters["both"]) {
1394                         foreach ($filters["both"] as $filter) {                 
1395                                 $reg_exp = $filter["reg_exp"];          
1396                                 $inverse = $filter["inverse"];
1397
1398                                 if ($inverse) {
1399                                         if (!preg_match("/$reg_exp/i", $title) || !preg_match("/$reg_exp/i", $content)) {
1400                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1401                                         }
1402                                 } else {
1403                                         if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1404                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
1405                                         }
1406                                 }
1407                         }
1408                 }
1409
1410                 if ($filters["link"]) {
1411                         $reg_exp = $filter["reg_exp"];
1412                         foreach ($filters["link"] as $filter) {
1413                                 $reg_exp = $filter["reg_exp"];
1414                                 $inverse = $filter["inverse"];
1415
1416                                 if ((!$inverse && preg_match("/$reg_exp/i", $link)) || 
1417                                                 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1418                                                 
1419                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1420                                 }
1421                         }
1422                 }
1423
1424                 return $matches;
1425         }
1426
1427         function find_article_filter($filters, $filter_name) {
1428                 foreach ($filters as $f) {
1429                         if ($f[0] == $filter_name) {
1430                                 return $f;
1431                         };
1432                 }
1433                 return false;
1434         }
1435
1436         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1437                 $rtl_content = false, $last_updated = false, $last_error = false) {
1438
1439                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1440                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1441                 } else {
1442                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1443                 }
1444
1445                 if ($rtl_content) {
1446                         $rtl_tag = "dir=\"rtl\"";
1447                 } else {
1448                         $rtl_tag = "dir=\"ltr\"";
1449                 }
1450
1451                 $error_notify_msg = "";
1452                 
1453                 if ($last_error) {
1454                         $link_title = "Error: $last_error ($last_updated)";
1455                         $error_notify_msg = "(Error)";
1456                 } else if ($last_updated) {
1457                         $link_title = "Updated: $last_updated";
1458                 }
1459
1460                 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\" 
1461                         href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1462
1463                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1464                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1465                         print "$feed_icon";
1466                 }
1467
1468                 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1469
1470                 if ($unread != 0) {
1471                         $fctr_class = "";
1472                 } else {
1473                         $fctr_class = "class=\"invisible\"";
1474                 }
1475
1476                 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1477                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1478
1479                 if (get_pref($link, "EXTENDED_FEEDLIST")) {                      
1480                         print "<div class=\"feedExtInfo\">
1481                                 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1482                 }
1483                          
1484                 print "</li>";
1485
1486         }
1487
1488         function getmicrotime() {
1489                 list($usec, $sec) = explode(" ",microtime());
1490                 return ((float)$usec + (float)$sec);
1491         }
1492
1493         function print_radio($id, $default, $true_is, $values, $attributes = "") {
1494                 foreach ($values as $v) {
1495                 
1496                         if ($v == $default)
1497                                 $sel = "checked";
1498                          else
1499                                 $sel = "";
1500
1501                         if ($v == $true_is) {
1502                                 $sel .= " value=\"1\"";
1503                         } else {
1504                                 $sel .= " value=\"0\"";
1505                         }
1506                         
1507                         print "<input class=\"noborder\" 
1508                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1509
1510                 }
1511         }
1512
1513         function initialize_user_prefs($link, $uid) {
1514
1515                 $uid = db_escape_string($uid);
1516
1517                 db_query($link, "BEGIN");
1518
1519                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1520                 
1521                 $u_result = db_query($link, "SELECT pref_name 
1522                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1523
1524                 $active_prefs = array();
1525
1526                 while ($line = db_fetch_assoc($u_result)) {
1527                         array_push($active_prefs, $line["pref_name"]);                  
1528                 }
1529
1530                 while ($line = db_fetch_assoc($result)) {
1531                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1532 //                              print "adding " . $line["pref_name"] . "<br>";
1533
1534                                 db_query($link, "INSERT INTO ttrss_user_prefs
1535                                         (owner_uid,pref_name,value) VALUES 
1536                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1537
1538                         }
1539                 }
1540
1541                 db_query($link, "COMMIT");
1542
1543         }
1544
1545         function lookup_user_id($link, $user) {
1546
1547                 $result = db_query($link, "SELECT id FROM ttrss_users WHERE 
1548                         login = '$login'");
1549
1550                 if (db_num_rows($result) == 1) {
1551                         return db_fetch_result($result, 0, "id");
1552                 } else {
1553                         return false;
1554                 }
1555         }
1556
1557         function http_authenticate_user($link) {
1558
1559                 error_log("http_authenticate_user: ".$_SERVER["PHP_AUTH_USER"]."\n", 3, '/tmp/tt-rss.log');
1560
1561                 if (!$_SERVER["PHP_AUTH_USER"]) {
1562
1563                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1564                         header('HTTP/1.0 401 Unauthorized');
1565                         exit;
1566                                         
1567                 } else {
1568                         $auth_result = authenticate_user($link, 
1569                                 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1570
1571                         if (!$auth_result) {
1572                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1573                                 header('HTTP/1.0 401 Unauthorized');
1574                                 exit;
1575                         }
1576                 }
1577
1578                 return true;
1579         }
1580
1581         function authenticate_user($link, $login, $password, $force_auth = false) {
1582
1583                 if (!SINGLE_USER_MODE) {
1584
1585                         $pwd_hash1 = encrypt_password($password);
1586                         $pwd_hash2 = encrypt_password($password, $login);
1587
1588                         if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH 
1589                                         && $_SERVER["REMOTE_USER"]) {
1590
1591                                 $login = db_escape_string($_SERVER["REMOTE_USER"]);
1592
1593                                 $query = "SELECT id,login,access_level
1594                     FROM ttrss_users WHERE
1595                                         login = '$login'";
1596
1597                         } else {
1598                                 $query = "SELECT id,login,access_level,pwd_hash
1599                     FROM ttrss_users WHERE
1600                                         login = '$login' AND (pwd_hash = '$pwd_hash1' OR
1601                                                 pwd_hash = '$pwd_hash2')";
1602                         }
1603
1604                         $result = db_query($link, $query);
1605         
1606                         if (db_num_rows($result) == 1) {
1607                                 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1608                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1609                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1610         
1611                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1612                                         $_SESSION["uid"]);
1613         
1614                                 $user_theme = get_user_theme_path($link);
1615         
1616                                 $_SESSION["theme"] = $user_theme;
1617                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1618                                 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
1619         
1620                                 initialize_user_prefs($link, $_SESSION["uid"]);
1621         
1622                                 return true;
1623                         }
1624         
1625                         return false;
1626
1627                 } else {
1628
1629                         $_SESSION["uid"] = 1;
1630                         $_SESSION["name"] = "admin";
1631
1632                         $user_theme = get_user_theme_path($link);
1633         
1634                         $_SESSION["theme"] = $user_theme;
1635                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1636         
1637                         initialize_user_prefs($link, $_SESSION["uid"]);
1638         
1639                         return true;
1640                 }
1641         }
1642
1643         function make_password($length = 8) {
1644
1645                 $password = "";
1646                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
1647                 
1648         $i = 0; 
1649     
1650                 while ($i < $length) { 
1651                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1652         
1653                         if (!strstr($password, $char)) { 
1654                                 $password .= $char;
1655                                 $i++;
1656                         }
1657                 }
1658                 return $password;
1659         }
1660
1661         // this is called after user is created to initialize default feeds, labels
1662         // or whatever else
1663         
1664         // user preferences are checked on every login, not here
1665
1666         function initialize_user($link, $uid) {
1667
1668                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1669                         values ('$uid','unread = true', 'Unread articles')");
1670
1671                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1672                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
1673
1674                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1675                         values ('$uid', 'Tiny Tiny RSS: New Releases',
1676                         'http://tt-rss.spb.ru/releases.rss')");
1677
1678                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1679                         values ('$uid', 'Tiny Tiny RSS: Forum',
1680                         'http://tt-rss.spb.ru/forum/rss.php')");
1681         }
1682
1683         function logout_user() {
1684                 session_destroy();
1685                 if (isset($_COOKIE[session_name()])) {
1686                    setcookie(session_name(), '', time()-42000, '/');
1687                 }
1688         }
1689
1690         function get_script_urlpath() {
1691                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1692         }
1693
1694         function validate_session($link) {
1695                 if (SINGLE_USER_MODE) { 
1696                         return true;
1697                 }
1698
1699                 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1700                         if ($_SESSION["ip_address"]) {
1701                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1702                                         $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1703                                         return false;
1704                                 }
1705                         }
1706                 }
1707
1708                 if ($_SESSION["uid"]) {
1709
1710                         $result = db_query($link, 
1711                                 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
1712
1713                         $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
1714
1715                         if ($pwd_hash != $_SESSION["pwd_hash"]) {
1716                                 return false;
1717                         }
1718                 }
1719
1720 /*              if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1721
1722                         //print_r($_SESSION);
1723
1724                         if (time() > $_SESSION["cookie_lifetime"]) {
1725                                 return false;
1726                         }
1727                 } */
1728
1729                 return true;
1730         }
1731
1732         function login_sequence($link, $mobile = false) {
1733                 if (!SINGLE_USER_MODE) {
1734
1735                         if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1736                                 $swu = db_escape_string($_REQUEST["swu"]);
1737                                 if ($swu) {
1738                                         $_SESSION["prefs_cache"] = false;
1739                                         return authenticate_user($link, $swu, null, true);
1740                                 }
1741                         }
1742
1743                         $login_action = $_POST["login_action"];
1744
1745                         # try to authenticate user if called from login form                    
1746                         if ($login_action == "do_login") {
1747                                 $login = $_POST["login"];
1748                                 $password = $_POST["password"];
1749                                 $remember_me = $_POST["remember_me"];
1750
1751                                 if (authenticate_user($link, $login, $password)) {
1752                                         $_POST["password"] = "";
1753
1754                                         $_SESSION["language"] = $_POST["language"];
1755
1756                                         header("Location: " . $_SERVER["REQUEST_URI"]);
1757                                         exit;
1758
1759                                         return;
1760                                 } else {
1761                                         $_SESSION["login_error_msg"] = "Incorrect username or password";
1762                                 }
1763                         }
1764
1765 //                      print session_id();
1766 //                      print_r($_SESSION);
1767
1768                         if (!$_SESSION["uid"] || !validate_session($link)) {
1769                                 render_login_form($link, $mobile);
1770                                 exit;
1771                         } else {
1772                                 /* bump login timestamp */
1773                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1774                                         $_SESSION["uid"]);
1775
1776                                 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME > 0) {
1777                                         setcookie("ttrss_lang", $_SESSION["language"], 
1778                                                 time() + SESSION_COOKIE_LIFETIME);
1779                                 }
1780                         }
1781
1782                 } else {
1783                         return authenticate_user($link, "admin", null);
1784                 }
1785         }
1786
1787         function truncate_string($str, $max_len) {
1788                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1789                         return mb_substr($str, 0, $max_len, "utf-8") . "&hellip;";
1790                 } else {
1791                         return $str;
1792                 }
1793         }
1794
1795         function get_user_theme_path($link) {
1796                 $result = db_query($link, "SELECT theme_path 
1797                         FROM 
1798                                 ttrss_themes,ttrss_users
1799                         WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1800                 if (db_num_rows($result) != 0) {
1801                         return db_fetch_result($result, 0, "theme_path");
1802                 } else {
1803                         return null;
1804                 }
1805         }
1806
1807         function smart_date_time($timestamp) {
1808                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1809                         return date("G:i", $timestamp);
1810                 } else if (date("Y", $timestamp) == date("Y")) {
1811                         return date("M d, G:i", $timestamp);
1812                 } else {
1813                         return date("Y/m/d, G:i", $timestamp);
1814                 }
1815         }
1816
1817         function smart_date($timestamp) {
1818                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1819                         return "Today";
1820                 } else if (date("Y", $timestamp) == date("Y")) {
1821                         return date("D m", $timestamp);
1822                 } else {
1823                         return date("Y/m/d", $timestamp);
1824                 }
1825         }
1826
1827         function sql_bool_to_string($s) {
1828                 if ($s == "t" || $s == "1") {
1829                         return "true";
1830                 } else {
1831                         return "false";
1832                 }
1833         }
1834
1835         function sql_bool_to_bool($s) {
1836                 if ($s == "t" || $s == "1") {
1837                         return true;
1838                 } else {
1839                         return false;
1840                 }
1841         }
1842         
1843
1844         function toggleEvenOdd($a) {
1845                 if ($a == "even") 
1846                         return "odd";
1847                 else
1848                         return "even";
1849         }
1850
1851         function sanity_check($link) {
1852
1853                 error_reporting(0);
1854
1855                 $error_code = 0;
1856                 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1857                 $schema_version = db_fetch_result($result, 0, "schema_version");
1858
1859                 if ($schema_version != SCHEMA_VERSION) {
1860                         $error_code = 5;
1861                 }
1862
1863                 if (DB_TYPE == "mysql") {
1864                         $result = db_query($link, "SELECT true", false);
1865                         if (db_num_rows($result) != 1) {
1866                                 $error_code = 10;
1867                         }
1868                 }
1869
1870                 error_reporting (DEFAULT_ERROR_LEVEL);
1871
1872                 if ($error_code != 0) {
1873                         print_error_xml($error_code);
1874                         return false;
1875                 } else {
1876                         return true;
1877                 }
1878         }
1879
1880         function file_is_locked($filename) {
1881                 if (function_exists('flock')) {
1882                         error_reporting(0);
1883                         $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
1884                         error_reporting(DEFAULT_ERROR_LEVEL);
1885                         if ($fp) {
1886                                 if (flock($fp, LOCK_EX | LOCK_NB)) {
1887                                         flock($fp, LOCK_UN);
1888                                         fclose($fp);
1889                                         return false;
1890                                 }
1891                                 fclose($fp);
1892                                 return true;
1893                         }
1894                 }
1895                 return false;
1896         }
1897
1898         function make_lockfile($filename) {
1899                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1900
1901                 if (flock($fp, LOCK_EX | LOCK_NB)) {            
1902                         return $fp;
1903                 } else {
1904                         return false;
1905                 }
1906         }
1907
1908         function make_stampfile($filename) {
1909                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
1910
1911                 if (flock($fp, LOCK_EX | LOCK_NB)) {
1912                         fwrite($fp, time() . "\n");
1913                         flock($fp, LOCK_UN);
1914                         fclose($fp);
1915                         return true;
1916                 } else {
1917                         return false;
1918                 }
1919         }
1920
1921         function read_stampfile($filename) {
1922
1923                 error_reporting(0);
1924                 $fp = fopen(LOCK_DIRECTORY . "/$filename", "r");
1925                 error_reporting (DEFAULT_ERROR_LEVEL);
1926
1927                 if (flock($fp, LOCK_EX)) {
1928                         $stamp = fgets($fp);
1929                         flock($fp, LOCK_UN);
1930                         fclose($fp);
1931                         return $stamp;
1932                 } else {
1933                         return false;
1934                 }
1935         }
1936
1937         function sql_random_function() {
1938                 if (DB_TYPE == "mysql") {
1939                         return "RAND()";
1940                 } else {
1941                         return "RANDOM()";
1942                 }
1943         }
1944
1945         function catchup_feed($link, $feed, $cat_view) {
1946
1947                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1948                         
1949                                 if ($cat_view) {
1950
1951                                         if ($feed > 0) {
1952                                                 $cat_qpart = "cat_id = '$feed'";
1953                                         } else {
1954                                                 $cat_qpart = "cat_id IS NULL";
1955                                         }
1956                                         
1957                                         $tmp_result = db_query($link, "SELECT id 
1958                                                 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " . 
1959                                                 $_SESSION["uid"]);
1960
1961                                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
1962
1963                                                 $tmp_feed = $tmp_line["id"];
1964
1965                                                 db_query($link, "UPDATE ttrss_user_entries 
1966                                                         SET unread = false,last_read = NOW() 
1967                                                         WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1968                                         }
1969
1970                                 } else if ($feed > 0) {
1971
1972                                         $tmp_result = db_query($link, "SELECT id 
1973                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
1974                                                 ORDER BY cat_id,title");
1975
1976                                         $parent_ids = array();
1977
1978                                         if (db_num_rows($tmp_result) > 0) {
1979                                                 while ($p = db_fetch_assoc($tmp_result)) {
1980                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
1981                                                 }
1982
1983                                                 $children_qpart = implode(" OR ", $parent_ids);
1984                                                 
1985                                                 db_query($link, "UPDATE ttrss_user_entries 
1986                                                         SET unread = false,last_read = NOW() 
1987                                                         WHERE (feed_id = '$feed' OR $children_qpart) 
1988                                                         AND owner_uid = " . $_SESSION["uid"]);
1989
1990                                         } else {                                                
1991                                                 db_query($link, "UPDATE ttrss_user_entries 
1992                                                         SET unread = false,last_read = NOW() 
1993                                                         WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1994                                         }
1995                                                 
1996                                 } else if ($feed < 0 && $feed > -10) { // special, like starred
1997
1998                                         if ($feed == -1) {
1999                                                 db_query($link, "UPDATE ttrss_user_entries 
2000                                                         SET unread = false,last_read = NOW()
2001                                                         WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
2002                                         }
2003
2004                                         if ($feed == -2) {
2005                                                 db_query($link, "UPDATE ttrss_user_entries 
2006                                                         SET unread = false,last_read = NOW()
2007                                                         WHERE published = true AND owner_uid = ".$_SESSION["uid"]);
2008                                         }
2009
2010                                         if ($feed == -3) {
2011
2012                                                 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2013
2014                                                 if (DB_TYPE == "pgsql") {
2015                                                         $match_part = "date_entered > NOW() - INTERVAL '$intl hour' "; 
2016                                                 } else {
2017                                                         $match_part = "date_entered > DATE_SUB(NOW(), 
2018                                                                 INTERVAL $intl HOUR) ";
2019                                                 }
2020
2021                                                 $result = db_query($link, "SELECT id FROM ttrss_entries, 
2022                                                         ttrss_user_entries WHERE $match_part AND
2023                                                         unread = true AND
2024                                                         ttrss_user_entries.ref_id = ttrss_entries.id AND        
2025                                                         owner_uid = ".$_SESSION["uid"]);
2026
2027                                                 $affected_ids = array();
2028
2029                                                 while ($line = db_fetch_assoc($result)) {
2030                                                         array_push($affected_ids, $line["id"]);
2031                                                 }
2032
2033                                                 catchupArticlesById($link, $affected_ids, 0);
2034                                         }
2035
2036                                 } else if ($feed < -10) { // label
2037
2038                                         // TODO make this more efficient
2039
2040                                         $label_id = -$feed - 11;
2041
2042                                         $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2043                                                 WHERE id = '$label_id'");                                       
2044
2045                                         if ($tmp_result) {
2046                                                 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
2047
2048                                                 db_query($link, "BEGIN");
2049
2050                                                 $tmp2_result = db_query($link,
2051                                                         "SELECT 
2052                                                                 int_id 
2053                                                         FROM 
2054                                                                 ttrss_user_entries,ttrss_entries,ttrss_feeds
2055                                                         WHERE
2056                                                                 ref_id = ttrss_entries.id AND 
2057                                                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2058                                                                 $sql_exp AND
2059                                                                 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2060
2061                                                 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
2062                                                         db_query($link, "UPDATE 
2063                                                                 ttrss_user_entries 
2064                                                         SET 
2065                                                                 unread = false, last_read = NOW()
2066                                                         WHERE
2067                                                                 int_id = " . $tmp_line["int_id"]);
2068                                                 }
2069                                                                 
2070                                                 db_query($link, "COMMIT");
2071
2072 /*                                              db_query($link, "UPDATE ttrss_user_entries,ttrss_entries 
2073                                                         SET unread = false,last_read = NOW()
2074                                                         WHERE $sql_exp
2075                                                         AND ref_id = id
2076                                                         AND owner_uid = ".$_SESSION["uid"]); */
2077                                         }
2078                                 }
2079                         } else { // tag
2080                                 db_query($link, "BEGIN");
2081
2082                                 $tag_name = db_escape_string($feed);
2083
2084                                 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
2085                                         WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
2086
2087                                 while ($line = db_fetch_assoc($result)) {
2088                                         db_query($link, "UPDATE ttrss_user_entries SET
2089                                                 unread = false, last_read = NOW() 
2090                                                 WHERE int_id = " . $line["post_int_id"]);
2091                                 }
2092                                 db_query($link, "COMMIT");
2093                         }
2094         }
2095
2096         function update_generic_feed($link, $feed, $cat_view, $force_update = false) {
2097                         if ($cat_view) {
2098
2099                                 if ($feed > 0) {
2100                                         $cat_qpart = "cat_id = '$feed'";
2101                                 } else {
2102                                         $cat_qpart = "cat_id IS NULL";
2103                                 }
2104                                 
2105                                 $tmp_result = db_query($link, "SELECT id,feed_url FROM ttrss_feeds
2106                                         WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
2107
2108                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
2109                                         $feed_url = $tmp_line["feed_url"];
2110                                         $feed_id = $tmp_line["id"];
2111                                         update_rss_feed($link, $feed_url, $feed_id, $force_update);
2112                                 }
2113
2114                         } else {
2115                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
2116                                         WHERE id = '$feed'");
2117                                 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");                                
2118                                 update_rss_feed($link, $feed_url, $feed, $force_update);
2119                         }
2120         }
2121
2122         function getAllCounters($link, $omode = "flc", $active_feed = false) {
2123 /*              getLabelCounters($link);
2124                 getFeedCounters($link);
2125                 getTagCounters($link);
2126                 getGlobalCounters($link);
2127                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2128                         getCategoryCounters($link);
2129                 } */
2130
2131                 if (!$omode) $omode = "flc";
2132
2133                 getGlobalCounters($link);
2134
2135                 if (strchr($omode, "l")) getLabelCounters($link);
2136                 if (strchr($omode, "f")) getFeedCounters($link, SMART_RPC_COUNTERS, $active_feed);
2137                 if (strchr($omode, "t")) getTagCounters($link);
2138                 if (strchr($omode, "c")) {                      
2139                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
2140                                 getCategoryCounters($link);
2141                         }
2142                 }
2143         }       
2144
2145         function getCategoryCounters($link) {
2146                 # two special categories are -1 and -2 (all virtuals; all labels)
2147
2148                 $ctr = getCategoryUnread($link, -1);
2149
2150                 print "<counter type=\"category\" id=\"-1\" counter=\"$ctr\"/>";
2151
2152                 $ctr = getCategoryUnread($link, -2);
2153
2154                 print "<counter type=\"category\" id=\"-2\" counter=\"$ctr\"/>";
2155
2156                 $age_qpart = getMaxAgeSubquery();
2157
2158                 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id) 
2159                                 FROM ttrss_user_entries, ttrss_entries WHERE feed_id = ttrss_feeds.id 
2160                                         AND id = ref_id AND $age_qpart 
2161                                         AND unread = true)) AS unread FROM ttrss_feeds 
2162                         WHERE 
2163                                 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
2164
2165                 while ($line = db_fetch_assoc($result)) {
2166                         $line["cat_id"] = sprintf("%d", $line["cat_id"]);
2167                         print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
2168                                 $line["unread"]."\"/>";
2169                 }
2170         }
2171
2172         function getCategoryUnread($link, $cat) {
2173
2174                 if ($cat >= 0) {
2175
2176                         if ($cat != 0) {
2177                                 $cat_query = "cat_id = '$cat'";
2178                         } else {
2179                                 $cat_query = "cat_id IS NULL";
2180                         }
2181
2182                         $age_qpart = getMaxAgeSubquery();
2183
2184                         $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query 
2185                                         AND hidden = false
2186                                         AND owner_uid = " . $_SESSION["uid"]);
2187         
2188                         $cat_feeds = array();
2189                         while ($line = db_fetch_assoc($result)) {
2190                                 array_push($cat_feeds, "feed_id = " . $line["id"]);
2191                         }
2192         
2193                         if (count($cat_feeds) == 0) return 0;
2194         
2195                         $match_part = implode(" OR ", $cat_feeds);
2196         
2197                         $result = db_query($link, "SELECT COUNT(int_id) AS unread 
2198                                 FROM ttrss_user_entries,ttrss_entries 
2199                                 WHERE   unread = true AND ($match_part) AND id = ref_id 
2200                                 AND $age_qpart AND owner_uid = " . $_SESSION["uid"]);
2201         
2202                         $unread = 0;
2203         
2204                         # this needs to be rewritten
2205                         while ($line = db_fetch_assoc($result)) {
2206                                 $unread += $line["unread"];
2207                         }
2208         
2209                         return $unread;
2210                 } else if ($cat == -1) {
2211                         return getFeedUnread($link, -1) + getFeedUnread($link, -2) + getFeedUnread($link, -3);
2212                 } else if ($cat == -2) {
2213
2214                         $rv = getLabelCounters($link, false, true);
2215                         $ctr = 0;
2216
2217                         foreach (array_keys($rv) as $k) {
2218                                 if ($k < -10) {
2219                                         $ctr += $rv[$k]["counter"];
2220                                 }
2221                         }
2222
2223                         return $ctr;
2224                 }
2225         }
2226
2227         function getMaxAgeSubquery($days = COUNTERS_MAX_AGE) {
2228                 if (DB_TYPE == "pgsql") {
2229                         return "ttrss_entries.date_entered > 
2230                                 NOW() - INTERVAL '$days days'";
2231                 } else {
2232                         return "ttrss_entries.date_entered > 
2233                                 DATE_SUB(NOW(), INTERVAL $days DAY)";
2234                 }
2235         }
2236
2237         function getFeedUnread($link, $feed, $is_cat = false) {
2238                 $n_feed = sprintf("%d", $feed);
2239
2240                 $age_qpart = getMaxAgeSubquery();
2241
2242                 if ($is_cat) {
2243                         return getCategoryUnread($link, $n_feed);               
2244                 } else if ($n_feed == -1) {
2245                         $match_part = "marked = true";
2246                 } else if ($n_feed == -2) {
2247                         $match_part = "published = true";
2248                 } else if ($n_feed == -3) {
2249                         $match_part = "unread = true";
2250
2251                         $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
2252
2253                         if (DB_TYPE == "pgsql") {
2254                                 $match_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' "; 
2255                         } else {
2256                                 $match_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2257                         }
2258
2259                 } else if ($n_feed > 0) {
2260
2261                         $result = db_query($link, "SELECT id FROM ttrss_feeds 
2262                                         WHERE parent_feed = '$n_feed'
2263                                         AND hidden = false
2264                                         AND owner_uid = " . $_SESSION["uid"]);
2265
2266                         if (db_num_rows($result) > 0) {
2267
2268                                 $linked_feeds = array();
2269                                 while ($line = db_fetch_assoc($result)) {
2270                                         array_push($linked_feeds, "feed_id = " . $line["id"]);
2271                                 }
2272
2273                                 array_push($linked_feeds, "feed_id = $n_feed");
2274                                 
2275                                 $match_part = implode(" OR ", $linked_feeds);
2276
2277                                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
2278                                         FROM ttrss_user_entries,ttrss_entries
2279                                         WHERE   unread = true AND
2280                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
2281                                         $age_qpart AND
2282                                         ($match_part) AND
2283                                         owner_uid = " . $_SESSION["uid"]);
2284
2285                                 $unread = 0;
2286
2287                                 # this needs to be rewritten
2288                                 while ($line = db_fetch_assoc($result)) {
2289                                         $unread += $line["unread"];
2290                                 }
2291
2292                                 return $unread;
2293
2294                         } else {
2295                                 $match_part = "feed_id = '$n_feed'";
2296                         }
2297                 } else if ($feed < -10) {
2298
2299                         $label_id = -$feed - 11;
2300
2301                         $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
2302                                 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
2303
2304                         $match_part = db_fetch_result($result, 0, "sql_exp");
2305                 }
2306
2307                 if ($match_part) {
2308                 
2309                         $result = db_query($link, "SELECT count(int_id) AS unread 
2310                                 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
2311                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2312                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
2313                                 ttrss_feeds.hidden = false AND
2314                                 $age_qpart AND
2315                                 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
2316                                 
2317                 } else {
2318                 
2319                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
2320                                 FROM ttrss_tags,ttrss_user_entries,ttrss_entries 
2321                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id 
2322                                 AND unread = true AND $age_qpart AND
2323                                         ttrss_tags.owner_uid = " . $_SESSION["uid"]);
2324                 }
2325                 
2326                 $unread = db_fetch_result($result, 0, "unread");
2327
2328                 return $unread;
2329         }
2330
2331         /* FIXME this needs reworking */
2332
2333         function getGlobalUnread($link, $user_id = false) {
2334
2335                 if (!$user_id) {
2336                         $user_id = $_SESSION["uid"];
2337                 }
2338
2339                 $age_qpart = getMaxAgeSubquery();
2340
2341                 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2342                         WHERE unread = true AND 
2343                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
2344                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
2345                         hidden = false AND
2346                         $age_qpart AND
2347                         ttrss_user_entries.owner_uid = '$user_id'");
2348                 $c_id = db_fetch_result($result, 0, "c_id");
2349                 return $c_id;
2350         }
2351
2352         function getGlobalCounters($link, $global_unread = -1) {
2353                 if ($global_unread == -1) {     
2354                         $global_unread = getGlobalUnread($link);
2355                 }
2356                 print "<counter type=\"global\" id='global-unread' 
2357                         counter='$global_unread'/>";
2358
2359                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM 
2360                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2361
2362                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
2363
2364                 print "<counter type=\"global\" id='subscribed-feeds' 
2365                         counter='$subscribed_feeds'/>";
2366
2367         }
2368
2369         function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
2370
2371                 if ($smart_mode) {
2372                         if (!$_SESSION["tctr_last_value"]) {
2373                                 $_SESSION["tctr_last_value"] = array();
2374                         }
2375                 }
2376
2377                 $old_counters = $_SESSION["tctr_last_value"];
2378
2379                 $tctrs_modified = false;
2380
2381 /*              $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
2382                         FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
2383                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
2384                         ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
2385                         post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name 
2386                 UNION
2387                         select tag_name,0 as count FROM ttrss_tags
2388                         WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
2389
2390                 $age_qpart = getMaxAgeSubquery();
2391
2392                 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
2393                         FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
2394                                 AND ref_id = id AND $age_qpart
2395                                 AND unread = true)) AS count FROM ttrss_tags 
2396                                 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name 
2397                                 ORDER BY count DESC LIMIT 55");
2398                         
2399                 $tags = array();
2400
2401                 while ($line = db_fetch_assoc($result)) {
2402                         $tags[$line["tag_name"]] += $line["count"];
2403                 }
2404
2405                 foreach (array_keys($tags) as $tag) {
2406                         $unread = $tags[$tag];                  
2407
2408                         $tag = htmlspecialchars($tag);
2409
2410                         if (!$smart_mode || $old_counters[$tag] != $unread) {                   
2411                                 $old_counters[$tag] = $unread;
2412                                 $tctrs_modified = true;
2413                                 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
2414                         }
2415
2416                 } 
2417
2418                 if ($smart_mode && $tctrs_modified) {
2419                         $_SESSION["tctr_last_value"] = $old_counters;
2420                 }
2421
2422         }
2423
2424         function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
2425
2426                 $age_qpart = getMaxAgeSubquery();
2427
2428                 if ($smart_mode) {
2429                         if (!$_SESSION["lctr_last_value"]) {
2430                                 $_SESSION["lctr_last_value"] = array();
2431                         }
2432                 }
2433
2434                 $ret_arr = array();
2435                 
2436                 $old_counters = $_SESSION["lctr_last_value"];
2437                 $lctrs_modified = false;
2438
2439                 $count = getFeedUnread($link, -1);
2440
2441                 if (!$ret_mode) {
2442                         print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
2443                 } else {
2444                         $ret_arr["-1"]["counter"] = $count;
2445                         $ret_arr["-1"]["description"] = __("Starred articles");
2446                 }
2447
2448                 $count = getFeedUnread($link, -2);
2449
2450                 if (!$ret_mode) {
2451                         print "<counter type=\"label\" id=\"-2\" counter=\"$count\"/>";
2452                 } else {
2453                         $ret_arr["-2"]["counter"] = $count;
2454                         $ret_arr["-2"]["description"] = __("Published articles");
2455                 }
2456
2457                 $count = getFeedUnread($link, -3);
2458
2459                 if (!$ret_mode) {
2460                         print "<counter type=\"label\" id=\"-3\" counter=\"$count\"/>";
2461                 } else {
2462                         $ret_arr["-3"]["counter"] = $count;
2463                         $ret_arr["-3"]["description"] = __("Fresh articles");
2464                 }
2465
2466
2467                 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
2468                         ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
2469         
2470                 while ($line = db_fetch_assoc($result)) {
2471
2472                         $id = -$line["id"] - 11;
2473
2474                         $label_name = $line["description"];
2475
2476                         error_reporting (0);
2477
2478                         $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
2479                                 WHERE (" . $line["sql_exp"] . ") AND unread = true AND 
2480                                 ttrss_feeds.hidden = false AND
2481                                 $age_qpart AND
2482                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2483                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
2484                                 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
2485
2486                         $count = db_fetch_result($tmp_result, 0, "count");
2487
2488                         if (!$smart_mode || $old_counters[$id] != $count) {     
2489                                 $old_counters[$id] = $count;
2490                                 $lctrs_modified = true;
2491                                 if (!$ret_mode) {
2492                                         print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
2493                                 } else {
2494                                         $ret_arr[$id]["counter"] = $count;
2495                                         $ret_arr[$id]["description"] = $label_name;
2496                                 }
2497                         }
2498
2499                         error_reporting (DEFAULT_ERROR_LEVEL);
2500                 }
2501
2502                 if ($smart_mode && $lctrs_modified) {
2503                         $_SESSION["lctr_last_value"] = $old_counters;
2504                 }
2505
2506                 return $ret_arr;
2507         }
2508
2509 /*      function getFeedCounter($link, $id) {
2510         
2511                 $result = db_query($link, "SELECT 
2512                                 count(id) as count,last_error
2513                         FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
2514                         WHERE feed_id = '$id' AND unread = true
2515                         AND ttrss_user_entries.feed_id = ttrss_feeds.id
2516                         AND ttrss_user_entries.ref_id = ttrss_entries.id");
2517         
2518                         $count = db_fetch_result($result, 0, "count");
2519                         $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
2520                         
2521                         print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";           
2522         } */
2523
2524         function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS, $active_feed = false) {
2525
2526                 $age_qpart = getMaxAgeSubquery();
2527
2528                 if ($smart_mode) {
2529                         if (!$_SESSION["fctr_last_value"]) {
2530                                 $_SESSION["fctr_last_value"] = array();
2531                         }
2532                 }
2533
2534                 $old_counters = $_SESSION["fctr_last_value"];
2535
2536 /*              $result = db_query($link, "SELECT id,last_error,parent_feed,
2537                         SUBSTRING(last_updated,1,19) AS last_updated,
2538                         (SELECT count(id) 
2539                                 FROM ttrss_entries,ttrss_user_entries 
2540                                 WHERE feed_id = ttrss_feeds.id AND 
2541                                         ttrss_user_entries.ref_id = ttrss_entries.id
2542                                 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
2543                         FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
2544                         AND parent_feed IS NULL"); */
2545
2546                 $query = "SELECT ttrss_feeds.id,
2547                                 ttrss_feeds.title,
2548                                 SUBSTRING(ttrss_feeds.last_updated,1,19) AS last_updated, 
2549                                 last_error, 
2550                                 COUNT(ttrss_entries.id) AS count 
2551                         FROM ttrss_feeds 
2552                                 LEFT JOIN ttrss_user_entries ON (ttrss_user_entries.feed_id = ttrss_feeds.id 
2553                                         AND ttrss_user_entries.owner_uid = ttrss_feeds.owner_uid 
2554                                         AND ttrss_user_entries.unread = true) 
2555                                 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id AND
2556                                         $age_qpart) 
2557                         WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."  
2558                                 AND parent_feed IS NULL 
2559                         GROUP BY ttrss_feeds.id, ttrss_feeds.title, ttrss_feeds.last_updated, last_error";
2560
2561                 $result = db_query($link, $query);
2562                 $fctrs_modified = false;
2563
2564                 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
2565
2566                 while ($line = db_fetch_assoc($result)) {
2567                 
2568                         $id = $line["id"];
2569                         $count = $line["count"];
2570                         $last_error = htmlspecialchars($line["last_error"]);
2571
2572                         if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2573                                 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2574                         } else {
2575                                 $last_updated = date($short_date, strtotime($line["last_updated"]));
2576                         }                               
2577
2578                         $last_updated = htmlspecialchars($last_updated);
2579
2580                         $has_img = is_file(ICONS_DIR . "/$id.ico");
2581
2582                         $tmp_result = db_query($link,
2583                                 "SELECT ttrss_feeds.id,COUNT(unread) AS unread
2584                                 FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
2585                                         ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
2586                                 LEFT JOIN ttrss_entries ON (ttrss_user_entries.ref_id = ttrss_entries.id) 
2587                                 WHERE parent_feed = '$id' AND $age_qpart AND unread = true GROUP BY ttrss_feeds.id");
2588                         
2589                         if (db_num_rows($tmp_result) > 0) {                             
2590                                 while ($l = db_fetch_assoc($tmp_result)) {
2591                                         $count += $l["unread"];
2592                                 }
2593                         }
2594
2595                         if (!$smart_mode || $old_counters[$id] != $count) {
2596                                 $old_counters[$id] = $count;
2597                                 $fctrs_modified = true;
2598
2599                                 if ($last_error) {
2600                                         $error_part = "error=\"$last_error\"";
2601                                 } else {
2602                                         $error_part = "";
2603                                 }
2604
2605                                 if ($has_img) {
2606                                         $has_img_part = "hi=\"$has_img\"";
2607                                 } else {
2608                                         $has_img_part = "";
2609                                 }                               
2610
2611                                 if ($active_feed && $id == $active_feed) {
2612                                         $has_title_part = "title=\"" . htmlspecialchars($line["title"]) . "\"";
2613                                 } else {
2614                                         $has_title_part = "";
2615                                 }
2616
2617                                 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\" $has_title_part/>";
2618                         }
2619                 }
2620
2621                 if ($smart_mode && $fctrs_modified) {
2622                         $_SESSION["fctr_last_value"] = $old_counters;
2623                 }
2624         }
2625
2626         function get_script_dt_add() {
2627                 if (strpos(VERSION, ".99") === false) {
2628                         return VERSION;
2629                 } else {
2630                         return time();
2631                 }
2632         }
2633
2634         function get_pgsql_version($link) {
2635                 $result = db_query($link, "SELECT version() AS version");
2636                 $version = split(" ", db_fetch_result($result, 0, "version"));
2637                 return $version[1];
2638         }
2639
2640         function print_error_xml($code, $add_msg = "") {
2641                 global $ERRORS;
2642
2643                 $error_msg = $ERRORS[$code];
2644                 
2645                 if ($add_msg) {
2646                         $error_msg = "$error_msg; $add_msg";
2647                 }
2648                 
2649                 print "<rpc-reply>";
2650                 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2651                 print "</rpc-reply>";
2652         }
2653
2654         function subscribe_to_feed($link, $feed_link, $cat_id = 0, 
2655                         $auth_login = '', $auth_pass = '') {
2656
2657                 # check for feed:http://url
2658                 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2659
2660                 # check for feed://URL
2661                 if (strpos($feed_link, "//") === 0) {
2662                         $feed_link = "http:$feed_link";
2663                 }
2664
2665                 if ($feed_link == "") return;
2666
2667                 if ($cat_id == "0" || !$cat_id) {
2668                         $cat_qpart = "NULL";
2669                 } else {
2670                         $cat_qpart = "'$cat_id'";
2671                 }
2672         
2673                 $result = db_query($link,
2674                         "SELECT id FROM ttrss_feeds 
2675                         WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2676         
2677                 if (db_num_rows($result) == 0) {
2678                         
2679                         $result = db_query($link,
2680                                 "INSERT INTO ttrss_feeds 
2681                                         (owner_uid,feed_url,title,cat_id, auth_login,auth_pass) 
2682                                 VALUES ('".$_SESSION["uid"]."', '$feed_link', 
2683                                 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2684         
2685                         $result = db_query($link,
2686                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link' 
2687                                         AND owner_uid = " . $_SESSION["uid"]);
2688         
2689                         $feed_id = db_fetch_result($result, 0, "id");
2690         
2691                         if ($feed_id) {
2692                                 update_rss_feed($link, $feed_link, $feed_id, true);
2693                         }
2694
2695                         return true;
2696                 } else {
2697                         return false;
2698                 }
2699         }
2700
2701         function print_feed_select($link, $id, $default_id = "", 
2702                 $attributes = "", $include_all_feeds = true) {
2703
2704                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2705                 if ($include_all_feeds) { 
2706                         print "<option value=\"0\">".__('All feeds')."</option>";
2707                 }
2708         
2709                 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2710                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2711
2712                 if (db_num_rows($result) > 0 && $include_all_feeds) {
2713                         print "<option disabled>--------</option>";
2714                 }
2715
2716                 while ($line = db_fetch_assoc($result)) {
2717                         if ($line["id"] == $default_id) {
2718                                 $is_selected = "selected";
2719                         } else {
2720                                 $is_selected = "";
2721                         }
2722                         printf("<option $is_selected value='%d'>%s</option>", 
2723                                 $line["id"], htmlspecialchars($line["title"]));
2724                 }
2725         
2726                 print "</select>";
2727         }
2728
2729         function print_feed_cat_select($link, $id, $default_id = "", 
2730                 $attributes = "", $include_all_cats = true) {
2731                 
2732                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2733
2734                 if ($include_all_cats) {
2735                         print "<option value=\"0\">".__('Uncategorized')."</option>";
2736                 }
2737
2738                 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2739                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2740
2741                 if (db_num_rows($result) > 0 && $include_all_cats) {
2742                         print "<option disabled>--------</option>";
2743                 }
2744
2745                 while ($line = db_fetch_assoc($result)) {
2746                         if ($line["id"] == $default_id) {
2747                                 $is_selected = "selected";
2748                         } else {
2749                                 $is_selected = "";
2750                         }
2751                         printf("<option $is_selected value='%d'>%s</option>", 
2752                                 $line["id"], htmlspecialchars($line["title"]));
2753                 }
2754
2755                 print "</select>";
2756         }
2757         
2758         function checkbox_to_sql_bool($val) {
2759                 return ($val == "on") ? "true" : "false";
2760         }
2761
2762         function getFeedCatTitle($link, $id) {
2763                 if ($id == -1) {
2764                         return __("Special");
2765                 } else if ($id < -10) {
2766                         return __("Labels");
2767                 } else if ($id > 0) {
2768                         $result = db_query($link, "SELECT ttrss_feed_categories.title 
2769                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2770                                         cat_id = ttrss_feed_categories.id");
2771                         if (db_num_rows($result) == 1) {
2772                                 return db_fetch_result($result, 0, "title");
2773                         } else {
2774                                 return __("Uncategorized");
2775                         }
2776                 } else {
2777                         return "getFeedCatTitle($id) failed";
2778                 }
2779
2780         }
2781
2782         function getFeedTitle($link, $id) {
2783                 if ($id == -1) {
2784                         return __("Starred articles");
2785                 } else if ($id == -2) {
2786                         return __("Published articles");
2787                 } else if ($id == -3) {
2788                         return __("Fresh articles");
2789                 } else if ($id < -10) {
2790                         $label_id = -10 - $id;
2791                         $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2792                         if (db_num_rows($result) == 1) {
2793                                 return db_fetch_result($result, 0, "description");
2794                         } else {
2795                                 return "Unknown label ($label_id)";
2796                         }
2797
2798                 } else if ($id > 0) {
2799                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2800                         if (db_num_rows($result) == 1) {
2801                                 return db_fetch_result($result, 0, "title");
2802                         } else {
2803                                 return "Unknown feed ($id)";
2804                         }
2805                 } else {
2806                         return "getFeedTitle($id) failed";
2807                 }
2808
2809         }
2810
2811         function get_session_cookie_name() {
2812                 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2813         }
2814
2815         function print_init_params($link) {
2816                 print "<init-params>";
2817                 if ($_SESSION["stored-params"]) {
2818                         foreach (array_keys($_SESSION["stored-params"]) as $key) {
2819                                 if ($key) {
2820                                         $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2821                                         print "<param key=\"$key\" value=\"$value\"/>";
2822                                 }
2823                         }
2824                 }
2825
2826                 print "<param key=\"theme\" value=\"".$_SESSION["theme"]."\"/>";
2827                 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2828                 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2829                 print "<param key=\"daemon_refresh_only\" value=\"true\"/>";
2830
2831                 print "<param key=\"on_catchup_show_next_feed\" value=\"" . 
2832                         get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2833
2834                 print "<param key=\"hide_read_feeds\" value=\"" . 
2835                         (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2836
2837                 print "<param key=\"feeds_sort_by_unread\" value=\"" . 
2838                         (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2839
2840                 print "<param key=\"confirm_feed_catchup\" value=\"" . 
2841                         (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2842
2843                 print "<param key=\"cdm_auto_catchup\" value=\"" . 
2844                         (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2845
2846                 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
2847
2848                 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
2849
2850                 print "<param key=\"default_view_mode\" value=\"" . 
2851                         get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2852
2853                 print "<param key=\"default_view_limit\" value=\"" . 
2854                         (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2855
2856                 print "<param key=\"prefs_active_tab\" value=\"" . 
2857                         get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2858
2859                 print "<param key=\"infobox_disable_overlay\" value=\"" . 
2860                         get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2861
2862                 print "<param key=\"icons_location\" value=\"" . 
2863                         ICONS_URL . "\"/>";
2864
2865                 print "<param key=\"hide_read_shows_special\" value=\"" . 
2866                         (int) get_pref($link, "HIDE_READ_SHOWS_SPECIAL") . "\"/>";
2867
2868                 print "</init-params>";
2869         }
2870
2871         function print_runtime_info($link) {
2872                 print "<runtime-info>";
2873
2874                 if (ENABLE_UPDATE_DAEMON) {
2875                         print "<param key=\"daemon_is_running\" value=\"".
2876                                 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2877
2878                         if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2879
2880                                 $stamp = (int)read_stampfile("update_daemon.stamp");
2881
2882 //                              print "<param key=\"daemon_stamp_delta\" value=\"$stamp_delta\"/>";
2883
2884                                 if ($stamp) {
2885                                         $stamp_delta = time() - $stamp;
2886
2887                                         if ($stamp_delta > 1800) {
2888                                                 $stamp_check = 0;
2889                                         } else {
2890                                                 $stamp_check = 1;
2891                                                 $_SESSION["daemon_stamp_check"] = time();
2892                                         }
2893
2894                                         print "<param key=\"daemon_stamp_ok\" value=\"$stamp_check\"/>";
2895
2896                                         $stamp_fmt = date("Y.m.d, G:i", $stamp);
2897
2898                                         print "<param key=\"daemon_stamp\" value=\"$stamp_fmt\"/>";
2899                                 }
2900                         }
2901                 }
2902
2903                 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
2904                         
2905                         if ($_SESSION["last_version_check"] + 7200 < time()) {
2906                                 $new_version_details = check_for_update($link);
2907
2908                                 print "<param key=\"new_version_available\" value=\"".
2909                                         sprintf("%d", $new_version_details != ""). "\"/>";
2910
2911                                 $_SESSION["last_version_check"] = time();
2912                         }
2913                 }
2914
2915 //              print "<param key=\"new_version_available\" value=\"1\"/>";
2916
2917                 print "</runtime-info>";
2918         }
2919
2920         function getSearchSql($search, $match_on) {
2921
2922                 $search_query_part = "";
2923
2924                 $keywords = split(" ", $search);
2925                 $query_keywords = array();
2926
2927                 if ($match_on == "both") {
2928
2929                         foreach ($keywords as $k) {
2930                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2931                                         OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2932                         }
2933
2934                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2935
2936                 } else if ($match_on == "title") {
2937
2938                         foreach ($keywords as $k) {
2939                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2940                         }
2941
2942                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2943
2944                 } else if ($match_on == "content") {
2945
2946                         foreach ($keywords as $k) {
2947                                 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2948                         }
2949                 }
2950
2951                 $search_query_part = implode("AND", $query_keywords);
2952
2953                 return $search_query_part;
2954         }
2955
2956         function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0) {
2957
2958                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2959
2960                         if ($search) {
2961                         
2962                                 $search_query_part = getSearchSql($search, $match_on);
2963                                 $search_query_part .= " AND ";
2964
2965                         } else {
2966                                 $search_query_part = "";
2967                         }
2968
2969                         $view_query_part = "";
2970         
2971                         if ($view_mode == "adaptive") {
2972                                 if ($search) {
2973                                         $view_query_part = " ";
2974                                 } else if ($feed != -1) {
2975                                         $unread = getFeedUnread($link, $feed, $cat_view);
2976                                         if ($unread > 0) {
2977                                                 $view_query_part = " unread = true AND ";
2978                                         }
2979                                 }
2980                         }
2981         
2982                         if ($view_mode == "marked") {
2983                                 $view_query_part = " marked = true AND ";
2984                         }
2985         
2986                         if ($view_mode == "unread") {
2987                                 $view_query_part = " unread = true AND ";
2988                         }
2989         
2990                         if ($limit > 0) {
2991                                 $limit_query_part = "LIMIT " . $limit;
2992                         } 
2993
2994                         $vfeed_query_part = "";
2995         
2996                         // override query strategy and enable feed display when searching globally
2997                         if ($search && $search_mode == "all_feeds") {
2998                                 $query_strategy_part = "ttrss_entries.id > 0";
2999                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
3000                         } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
3001                                 $query_strategy_part = "ttrss_entries.id > 0";
3002                                 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
3003                                         id = feed_id) as feed_title,";
3004                         } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
3005         
3006                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
3007
3008                                 $tmp_result = false;
3009
3010                                 if ($cat_view) {
3011                                         $tmp_result = db_query($link, "SELECT id 
3012                                                 FROM ttrss_feeds WHERE cat_id = '$feed'");
3013                                 } else {
3014                                         $tmp_result = db_query($link, "SELECT id
3015                                                 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds 
3016                                                         WHERE id = '$feed') AND id != '$feed'");
3017                                 }
3018         
3019                                 $cat_siblings = array();
3020         
3021                                 if (db_num_rows($tmp_result) > 0) {
3022                                         while ($p = db_fetch_assoc($tmp_result)) {
3023                                                 array_push($cat_siblings, "feed_id = " . $p["id"]);
3024                                         }
3025         
3026                                         $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
3027                                                 $feed, implode(" OR ", $cat_siblings));
3028         
3029                                 } else {
3030                                         $query_strategy_part = "ttrss_entries.id > 0";
3031                                 }
3032                                 
3033                         } else if ($feed >= 0) {
3034         
3035                                 if ($cat_view) {
3036
3037                                         if ($feed > 0) {
3038                                                 $query_strategy_part = "cat_id = '$feed'";
3039                                         } else {
3040                                                 $query_strategy_part = "cat_id IS NULL";
3041                                         }
3042         
3043                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3044
3045                                 } else {                
3046                                         $tmp_result = db_query($link, "SELECT id 
3047                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
3048                                                 ORDER BY cat_id,title");
3049                 
3050                                         $parent_ids = array();
3051                 
3052                                         if (db_num_rows($tmp_result) > 0) {
3053                                                 while ($p = db_fetch_assoc($tmp_result)) {
3054                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
3055                                                 }
3056                 
3057                                                 $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
3058                                                         $feed, implode(" OR ", $parent_ids));
3059                 
3060                                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3061                                         } else {
3062                                                 $query_strategy_part = "feed_id = '$feed'";
3063                                         }
3064                                 }
3065                         } else if ($feed == -1) { // starred virtual feed
3066                                 $query_strategy_part = "marked = true";
3067                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3068                         } else if ($feed == -2) { // published virtual feed
3069                                 $query_strategy_part = "published = true";
3070                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3071                         } else if ($feed == -3) { // fresh virtual feed
3072                                 $query_strategy_part = "unread = true";
3073
3074                                 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
3075
3076                                 if (DB_TYPE == "pgsql") {
3077                                         $query_strategy_part .= " AND date_entered > NOW() - INTERVAL '$intl hour' "; 
3078                                 } else {
3079                                         $query_strategy_part .= " AND date_entered > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
3080                                 }
3081
3082                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3083                         } else if ($feed <= -10) { // labels
3084                                 $label_id = -$feed - 11;
3085         
3086                                 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
3087                                         WHERE id = '$label_id'");
3088                         
3089                                 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
3090
3091                                 if (!$query_strategy_part) {
3092                                         return false;
3093                                 }
3094
3095                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
3096                         } else {
3097                                 $query_strategy_part = "id > 0"; // dumb
3098                         }
3099
3100                         if (get_pref($link, 'REVERSE_HEADLINES')) {
3101                                 $order_by = "updated";
3102                         } else {        
3103                                 $order_by = "updated DESC";
3104                         }
3105
3106                         if ($override_order) {
3107                                 $order_by = $override_order;
3108                         }
3109         
3110                         $feed_title = "";
3111
3112                         if ($search && $search_mode == "all_feeds") {
3113                                 $feed_title = __("Search results")." ($search)";
3114                         } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3115                                 $feed_title = __("Search results")." ($search, $feed)";
3116                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
3117                                 $feed_title = $feed;
3118                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
3119         
3120                                 if ($cat_view) {
3121
3122                                         if ($feed != 0) {                       
3123                                                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
3124                                                         WHERE id = '$feed' AND owner_uid = $owner_uid");
3125                                                 $feed_title = db_fetch_result($result, 0, "title");
3126                                         } else {
3127                                                 $feed_title = __("Uncategorized");
3128                                         }
3129
3130                                         if ($search) {
3131                                                 $feed_title = __("Searched for")." $search ($feed_title)";
3132                                         }
3133
3134                                 } else {
3135                                         
3136                                         $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds 
3137                                                 WHERE id = '$feed' AND owner_uid = $owner_uid");
3138                 
3139                                         $feed_title = db_fetch_result($result, 0, "title");
3140                                         $feed_site_url = db_fetch_result($result, 0, "site_url");
3141                                         $last_error = db_fetch_result($result, 0, "last_error");
3142
3143                                         if ($search) {
3144                                                 $feed_title = __("Searched for") . " $search ($feed_title)";
3145                                         }
3146                                 }
3147         
3148                         } else if ($feed == -1) {
3149                                 $feed_title = __("Starred articles");
3150                         } else if ($feed == -2) {
3151                                 $feed_title = __("Published articles");
3152                         } else if ($feed == -3) {
3153                                 $feed_title = __("Fresh articles");
3154                         } else if ($feed < -10) {
3155                                 $label_id = -$feed - 11;
3156                                 $result = db_query($link, "SELECT description FROM ttrss_labels
3157                                         WHERE id = '$label_id'");
3158                                 $feed_title = db_fetch_result($result, 0, "description");
3159
3160                                 if ($search) {
3161                                         $feed_title = __("Searched for") . " $search ($feed_title)";
3162                                 }
3163                         } else {
3164                                 $feed_title = "?";
3165                         }
3166
3167                         if ($feed < -10) error_reporting (0);
3168
3169                         $content_query_part = "content as content_preview,";
3170
3171                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3172         
3173                                 if ($feed >= 0) {
3174                                         $feed_kind = "Feeds";
3175                                 } else {
3176                                         $feed_kind = "Labels";
3177                                 }
3178         
3179                                 if ($limit_query_part) {
3180                                         $offset_query_part = "OFFSET $offset";
3181                                 }
3182
3183                                 $query = "SELECT 
3184                                                 guid,
3185                                                 ttrss_entries.id,ttrss_entries.title,
3186                                                 updated,
3187                                                 unread,feed_id,marked,published,link,last_read,
3188                                                 SUBSTRING(last_read,1,19) as last_read_noms,
3189                                                 $vfeed_query_part
3190                                                 $content_query_part
3191                                                 SUBSTRING(updated,1,19) as updated_noms,
3192                                                 author
3193                                         FROM
3194                                                 ttrss_entries,ttrss_user_entries,ttrss_feeds
3195                                         WHERE
3196                                         ttrss_feeds.hidden = false AND
3197                                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
3198                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
3199                                         ttrss_user_entries.owner_uid = '$owner_uid' AND
3200                                         $search_query_part
3201                                         $view_query_part
3202                                         $query_strategy_part ORDER BY $order_by
3203                                         $limit_query_part $offset_query_part";
3204                                         
3205                                 $result = db_query($link, $query);
3206         
3207                                 if ($_GET["debug"]) print $query;
3208         
3209                         } else {
3210                                 // browsing by tag
3211         
3212                                 $feed_kind = "Tags";
3213         
3214                                 $result = db_query($link, "SELECT
3215                                         guid,
3216                                         ttrss_entries.id as id,title,
3217                                         updated,
3218                                         unread,feed_id,
3219                                         marked,link,last_read,                          
3220                                         SUBSTRING(last_read,1,19) as last_read_noms,
3221                                         $vfeed_query_part
3222                                         $content_query_part
3223                                         SUBSTRING(updated,1,19) as updated_noms
3224                                         FROM
3225                                                 ttrss_entries,ttrss_user_entries,ttrss_tags
3226                                         WHERE
3227                                                 ref_id = ttrss_entries.id AND
3228                                                 ttrss_user_entries.owner_uid = '$owner_uid' AND
3229                                                 post_int_id = int_id AND tag_name = '$feed' AND
3230                                                 $view_query_part
3231                                                 $search_query_part
3232                                                 $query_strategy_part ORDER BY $order_by
3233                                         $limit_query_part");    
3234                         }
3235
3236                         return array($result, $feed_title, $feed_site_url, $last_error);
3237                         
3238         }
3239
3240         function generate_syndicated_feed($link, $owner_uid, $feed, $is_cat,
3241                 $search, $search_mode, $match_on) {
3242
3243                 $qfh_ret = queryFeedHeadlines($link, $feed, 
3244                         30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC", 0,
3245                         $owner_uid);
3246
3247                 $result = $qfh_ret[0];
3248                 $feed_title = htmlspecialchars($qfh_ret[1]);
3249                 $feed_site_url = $qfh_ret[2];
3250                 $last_error = $qfh_ret[3];
3251
3252 //              if (!$feed_site_url) $feed_site_url = "http://localhost/";
3253
3254                 print "<?xml version=\"1.0\" encoding=\"utf-8\"?>
3255                         <?xml-stylesheet type=\"text/xsl\" href=\"rss.xsl\"?>
3256                         <rss version=\"2.0\">
3257                         <channel>
3258                         <title>$feed_title</title>
3259                         <link>$feed_site_url</link>
3260                         <description>Feed generated by Tiny Tiny RSS</description>";
3261  
3262                 while ($line = db_fetch_assoc($result)) {
3263                         print "<item>";
3264                         print "<guid>" . htmlspecialchars($line["guid"]) . "</guid>";
3265                         print "<link>" . htmlspecialchars($line["link"]) . "</link>";
3266
3267                         $tags = get_article_tags($link, $line["id"], $owner_uid);
3268
3269                         foreach ($tags as $tag) {
3270                                 print "<category>" . htmlspecialchars($tag) . "</category>";
3271                         }
3272
3273                         $rfc822_date = date('r', strtotime($line["updated"]));
3274   
3275                         print "<pubDate>$rfc822_date</pubDate>";
3276  
3277                         print "<title>" . 
3278                                 htmlspecialchars($line["title"]) . "</title>";
3279   
3280                         print "<description><![CDATA[" . 
3281                                 $line["content_preview"] . "]]></description>";
3282   
3283                         print "</item>";
3284                 }
3285   
3286                 print "</channel></rss>";
3287
3288         }
3289
3290         function getCategoryTitle($link, $cat_id) {
3291
3292                 if ($cat_id == -1) {
3293                         return __("Special");
3294                 } else if ($cat_id == -2) {
3295                         return __("Labels");
3296                 } else {
3297
3298                         $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
3299                                 id = '$cat_id'");
3300
3301                         if (db_num_rows($result) == 1) {
3302                                 return db_fetch_result($result, 0, "title");
3303                         } else {
3304                                 return "Uncategorized";
3305                         }
3306                 }
3307         }
3308
3309         // http://ru2.php.net/strip-tags
3310
3311         function strip_tags_long($textstring, $allowed){
3312         while($textstring != strip_tags($textstring, $allowed))
3313     {
3314     while (strlen($textstring) != 0)
3315          {
3316          if (strlen($textstring) > 1024) {
3317               $otherlen = 1024;
3318          } else {
3319               $otherlen = strlen($textstring);
3320          }
3321          $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
3322          $safetext .= $temptext;
3323          $textstring = substr_replace($textstring,'',0,$otherlen);
3324          }  
3325     $textstring = $safetext;
3326     }
3327         return $textstring;
3328         }
3329
3330
3331         function sanitize_rss($link, $str, $force_strip_tags = false) {
3332                 $res = $str;
3333
3334                 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
3335
3336                         $res = strip_tags_long($res, 
3337                                 "<p><a><i><em><b><strong><blockquote><br><img><div><span><ul><ol><li>");
3338
3339 //                      $res = preg_replace("/\r\n|\n|\r/", "", $res);
3340 //                      $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");                       
3341                 }
3342
3343                 return $res;
3344         }
3345
3346         function send_headlines_digests($link, $limit = 100) {
3347
3348                 if (!DIGEST_ENABLE) return false;
3349
3350                 $user_limit = DIGEST_EMAIL_LIMIT;
3351                 $days = 1;
3352
3353                 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
3354
3355                 if (DB_TYPE == "pgsql") {
3356                         $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
3357                 } else if (DB_TYPE == "mysql") {
3358                         $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
3359                 }
3360
3361                 $result = db_query($link, "SELECT id,email FROM ttrss_users 
3362                                 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
3363
3364                 while ($line = db_fetch_assoc($result)) {
3365
3366                         if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
3367                                 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
3368
3369                                 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
3370
3371                                 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
3372                                 $digest = $tuple[0];
3373                                 $headlines_count = $tuple[1];
3374                                 $affected_ids = $tuple[2];
3375                                 $digest_text = $tuple[3];
3376
3377                                 if ($headlines_count > 0) {
3378
3379                                         $mail = new PHPMailer();
3380
3381                                         $mail->PluginDir = "phpmailer/";
3382                                         $mail->SetLanguage("en", "phpmailer/language/");
3383
3384                                         $mail->CharSet = "UTF-8";
3385
3386                                         $mail->From = DIGEST_FROM_ADDRESS;
3387                                         $mail->FromName = DIGEST_FROM_NAME;
3388                                         $mail->AddAddress($line["email"], $line["login"]);
3389
3390                                         if (DIGEST_SMTP_HOST) {
3391                                                 $mail->Host = DIGEST_SMTP_HOST;
3392                                                 $mail->Mailer = "smtp";
3393                                                 $mail->Username = DIGEST_SMTP_LOGIN;
3394                                                 $mail->Password = DIGEST_SMTP_PASSWORD;
3395                                         }
3396
3397                                         $mail->IsHTML(true);
3398                                         $mail->Subject = DIGEST_SUBJECT;
3399                                         $mail->Body = $digest;
3400                                         $mail->AltBody = $digest_text;
3401
3402                                         $rc = $mail->Send();
3403
3404                                         if (!$rc) print "ERROR: " . $mail->ErrorInfo;
3405
3406                                         print "RC=$rc\n";
3407
3408                                         if ($rc && $do_catchup) {
3409                                                 print "Marking affected articles as read...\n";
3410                                                 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
3411                                         }
3412
3413                                         db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
3414                                                         WHERE id = " . $line["id"]);
3415                                 } else {
3416                                         print "No headlines\n";
3417                                 }
3418                         }
3419                 }
3420
3421                 print "All done.\n";
3422
3423         }
3424
3425         function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
3426
3427                 require_once "MiniTemplator.class.php";
3428
3429                 $tpl = new MiniTemplator;
3430                 $tpl_t = new MiniTemplator;
3431
3432                 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
3433                 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
3434
3435                 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
3436                 $tpl->setVariable('CUR_TIME', date('G:i'));
3437
3438                 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
3439                 $tpl_t->setVariable('CUR_TIME', date('G:i'));
3440
3441                 $affected_ids = array();
3442
3443                 if (DB_TYPE == "pgsql") {
3444                         $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
3445                 } else if (DB_TYPE == "mysql") {
3446                         $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
3447                 }
3448
3449                 $result = db_query($link, "SELECT ttrss_entries.title,
3450                                 ttrss_feeds.title AS feed_title,
3451                                 date_entered,
3452                                 ttrss_user_entries.ref_id,
3453                                 link,
3454                                 SUBSTRING(content, 1, 120) AS excerpt,
3455                                 SUBSTRING(last_updated,1,19) AS last_updated
3456                         FROM 
3457                                 ttrss_user_entries,ttrss_entries,ttrss_feeds 
3458                         WHERE 
3459                                 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id 
3460                                 AND include_in_digest = true
3461                                 AND $interval_query
3462                                 AND hidden = false
3463                                 AND ttrss_user_entries.owner_uid = $user_id
3464                                 AND unread = true 
3465                         ORDER BY ttrss_feeds.title, date_entered DESC
3466                         LIMIT $limit");
3467
3468                 $cur_feed_title = "";
3469
3470                 $headlines_count = db_num_rows($result);
3471
3472                 $headlines = array();
3473
3474                 while ($line = db_fetch_assoc($result)) {
3475                         array_push($headlines, $line);
3476                 }
3477
3478                 for ($i = 0; $i < sizeof($headlines); $i++) {   
3479
3480                         $line = $headlines[$i];
3481
3482                         array_push($affected_ids, $line["ref_id"]);
3483
3484                         $updated = smart_date_time(strtotime($line["last_updated"]));
3485
3486                         $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
3487                         $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
3488                         $tpl->setVariable('ARTICLE_LINK', $line["link"]);
3489                         $tpl->setVariable('ARTICLE_UPDATED', $updated);
3490                         $tpl->setVariable('ARTICLE_EXCERPT', 
3491                                 truncate_string(strip_tags($line["excerpt"]), 100));
3492
3493                         $tpl->addBlock('article');
3494
3495                         $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
3496                         $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
3497                         $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
3498                         $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
3499 //                      $tpl_t->setVariable('ARTICLE_EXCERPT', 
3500 //                              truncate_string(strip_tags($line["excerpt"]), 100));
3501
3502                         $tpl_t->addBlock('article');
3503
3504                         if ($headlines[$i]['feed_title'] != $headlines[$i+1]['feed_title']) {
3505                                 $tpl->addBlock('feed');
3506                                 $tpl_t->addBlock('feed');
3507                         }
3508
3509                 }
3510
3511                 $tpl->addBlock('digest');
3512                 $tpl->generateOutputToString($tmp);
3513
3514                 $tpl_t->addBlock('digest');
3515                 $tpl_t->generateOutputToString($tmp_t);
3516
3517                 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
3518         }
3519
3520         function check_for_update($link, $brief_fmt = true) {
3521                 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
3522
3523                 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
3524                         return;
3525                 }
3526
3527                 error_reporting(0);
3528                 if (ENABLE_SIMPLEPIE) {
3529                         $rss = new SimplePie();
3530                         $rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
3531 //                      $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
3532                         $rss->set_feed_url($fetch_url);
3533                         $rss->set_output_encoding('UTF-8');
3534                         $rss->init();
3535                 } else {
3536                         $rss = fetch_rss($releases_feed);
3537                 }
3538                 error_reporting (DEFAULT_ERROR_LEVEL);
3539
3540                 if ($rss) {
3541
3542                         if (ENABLE_SIMPLEPIE) {
3543                                 $items = $rss->get_items();
3544                         } else {
3545                                 $items = $rss->items;
3546
3547                                 if (!$items || !is_array($items)) $items = $rss->entries;
3548                                 if (!$items || !is_array($items)) $items = $rss;
3549                         }
3550
3551                         if (!is_array($items) || count($items) == 0) {
3552                                 return;
3553                         }                       
3554
3555                         $latest_item = $items[0];
3556
3557                         if (ENABLE_SIMPLEPIE) {
3558                                 $last_title = $latest_item->get_title();
3559                         } else {
3560                                 $last_title = $latest_item["title"];
3561                         }
3562
3563                         $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
3564
3565                         if (ENABLE_SIMPLEPIE) {
3566                                 $release_url = sanitize_rss($link, $latest_item->get_link());
3567                                 $content = sanitize_rss($link, $latest_item->get_description());
3568                         } else {
3569                                 $release_url = sanitize_rss($link, $latest_item["link"]);
3570                                 $content = sanitize_rss($link, $latest_item["description"]);
3571                         }
3572
3573                         if (version_compare(VERSION, $latest_version) == -1) {
3574                                 if ($brief_fmt) {
3575                                         return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">      
3576                                                 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
3577                                                 <div id=\"milestoneDetails\">$content</div>");
3578                                 } else {
3579                                         return "New version of Tiny-Tiny RSS ($latest_version) is available:
3580                                                 <div class='milestoneDetails'>$content</div>
3581                                                 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
3582                                                 download and update information.";      
3583                                 }
3584
3585                         }                       
3586                 }
3587         }
3588
3589         function markArticlesById($link, $ids, $cmode) {
3590
3591                 $tmp_ids = array();
3592
3593                 foreach ($ids as $id) {
3594                         array_push($tmp_ids, "ref_id = '$id'");
3595                 }
3596
3597                 $ids_qpart = join(" OR ", $tmp_ids);
3598
3599                 if ($cmode == 0) {
3600                         db_query($link, "UPDATE ttrss_user_entries SET 
3601                         marked = false,last_read = NOW()
3602                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3603                 } else if ($cmode == 1) {
3604                         db_query($link, "UPDATE ttrss_user_entries SET 
3605                         marked = true
3606                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3607                 } else {
3608                         db_query($link, "UPDATE ttrss_user_entries SET 
3609                         marked = NOT marked,last_read = NOW()
3610                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3611                 }
3612         }
3613
3614         function publishArticlesById($link, $ids, $cmode) {
3615
3616                 $tmp_ids = array();
3617
3618                 foreach ($ids as $id) {
3619                         array_push($tmp_ids, "ref_id = '$id'");
3620                 }
3621
3622                 $ids_qpart = join(" OR ", $tmp_ids);
3623
3624                 if ($cmode == 0) {
3625                         db_query($link, "UPDATE ttrss_user_entries SET 
3626                         published = false,last_read = NOW()
3627                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3628                 } else if ($cmode == 1) {
3629                         db_query($link, "UPDATE ttrss_user_entries SET 
3630                         published = true
3631                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3632                 } else {
3633                         db_query($link, "UPDATE ttrss_user_entries SET 
3634                         published = NOT published,last_read = NOW()
3635                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
3636                 }
3637         }
3638
3639         function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
3640
3641                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3642
3643                 $tmp_ids = array();
3644
3645                 foreach ($ids as $id) {
3646                         array_push($tmp_ids, "ref_id = '$id'");
3647                 }
3648
3649                 $ids_qpart = join(" OR ", $tmp_ids);
3650
3651                 if ($cmode == 0) {
3652                         db_query($link, "UPDATE ttrss_user_entries SET 
3653                         unread = false,last_read = NOW()
3654                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3655                 } else if ($cmode == 1) {
3656                         db_query($link, "UPDATE ttrss_user_entries SET 
3657                         unread = true
3658                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3659                 } else {
3660                         db_query($link, "UPDATE ttrss_user_entries SET 
3661                         unread = NOT unread,last_read = NOW()
3662                         WHERE ($ids_qpart) AND owner_uid = $owner_uid");
3663                 }
3664         }
3665
3666         function catchupArticleById($link, $id, $cmode) {
3667
3668                 if ($cmode == 0) {
3669                         db_query($link, "UPDATE ttrss_user_entries SET 
3670                         unread = false,last_read = NOW()
3671                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3672                 } else if ($cmode == 1) {
3673                         db_query($link, "UPDATE ttrss_user_entries SET 
3674                         unread = true
3675                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3676                 } else {
3677                         db_query($link, "UPDATE ttrss_user_entries SET 
3678                         unread = NOT unread,last_read = NOW()
3679                         WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3680                 }
3681         }
3682
3683         function make_guid_from_title($title) {
3684                 return preg_replace("/[ \"\',.:;]/", "-", 
3685                         mb_strtolower(strip_tags($title), 'utf-8'));
3686         }
3687
3688         function print_headline_subtoolbar($link, $feed_site_url, $feed_title, 
3689                         $bottom = false, $rtl_content = false, $feed_id = 0,
3690                         $is_cat = false, $search = false, $match_on = false,
3691                         $search_mode = false, $offset = 0, $limit = 0) {
3692
3693                         $user_page_offset = $offset + 1;
3694
3695                         if (!$bottom) {
3696                                 $class = "headlinesSubToolbar";
3697                                 $tid = "headlineActionsTop";
3698                         } else {
3699                                 $class = "headlinesSubToolbar";
3700                                 $tid = "headlineActionsBottom";
3701                         }
3702
3703                         print "<table class=\"$class\" id=\"$tid\"
3704                                 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
3705
3706                         if ($rtl_content) {
3707                                 $rtl_cpart = "RTL";
3708                         } else {
3709                                 $rtl_cpart = "";
3710                         }
3711
3712                         $page_prev_link = "javascript:viewFeedGoPage(-1)";
3713                         $page_next_link = "javascript:viewFeedGoPage(1)";
3714                         $page_first_link = "javascript:viewFeedGoPage(0)";
3715
3716                         $catchup_page_link = "javascript:catchupPage()";
3717                         $catchup_feed_link = "javascript:catchupCurrentFeed()";
3718                         $catchup_sel_link = "javascript:catchupSelection()";
3719
3720                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3721
3722                                 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
3723                                 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
3724                                 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
3725
3726                                 $tog_unread_link = "javascript:selectionToggleUnread()";
3727                                 $tog_marked_link = "javascript:selectionToggleMarked()";
3728                                 $tog_published_link = "javascript:selectionTogglePublished()";
3729
3730                         } else {
3731
3732                                 $sel_all_link = "javascript:cdmSelectArticles('all')";
3733                                 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
3734                                 $sel_none_link = "javascript:cdmSelectArticles('none')";
3735
3736                                 $tog_unread_link = "javascript:selectionToggleUnread(true)";
3737                                 $tog_marked_link = "javascript:selectionToggleMarked(true)";
3738                                 $tog_published_link = "javascript:selectionTogglePublished(true)";
3739
3740                         }
3741
3742                         if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
3743
3744                                 print "<td class=\"headlineActions$rtl_cpart\">
3745                                         <ul class=\"headlineDropdownMenu\">
3746                                         <li class=\"top2\">
3747                                         ".__('Select:')."
3748                                                 <a href=\"$sel_all_link\">".__('All')."</a>,
3749                                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3750                                                 <a href=\"$sel_none_link\">".__('None')."</a></li>
3751                                         <li class=\"vsep\">&nbsp;</li>
3752                                         <li class=\"top\">".__('Toggle')."<ul>
3753                                                 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
3754                                                 <li onclick=\"$tog_marked_link\">".__('Starred')."</li>
3755                                                 <li onclick=\"$tog_published_link\">".__('Published')."</li>
3756                                                 </ul></li>
3757                                         <li class=\"vsep\">&nbsp;</li>
3758                                         <li class=\"top\">".__('Mark as read')."<ul>
3759                                                 <li onclick=\"$catchup_sel_link\">".__('Selection')."</li>
3760                                                 <!-- <li onclick=\"$catchup_page_link\">".__('This page')."</li> -->
3761                                                 <li><span class=\"insensitive\">--------</span></li>
3762                                                 <li onclick=\"catchupRelativeToArticle(0)\">".__("Above active article")."</li>
3763                                                 <li onclick=\"catchupRelativeToArticle(1)\">".__("Below active article")."</li>
3764                                                 <li><span class=\"insensitive\">--------</span></li>
3765                                                 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
3766                                         ";
3767
3768                                         $enable_pagination = get_pref($link, "_PREFS_ENABLE_PAGINATION");
3769
3770                                         if ($limit != 0 && !$search && $enable_pagination) {
3771                                                 print "
3772                                                 <li class=\"vsep\">&nbsp;</li>
3773                                                 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
3774                                                         <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
3775                                                         <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
3776                                                         </ul>";
3777                                                 }
3778
3779                                         if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3780                                                 print "
3781                                                         <li class=\"vsep\">&nbsp;</li>
3782                                                         <li class=\"top3\">
3783                                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3784                                                                 '$match_on', '$feed_id', '$is_cat');\">
3785                                                                 ".__('Convert to label')."</a></td>";
3786                                         }
3787                                         print " 
3788                                         </td>"; 
3789
3790                         } else {
3791                         // old style subtoolbar:
3792
3793                                 print "<td class=\"headlineActions$rtl_cpart\">".
3794                                         __('Select:')."
3795                                                                 <a href=\"$sel_all_link\">".__('All')."</a>,
3796                                                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
3797                                                                 <a href=\"$sel_none_link\">".__('None')."</a>
3798                                                 &nbsp;&nbsp;".
3799                                                 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3800                                                         <a href=\"$tog_marked_link\">".__('Starred')."</a>
3801                                                 &nbsp;&nbsp;".
3802                                                 __('Mark as read:')."
3803                                                         <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3804                                                         <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3805
3806                                 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3807
3808                                         print "&nbsp;&nbsp;
3809                                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3810                                                                 '$match_on', '$feed_id', '$is_cat');\">
3811                                                         ".__('Convert to label')."</a>";
3812                                 }
3813
3814                                 print "</td>";  
3815
3816                         }
3817
3818 /*                      if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3819                                 print "<td class=\"headlineActions$rtl_cpart\">
3820                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3821                                                         '$match_on', '$feed_id', '$is_cat');\">
3822                                                 ".__('Convert to Label')."</a></td>";
3823 } */
3824
3825                         print "<td class=\"headlineTitle$rtl_cpart\">";
3826
3827                         print "<span class=\"headlineInnerTitle\">";
3828
3829                         if ($feed_site_url) {
3830                                 if (!$bottom) {
3831                                         $target = "target=\"_new\"";
3832                                 }
3833                                 print "<a $target href=\"$feed_site_url\">".
3834                                         truncate_string($feed_title,30)."</a>";
3835                         } else {
3836                                 print $feed_title;
3837                         }
3838
3839                         if ($search) {
3840                                 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3841                         }
3842
3843                         if ($user_page_offset > 1) {
3844                                 print " [$user_page_offset] ";
3845                         }
3846
3847                         print "</span>";
3848
3849                         if (!$bottom) {
3850                                 print "
3851                                         <a target=\"_new\" 
3852                                                 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3853                                                 <img class=\"noborder\" 
3854                                                         alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3855                                         </a>";
3856                         }
3857                                 
3858                         print "</td>";
3859                         print "</tr></table>";
3860
3861                 }
3862
3863         function printCategoryHeader($link, $cat_id, $hidden = false, $can_browse = true) {
3864
3865                         $tmp_category = getCategoryTitle($link, $cat_id);
3866                         $cat_unread = getCategoryUnread($link, $cat_id);
3867
3868                         if ($hidden) {
3869                                 $holder_style = "display:none;";
3870                                 $ellipsis = "…";
3871                         } else {
3872                                 $holder_style = "";
3873                                 $ellipsis = "";
3874                         }
3875
3876                         $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3877
3878                         print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3879                                 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>";
3880
3881                         if ($can_browse) {
3882                                 print "<a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">";
3883                         } else {
3884                                 print "<span id=\"FCAP-$cat_id\">";
3885                         }
3886
3887                         print " <span id=\"FCATCTR-$cat_id\" 
3888                                 class=\"$catctr_class\">($cat_unread)</span> $ellipsis";
3889
3890                         if ($can_browse) {
3891                                 print "</a>";
3892                         } else {
3893                                 print "</span>";
3894                         }
3895
3896                         print "</li>";
3897
3898                         print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
3899         }
3900         
3901         function outputFeedList($link, $tags = false) {
3902
3903                 print "<ul class=\"feedList\" id=\"feedList\">";
3904
3905                 $owner_uid = $_SESSION["uid"];
3906
3907                 /* virtual feeds */
3908
3909                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3910
3911                         if ($_COOKIE["ttrss_vf_vclps"] == 1) {
3912                                 $cat_hidden = true;
3913                         } else {
3914                                 $cat_hidden = false;
3915                         }
3916
3917 #                       print "<li class=\"feedCat\">".__('Special')."</li>";
3918 #                       print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";            
3919 #                       print "<li class=\"feedCat\">".
3920 #                               "<a id=\"FCATN--1\" href=\"javascript:toggleCollapseCat(-1)\">".
3921 #                               __('Special')."</a> <span id='FCAP--1'>$ellipsis</span></li>";
3922 #
3923 #                       print "<li id=\"feedCatHolder\" class=\"feedCatHolder\">
3924 #                               <ul class=\"feedCatList\" id='FCATLIST--1' style='$holder_style'>";
3925
3926 #                       $cat_unread = getCategoryUnread($link, -1);
3927 #                       $tmp_category = __("Special");
3928 #                       $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3929
3930                         printCategoryHeader($link, -1, $cat_hidden, false);
3931                 }
3932
3933                 $num_starred = getFeedUnread($link, -1);
3934                 $num_published = getFeedUnread($link, -2);
3935                 $num_fresh = getFeedUnread($link, -3);
3936
3937                 $class = "virt";
3938
3939                 if ($num_fresh > 0) $class .= "Unread";
3940
3941                 printFeedEntry(-3, $class, __("Fresh articles"), $num_fresh, 
3942                         "images/fresh.png", $link);
3943
3944                 $class = "virt";
3945
3946                 if ($num_starred > 0) $class .= "Unread";
3947
3948                 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
3949
3950                 if ($is_ie) {
3951                         $mark_img_ext = "gif";
3952                 } else {
3953                         $mark_img_ext = "png";
3954                 }
3955
3956                 printFeedEntry(-1, $class, __("Starred articles"), $num_starred, 
3957                         "images/mark_set.$mark_img_ext", $link);
3958
3959                 $class = "virt";
3960
3961                 if ($num_published > 0) $class .= "Unread";
3962
3963                 printFeedEntry(-2, $class, __("Published articles"), $num_published, 
3964                         "images/pub_set.gif", $link);
3965
3966                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3967                         print "</ul>";
3968                 }
3969
3970                 if (!$tags) {
3971
3972                         if (GLOBAL_ENABLE_LABELS && get_pref($link, 'ENABLE_LABELS')) {
3973         
3974                                 $result = db_query($link, "SELECT id,sql_exp,description FROM
3975                                         ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3976                 
3977                                 if (db_num_rows($result) > 0) {
3978                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3979
3980                                                 if ($_COOKIE["ttrss_vf_lclps"] == 1) {
3981                                                         $cat_hidden = true;
3982                                                 } else {
3983                                                         $cat_hidden = false;
3984                                                 }
3985
3986                                                 printCategoryHeader($link, -2, $cat_hidden, false);
3987
3988 #                                               print "<li class=\"feedCat\">".
3989 #                                                       "<a id=\"FCATN--2\" href=\"javascript:toggleCollapseCat(-2)\">".
3990 #                                                       __('Labels')."</a> <span id='FCAP--2'>$ellipsis</span></li>";
3991 #
3992 #                                               print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\" id='FCATLIST--2' style='$holder_style'>";
3993                                         } else {
3994                                                 print "<li><hr></li>";
3995                                         }
3996                                 }
3997                 
3998                                 while ($line = db_fetch_assoc($result)) {
3999         
4000                                         error_reporting (0);
4001
4002                                         $label_id = -$line['id'] - 11;
4003                                         $count = getFeedUnread($link, $label_id);
4004
4005                                         $class = "label";
4006         
4007                                         if ($count > 0) {
4008                                                 $class .= "Unread";
4009                                         }
4010                                         
4011                                         error_reporting (DEFAULT_ERROR_LEVEL);
4012         
4013                                         printFeedEntry($label_id, 
4014                                                 $class, $line["description"], 
4015                                                 $count, "images/label.png", $link);
4016                 
4017                                 }
4018
4019                                 if (db_num_rows($result) > 0) {
4020                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4021                                                 print "</ul>";
4022                                         }
4023                                 }
4024
4025                         }
4026
4027                         if (!get_pref($link, 'ENABLE_FEED_CATS')) {
4028                                 print "<li><hr></li>";
4029                         }
4030
4031                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4032                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4033                                         $order_by_qpart = "category,unread DESC,title";
4034                                 } else {
4035                                         $order_by_qpart = "category,title";
4036                                 }
4037                         } else {
4038                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
4039                                         $order_by_qpart = "unread DESC,title";
4040                                 } else {                
4041                                         $order_by_qpart = "title";
4042                                 }
4043                         }
4044
4045                         $age_qpart = getMaxAgeSubquery();
4046
4047                         $result = db_query($link, "SELECT ttrss_feeds.*,
4048                                 SUBSTRING(last_updated,1,19) AS last_updated_noms,
4049                                 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
4050                                         WHERE feed_id = ttrss_feeds.id AND unread = true
4051                                                 AND $age_qpart
4052                                                 AND ttrss_user_entries.ref_id = ttrss_entries.id
4053                                                 AND owner_uid = '$owner_uid') as unread,
4054                                 cat_id,last_error,
4055                                 ttrss_feed_categories.title AS category,
4056                                 ttrss_feed_categories.collapsed 
4057                                 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories 
4058                                         ON (ttrss_feed_categories.id = cat_id)                          
4059                                 WHERE 
4060                                         ttrss_feeds.hidden = false AND
4061                                         ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
4062                                 ORDER BY $order_by_qpart"); 
4063
4064                         $actid = $_GET["actid"];
4065         
4066                         /* real feeds */
4067         
4068                         $lnum = 0;
4069         
4070                         $total_unread = 0;
4071
4072                         $category = "";
4073
4074                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4075         
4076                         while ($line = db_fetch_assoc($result)) {
4077                         
4078                                 $feed = trim($line["title"]);
4079
4080                                 if (!$feed) $feed = "[Untitled]";
4081
4082                                 $feed_id = $line["id"];   
4083         
4084                                 $subop = $_GET["subop"];
4085                                 
4086                                 $unread = $line["unread"];
4087
4088                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4089                                         $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
4090                                 } else {
4091                                         $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
4092                                 }
4093
4094                                 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
4095
4096                                 if ($rtl_content) {
4097                                         $rtl_tag = "dir=\"RTL\"";
4098                                 } else {
4099                                         $rtl_tag = "";
4100                                 }
4101
4102                                 $tmp_result = db_query($link,
4103                                         "SELECT id,COUNT(unread) AS unread
4104                                         FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
4105                                                 ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
4106                                         WHERE parent_feed = '$feed_id' AND unread = true 
4107                                         GROUP BY ttrss_feeds.id");
4108                         
4109                                 if (db_num_rows($tmp_result) > 0) {                             
4110                                         while ($l = db_fetch_assoc($tmp_result)) {
4111                                                 $unread += $l["unread"];
4112                                         }
4113                                 }
4114
4115                                 $cat_id = $line["cat_id"];
4116
4117                                 $tmp_category = $line["category"];
4118
4119                                 if (!$tmp_category) {
4120                                         $tmp_category = __("Uncategorized");
4121                                 }
4122                                 
4123         //                      $class = ($lnum % 2) ? "even" : "odd";
4124
4125                                 if ($line["last_error"]) {
4126                                         $class = "error";
4127                                 } else {
4128                                         $class = "feed";
4129                                 }
4130         
4131                                 if ($unread > 0) $class .= "Unread";
4132         
4133                                 if ($actid == $feed_id) {
4134                                         $class .= "Selected";
4135                                 }
4136         
4137                                 $total_unread += $unread;
4138
4139                                 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
4140                                 
4141                                         if ($category) {
4142                                                 print "</ul></li>";
4143                                         }
4144                                 
4145                                         $category = $tmp_category;
4146
4147                                         $collapsed = $line["collapsed"];
4148
4149                                         // workaround for NULL category
4150                                         if ($category == __("Uncategorized")) {
4151                                                 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
4152                                                         $collapsed = "t";
4153                                                 }
4154                                         }
4155
4156                                         if ($collapsed == "t" || $collapsed == "1") {
4157                                                 $holder_class = "feedCatHolder";
4158                                                 $holder_style = "display:none;";
4159                                                 $ellipsis = "…";
4160                                         } else {
4161                                                 $holder_class = "feedCatHolder";
4162                                                 $holder_style = "";
4163                                                 $ellipsis = "";
4164                                         }
4165
4166                                         $cat_id = sprintf("%d", $cat_id);
4167
4168                                         $cat_unread = getCategoryUnread($link, $cat_id);
4169
4170                                         $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
4171
4172                                         print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
4173                                                 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
4174                                                         <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
4175                                                         <span id=\"FCATCTR-$cat_id\" 
4176                                                         class=\"$catctr_class\">($cat_unread)</span> $ellipsis
4177                                                         </a></li>";
4178
4179                                         print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\" style='$holder_style'>";
4180                                 }
4181         
4182                                 printFeedEntry($feed_id, $class, $feed, $unread, 
4183                                         ICONS_URL."/$feed_id.ico", $link, $rtl_content, 
4184                                         $last_updated, $line["last_error"]);
4185         
4186                                 ++$lnum;
4187                         }
4188
4189                         if (db_num_rows($result) == 0) {
4190                                 print "<li>".__('No feeds to display.')."</li>";
4191                         }
4192
4193                 } else {
4194
4195                         // tags
4196
4197 /*                      $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
4198                                 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
4199                                 post_int_id = ttrss_user_entries.int_id AND 
4200                                 unread = true AND ref_id = ttrss_entries.id
4201                                 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name       
4202                         UNION
4203                                 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
4204                         ORDER BY tag_name"); */
4205
4206                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4207                                 print "<li class=\"feedCat\">".__('Tags')."</li>";
4208                                 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
4209                         }
4210
4211                         $age_qpart = getMaxAgeSubquery();
4212
4213                         $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
4214                                 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id 
4215                                         AND ref_id = id AND $age_qpart
4216                                         AND unread = true)) AS count FROM ttrss_tags 
4217                                         WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name 
4218                                         ORDER BY count DESC LIMIT 50");
4219
4220                         $tags = array();
4221         
4222                         while ($line = db_fetch_assoc($result)) {
4223                                 $tags[$line["tag_name"]] += $line["count"];
4224                         }
4225         
4226                         foreach (array_keys($tags) as $tag) {
4227         
4228                                 $unread = $tags[$tag];
4229         
4230                                 $class = "tag";
4231         
4232                                 if ($unread > 0) {
4233                                         $class .= "Unread";
4234                                 }
4235         
4236                                 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
4237         
4238                         } 
4239
4240                         if (db_num_rows($result) == 0) {
4241                                 print "<li>No tags to display.</li>";
4242                         }
4243
4244                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
4245                                 print "</ul>";
4246                         }
4247
4248                 }
4249
4250                 print "</ul>";
4251
4252         }
4253
4254         function get_article_tags($link, $id, $owner_uid = 0) {
4255
4256                 $a_id = db_escape_string($id);
4257
4258                 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4259
4260                 $tmp_result = db_query($link, "SELECT DISTINCT tag_name, 
4261                         owner_uid as owner FROM
4262                         ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
4263                                 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name");
4264
4265                 $tags = array();        
4266         
4267                 while ($tmp_line = db_fetch_assoc($tmp_result)) {
4268                         array_push($tags, $tmp_line["tag_name"]);                               
4269                 }
4270
4271                 return $tags;
4272         }
4273
4274         function trim_value(&$value) {
4275                 $value = trim($value);
4276         }       
4277
4278         function trim_array($array) {
4279                 $tmp = $array;
4280                 array_walk($tmp, 'trim_value');
4281                 return $tmp;
4282         }
4283
4284         function tag_is_valid($tag) {
4285                 if ($tag == '') return false;
4286                 if (preg_match("/^[0-9]*$/", $tag)) return false;
4287
4288                 $tag = iconv("utf-8", "utf-8", $tag);
4289                 if (!$tag) return false;
4290
4291                 return true;
4292         }
4293
4294         function render_login_form($link, $mobile = false) {
4295                 if (!$mobile) {
4296                         require_once "login_form.php";
4297                 } else {
4298                         require_once "mobile/login_form.php";
4299                 }
4300         }
4301
4302         // from http://developer.apple.com/internet/safari/faq.html
4303         function no_cache_incantation() {
4304                 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
4305                 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
4306                 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
4307                 header("Cache-Control: post-check=0, pre-check=0", false);
4308                 header("Pragma: no-cache"); // HTTP/1.0
4309         }
4310
4311         function format_warning($msg, $id = "") {
4312                 return "<div class=\"warning\" id=\"$id\"> 
4313                         <img src=\"images/sign_excl.gif\">$msg</div>";
4314         }
4315
4316         function format_notice($msg) {
4317                 return "<div class=\"notice\"> 
4318                         <img src=\"images/sign_info.gif\">$msg</div>";
4319         }
4320
4321         function format_error($msg) {
4322                 return "<div class=\"error\"> 
4323                         <img src=\"images/sign_excl.gif\">$msg</div>";
4324         }
4325
4326         function print_notice($msg) {
4327                 return print format_notice($msg);
4328         }
4329
4330         function print_warning($msg) {
4331                 return print format_warning($msg);
4332         }
4333
4334         function print_error($msg) {
4335                 return print format_error($msg);
4336         }
4337
4338
4339         function T_sprintf() {
4340                 $args = func_get_args();
4341                 return vsprintf(__(array_shift($args)), $args);
4342         }
4343
4344         function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
4345
4346                 /* we can figure out feed_id from article id anyway, why do we
4347                  * pass feed_id here? */
4348
4349                 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4350                         WHERE ref_id = '$id'");
4351
4352                 $feed_id = db_fetch_result($result, 0, "feed_id");
4353
4354                 print "<article id='$id'><![CDATA[";
4355
4356                 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4357                         WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
4358
4359                 if (db_num_rows($result) == 1) {
4360                         $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4361                 } else {
4362                         $rtl_content = false;
4363                 }
4364
4365                 if ($rtl_content) {
4366                         $rtl_tag = "dir=\"RTL\"";
4367                         $rtl_class = "RTL";
4368                 } else {
4369                         $rtl_tag = "";
4370                         $rtl_class = "";
4371                 }
4372
4373                 if ($mark_as_read) {
4374                         $result = db_query($link, "UPDATE ttrss_user_entries 
4375                                 SET unread = false,last_read = NOW() 
4376                                 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4377                 }
4378
4379                 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
4380                         SUBSTRING(updated,1,16) as updated,
4381                         (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
4382                         num_comments,
4383                         author
4384                         FROM ttrss_entries,ttrss_user_entries
4385                         WHERE   id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
4386
4387                 if ($result) {
4388
4389                         $link_target = "";
4390
4391                         if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4392                                 $link_target = "target=\"_new\"";
4393                         }
4394
4395                         $line = db_fetch_assoc($result);
4396
4397                         if ($line["icon_url"]) {
4398                                 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
4399                         } else {
4400                                 $feed_icon = "&nbsp;";
4401                         }
4402
4403 /*                      if ($line["comments"] && $line["link"] != $line["comments"]) {
4404                                 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
4405                         } else {
4406                                 $entry_comments = "";
4407                         } */
4408
4409                         $num_comments = $line["num_comments"];
4410                         $entry_comments = "";
4411
4412                         if ($num_comments > 0) {
4413                                 if ($line["comments"]) {
4414                                         $comments_url = $line["comments"];
4415                                 } else {
4416                                         $comments_url = $line["link"];
4417                                 }
4418                                 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
4419                         } else {
4420                                 if ($line["comments"] && $line["link"] != $line["comments"]) {
4421                                         $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
4422                                 }                               
4423                         }
4424
4425                         print "<div class=\"postReply\">";
4426
4427                         print "<div class=\"postHeader\">";
4428
4429                         $entry_author = $line["author"];
4430
4431                         if ($entry_author) {
4432                                 $entry_author = __(" - by ") . $entry_author;
4433                         }
4434
4435                         $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'), 
4436                                 strtotime($line["updated"]));
4437                 
4438                         print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
4439
4440                         if ($line["link"]) {
4441                                 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" . 
4442                                         $line["title"] . "</a><span class='author'>$entry_author</span></div>";
4443                         } else {
4444                                 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
4445                         }
4446
4447 /*                      $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
4448                                 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
4449                                 ORDER BY tag_name"); */
4450
4451                         $tags = get_article_tags($link, $id);
4452         
4453                         $tags_str = "";
4454                         $f_tags_str = "";
4455
4456                         $num_tags = 0;
4457
4458                         if ($_SESSION["theme"] == "3pane") {
4459                                 $tag_limit = 3;
4460                         } else {
4461                                 $tag_limit = 6;
4462                         }
4463
4464                         foreach ($tags as $tag) {
4465                                 $num_tags++;
4466                                 $tag_escaped = str_replace("'", "\\'", $tag);
4467
4468                                 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
4469                                 
4470                                 if ($num_tags == $tag_limit) {
4471                                         $tags_str .= "&hellip;";
4472
4473                                 } else if ($num_tags < $tag_limit) {
4474                                         $tags_str .= $tag_str;
4475                                 }
4476                                 $f_tags_str .= $tag_str;
4477                         }
4478
4479                         $tags_str = preg_replace("/, $/", "", $tags_str);
4480                         $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
4481
4482                         $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $f_tags_str</div></span>";
4483                         $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4484
4485                         if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
4486
4487                         if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
4488
4489                         print "<div style='float : right'>
4490                                 <img src='images/tag.png' class='tagsPic' alt='Tags' title='Tags'>
4491                                 $tags_str 
4492                                 <a title=\"Edit tags for this article\" 
4493                                         href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
4494                                 <div clear='both'>$entry_comments</div>";
4495
4496                         print "</div>";
4497
4498                         print "<div class=\"postIcon\">" . $feed_icon . "</div>";
4499                         print "<div class=\"postContent\">";
4500                         
4501                         #print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
4502
4503                         $line["content"] = sanitize_rss($link, $line["content"]);
4504
4505                         if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4506                                 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
4507                         }
4508
4509                         print $line["content"];
4510
4511                         $result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4512                                 post_id = '$id'");
4513
4514                         if (db_num_rows($result) > 0) {
4515                                 print "<div class=\"postEnclosures\">";
4516
4517                                 if (db_num_rows($result) == 1) {
4518                                         print __("Attachment:") . " ";
4519                                 } else {
4520                                         print __("Attachments:") . " ";
4521                                 }
4522
4523                                 $entries = array();
4524
4525                                 while ($line = db_fetch_assoc($result)) {
4526
4527                                         $url = $line["content_url"];
4528
4529                                         $filename = substr($url, strrpos($url, "/")+1);
4530
4531                                         $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4532                                                 $filename . " (" . $line["content_type"] . ")" . "</a>";
4533
4534                                         array_push($entries, $entry);
4535                                 }
4536
4537                                 print join(", ", $entries);
4538
4539                                 print "</div>";
4540                         }
4541                 
4542                         print "</div>";
4543                         
4544                         print "</div>";
4545
4546                 }
4547
4548                 print "]]></article>";
4549
4550         }
4551
4552         function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
4553                                         $next_unread_feed, $offset) {
4554
4555                 $disable_cache = false;
4556
4557                 $timing_info = getmicrotime();
4558
4559                 $topmost_article_ids = array();
4560
4561                 if (!$offset) {
4562                         $offset = 0;
4563                 }
4564
4565                 if ($subop == "undefined") $subop = "";
4566
4567                 if ($subop == "CatchupSelected") {
4568                         $ids = split(",", db_escape_string($_GET["ids"]));
4569                         $cmode = sprintf("%d", $_GET["cmode"]);
4570
4571                         catchupArticlesById($link, $ids, $cmode);
4572                 }
4573
4574                 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
4575                         update_generic_feed($link, $feed, $cat_view, true);
4576                 }
4577
4578                 if ($subop == "MarkAllRead")  {
4579                         catchup_feed($link, $feed, $cat_view);
4580
4581                         if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
4582                                 if ($next_unread_feed) {
4583                                         $feed = $next_unread_feed;
4584                                 }
4585                         }
4586                 }
4587
4588                 if ($feed_id > 0) {             
4589                         $result = db_query($link,
4590                                 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
4591                 
4592                         if (db_num_rows($result) == 0) {
4593                                 print "<div align='center'>".__('Feed not found.')."</div>";                            
4594                                 return;
4595                         }
4596                 }
4597
4598                 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
4599
4600                         $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
4601                                 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
4602
4603                         if (db_num_rows($result) == 1) {
4604                                 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
4605                         } else {
4606                                 $rtl_content = false;
4607                         }
4608         
4609                         if ($rtl_content) {
4610                                 $rtl_tag = "dir=\"RTL\"";
4611                         } else {
4612                                 $rtl_tag = "";
4613                         }
4614                 } else {
4615                         $rtl_tag = "";
4616                         $rtl_content = false;
4617                 }
4618
4619                 $script_dt_add = get_script_dt_add();
4620
4621                 /// START /////////////////////////////////////////////////////////////////////////////////
4622
4623                 $search = db_escape_string($_GET["query"]);
4624
4625                 if ($search) { 
4626                         $disable_cache = true;
4627                 }
4628
4629                 $search_mode = db_escape_string($_GET["search_mode"]);
4630                 $match_on = db_escape_string($_GET["match_on"]);
4631
4632                 if (!$match_on) {
4633                         $match_on = "both";
4634                 }
4635
4636                 $real_offset = $offset * $limit;
4637
4638                 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
4639
4640                 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, 
4641                         $search, $search_mode, $match_on, false, $real_offset);
4642
4643                 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
4644
4645                 $result = $qfh_ret[0];
4646                 $feed_title = $qfh_ret[1];
4647                 $feed_site_url = $qfh_ret[2];
4648                 $last_error = $qfh_ret[3];
4649
4650                 if ($feed == -2) {
4651                         $feed_site_url = article_publish_url($link);
4652                 }
4653
4654                 /// STOP //////////////////////////////////////////////////////////////////////////////////
4655
4656                 if (!$offset) {
4657                         print "<div id=\"headlinesContainer\" $rtl_tag>";
4658
4659                         if (!$result) {
4660                                 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
4661                                 return;
4662                         }
4663
4664                         print_headline_subtoolbar($link, $feed_site_url, $feed_title, false, 
4665                                 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode, 
4666                                 $offset, $limit);
4667
4668                         print "<div id=\"headlinesInnerContainer\" onscroll=\"headlines_scroll_handler()\">";
4669                 }
4670
4671                 $headlines_count = db_num_rows($result);
4672
4673                 if (db_num_rows($result) > 0) {
4674
4675 #                       print "\{$offset}";
4676
4677                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {
4678                                 print "<table class=\"headlinesList\" id=\"headlinesList\" 
4679                                         cellspacing=\"0\">";
4680                         }
4681
4682                         $lnum = $limit*$offset;
4683
4684                         error_reporting (DEFAULT_ERROR_LEVEL);
4685         
4686                         $num_unread = 0;
4687         
4688                         while ($line = db_fetch_assoc($result)) {
4689
4690                                 $class = ($lnum % 2) ? "even" : "odd";
4691         
4692                                 $id = $line["id"];
4693                                 $feed_id = $line["feed_id"];
4694
4695                                 if (count($topmost_article_ids) < 5) {
4696                                         array_push($topmost_article_ids, $id);
4697                                 }
4698
4699                                 if ($line["last_read"] == "" && 
4700                                                 ($line["unread"] != "t" && $line["unread"] != "1")) {
4701         
4702                                         $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\" 
4703                                                 alt=\"Updated\">";
4704                                 } else {
4705                                         $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\" 
4706                                                 alt=\"Updated\">";
4707                                 }
4708         
4709                                 if ($line["unread"] == "t" || $line["unread"] == "1") {
4710                                         $class .= "Unread";
4711                                         ++$num_unread;
4712                                         $is_unread = true;
4713                                 } else {
4714                                         $is_unread = false;
4715                                 }
4716
4717                                 $is_ie = (strpos($_SESSION["client.userAgent"], "MSIE") !== false);
4718
4719                                 if ($is_ie) {
4720                                         $mark_img_ext = "gif";
4721                                 } else {
4722                                         $mark_img_ext = "png";
4723                                 }
4724
4725                                 if ($line["marked"] == "t" || $line["marked"] == "1") {
4726                                         $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.$mark_img_ext\" 
4727                                                 class=\"markedPic\"
4728                                                 alt=\"Unstar article\" onclick='javascript:tMark($id)'>";
4729                                 } else {
4730                                         $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.$mark_img_ext\" 
4731                                                 class=\"markedPic\"
4732                                                 alt=\"Star article\" onclick='javascript:tMark($id)'>";
4733                                 }
4734
4735                                 if ($line["published"] == "t" || $line["published"] == "1") {
4736                                         $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_set.gif\" 
4737                                                 class=\"markedPic\"
4738                                                 alt=\"Unpublish article\" onclick='javascript:tPub($id)'>";
4739                                 } else {
4740                                         $published_pic = "<img id=\"FPPIC-$id\" src=\"images/pub_unset.gif\" 
4741                                                 class=\"markedPic\"
4742                                                 alt=\"Publish article\" onclick='javascript:tPub($id)'>";
4743                                 }
4744
4745 #                               $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
4746 #                                       $line["title"] . "</a>";
4747
4748                                 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
4749                                         $line["title"] . "</a>";
4750
4751 #                               $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
4752 #                                       $line["title"] . "</a>";
4753
4754                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
4755                                         $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
4756                                 } else {
4757                                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
4758                                         $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
4759                                 }                               
4760
4761                                 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4762                                         $content_preview = truncate_string(strip_tags($line["content_preview"]), 
4763                                                 100);
4764                                 }
4765
4766                                 $entry_author = $line["author"];
4767
4768                                 if ($entry_author) {
4769                                         $entry_author = " - by $entry_author";
4770                                 }
4771
4772                                 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
4773                                         
4774                                         print "<tr class='$class' id='RROW-$id'>";
4775                 
4776                                         print "<td class='hlUpdPic'>$update_pic</td>";
4777                 
4778                                         print "<td class='hlSelectRow'>
4779                                                 <input type=\"checkbox\" onclick=\"tSR(this)\"
4780                                                         id=\"RCHK-$id\">
4781                                                 </td>";
4782                 
4783                                         print "<td class='hlMarkedPic'>$marked_pic</td>";
4784                                         print "<td class='hlMarkedPic'>$published_pic</td>";
4785
4786 #                                       if ($line["feed_title"]) {                      
4787 #                                               print "<td class='hlContent'>$content_link</td>";
4788 #                                               print "<td class='hlFeed'>
4789 #                                                       <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4790 #                                                               truncate_string($line["feed_title"],30)."</a>&nbsp;</td>";
4791 #                                       } else {                        
4792
4793                                         print "<td class='hlContent' valign='middle'>";
4794
4795                                         print "<a href=\"javascript:view($id,$feed_id);\">" .
4796                                                 $line["title"];
4797
4798                                         if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
4799                                                 if ($content_preview) {
4800                                                         print "<span class=\"contentPreview\"> - $content_preview</span>";
4801                                                 }
4802                                         }
4803
4804                                         print "</a>";
4805
4806 #                                                       <a href=\"javascript:viewfeed($feed_id, '', false)\">".
4807 #                                                       $line["feed_title"]."</a>       
4808
4809                                         if ($line["feed_title"]) {                      
4810                                                 print "<span class=\"hlFeed\">
4811                                                         (<a href=\"javascript:viewfeed($feed_id, '', false)\">".
4812                                                         $line["feed_title"]."</a>)
4813                                                 </span>";
4814                                         }
4815
4816
4817                                         print "</td>";
4818                                         
4819 #                                       }
4820                                         
4821                                         print "<td class=\"hlUpdated\"><nobr>$updated_fmt&nbsp;</nobr></td>";
4822                 
4823                                         print "</tr>";
4824
4825                                 } else {
4826                                         
4827                                         if ($is_unread) {
4828                                                 $add_class = "Unread";
4829                                         } else {
4830                                                 $add_class = "";
4831                                         }       
4832
4833                                         $expand_cdm = get_pref($link, 'CDM_EXPANDED');
4834
4835                                         if ($expand_cdm) {
4836                                                 $cdm_cstyle = "";
4837                                         } else {
4838                                                 $cdm_cstyle = "style=\"display : none\"";
4839                                         }
4840
4841                                         print "<div class=\"cdmArticle$add_class\" 
4842                                                 id=\"RROW-$id\" onmouseover='cdmMouseIn(this)' 
4843                                                 onmouseout='cdmMouseOut(this)'>";
4844
4845                                         print "<div class=\"cdmHeader\">";
4846
4847                                         print "<div class=\"articleUpdated\">$updated_fmt</div>";
4848                                         
4849                                         print "<a class=\"title\" 
4850                                                 onclick=\"javascript:toggleUnread($id, 0)\"
4851                                                 target=\"_new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
4852
4853                                         print $entry_author;
4854
4855                                         if (!$expand_cdm) {
4856                                                 print "&nbsp;<a id=\"CICH-$id\" 
4857                                                         href=\"javascript:cdmExpandArticle($id)\">
4858                                                         (".__('Show article').")</a>";
4859                                         } 
4860
4861
4862                                         if ($line["feed_title"]) {      
4863                                                 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
4864                                         }
4865
4866                                         print "</div>";
4867
4868                                         if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
4869                                                 $line["content_preview"] = preg_replace("/href=/i", 
4870                                                         "target=\"_new\" href=", $line["content_preview"]);
4871                                         }
4872
4873                                         print "<div class=\"cdmContent\" id=\"CICD-$id\" $cdm_cstyle>";
4874
4875 //                                      print "<div class=\"cdmInnerContent\" id=\"CICD-$id\" $cdm_cstyle>";
4876                                         print $line["content_preview"];
4877
4878                                         $e_result = db_query($link, "SELECT * FROM ttrss_enclosures WHERE
4879                                                 post_id = '$id'");
4880
4881                                         if (db_num_rows($e_result) > 0) {
4882                                 print "<div class=\"cdmEnclosures\">";
4883
4884                                 if (db_num_rows($e_result) == 1) {
4885                                         print __("Attachment:") . " ";
4886                                 } else {
4887                                         print __("Attachments:") . " ";
4888                                 }
4889
4890                                 $entries = array();
4891
4892                                 while ($e_line = db_fetch_assoc($e_result)) {
4893
4894                                         $url = $e_line["content_url"];
4895
4896                                         $filename = substr($url, strrpos($url, "/")+1);
4897
4898                                         $entry = "<a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4899                                                 $filename . " (" . $e_line["content_type"] . ")" . "</a>";
4900
4901                                         array_push($entries, $entry);
4902                                 }
4903
4904                                 print join(", ", $entries);
4905
4906                                 print "</div>";
4907                         }
4908
4909                                         print "<br clear='both'>";
4910 //                                      print "</div>";
4911
4912 /*                                      if (!$expand_cdm) {
4913                                                 print "<a id=\"CICH-$id\" 
4914                                                         href=\"javascript:cdmExpandArticle($id)\">
4915                                                         Show article</a>";
4916                                         } */
4917
4918                                         print "</div>";
4919
4920                                         print "<div class=\"cdmFooter\"><span class='s0'>";
4921
4922                                         /* print "<div class=\"markedPic\">Star it: $marked_pic</div>"; */
4923
4924                                         print __("Select:").
4925                                                         " <input type=\"checkbox\" onclick=\"toggleSelectRowById(this, 
4926                                                         'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
4927
4928                                         print "</span><span class='s1'>$marked_pic</span> ";
4929                                         print "<span class='s1'>$published_pic</span> ";
4930
4931                                         $tags = get_article_tags($link, $id);
4932
4933                                         $tags_str = "";
4934                                         $full_tags_str = "";
4935                                         $num_tags = 0;
4936
4937                                         foreach ($tags as $tag) {
4938                                                 $num_tags++;
4939                                                 $full_tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, "; 
4940                                                 if ($num_tags < 5) {
4941                                                         $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, "; 
4942                                                 } else if ($num_tags == 5) {
4943                                                         $tags_str .= "&hellip;";
4944                                                 }
4945                                         }
4946
4947                                         $tags_str = preg_replace("/, $/", "", $tags_str);
4948                                         $full_tags_str = preg_replace("/, $/", "", $full_tags_str);
4949
4950                                         $all_tags_div = "<span class='cdmAllTagsCtr'>&hellip;<div class='cdmAllTags'>All Tags: $full_tags_str</div></span>";
4951
4952                                         $tags_str = preg_replace("/\.\.\.$/", "$all_tags_div", $tags_str);
4953
4954
4955                                         if ($tags_str == "") $tags_str = "no tags";
4956
4957 //                                      print "<img src='images/tag.png' class='markedPic'>";
4958
4959                                         print "<span class='s1'>
4960                                                 <img class='tagsPic' src='images/tag.png' alt='Tags' 
4961                                                         title='Tags'> $tags_str <a title=\"Edit tags for this article\" 
4962                                                         href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
4963
4964                                         print "</span>";
4965
4966                                         print "<span class='s2'>Toggle: <a class=\"cdmToggleLink\"
4967                                                         href=\"javascript:toggleUnread($id)\">
4968                                                         Unread</a></span>";
4969
4970                                         print "</div>";
4971                                         print "</div>"; 
4972
4973                                 }                               
4974         
4975                                 ++$lnum;
4976                         }
4977
4978                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE') && !$offset) {                    
4979                                 print "</table>";
4980                         }
4981
4982 //                      print_headline_subtoolbar($link, 
4983 //                              "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
4984
4985
4986                 } else {
4987                         if (!$offset) print "<div class='whiteBox'>".__('No articles found.')."</div>";
4988                 }
4989
4990                 if (!$offset) {
4991                         print "</div>";
4992                         print "</div>";
4993                 }
4994
4995                 return array($topmost_article_ids, $headlines_count, $feed, $disable_cache);
4996         }
4997
4998 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
4999
5000         function printTagCloud($link) {
5001
5002                 /* get first ref_id to count from */
5003
5004                 /*
5005
5006                 $query = "";
5007
5008                 if (DB_TYPE == "pgsql") {
5009                         $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries 
5010                                 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
5011                                 AND date_entered > NOW() - INTERVAL '30 days'";
5012                 } else {
5013                         $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries 
5014                                 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]." 
5015                                 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
5016                 }
5017
5018                 $result = db_query($link, $query);
5019                 $first_id = db_fetch_result($result, 0, "id"); */
5020
5021                 //AND post_int_id >= '$first_id'
5022                 $query = "SELECT tag_name, COUNT(post_int_id) AS count 
5023                         FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]." 
5024                         GROUP BY tag_name ORDER BY count DESC LIMIT 50";
5025
5026                 $result = db_query($link, $query);
5027
5028                 $tags = array();
5029
5030                 while ($line = db_fetch_assoc($result)) {
5031                         $tags[$line["tag_name"]] = $line["count"];
5032                 }
5033
5034                 ksort($tags);
5035
5036                 $max_size = 32; // max font size in pixels
5037                 $min_size = 11; // min font size in pixels
5038                    
5039                 // largest and smallest array values
5040                 $max_qty = max(array_values($tags));
5041                 $min_qty = min(array_values($tags));
5042                    
5043                 // find the range of values
5044                 $spread = $max_qty - $min_qty;
5045                 if ($spread == 0) { // we don't want to divide by zero
5046                                 $spread = 1;
5047                 }
5048                    
5049                 // set the font-size increment
5050                 $step = ($max_size - $min_size) / ($spread);
5051                    
5052                 // loop through the tag array
5053                 foreach ($tags as $key => $value) {
5054                         // calculate font-size
5055                         // find the $value in excess of $min_qty
5056                         // multiply by the font-size increment ($size)
5057                         // and add the $min_size set above
5058                         $size = round($min_size + (($value - $min_qty) * $step));
5059
5060                         $key_escaped = str_replace("'", "\\'", $key);
5061
5062                         echo "<a href=\"javascript:viewfeed('$key_escaped') \" style=\"font-size: " . 
5063                                 $size . "px\" title=\"$value articles tagged with " . 
5064                                 $key . '">' . $key . '</a> ';
5065                 }
5066         }
5067
5068         function print_checkpoint($n, $s) {
5069                 $ts = getmicrotime();   
5070                 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
5071                 return $ts;
5072         }
5073
5074         function sanitize_tag($tag) {
5075                 $tag = trim($tag);
5076
5077                 $tag = mb_strtolower($tag, 'utf-8');
5078
5079                 $tag = preg_replace('/[\"\+\>\<]/', "", $tag);  
5080
5081 //              $tag = str_replace('"', "", $tag);      
5082 //              $tag = str_replace("+", " ", $tag);     
5083                 $tag = str_replace("technorati tag: ", "", $tag);
5084
5085                 return $tag;
5086         }
5087
5088         function generate_publish_key() {
5089                 return sha1(uniqid(rand(), true));
5090         }
5091
5092         function article_publish_url($link) {
5093
5094                 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5095
5096                 $url_path .= "?op=publish&key=" . get_pref($link, "_PREFS_PUBLISH_KEY");
5097
5098                 return $url_path;
5099         }
5100
5101         function clear_feed_articles($link, $id) {
5102                 $result = db_query($link, "DELETE FROM ttrss_user_entries
5103                         WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
5104
5105                 $result = db_query($link, "DELETE FROM ttrss_entries WHERE 
5106                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
5107         }
5108
5109         function add_feed_url() {
5110                 $url_path = 'http://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
5111                 $url_path .= "?op=pref-feeds&quiet=1&subop=add&feed_url=%s";
5112                 return $url_path;
5113         }
5114
5115         function encrypt_password($pass, $login = '') {
5116                 if ($login) {
5117                         return "SHA1X:" . sha1("$login:$pass");
5118                 } else {
5119                         return "SHA1:" . sha1($pass);
5120                 }
5121         }
5122
5123 ?>