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