]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
mark feed as updated even if blank
[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 "accept-to-gettext.php";
10         require_once "gettext/gettext.inc";
11
12         require_once 'config.php';
13
14         function startup_gettext() {
15
16                 # Get locale from Accept-Language header
17                 $lang = al2gt(array("en_US", "ru_RU"), "text/html");
18
19                 if ($lang) {
20                         _setlocale(LC_MESSAGES, $lang);
21                         _bindtextdomain("messages", "locale");
22                         _textdomain("messages");
23                         _bind_textdomain_codeset("messages", "UTF-8");
24                 }
25         }
26
27         if (ENABLE_TRANSLATIONS == true) { 
28                 startup_gettext();
29         }
30
31         require_once 'db-prefs.php';
32         require_once 'compat.php';
33         require_once 'errors.php';
34         require_once 'version.php';
35
36         define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
37         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
38
39         require_once "magpierss/rss_fetch.inc";
40         require_once 'magpierss/rss_utils.inc';
41
42         function _debug($msg) {
43                 $ts = strftime("%H:%M:%S", time());
44                 print "[$ts] $msg\n";
45         }
46
47         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
48
49                 $rows = -1;
50
51                 if (DB_TYPE == "pgsql") {
52 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
53                                 marked = false AND feed_id = '$feed_id' AND
54                                 (SELECT date_entered FROM ttrss_entries WHERE
55                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
56
57                         $pg_version = get_pgsql_version($link);
58
59                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
60
61                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE 
62                                         ttrss_entries.id = ref_id AND 
63                                         marked = false AND 
64                                         feed_id = '$feed_id' AND 
65                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
66
67                         } else {
68
69                                 $result = db_query($link, "DELETE FROM ttrss_user_entries 
70                                         USING ttrss_entries 
71                                         WHERE ttrss_entries.id = ref_id AND 
72                                         marked = false AND 
73                                         feed_id = '$feed_id' AND 
74                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
75                         }
76
77                         $rows = pg_affected_rows($result);
78                         
79                 } else {
80                 
81 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
82                                 marked = false AND feed_id = '$feed_id' AND
83                                 (SELECT date_entered FROM ttrss_entries WHERE 
84                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
85
86                         $result = db_query($link, "DELETE FROM ttrss_user_entries 
87                                 USING ttrss_user_entries, ttrss_entries 
88                                 WHERE ttrss_entries.id = ref_id AND 
89                                 marked = false AND 
90                                 feed_id = '$feed_id' AND 
91                                 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
92                                         
93                         $rows = mysql_affected_rows($link);
94
95                 }
96
97                 if ($debug) {
98                         _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
99                 }
100         }
101
102         function global_purge_old_posts($link, $do_output = false, $limit = false) {
103
104                 $random_qpart = sql_random_function();
105
106                 if ($limit) {
107                         $limit_qpart = "LIMIT $limit";
108                 } else {
109                         $limit_qpart = "";
110                 }
111                 
112                 $result = db_query($link, 
113                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds 
114                                 ORDER BY $random_qpart $limit_qpart");
115
116                 while ($line = db_fetch_assoc($result)) {
117
118                         $feed_id = $line["id"];
119                         $purge_interval = $line["purge_interval"];
120                         $owner_uid = $line["owner_uid"];
121
122                         if ($purge_interval == 0) {
123                         
124                                 $tmp_result = db_query($link, 
125                                         "SELECT value FROM ttrss_user_prefs WHERE
126                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
127
128                                 if (db_num_rows($tmp_result) != 0) {                    
129                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
130                                 }
131                         }
132
133                         if ($do_output) {
134 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
135                         }
136
137                         if ($purge_interval > 0) {
138                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
139                         }
140                 }       
141
142                 // purge orphaned posts in main content table
143                 db_query($link, "DELETE FROM ttrss_entries WHERE 
144                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
145
146         }
147
148         function purge_old_posts($link) {
149
150                 $user_id = $_SESSION["uid"];
151         
152                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
153                         WHERE owner_uid = '$user_id'");
154
155                 while ($line = db_fetch_assoc($result)) {
156
157                         $feed_id = $line["id"];
158                         $purge_interval = $line["purge_interval"];
159
160                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
161
162                         if ($purge_interval > 0) {
163                                 purge_feed($link, $feed_id, $purge_interval);
164                         }
165                 }       
166
167                 // purge orphaned posts in main content table
168                 db_query($link, "DELETE FROM ttrss_entries WHERE 
169                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
170         }
171
172         function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
173
174                 if (WEB_DEMO_MODE) return;
175
176                 if (!$user_id) {
177                         $user_id = $_SESSION["uid"];
178                         purge_old_posts($link);
179                 }
180
181 //              db_query($link, "BEGIN");
182
183                 if (MAX_UPDATE_TIME > 0) {
184                         if (DB_TYPE == "mysql") {
185                                 $q_order = "RAND()";
186                         } else {
187                                 $q_order = "RANDOM()";
188                         }
189                 } else {
190                         $q_order = "last_updated DESC";
191                 }
192
193                 $result = db_query($link, "SELECT feed_url,id,
194                         SUBSTRING(last_updated,1,19) AS last_updated,
195                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
196                         ORDER BY $q_order");
197
198                 $upd_start = time();
199
200                 while ($line = db_fetch_assoc($result)) {
201                         $upd_intl = $line["update_interval"];
202
203                         if (!$upd_intl || $upd_intl == 0) {
204                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
205                         }
206
207                         if ($upd_intl < 0) { 
208                                 // Updates for this feed are disabled
209                                 continue; 
210                         }
211
212                         if ($fetch || (!$line["last_updated"] || 
213                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
214
215 //                              print "<!-- feed: ".$line["feed_url"]." -->";
216
217                                 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
218
219                                 $upd_elapsed = time() - $upd_start;
220
221                                 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
222                                         return;
223                                 }
224                         }
225                 }
226
227 //              db_query($link, "COMMIT");
228
229         }
230
231         function fetch_file_contents($url) {
232                 if (USE_CURL_FOR_ICONS) {
233                         $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
234
235                         $ch = curl_init($url);
236                         $fp = fopen($tmpfile, "w");
237
238                         if ($fp) {
239                                 curl_setopt($ch, CURLOPT_FILE, $fp);
240                                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
241                                 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
242                                 curl_exec($ch);
243                                 curl_close($ch);
244                                 fclose($fp);                                    
245                         }
246
247                         $contents =  file_get_contents($tmpfile);
248                         unlink($tmpfile);
249
250                         return $contents;
251
252                 } else {
253                         return file_get_contents($url);
254                 }
255
256         }
257
258         // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
259         // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
260
261         function get_favicon_url($url) {
262
263                 if ($html = @fetch_file_contents($url)) {
264
265                         if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
266                                 // Attempt to grab a favicon link from their webpage url
267                                 $linkUrl = html_entity_decode($matches[1]);
268
269                                 if (substr($linkUrl, 0, 1) == '/') {
270                                         $urlParts = parse_url($url);
271                                         $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
272                                 } else if (substr($linkUrl, 0, 7) == 'http://') {
273                                         $faviconURL = $linkUrl;
274                                 } else if (substr($url, -1, 1) == '/') {
275                                         $faviconURL = $url.$linkUrl;
276                                 } else {
277                                         $faviconURL = $url.'/'.$linkUrl;
278                                 }
279
280                         } else {
281                                 // If unsuccessful, attempt to "guess" the favicon location
282                                 $urlParts = parse_url($url);
283                                 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
284                         }
285                 }
286
287                 // Run a test to see if what we have attempted to get actually exists.
288                 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
289                         return $faviconURL;
290                 } else {
291                         return false;
292                 }
293         }
294
295         function url_validate($link) {
296                 
297                 $url_parts = @parse_url($link);
298
299                 if ( empty( $url_parts["host"] ) )
300                                 return false;
301
302                 if ( !empty( $url_parts["path"] ) ) {
303                                 $documentpath = $url_parts["path"];
304                 } else {
305                                 $documentpath = "/";
306                 }
307
308                 if ( !empty( $url_parts["query"] ) )
309                                 $documentpath .= "?" . $url_parts["query"];
310
311                 $host = $url_parts["host"];
312                 $port = $url_parts["port"];
313                 
314                 if ( empty($port) )
315                                 $port = "80";
316
317                 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
318                 
319                 if ( !$socket )
320                                 return false;
321                                 
322                 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
323
324                 $http_response = fgets( $socket, 22 );
325
326                 $responses = "/(200 OK)|(30[0-9] Moved)/";
327                 if ( preg_match($responses, $http_response) ) {
328                                 fclose($socket);
329                                 return true;
330                 } else {
331                                 return false;
332                 }
333
334         } 
335
336         function check_feed_favicon($site_url, $feed, $link) {
337                 $favicon_url = get_favicon_url($site_url);
338
339 #               print "FAVICON [$site_url]: $favicon_url\n";
340
341                 error_reporting(0);
342
343                 $icon_file = ICONS_DIR . "/$feed.ico";
344
345                 if ($favicon_url && !file_exists($icon_file)) {
346                         $contents = fetch_file_contents($favicon_url);
347
348                         $fp = fopen($icon_file, "w");
349
350                         if ($fp) {
351                                 fwrite($fp, $contents);
352                                 fclose($fp);
353                                 chmod($icon_file, 0644);
354                         }
355                 }
356
357                 error_reporting(DEFAULT_ERROR_LEVEL);
358
359         }
360
361         function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
362
363                 if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
364                         return;                 
365                 }
366
367                 if (defined('DAEMON_EXTENDED_DEBUG')) {
368                         _debug("update_rss_feed: start");
369                 }
370
371                 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
372                         FROM ttrss_feeds WHERE id = '$feed'");
373
374                 $auth_login = db_unescape_string(db_fetch_result($result, 0, "auth_login"));
375                 $auth_pass = db_unescape_string(db_fetch_result($result, 0, "auth_pass"));
376
377                 $update_interval = db_fetch_result($result, 0, "update_interval");
378
379                 if ($update_interval < 0) { return; }
380
381                 $feed = db_escape_string($feed);
382
383                 $fetch_url = $feed_url;
384
385                 if ($auth_login && $auth_pass) {
386                         $url_parts = array();
387                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
388
389                         if ($url_parts[1] && $url_parts[2]) {
390                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
391                         }
392
393                 }
394
395                 if (defined('DAEMON_EXTENDED_DEBUG')) {
396                         _debug("update_rss_feed: fetching...");
397                 }
398
399                 if (!defined('DAEMON_EXTENDED_DEBUG')) {
400                         error_reporting(0);
401                 }
402
403                 $rss = fetch_rss($fetch_url);
404
405                 if (defined('DAEMON_EXTENDED_DEBUG')) {
406                         _debug("update_rss_feed: fetch done, parsing...");
407                 } else {
408                         error_reporting (DEFAULT_ERROR_LEVEL);
409                 }
410
411                 $feed = db_escape_string($feed);
412
413                 if ($rss) {
414
415                         if (defined('DAEMON_EXTENDED_DEBUG')) {
416                                 _debug("update_rss_feed: processing feed data...");
417                         }
418
419 //                      db_query($link, "BEGIN");
420
421                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
422                                 FROM ttrss_feeds WHERE id = '$feed'");
423
424                         $registered_title = db_fetch_result($result, 0, "title");
425                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
426                         $orig_site_url = db_fetch_result($result, 0, "site_url");
427
428                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
429
430                         if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {  
431                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
432                                         _debug("update_rss_feed: checking favicon...");
433                                 }
434                                 check_feed_favicon($rss->channel["link"], $feed, $link);
435                         }
436
437                         if (!$registered_title || $registered_title == "[Unknown]") {
438                         
439                                 $feed_title = db_escape_string($rss->channel["title"]);
440                                 
441                                 db_query($link, "UPDATE ttrss_feeds SET 
442                                         title = '$feed_title' WHERE id = '$feed'");
443                         }
444
445                         $site_url = $rss->channel["link"];
446                         // weird, weird Magpie
447                         if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
448
449                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
450                                 db_query($link, "UPDATE ttrss_feeds SET 
451                                         site_url = '$site_url' WHERE id = '$feed'");
452                         }
453
454 //                      print "I: " . $rss->channel["image"]["url"];
455
456                         $icon_url = $rss->image["url"];
457
458                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
459                                 $icon_url = db_escape_string($icon_url);
460                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
461                         }
462
463                         if (defined('DAEMON_EXTENDED_DEBUG')) {
464                                 _debug("update_rss_feed: loading filters...");
465                         }
466
467                         $filters = array();
468
469                         $result = db_query($link, "SELECT reg_exp,
470                                 ttrss_filter_types.name AS name,
471                                 ttrss_filter_actions.name AS action,
472                                 inverse,
473                                 action_param
474                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
475                                         enabled = true AND
476                                         owner_uid = $owner_uid AND
477                                         ttrss_filter_types.id = filter_type AND
478                                         ttrss_filter_actions.id = action_id AND
479                                 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
480
481                         while ($line = db_fetch_assoc($result)) {
482                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
483
484                                 $filter["reg_exp"] = $line["reg_exp"];
485                                 $filter["action"] = $line["action"];
486                                 $filter["action_param"] = $line["action_param"];
487                                 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
488                         
489                                 array_push($filters[$line["name"]], $filter);
490                         }
491
492                         $iterator = $rss->items;
493
494                         if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
495                         if (!$iterator || !is_array($iterator)) $iterator = $rss;
496
497                         if (!is_array($iterator)) {
498                                 /* db_query($link, "UPDATE ttrss_feeds 
499                                         SET last_error = 'Parse error: can\'t find any articles.'
500                                         WHERE id = '$feed'"); */
501
502                                 // clear any errors and mark feed as updated if fetched okay
503                                 // even if it's blank
504
505                                 db_query($link, "UPDATE ttrss_feeds 
506                                         SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
507
508                                 return; // no articles
509                         }
510
511                         if (defined('DAEMON_EXTENDED_DEBUG')) {
512                                 _debug("update_rss_feed: processing articles...");
513                         }
514
515                         foreach ($iterator as $item) {
516
517                                 $entry_guid = $item["id"];
518
519                                 if (!$entry_guid) $entry_guid = $item["guid"];
520                                 if (!$entry_guid) $entry_guid = $item["link"];
521                                 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
522
523                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
524                                         _debug("update_rss_feed: guid $entry_guid");
525                                 }
526
527                                 if (!$entry_guid) continue;
528
529                                 $entry_timestamp = "";
530
531                                 $rss_2_date = $item['pubdate'];
532                                 $rss_1_date = $item['dc']['date'];
533                                 $atom_date = $item['issued'];
534                                 if (!$atom_date) $atom_date = $item['updated'];
535                         
536                                 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
537                                 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
538                                 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
539                                 
540                                 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
541                                         $entry_timestamp = time();
542                                         $no_orig_date = 'true';
543                                 } else {
544                                         $no_orig_date = 'false';
545                                 }
546
547                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
548
549                                 $entry_title = trim(strip_tags($item["title"]));
550
551                                 // strange Magpie workaround
552                                 $entry_link = $item["link_"];
553                                 if (!$entry_link) $entry_link = $item["link"];
554
555                                 if (!$entry_title) continue;
556 #                                       if (!$entry_link) continue;
557
558                                 $entry_link = strip_tags($entry_link);
559
560                                 $entry_content = $item["content:escaped"];
561
562                                 if (!$entry_content) $entry_content = $item["content:encoded"];
563                                 if (!$entry_content) $entry_content = $item["content"];
564                                 if (!$entry_content) $entry_content = $item["atom_content"];
565                                 if (!$entry_content) $entry_content = $item["summary"];
566                                 if (!$entry_content) $entry_content = $item["description"];
567
568 //                              if (!$entry_content) continue;
569
570                                 // WTF
571                                 if (is_array($entry_content)) {
572                                         $entry_content = $entry_content["encoded"];
573                                         if (!$entry_content) $entry_content = $entry_content["escaped"];
574                                 }
575
576 //                              print_r($item);
577 //                              print_r(htmlspecialchars($entry_content));
578 //                              print "<br>";
579
580                                 $entry_content_unescaped = $entry_content;
581                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
582
583                                 $entry_comments = strip_tags($item["comments"]);
584
585                                 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
586
587                                 if ($item['author']) {
588
589                                         if (is_array($item['author'])) {
590
591                                                 if (!$entry_author) {
592                                                         $entry_author = db_escape_string(strip_tags($item['author']['name']));
593                                                 }
594
595                                                 if (!$entry_author) {
596                                                         $entry_author = db_escape_string(strip_tags($item['author']['email']));
597                                                 }
598                                         }
599
600                                         if (!$entry_author) {
601                                                 $entry_author = db_escape_string(strip_tags($item['author']));
602                                         }
603                                 }
604
605                                 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
606
607                                 $entry_guid = db_escape_string(strip_tags($entry_guid));
608
609                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
610                                         WHERE guid = '$entry_guid'");
611
612                                 $entry_content = db_escape_string($entry_content);
613                                 $entry_title = db_escape_string($entry_title);
614                                 $entry_link = db_escape_string($entry_link);
615                                 $entry_comments = db_escape_string($entry_comments);
616
617                                 $num_comments = db_escape_string($item["slash"]["comments"]);
618
619                                 if (!$num_comments) $num_comments = 0;
620
621 /*                              $dc_subject = $item['dc']['subject'];
622
623                                 $subject_tags = false;
624
625                                 if (is_array($dc_subject)) {
626                                         $subject_tags = $dc_subject;
627                                 } else if ($dc_subject) {
628                                         $subject_tags = array($dc_subject);
629                                 } */
630
631                                 # sanitize content
632                                 
633                                 $entry_content = sanitize_rss($entry_content);
634
635                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
636                                         _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
637                                 }
638
639                                 db_query($link, "BEGIN");
640
641                                 if (db_num_rows($result) == 0) {
642
643                                         if (defined('DAEMON_EXTENDED_DEBUG')) {
644                                                 _debug("update_rss_feed: base guid not found");
645                                         }
646
647                                         // base post entry does not exist, create it
648
649                                         $result = db_query($link,
650                                                 "INSERT INTO ttrss_entries 
651                                                         (title,
652                                                         guid,
653                                                         link,
654                                                         updated,
655                                                         content,
656                                                         content_hash,
657                                                         no_orig_date,
658                                                         date_entered,
659                                                         comments,
660                                                         num_comments,
661                                                         author)
662                                                 VALUES
663                                                         ('$entry_title', 
664                                                         '$entry_guid', 
665                                                         '$entry_link',
666                                                         '$entry_timestamp_fmt', 
667                                                         '$entry_content', 
668                                                         '$content_hash',
669                                                         $no_orig_date, 
670                                                         NOW(), 
671                                                         '$entry_comments',
672                                                         '$num_comments',
673                                                         '$entry_author')");
674                                 } else {
675                                         // we keep encountering the entry in feeds, so we need to
676                                         // update date_entered column so that we don't get horrible
677                                         // dupes when the entry gets purged and reinserted again e.g.
678                                         // in the case of SLOW SLOW OMG SLOW updating feeds
679
680                                         $base_entry_id = db_fetch_result($result, 0, "id");
681
682                                         db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
683                                                 WHERE id = '$base_entry_id'");
684                                 }
685
686                                 // now it should exist, if not - bad luck then
687
688                                 $result = db_query($link, "SELECT 
689                                                 id,content_hash,no_orig_date,title,
690                                                 substring(date_entered,1,19) as date_entered,
691                                                 substring(updated,1,19) as updated,
692                                                 num_comments
693                                         FROM 
694                                                 ttrss_entries 
695                                         WHERE guid = '$entry_guid'");
696
697                                 if (db_num_rows($result) == 1) {
698
699                                         if (defined('DAEMON_EXTENDED_DEBUG')) {
700                                                 _debug("update_rss_feed: base guid found, checking for user record");
701                                         }
702
703                                         // this will be used below in update handler
704                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
705                                         $orig_title = db_fetch_result($result, 0, "title");
706                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
707                                         $orig_date_entered = strtotime(db_fetch_result($result, 
708                                                 0, "date_entered"));
709
710                                         $ref_id = db_fetch_result($result, 0, "id");
711
712                                         // check for user post link to main table
713
714                                         // do we allow duplicate posts with same GUID in different feeds?
715                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
716                                                 $dupcheck_qpart = "AND feed_id = '$feed'";
717                                         } else { 
718                                                 $dupcheck_qpart = "";
719                                         }
720
721 //                                      error_reporting(0);
722
723                                         $article_filters = get_article_filters($filters, $entry_title, 
724                                                         $entry_content, $entry_link);
725
726                                         if (defined('DAEMON_EXTENDED_DEBUG')) {
727                                                 _debug("update_rss_feed: article filters: ");
728                                                 if (count($article_filters) != 0) {
729                                                         print_r($article_filters);
730                                                 }
731                                         }
732
733                                         if (find_article_filter($article_filters, "filter")) {
734                                                 continue;
735                                         }
736
737 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
738
739                                         $result = db_query($link,
740                                                 "SELECT ref_id FROM ttrss_user_entries WHERE
741                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
742                                                         $dupcheck_qpart");
743
744                                         // okay it doesn't exist - create user entry
745                                         if (db_num_rows($result) == 0) {
746
747                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
748                                                         _debug("update_rss_feed: user record not found, creating...");
749                                                 }
750
751                                                 if (!find_article_filter($article_filters, 'catchup')) {
752                                                         $unread = 'true';
753                                                         $last_read_qpart = 'NULL';
754                                                 } else {
755                                                         $unread = 'false';
756                                                         $last_read_qpart = 'NOW()';
757                                                 }                                               
758
759                                                 if (find_article_filter($article_filters, 'mark')) {
760                                                         $marked = 'true';
761                                                 } else {
762                                                         $marked = 'false';
763                                                 }
764                                                 
765                                                 $result = db_query($link,
766                                                         "INSERT INTO ttrss_user_entries 
767                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked) 
768                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
769                                                                 $last_read_qpart, $marked)");
770                                         }
771                                         
772                                         $post_needs_update = false;
773
774                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
775                                                 ($content_hash != $orig_content_hash)) {
776                                                 $post_needs_update = true;
777                                         }
778
779                                         if ($orig_title != $entry_title) {
780                                                 $post_needs_update = true;
781                                         }
782
783                                         if ($orig_num_comments != $num_comments) {
784                                                 $post_needs_update = true;
785                                         }
786
787 //                                      this doesn't seem to be very reliable
788 //
789 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
790 //                                              $post_needs_update = true;
791 //                                      }
792
793                                         // if post needs update, update it and mark all user entries 
794                                         // linking to this post as updated                                      
795                                         if ($post_needs_update) {
796
797                                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
798                                                         _debug("update_rss_feed: post $entry_guid needs update...");
799                                                 }
800
801 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
802
803                                                 db_query($link, "UPDATE ttrss_entries 
804                                                         SET title = '$entry_title', content = '$entry_content',
805                                                                 num_comments = '$num_comments'
806                                                         WHERE id = '$ref_id'");
807
808                                                 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
809                                                         db_query($link, "UPDATE ttrss_user_entries 
810                                                                 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
811                                                 } else {
812                                                         db_query($link, "UPDATE ttrss_user_entries 
813                                                                 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
814                                                 }
815
816                                         }
817                                 }
818
819                                 db_query($link, "COMMIT");
820
821                                 if (defined('DAEMON_EXTENDED_DEBUG')) {
822                                         _debug("update_rss_feed: looking for tags...");
823                                 }
824
825                                 /* taaaags */
826                                 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
827
828                                 $entry_tags = null;
829
830                                 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i", 
831                                         $entry_content_unescaped, $entry_tags);
832
833 //                              print "<br>$entry_title : $entry_content_unescaped<br>";
834 //                              print_r($entry_tags);
835 //                              print "<br>";
836
837                                 $entry_tags = $entry_tags[1];
838
839                                 # check for manual tags
840
841                                 $tag_filter = find_article_filter($article_filters, "tag"); 
842
843                                 if ($tag_filter) {
844
845                                         $manual_tags = trim_array(split(",", $tag_filter[1]));
846
847                                         foreach ($manual_tags as $tag) {
848                                                 if (tag_is_valid($tag)) {
849                                                         array_push($entry_tags, $tag);
850                                                 }
851                                         }
852                                 }
853
854 /*                              if ($subject_tags) {
855                                         foreach ($subject_tags as $tag) {
856                                                 if (tag_is_valid($tag)) {
857                                                         array_push($entry_tags, $tag);
858                                                 }
859                                         }
860                                 } */
861
862                                 if (count($entry_tags) > 0) {
863                                 
864                                         db_query($link, "BEGIN");
865                         
866                                         $result = db_query($link, "SELECT id,int_id 
867                                                 FROM ttrss_entries,ttrss_user_entries 
868                                                 WHERE guid = '$entry_guid' 
869                                                 AND feed_id = '$feed' AND ref_id = id
870                                                 AND owner_uid = '$owner_uid'");
871
872                                         if (db_num_rows($result) == 1) {
873
874                                                 $entry_id = db_fetch_result($result, 0, "id");
875                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
876                                                 
877                                                 foreach ($entry_tags as $tag) {
878                                                         $tag = db_escape_string(mb_strtolower(strip_tags($tag)));
879
880                                                         $tag = str_replace("+", " ", $tag);     
881                                                         $tag = str_replace("technorati tag: ", "", $tag);
882
883                                                         if (!tag_is_valid($tag)) continue;
884                                                         
885                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
886                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
887                                                                 owner_uid = '$owner_uid' LIMIT 1");
888         
889         //                                              print db_fetch_result($result, 0, "id");
890         
891                                                         if ($result && db_num_rows($result) == 0) {
892                                                                 
893         //                                                      print "tagging $entry_id as $tag<br>";
894         
895                                                                 db_query($link, "INSERT INTO ttrss_tags 
896                                                                         (owner_uid,tag_name,post_int_id)
897                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
898                                                         }                                                       
899                                                 }
900                                         }
901                                         db_query($link, "COMMIT");
902                                 } 
903                         } 
904
905                         db_query($link, "UPDATE ttrss_feeds 
906                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
907
908 //                      db_query($link, "COMMIT");
909
910                 } else {
911                         $error_msg = db_escape_string(magpie_error());
912                         db_query($link, 
913                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
914                                         last_updated = NOW() WHERE id = '$feed'");
915                 }
916
917                 if (defined('DAEMON_EXTENDED_DEBUG')) {
918                         _debug("update_rss_feed: done");
919                 }
920
921         }
922
923         function print_select($id, $default, $values, $attributes = "") {
924                 print "<select name=\"$id\" id=\"$id\" $attributes>";
925                 foreach ($values as $v) {
926                         if ($v == $default)
927                                 $sel = " selected";
928                          else
929                                 $sel = "";
930                         
931                         print "<option$sel>$v</option>";
932                 }
933                 print "</select>";
934         }
935
936         function print_select_hash($id, $default, $values, $attributes = "") {
937                 print "<select name=\"$id\" id='$id' $attributes>";
938                 foreach (array_keys($values) as $v) {
939                         if ($v == $default)
940                                 $sel = "selected";
941                          else
942                                 $sel = "";
943                         
944                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
945                 }
946
947                 print "</select>";
948         }
949
950         function get_article_filters($filters, $title, $content, $link) {
951                 $matches = array();
952
953                 if ($filters["title"]) {
954                         foreach ($filters["title"] as $filter) {
955                                 $reg_exp = $filter["reg_exp"];          
956                                 $inverse = $filter["inverse"];  
957                                 if ((!$inverse && preg_match("/$reg_exp/i", $title)) || 
958                                                 ($inverse && !preg_match("/$reg_exp/i", $title))) {
959
960                                         array_push($matches, array($filter["action"], $filter["action_param"]));
961                                 }
962                         }
963                 }
964
965                 if ($filters["content"]) {
966                         foreach ($filters["content"] as $filter) {
967                                 $reg_exp = $filter["reg_exp"];
968                                 $inverse = $filter["inverse"];
969
970                                 if ((!$inverse && preg_match("/$reg_exp/i", $content)) || 
971                                                 ($inverse && !preg_match("/$reg_exp/i", $content))) {
972
973                                         array_push($matches, array($filter["action"], $filter["action_param"]));
974                                 }               
975                         }
976                 }
977
978                 if ($filters["both"]) {
979                         foreach ($filters["both"] as $filter) {                 
980                                 $reg_exp = $filter["reg_exp"];          
981                                 $inverse = $filter["inverse"];
982
983                                 if ($inverse) {
984                                         if (!preg_match("/$reg_exp/i", $title) || !preg_match("/$reg_exp/i", $content)) {
985                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
986                                         }
987                                 } else {
988                                         if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
989                                                 array_push($matches, array($filter["action"], $filter["action_param"]));
990                                         }
991                                 }
992                         }
993                 }
994
995                 if ($filters["link"]) {
996                         $reg_exp = $filter["reg_exp"];
997                         foreach ($filters["link"] as $filter) {
998                                 $reg_exp = $filter["reg_exp"];
999                                 $inverse = $filter["inverse"];
1000
1001                                 if ((!$inverse && preg_match("/$reg_exp/i", $link)) || 
1002                                                 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1003                                                 
1004                                         array_push($matches, array($filter["action"], $filter["action_param"]));
1005                                 }
1006                         }
1007                 }
1008
1009                 return $matches;
1010         }
1011
1012         function find_article_filter($filters, $filter_name) {
1013                 foreach ($filters as $f) {
1014                         if ($f[0] == $filter_name) {
1015                                 return $f;
1016                         };
1017                 }
1018                 return false;
1019         }
1020
1021         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1022                 $rtl_content = false, $last_updated = false, $last_error = false) {
1023
1024                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1025                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1026                 } else {
1027                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1028                 }
1029
1030                 if ($rtl_content) {
1031                         $rtl_tag = "dir=\"rtl\"";
1032                 } else {
1033                         $rtl_tag = "dir=\"ltr\"";
1034                 }
1035
1036                 $error_notify_msg = "";
1037                 
1038                 if ($last_error) {
1039                         $link_title = "Error: $last_error ($last_updated)";
1040                         $error_notify_msg = "(Error)";
1041                 } else if ($last_updated) {
1042                         $link_title = "Updated: $last_updated";
1043                 }
1044
1045                 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\" 
1046                         href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1047
1048                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1049                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1050                         print "$feed_icon";
1051                 }
1052
1053                 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1054
1055                 if ($unread != 0) {
1056                         $fctr_class = "";
1057                 } else {
1058                         $fctr_class = "class=\"invisible\"";
1059                 }
1060
1061                 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1062                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1063
1064                 if (get_pref($link, "EXTENDED_FEEDLIST")) {                      
1065                         print "<div class=\"feedExtInfo\">
1066                                 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1067                 }
1068                          
1069                 print "</li>";
1070
1071         }
1072
1073         function getmicrotime() {
1074                 list($usec, $sec) = explode(" ",microtime());
1075                 return ((float)$usec + (float)$sec);
1076         }
1077
1078         function print_radio($id, $default, $values, $attributes = "") {
1079                 foreach ($values as $v) {
1080                 
1081                         if ($v == $default)
1082                                 $sel = "checked";
1083                          else
1084                                 $sel = "";
1085
1086                         if ($v == "Yes") {
1087                                 $sel .= " value=\"1\"";
1088                         } else {
1089                                 $sel .= " value=\"0\"";
1090                         }
1091                         
1092                         print "<input class=\"noborder\" 
1093                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1094
1095                 }
1096         }
1097
1098         function initialize_user_prefs($link, $uid) {
1099
1100                 $uid = db_escape_string($uid);
1101
1102                 db_query($link, "BEGIN");
1103
1104                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1105                 
1106                 $u_result = db_query($link, "SELECT pref_name 
1107                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1108
1109                 $active_prefs = array();
1110
1111                 while ($line = db_fetch_assoc($u_result)) {
1112                         array_push($active_prefs, $line["pref_name"]);                  
1113                 }
1114
1115                 while ($line = db_fetch_assoc($result)) {
1116                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1117 //                              print "adding " . $line["pref_name"] . "<br>";
1118
1119                                 db_query($link, "INSERT INTO ttrss_user_prefs
1120                                         (owner_uid,pref_name,value) VALUES 
1121                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1122
1123                         }
1124                 }
1125
1126                 db_query($link, "COMMIT");
1127
1128         }
1129
1130         function lookup_user_id($link, $user) {
1131
1132                 $result = db_query($link, "SELECT id FROM ttrss_users WHERE 
1133                         login = '$login'");
1134
1135                 if (db_num_rows($result) == 1) {
1136                         return db_fetch_result($result, 0, "id");
1137                 } else {
1138                         return false;
1139                 }
1140         }
1141
1142         function http_authenticate_user($link) {
1143
1144                 if (!$_SERVER["PHP_AUTH_USER"]) {
1145
1146                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1147                         header('HTTP/1.0 401 Unauthorized');
1148                         exit;
1149                                         
1150                 } else {
1151                         $auth_result = authenticate_user($link, 
1152                                 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1153
1154                         if (!$auth_result) {
1155                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1156                                 header('HTTP/1.0 401 Unauthorized');
1157                                 exit;
1158                         }
1159                 }
1160
1161                 return true;
1162         }
1163
1164         function authenticate_user($link, $login, $password, $force_auth = false) {
1165
1166                 if (!SINGLE_USER_MODE) {
1167
1168                         $pwd_hash = 'SHA1:' . sha1($password);
1169
1170                         if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1171                                 $query = "SELECT id,login,access_level
1172                     FROM ttrss_users WHERE
1173                          login = '$login'";
1174                         } else {
1175                                 $query = "SELECT id,login,access_level
1176                     FROM ttrss_users WHERE
1177                          login = '$login' AND pwd_hash = '$pwd_hash'";
1178                         }
1179
1180                         $result = db_query($link, $query);
1181         
1182                         if (db_num_rows($result) == 1) {
1183                                 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1184                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1185                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1186         
1187                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1188                                         $_SESSION["uid"]);
1189         
1190                                 $user_theme = get_user_theme_path($link);
1191         
1192                                 $_SESSION["theme"] = $user_theme;
1193                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1194         
1195                                 initialize_user_prefs($link, $_SESSION["uid"]);
1196         
1197                                 return true;
1198                         }
1199         
1200                         return false;
1201
1202                 } else {
1203
1204                         $_SESSION["uid"] = 1;
1205                         $_SESSION["name"] = "admin";
1206
1207                         $user_theme = get_user_theme_path($link);
1208         
1209                         $_SESSION["theme"] = $user_theme;
1210                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1211         
1212                         initialize_user_prefs($link, $_SESSION["uid"]);
1213         
1214                         return true;
1215                 }
1216         }
1217
1218         function make_password($length = 8) {
1219
1220                 $password = "";
1221                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
1222                 
1223         $i = 0; 
1224     
1225                 while ($i < $length) { 
1226                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1227         
1228                         if (!strstr($password, $char)) { 
1229                                 $password .= $char;
1230                                 $i++;
1231                         }
1232                 }
1233                 return $password;
1234         }
1235
1236         // this is called after user is created to initialize default feeds, labels
1237         // or whatever else
1238         
1239         // user preferences are checked on every login, not here
1240
1241         function initialize_user($link, $uid) {
1242
1243                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1244                         values ('$uid','unread = true', 'Unread articles')");
1245
1246                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1247                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
1248                 
1249                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1250                         values ('$uid', 'Tiny Tiny RSS: New Releases',
1251                         'http://tt-rss.spb.ru/releases.rss')");
1252
1253                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1254                         values ('$uid', 'Tiny Tiny RSS: Forum',
1255                         'http://tt-rss.spb.ru/forum/rss.php')");
1256         }
1257
1258         function logout_user() {
1259                 session_destroy();
1260                 if (isset($_COOKIE[session_name()])) {
1261                    setcookie(session_name(), '', time()-42000, '/');
1262                 }
1263         }
1264
1265         function get_script_urlpath() {
1266                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1267         }
1268
1269         function validate_session($link) {
1270                 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1271                         if ($_SESSION["ip_address"]) {
1272                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1273                                         $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1274                                         return false;
1275                                 }
1276                         }
1277                 }
1278
1279 /*              if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1280
1281                         //print_r($_SESSION);
1282
1283                         if (time() > $_SESSION["cookie_lifetime"]) {
1284                                 return false;
1285                         }
1286                 } */
1287
1288                 return true;
1289         }
1290
1291         function login_sequence($link, $mobile = false) {
1292                 if (!SINGLE_USER_MODE) {
1293
1294                         if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1295                                 $swu = db_escape_string($_REQUEST["swu"]);
1296                                 if ($swu) {
1297                                         $_SESSION["prefs_cache"] = false;
1298                                         return authenticate_user($link, $swu, null, true);
1299                                 }
1300                         }
1301
1302                         $login_action = $_POST["login_action"];
1303
1304                         # try to authenticate user if called from login form                    
1305                         if ($login_action == "do_login") {
1306                                 $login = $_POST["login"];
1307                                 $password = $_POST["password"];
1308                                 $remember_me = $_POST["remember_me"];
1309
1310                                 if (authenticate_user($link, $login, $password)) {
1311                                         $_POST["password"] = "";
1312
1313                                         header("Location: " . $_SERVER["REQUEST_URI"]);
1314                                         exit;
1315
1316                                         return;
1317                                 } else {
1318                                         $_SESSION["login_error_msg"] = "Incorrect username or password";
1319                                 }
1320                         }
1321
1322 //                      print session_id();
1323 //                      print_r($_SESSION);
1324
1325                         if (!$_SESSION["uid"] || !validate_session($link)) {
1326                                 render_login_form($link, $mobile);
1327                                 exit;
1328                         }
1329
1330
1331                 } else {
1332                         return authenticate_user($link, "admin", null);
1333                 }
1334         }
1335
1336         function truncate_string($str, $max_len) {
1337                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1338                         return mb_substr($str, 0, $max_len, "utf-8") . "...";
1339                 } else {
1340                         return $str;
1341                 }
1342         }
1343
1344         function get_user_theme_path($link) {
1345                 $result = db_query($link, "SELECT theme_path 
1346                         FROM 
1347                                 ttrss_themes,ttrss_users
1348                         WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1349                 if (db_num_rows($result) != 0) {
1350                         return db_fetch_result($result, 0, "theme_path");
1351                 } else {
1352                         return null;
1353                 }
1354         }
1355
1356         function smart_date_time($timestamp) {
1357                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1358                         return date("G:i", $timestamp);
1359                 } else if (date("Y", $timestamp) == date("Y")) {
1360                         return date("M d, G:i", $timestamp);
1361                 } else {
1362                         return date("Y/m/d G:i", $timestamp);
1363                 }
1364         }
1365
1366         function smart_date($timestamp) {
1367                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1368                         return "Today";
1369                 } else if (date("Y", $timestamp) == date("Y")) {
1370                         return date("D m", $timestamp);
1371                 } else {
1372                         return date("Y/m/d", $timestamp);
1373                 }
1374         }
1375
1376         function sql_bool_to_string($s) {
1377                 if ($s == "t" || $s == "1") {
1378                         return "true";
1379                 } else {
1380                         return "false";
1381                 }
1382         }
1383
1384         function sql_bool_to_bool($s) {
1385                 if ($s == "t" || $s == "1") {
1386                         return true;
1387                 } else {
1388                         return false;
1389                 }
1390         }
1391         
1392
1393         function toggleEvenOdd($a) {
1394                 if ($a == "even") 
1395                         return "odd";
1396                 else
1397                         return "even";
1398         }
1399
1400         function sanity_check($link) {
1401
1402                 error_reporting(0);
1403
1404                 $error_code = 0;
1405                 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1406                 $schema_version = db_fetch_result($result, 0, "schema_version");
1407
1408                 if ($schema_version != SCHEMA_VERSION) {
1409                         $error_code = 5;
1410                 }
1411
1412                 if (DB_TYPE == "mysql") {
1413                         $result = db_query($link, "SELECT true", false);
1414                         if (db_num_rows($result) != 1) {
1415                                 $error_code = 10;
1416                         }
1417                 }
1418
1419                 error_reporting (DEFAULT_ERROR_LEVEL);
1420
1421                 if ($error_code != 0) {
1422                         print_error_xml($error_code);
1423                         return false;
1424                 } else {
1425                         return true;
1426                 }
1427         }
1428
1429         function file_is_locked($filename) {
1430                 error_reporting(0);
1431                 $fp = fopen($filename, "r");
1432                 error_reporting(DEFAULT_ERROR_LEVEL);
1433                 if ($fp) {
1434                         if (flock($fp, LOCK_EX | LOCK_NB)) {
1435                                 flock($fp, LOCK_UN);
1436                                 fclose($fp);
1437                                 return false;
1438                         }
1439                         fclose($fp);
1440                         return true;
1441                 }
1442                 return false;
1443         }
1444
1445         function make_lockfile($filename) {
1446                 $fp = fopen($filename, "w");
1447
1448                 if (flock($fp, LOCK_EX | LOCK_NB)) {            
1449                         return $fp;
1450                 } else {
1451                         return false;
1452                 }
1453         }
1454
1455         function sql_random_function() {
1456                 if (DB_TYPE == "mysql") {
1457                         return "RAND()";
1458                 } else {
1459                         return "RANDOM()";
1460                 }
1461         }
1462
1463         function catchup_feed($link, $feed, $cat_view) {
1464
1465                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1466                         
1467                                 if ($cat_view) {
1468
1469                                         if ($feed > 0) {
1470                                                 $cat_qpart = "cat_id = '$feed'";
1471                                         } else {
1472                                                 $cat_qpart = "cat_id IS NULL";
1473                                         }
1474                                         
1475                                         $tmp_result = db_query($link, "SELECT id 
1476                                                 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " . 
1477                                                 $_SESSION["uid"]);
1478
1479                                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
1480
1481                                                 $tmp_feed = $tmp_line["id"];
1482
1483                                                 db_query($link, "UPDATE ttrss_user_entries 
1484                                                         SET unread = false,last_read = NOW() 
1485                                                         WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1486                                         }
1487
1488                                 } else if ($feed > 0) {
1489
1490                                         $tmp_result = db_query($link, "SELECT id 
1491                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
1492                                                 ORDER BY cat_id,title");
1493
1494                                         $parent_ids = array();
1495
1496                                         if (db_num_rows($tmp_result) > 0) {
1497                                                 while ($p = db_fetch_assoc($tmp_result)) {
1498                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
1499                                                 }
1500
1501                                                 $children_qpart = implode(" OR ", $parent_ids);
1502                                                 
1503                                                 db_query($link, "UPDATE ttrss_user_entries 
1504                                                         SET unread = false,last_read = NOW() 
1505                                                         WHERE (feed_id = '$feed' OR $children_qpart) 
1506                                                         AND owner_uid = " . $_SESSION["uid"]);
1507
1508                                         } else {                                                
1509                                                 db_query($link, "UPDATE ttrss_user_entries 
1510                                                         SET unread = false,last_read = NOW() 
1511                                                         WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1512                                         }
1513                                                 
1514                                 } else if ($feed < 0 && $feed > -10) { // special, like starred
1515
1516                                         if ($feed == -1) {
1517                                                 db_query($link, "UPDATE ttrss_user_entries 
1518                                                         SET unread = false,last_read = NOW()
1519                                                         WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1520                                         }
1521                         
1522                                 } else if ($feed < -10) { // label
1523
1524                                         // TODO make this more efficient
1525
1526                                         $label_id = -$feed - 11;
1527
1528                                         $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1529                                                 WHERE id = '$label_id'");                                       
1530
1531                                         if ($tmp_result) {
1532                                                 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1533
1534                                                 db_query($link, "BEGIN");
1535
1536                                                 $tmp2_result = db_query($link,
1537                                                         "SELECT 
1538                                                                 int_id 
1539                                                         FROM 
1540                                                                 ttrss_user_entries,ttrss_entries,ttrss_feeds
1541                                                         WHERE
1542                                                                 ref_id = ttrss_entries.id AND 
1543                                                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1544                                                                 $sql_exp AND
1545                                                                 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1546
1547                                                 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1548                                                         db_query($link, "UPDATE 
1549                                                                 ttrss_user_entries 
1550                                                         SET 
1551                                                                 unread = false, last_read = NOW()
1552                                                         WHERE
1553                                                                 int_id = " . $tmp_line["int_id"]);
1554                                                 }
1555                                                                 
1556                                                 db_query($link, "COMMIT");
1557
1558 /*                                              db_query($link, "UPDATE ttrss_user_entries,ttrss_entries 
1559                                                         SET unread = false,last_read = NOW()
1560                                                         WHERE $sql_exp
1561                                                         AND ref_id = id
1562                                                         AND owner_uid = ".$_SESSION["uid"]); */
1563                                         }
1564                                 }
1565                         } else { // tag
1566                                 db_query($link, "BEGIN");
1567
1568                                 $tag_name = db_escape_string($feed);
1569
1570                                 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1571                                         WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1572
1573                                 while ($line = db_fetch_assoc($result)) {
1574                                         db_query($link, "UPDATE ttrss_user_entries SET
1575                                                 unread = false, last_read = NOW() 
1576                                                 WHERE int_id = " . $line["post_int_id"]);
1577                                 }
1578                                 db_query($link, "COMMIT");
1579                         }
1580         }
1581
1582         function update_generic_feed($link, $feed, $cat_view) {
1583                         if ($cat_view) {
1584
1585                                 if ($feed > 0) {
1586                                         $cat_qpart = "cat_id = '$feed'";
1587                                 } else {
1588                                         $cat_qpart = "cat_id IS NULL";
1589                                 }
1590                                 
1591                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1592                                         WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1593
1594                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
1595                                         $feed_url = $tmp_line["feed_url"];
1596                                         update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1597                                 }
1598
1599                         } else {
1600                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1601                                         WHERE id = '$feed'");
1602                                 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");                                
1603                                 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1604                         }
1605         }
1606
1607         function getAllCounters($link, $omode = "tflc") {
1608 /*              getLabelCounters($link);
1609                 getFeedCounters($link);
1610                 getTagCounters($link);
1611                 getGlobalCounters($link);
1612                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1613                         getCategoryCounters($link);
1614                 } */
1615
1616                 if (!$omode) $omode = "tflc";
1617
1618                 getGlobalCounters($link);
1619
1620                 if (strchr($omode, "l")) getLabelCounters($link);
1621                 if (strchr($omode, "f")) getFeedCounters($link);
1622                 if (strchr($omode, "t")) getTagCounters($link);
1623                 if (strchr($omode, "c")) {                      
1624                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
1625                                 getCategoryCounters($link);
1626                         }
1627                 }
1628         }       
1629
1630         function getCategoryCounters($link) {
1631                 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id) 
1632                                 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id 
1633                                         AND unread = true)) AS unread FROM ttrss_feeds 
1634                         WHERE 
1635                                 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1636
1637                 while ($line = db_fetch_assoc($result)) {
1638                         $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1639                         print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1640                                 $line["unread"]."\"/>";
1641                 }
1642         }
1643
1644         function getCategoryUnread($link, $cat) {
1645
1646                 if ($cat != 0) {
1647                         $cat_query = "cat_id = '$cat'";
1648                 } else {
1649                         $cat_query = "cat_id IS NULL";
1650                 }
1651
1652                 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query 
1653                                 AND hidden = false
1654                                 AND owner_uid = " . $_SESSION["uid"]);
1655
1656                 $cat_feeds = array();
1657                 while ($line = db_fetch_assoc($result)) {
1658                         array_push($cat_feeds, "feed_id = " . $line["id"]);
1659                 }
1660
1661                 if (count($cat_feeds) == 0) return 0;
1662
1663                 $match_part = implode(" OR ", $cat_feeds);
1664
1665                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
1666                         FROM ttrss_user_entries 
1667                         WHERE   unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1668
1669                 $unread = 0;
1670
1671                 # this needs to be rewritten
1672                 while ($line = db_fetch_assoc($result)) {
1673                         $unread += $line["unread"];
1674                 }
1675
1676                 return $unread;
1677
1678         }
1679
1680         function getFeedUnread($link, $feed, $is_cat = false) {
1681                 $n_feed = sprintf("%d", $feed);
1682
1683                 if ($is_cat) {
1684                         return getCategoryUnread($link, $n_feed);               
1685                 } else if ($n_feed == -1) {
1686                         $match_part = "marked = true";
1687                 } else if ($n_feed > 0) {
1688
1689                         $result = db_query($link, "SELECT id FROM ttrss_feeds 
1690                                         WHERE parent_feed = '$n_feed'
1691                                         AND hidden = false
1692                                         AND owner_uid = " . $_SESSION["uid"]);
1693
1694                         if (db_num_rows($result) > 0) {
1695
1696                                 $linked_feeds = array();
1697                                 while ($line = db_fetch_assoc($result)) {
1698                                         array_push($linked_feeds, "feed_id = " . $line["id"]);
1699                                 }
1700
1701                                 array_push($linked_feeds, "feed_id = $n_feed");
1702                                 
1703                                 $match_part = implode(" OR ", $linked_feeds);
1704
1705                                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
1706                                         FROM ttrss_user_entries
1707                                         WHERE   unread = true AND ($match_part) 
1708                                         AND owner_uid = " . $_SESSION["uid"]);
1709
1710                                 $unread = 0;
1711
1712                                 # this needs to be rewritten
1713                                 while ($line = db_fetch_assoc($result)) {
1714                                         $unread += $line["unread"];
1715                                 }
1716
1717                                 return $unread;
1718
1719                         } else {
1720                                 $match_part = "feed_id = '$n_feed'";
1721                         }
1722                 } else if ($feed < -10) {
1723
1724                         $label_id = -$feed - 11;
1725
1726                         $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1727                                 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1728
1729                         $match_part = db_fetch_result($result, 0, "sql_exp");
1730                 }
1731
1732                 if ($match_part) {
1733                 
1734                         $result = db_query($link, "SELECT count(int_id) AS unread 
1735                                 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1736                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1737                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1738                                 ttrss_feeds.hidden = false AND
1739                                 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1740                                 
1741                 } else {
1742                 
1743                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1744                                 FROM ttrss_tags,ttrss_user_entries 
1745                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1746                                         ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1747                 }
1748                 
1749                 $unread = db_fetch_result($result, 0, "unread");
1750
1751                 return $unread;
1752         }
1753
1754         /* FIXME this needs reworking */
1755
1756         function getGlobalUnread($link, $user_id = false) {
1757
1758                 if (!$user_id) {
1759                         $user_id = $_SESSION["uid"];
1760                 }
1761
1762                 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1763                         WHERE unread = true AND 
1764                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
1765                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1766                         hidden = false AND
1767                         ttrss_user_entries.owner_uid = '$user_id'");
1768                 $c_id = db_fetch_result($result, 0, "c_id");
1769                 return $c_id;
1770         }
1771
1772         function getGlobalCounters($link, $global_unread = -1) {
1773                 if ($global_unread == -1) {     
1774                         $global_unread = getGlobalUnread($link);
1775                 }
1776                 print "<counter type=\"global\" id='global-unread' 
1777                         counter='$global_unread'/>";
1778
1779                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM 
1780                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1781
1782                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1783
1784                 print "<counter type=\"global\" id='subscribed-feeds' 
1785                         counter='$subscribed_feeds'/>";
1786
1787         }
1788
1789         function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1790
1791                 if ($smart_mode) {
1792                         if (!$_SESSION["tctr_last_value"]) {
1793                                 $_SESSION["tctr_last_value"] = array();
1794                         }
1795                 }
1796
1797                 $old_counters = $_SESSION["tctr_last_value"];
1798
1799                 $tctrs_modified = false;
1800
1801 /*              $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1802                         FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1803                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1804                         ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1805                         post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name 
1806                 UNION
1807                         select tag_name,0 as count FROM ttrss_tags
1808                         WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1809
1810                 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
1811                         FROM ttrss_user_entries WHERE int_id = post_int_id 
1812                                 AND unread = true)) AS count FROM ttrss_tags 
1813                         WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1814                         
1815                 $tags = array();
1816
1817                 while ($line = db_fetch_assoc($result)) {
1818                         $tags[$line["tag_name"]] += $line["count"];
1819                 }
1820
1821                 foreach (array_keys($tags) as $tag) {
1822                         $unread = $tags[$tag];                  
1823
1824                         $tag = htmlspecialchars($tag);
1825
1826                         if (!$smart_mode || $old_counters[$tag] != $unread) {                   
1827                                 $old_counters[$tag] = $unread;
1828                                 $tctrs_modified = true;
1829                                 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1830                         }
1831
1832                 } 
1833
1834                 if ($smart_mode && $tctrs_modified) {
1835                         $_SESSION["tctr_last_value"] = $old_counters;
1836                 }
1837
1838         }
1839
1840         function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
1841
1842                 if ($smart_mode) {
1843                         if (!$_SESSION["lctr_last_value"]) {
1844                                 $_SESSION["lctr_last_value"] = array();
1845                         }
1846                 }
1847
1848                 $ret_arr = array();
1849                 
1850                 $old_counters = $_SESSION["lctr_last_value"];
1851                 $lctrs_modified = false;
1852
1853                 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1854                         WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND 
1855                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
1856                         unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1857
1858                 $count = db_fetch_result($result, 0, "count");
1859
1860                 if (!$ret_mode) {
1861                         print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1862                 } else {
1863                         $ret_arr["-1"]["counter"] = $count;
1864                         $ret_arr["-1"]["description"] = "Starred";
1865                 }
1866
1867                 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1868                         ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1869         
1870                 while ($line = db_fetch_assoc($result)) {
1871
1872                         $id = -$line["id"] - 11;
1873
1874                         $label_name = $line["description"];
1875
1876                         error_reporting (0);
1877
1878                         $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1879                                 WHERE (" . $line["sql_exp"] . ") AND unread = true AND 
1880                                 ttrss_feeds.hidden = false AND
1881                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1882                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1883                                 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1884
1885                         $count = db_fetch_result($tmp_result, 0, "count");
1886
1887                         if (!$smart_mode || $old_counters[$id] != $count) {     
1888                                 $old_counters[$id] = $count;
1889                                 $lctrs_modified = true;
1890                                 if (!$ret_mode) {
1891                                         print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1892                                 } else {
1893                                         $ret_arr[$id]["counter"] = $count;
1894                                         $ret_arr[$id]["description"] = $label_name;
1895                                 }
1896                         }
1897
1898                         error_reporting (DEFAULT_ERROR_LEVEL);
1899                 }
1900
1901                 if ($smart_mode && $lctrs_modified) {
1902                         $_SESSION["lctr_last_value"] = $old_counters;
1903                 }
1904
1905                 return $ret_arr;
1906         }
1907
1908 /*      function getFeedCounter($link, $id) {
1909         
1910                 $result = db_query($link, "SELECT 
1911                                 count(id) as count,last_error
1912                         FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1913                         WHERE feed_id = '$id' AND unread = true
1914                         AND ttrss_user_entries.feed_id = ttrss_feeds.id
1915                         AND ttrss_user_entries.ref_id = ttrss_entries.id");
1916         
1917                         $count = db_fetch_result($result, 0, "count");
1918                         $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1919                         
1920                         print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";           
1921         } */
1922
1923         function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1924
1925                 if ($smart_mode) {
1926                         if (!$_SESSION["fctr_last_value"]) {
1927                                 $_SESSION["fctr_last_value"] = array();
1928                         }
1929                 }
1930
1931                 $old_counters = $_SESSION["fctr_last_value"];
1932
1933                 $result = db_query($link, "SELECT id,last_error,parent_feed,
1934                         SUBSTRING(last_updated,1,19) AS last_updated,
1935                         (SELECT count(id) 
1936                                 FROM ttrss_entries,ttrss_user_entries 
1937                                 WHERE feed_id = ttrss_feeds.id AND 
1938                                         ttrss_user_entries.ref_id = ttrss_entries.id
1939                                 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1940                         FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1941                                 AND parent_feed IS NULL");
1942
1943                 $fctrs_modified = false;
1944
1945                 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1946
1947                 while ($line = db_fetch_assoc($result)) {
1948                 
1949                         $id = $line["id"];
1950                         $count = $line["count"];
1951                         $last_error = htmlspecialchars($line["last_error"]);
1952
1953                         if (get_pref($link, 'HEADLINES_SMART_DATE')) {
1954                                 $last_updated = smart_date_time(strtotime($line["last_updated"]));
1955                         } else {
1956                                 $last_updated = date($short_date, strtotime($line["last_updated"]));
1957                         }                               
1958
1959                         $has_img = is_file(ICONS_DIR . "/$id.ico");
1960
1961                         $tmp_result = db_query($link,
1962                                 "SELECT id,COUNT(unread) AS unread
1963                                 FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
1964                                         ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
1965                                 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
1966                         
1967                         if (db_num_rows($tmp_result) > 0) {                             
1968                                 while ($l = db_fetch_assoc($tmp_result)) {
1969                                         $count += $l["unread"];
1970                                 }
1971                         }
1972
1973                         if (!$smart_mode || $old_counters[$id] != $count) {
1974                                 $old_counters[$id] = $count;
1975                                 $fctrs_modified = true;
1976
1977                                 if ($last_error) {
1978                                         $error_part = "error=\"$last_error\"";
1979                                 } else {
1980                                         $error_part = "";
1981                                 }
1982
1983                                 if ($has_img) {
1984                                         $has_img_part = "hi=\"$has_img\"";
1985                                 } else {
1986                                         $has_img_part = "";
1987                                 }                               
1988
1989                                 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
1990                         }
1991                 }
1992
1993                 if ($smart_mode && $fctrs_modified) {
1994                         $_SESSION["fctr_last_value"] = $old_counters;
1995                 }
1996         }
1997
1998         function get_script_dt_add() {
1999                 if (strpos(VERSION, ".99") === false) {
2000                         return VERSION;
2001                 } else {
2002                         return time();
2003                 }
2004         }
2005
2006         function get_pgsql_version($link) {
2007                 $result = db_query($link, "SELECT version() AS version");
2008                 $version = split(" ", db_fetch_result($result, 0, "version"));
2009                 return $version[1];
2010         }
2011
2012         function print_error_xml($code, $add_msg = "") {
2013                 global $ERRORS;
2014
2015                 $error_msg = $ERRORS[$code];
2016                 
2017                 if ($add_msg) {
2018                         $error_msg = "$error_msg; $add_msg";
2019                 }
2020                 
2021                 print "<rpc-reply>";
2022                 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2023                 print "</rpc-reply>";
2024         }
2025
2026         function subscribe_to_feed($link, $feed_link, $cat_id = 0) {
2027
2028                 # check for feed:http://url
2029                 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2030
2031                 # check for feed://URL
2032                 if (strpos($feed_link, "//") === 0) {
2033                         $feed_link = "http:$feed_link";
2034                 }
2035
2036                 if ($feed_link == "") return;
2037
2038                 if ($cat_id == "0" || !$cat_id) {
2039                         $cat_qpart = "NULL";
2040                 } else {
2041                         $cat_qpart = "'$cat_id'";
2042                 }
2043         
2044                 $result = db_query($link,
2045                         "SELECT id FROM ttrss_feeds 
2046                         WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2047         
2048                 if (db_num_rows($result) == 0) {
2049                         
2050                         $result = db_query($link,
2051                                 "INSERT INTO ttrss_feeds (owner_uid,feed_url,title,cat_id) 
2052                                 VALUES ('".$_SESSION["uid"]."', '$feed_link', 
2053                                 '[Unknown]', $cat_qpart)");
2054         
2055                         $result = db_query($link,
2056                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link' 
2057                                 AND owner_uid = " . $_SESSION["uid"]);
2058         
2059                         $feed_id = db_fetch_result($result, 0, "id");
2060         
2061                         if ($feed_id) {
2062                                 update_rss_feed($link, $feed_link, $feed_id, true);
2063                         }
2064
2065                         return true;
2066                 } else {
2067                         return false;
2068                 }
2069         }
2070
2071         function print_feed_select($link, $id, $default_id = "", 
2072                 $attributes = "", $include_all_feeds = true) {
2073
2074                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2075                 if ($include_all_feeds) { 
2076                         print "<option value=\"0\">All feeds</option>";
2077                 }
2078         
2079                 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2080                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2081
2082                 if (db_num_rows($result) > 0 && $include_all_feeds) {
2083                         print "<option disabled>--------</option>";
2084                 }
2085
2086                 while ($line = db_fetch_assoc($result)) {
2087                         if ($line["id"] == $default_id) {
2088                                 $is_selected = "selected";
2089                         } else {
2090                                 $is_selected = "";
2091                         }
2092                         printf("<option $is_selected value='%d'>%s</option>", 
2093                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2094                 }
2095         
2096                 print "</select>";
2097         }
2098
2099         function print_feed_cat_select($link, $id, $default_id = "", 
2100                 $attributes = "", $include_all_cats = true) {
2101                 
2102                 print "<select id=\"$id\" name=\"$id\" $attributes>";
2103
2104                 if ($include_all_cats) {
2105                         print "<option value=\"0\">".__('Uncategorized')."</option>";
2106                 }
2107
2108                 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2109                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2110
2111                 if (db_num_rows($result) > 0 && $include_all_cats) {
2112                         print "<option disabled>--------</option>";
2113                 }
2114
2115                 while ($line = db_fetch_assoc($result)) {
2116                         if ($line["id"] == $default_id) {
2117                                 $is_selected = "selected";
2118                         } else {
2119                                 $is_selected = "";
2120                         }
2121                         printf("<option $is_selected value='%d'>%s</option>", 
2122                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
2123                 }
2124
2125                 print "</select>";
2126         }
2127         
2128         function checkbox_to_sql_bool($val) {
2129                 return ($val == "on") ? "true" : "false";
2130         }
2131
2132         function getFeedCatTitle($link, $id) {
2133                 if ($id == -1) {
2134                         return __("Special");
2135                 } else if ($id < -10) {
2136                         return __("Labels");
2137                 } else if ($id > 0) {
2138                         $result = db_query($link, "SELECT ttrss_feed_categories.title 
2139                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2140                                         cat_id = ttrss_feed_categories.id");
2141                         if (db_num_rows($result) == 1) {
2142                                 return db_fetch_result($result, 0, "title");
2143                         } else {
2144                                 return __("Uncategorized");
2145                         }
2146                 } else {
2147                         return "getFeedCatTitle($id) failed";
2148                 }
2149
2150         }
2151
2152         function getFeedTitle($link, $id) {
2153                 if ($id == -1) {
2154                         return __("Starred articles");
2155                 } else if ($id < -10) {
2156                         $label_id = -10 - $id;
2157                         $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2158                         if (db_num_rows($result) == 1) {
2159                                 return db_fetch_result($result, 0, "description");
2160                         } else {
2161                                 return "Unknown label ($label_id)";
2162                         }
2163
2164                 } else if ($id > 0) {
2165                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2166                         if (db_num_rows($result) == 1) {
2167                                 return db_fetch_result($result, 0, "title");
2168                         } else {
2169                                 return "Unknown feed ($id)";
2170                         }
2171                 } else {
2172                         return "getFeedTitle($id) failed";
2173                 }
2174
2175         }
2176
2177         function get_session_cookie_name() {
2178                 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2179         }
2180
2181         function print_init_params($link) {
2182                 print "<init-params>";
2183                 if ($_SESSION["stored-params"]) {
2184                         foreach (array_keys($_SESSION["stored-params"]) as $key) {
2185                                 if ($key) {
2186                                         $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2187                                         print "<param key=\"$key\" value=\"$value\"/>";
2188                                 }
2189                         }
2190                 }
2191
2192                 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2193                 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2194                 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY . "\"/>";
2195
2196                 print "<param key=\"on_catchup_show_next_feed\" value=\"" . 
2197                         get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2198
2199                 print "<param key=\"hide_read_feeds\" value=\"" . 
2200                         sprintf("%d", get_pref($link, "HIDE_READ_FEEDS")) . "\"/>";
2201
2202                 print "<param key=\"feeds_sort_by_unread\" value=\"" . 
2203                         sprintf("%d", get_pref($link, "FEEDS_SORT_BY_UNREAD")) . "\"/>";
2204
2205                 print "<param key=\"confirm_feed_catchup\" value=\"" . 
2206                         sprintf("%d", get_pref($link, "CONFIRM_FEED_CATCHUP")) . "\"/>";
2207
2208                 print "<param key=\"cdm_auto_catchup\" value=\"" . 
2209                         sprintf("%d", get_pref($link, "CDM_AUTO_CATCHUP")) . "\"/>";
2210
2211                 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
2212
2213                 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
2214
2215                 print "<param key=\"default_view_mode\" value=\"" . 
2216                         get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2217
2218                 print "<param key=\"default_view_limit\" value=\"" . 
2219                         sprintf("%d", get_pref($link, "_DEFAULT_VIEW_LIMIT")) . "\"/>";
2220
2221                 print "</init-params>";
2222         }
2223
2224         function print_runtime_info($link) {
2225                 print "<runtime-info>";
2226                 if (ENABLE_UPDATE_DAEMON) {
2227                         print "<param key=\"daemon_is_running\" value=\"".
2228                                 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2229                 }
2230                 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
2231                         
2232                         if ($_SESSION["last_version_check"] + 600 < time()) {
2233                                 $new_version_details = check_for_update($link);
2234
2235                                 print "<param key=\"new_version_available\" value=\"".
2236                                         sprintf("%d", $new_version_details != ""). "\"/>";
2237
2238                                 $_SESSION["last_version_check"] = time();
2239                         }
2240                 }
2241
2242                 print "</runtime-info>";
2243         }
2244
2245         function getSearchSql($search, $match_on) {
2246
2247                 $search_query_part = "";
2248
2249                 $keywords = split(" ", $search);
2250                 $query_keywords = array();
2251
2252                 if ($match_on == "both") {
2253
2254                         foreach ($keywords as $k) {
2255                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2256                                         OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2257                         }
2258
2259                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2260
2261                 } else if ($match_on == "title") {
2262
2263                         foreach ($keywords as $k) {
2264                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2265                         }
2266
2267                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2268
2269                 } else if ($match_on == "content") {
2270
2271                         foreach ($keywords as $k) {
2272                                 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2273                         }
2274                 }
2275
2276                 $search_query_part = implode("AND", $query_keywords);
2277
2278                 return $search_query_part;
2279         }
2280
2281         function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2282
2283                         if ($search) {
2284                         
2285                                 $search_query_part = getSearchSql($search, $match_on);
2286                                 $search_query_part .= " AND ";
2287
2288                         } else {
2289                                 $search_query_part = "";
2290                         }
2291
2292                         $view_query_part = "";
2293         
2294                         if ($view_mode == "adaptive") {
2295                                 if ($search) {
2296                                         $view_query_part = " ";
2297                                 } else if ($feed != -1) {
2298                                         $unread = getFeedUnread($link, $feed, $cat_view);
2299                                         if ($unread > 0) {
2300                                                 $view_query_part = " unread = true AND ";
2301                                         }
2302                                 }
2303                         }
2304         
2305                         if ($view_mode == "marked") {
2306                                 $view_query_part = " marked = true AND ";
2307                         }
2308         
2309                         if ($view_mode == "unread") {
2310                                 $view_query_part = " unread = true AND ";
2311                         }
2312         
2313                         if ($limit > 0) {
2314                                 $limit_query_part = "LIMIT " . $limit;
2315                         } 
2316
2317                         $vfeed_query_part = "";
2318         
2319                         // override query strategy and enable feed display when searching globally
2320                         if ($search && $search_mode == "all_feeds") {
2321                                 $query_strategy_part = "ttrss_entries.id > 0";
2322                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
2323                         } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2324                                 $query_strategy_part = "ttrss_entries.id > 0";
2325                                 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2326                                         id = feed_id) as feed_title,";
2327                         } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2328         
2329                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
2330
2331                                 $tmp_result = false;
2332
2333                                 if ($cat_view) {
2334                                         $tmp_result = db_query($link, "SELECT id 
2335                                                 FROM ttrss_feeds WHERE cat_id = '$feed'");
2336                                 } else {
2337                                         $tmp_result = db_query($link, "SELECT id
2338                                                 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds 
2339                                                         WHERE id = '$feed') AND id != '$feed'");
2340                                 }
2341         
2342                                 $cat_siblings = array();
2343         
2344                                 if (db_num_rows($tmp_result) > 0) {
2345                                         while ($p = db_fetch_assoc($tmp_result)) {
2346                                                 array_push($cat_siblings, "feed_id = " . $p["id"]);
2347                                         }
2348         
2349                                         $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
2350                                                 $feed, implode(" OR ", $cat_siblings));
2351         
2352                                 } else {
2353                                         $query_strategy_part = "ttrss_entries.id > 0";
2354                                 }
2355                                 
2356                         } else if ($feed >= 0) {
2357         
2358                                 if ($cat_view) {
2359
2360                                         if ($feed > 0) {
2361                                                 $query_strategy_part = "cat_id = '$feed'";
2362                                         } else {
2363                                                 $query_strategy_part = "cat_id IS NULL";
2364                                         }
2365         
2366                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2367
2368                                 } else {                
2369                                         $tmp_result = db_query($link, "SELECT id 
2370                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
2371                                                 ORDER BY cat_id,title");
2372                 
2373                                         $parent_ids = array();
2374                 
2375                                         if (db_num_rows($tmp_result) > 0) {
2376                                                 while ($p = db_fetch_assoc($tmp_result)) {
2377                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
2378                                                 }
2379                 
2380                                                 $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
2381                                                         $feed, implode(" OR ", $parent_ids));
2382                 
2383                                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2384                                         } else {
2385                                                 $query_strategy_part = "feed_id = '$feed'";
2386                                         }
2387                                 }
2388                         } else if ($feed == -1) { // starred virtual feed
2389                                 $query_strategy_part = "marked = true";
2390                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2391                         } else if ($feed <= -10) { // labels
2392                                 $label_id = -$feed - 11;
2393         
2394                                 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2395                                         WHERE id = '$label_id'");
2396                         
2397                                 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2398                 
2399                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2400                         } else {
2401                                 $query_strategy_part = "id > 0"; // dumb
2402                         }
2403
2404                         if (get_pref($link, 'REVERSE_HEADLINES')) {
2405                                 $order_by = "updated";
2406                         } else {        
2407                                 $order_by = "updated DESC";
2408                         }
2409
2410                         if ($override_order) {
2411                                 $order_by = $override_order;
2412                         }
2413         
2414                         $feed_title = "";
2415
2416                         if ($search && $search_mode == "all_feeds") {
2417                                 $feed_title = __("Global search results")." ($search)";
2418                         } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2419                                 $feed_title = __("Tag search results")." ($search, $feed)";
2420                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2421                                 $feed_title = $feed;
2422                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2423         
2424                                 if ($cat_view) {
2425
2426                                         if ($feed != 0) {                       
2427                                                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2428                                                         WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2429                                                 $feed_title = db_fetch_result($result, 0, "title");
2430                                         } else {
2431                                                 $feed_title = __("Uncategorized");
2432                                         }
2433
2434                                         if ($search) {
2435                                                 $feed_title = __("Category search results")." ($search, $feed_title)";
2436                                         }
2437
2438                                 } else {
2439                                         
2440                                         $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds 
2441                                                 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2442                 
2443                                         $feed_title = db_fetch_result($result, 0, "title");
2444                                         $feed_site_url = db_fetch_result($result, 0, "site_url");
2445                                         $last_error = db_fetch_result($result, 0, "last_error");
2446
2447                                         if ($search) {
2448                                                 $feed_title = __("Feed search results") . " ($search, $feed_title)";
2449                                         }
2450                                 }
2451         
2452                         } else if ($feed == -1) {
2453                                 $feed_title = __("Starred articles");
2454                         } else if ($feed < -10) {
2455                                 $label_id = -$feed - 11;
2456                                 $result = db_query($link, "SELECT description FROM ttrss_labels
2457                                         WHERE id = '$label_id'");
2458                                 $feed_title = db_fetch_result($result, 0, "description");
2459
2460                                 if ($search) {
2461                                         $feed_title = __("Label search results") . " ($search, $feed_title)";
2462                                 }
2463                         } else {
2464                                 $feed_title = "?";
2465                         }
2466
2467                         $feed_title = db_unescape_string($feed_title);
2468
2469                         if ($feed < -10) error_reporting (0);
2470
2471                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2472         
2473                                 if ($feed >= 0) {
2474                                         $feed_kind = "Feeds";
2475                                 } else {
2476                                         $feed_kind = "Labels";
2477                                 }
2478         
2479                                 $content_query_part = "content as content_preview,";
2480
2481                                 if ($limit_query_part) {
2482                                         $offset_query_part = "OFFSET $offset";
2483                                 }
2484
2485                                 $query = "SELECT 
2486                                                 guid,
2487                                                 ttrss_entries.id,ttrss_entries.title,
2488                                                 SUBSTRING(updated,1,16) as updated,
2489                                                 unread,feed_id,marked,link,last_read,
2490                                                 SUBSTRING(last_read,1,19) as last_read_noms,
2491                                                 $vfeed_query_part
2492                                                 $content_query_part
2493                                                 SUBSTRING(updated,1,19) as updated_noms,
2494                                                 author
2495                                         FROM
2496                                                 ttrss_entries,ttrss_user_entries,ttrss_feeds
2497                                         WHERE
2498                                         ttrss_feeds.hidden = false AND
2499                                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
2500                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
2501                                         ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2502                                         $search_query_part
2503                                         $view_query_part
2504                                         $query_strategy_part ORDER BY $order_by
2505                                         $limit_query_part $offset_query_part";
2506                                         
2507                                 $result = db_query($link, $query);
2508         
2509                                 if ($_GET["debug"]) print $query;
2510         
2511                         } else {
2512                                 // browsing by tag
2513         
2514                                 $feed_kind = "Tags";
2515         
2516                                 $result = db_query($link, "SELECT
2517                                         guid,
2518                                         ttrss_entries.id as id,title,
2519                                         SUBSTRING(updated,1,16) as updated,
2520                                         unread,feed_id,
2521                                         marked,link,last_read,                          
2522                                         SUBSTRING(last_read,1,19) as last_read_noms,
2523                                         $vfeed_query_part
2524                                         $content_query_part
2525                                         SUBSTRING(updated,1,19) as updated_noms
2526                                         FROM
2527                                                 ttrss_entries,ttrss_user_entries,ttrss_tags
2528                                         WHERE
2529                                                 ref_id = ttrss_entries.id AND
2530                                                 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2531                                                 post_int_id = int_id AND tag_name = '$feed' AND
2532                                                 $view_query_part
2533                                                 $search_query_part
2534                                                 $query_strategy_part ORDER BY $order_by
2535                                         $limit_query_part");    
2536                         }
2537
2538                         return array($result, $feed_title, $feed_site_url, $last_error);
2539                         
2540         }
2541
2542         function generate_syndicated_feed($link, $feed, $is_cat,
2543                 $search, $search_mode, $match_on) {
2544
2545                 $qfh_ret = queryFeedHeadlines($link, $feed, 
2546                                 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2547
2548                 $result = $qfh_ret[0];
2549                 $feed_title = htmlspecialchars($qfh_ret[1]);
2550                 $feed_site_url = $qfh_ret[2];
2551                 $last_error = $qfh_ret[3];
2552
2553                 print "<rss version=\"2.0\">
2554                         <channel>
2555                         <title>$feed_title</title>
2556                         <link>$feed_site_url</link>
2557                         <generator>Tiny Tiny RSS v".VERSION."</generator>";
2558  
2559                 while ($line = db_fetch_assoc($result)) {
2560                         print "<item>";
2561                         print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2562                         print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2563   
2564                         $rfc822_date = date('r', strtotime($line["updated"]));
2565   
2566                         print "<pubDate>$rfc822_date</pubDate>";
2567  
2568                         print "<title>" . 
2569                                 htmlspecialchars($line["title"]) . "</title>";
2570   
2571                         print "<description>" . 
2572                                 htmlspecialchars($line["content_preview"]) . "</description>";
2573   
2574                         print "</item>";
2575                 }
2576   
2577                 print "</channel></rss>";
2578
2579         }
2580
2581         function getCategoryTitle($link, $cat_id) {
2582
2583                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2584                         id = '$cat_id'");
2585
2586                 if (db_num_rows($result) == 1) {
2587                         return db_fetch_result($result, 0, "title");
2588                 } else {
2589                         return "Uncategorized";
2590                 }
2591         }
2592
2593         function sanitize_rss($str) {
2594                 $res = $str;
2595
2596                 $res = preg_replace('/<script.*?>/i', 
2597                         "<p class=\"scriptWarn\">Disabled script: ", $res);
2598
2599                 $res = preg_replace('/<\/script.*?>/i', "</p>", $res);
2600
2601 /*              $res = preg_replace('/<embed.*?>/i', "", $res);
2602
2603                 $res = preg_replace('/<object.*?>.*?<\/object>/i', 
2604                         "<p class=\"objectWarn\">(Disabled html object 
2605                         - flash or other embedded content)</p>", $res);  */
2606
2607                 return $res;
2608         }
2609
2610         function send_headlines_digests($link, $limit = 100) {
2611
2612                 if (!DIGEST_ENABLE) return false;
2613
2614                 $user_limit = DIGEST_EMAIL_LIMIT;
2615                 $days = 1;
2616
2617                 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2618
2619                 if (DB_TYPE == "pgsql") {
2620                         $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2621                 } else if (DB_TYPE == "mysql") {
2622                         $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2623                 }
2624
2625                 $result = db_query($link, "SELECT id,email FROM ttrss_users 
2626                                 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2627
2628                 while ($line = db_fetch_assoc($result)) {
2629                         if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2630                                 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2631
2632                                 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2633                                 $digest = $tuple[0];
2634                                 $headlines_count = $tuple[1];
2635
2636                                 if ($headlines_count > 0) {
2637                                         $rc = mail($line["login"] . " <" . $line["email"] . ">",
2638                                                 "[tt-rss] New headlines for last 24 hours", $digest,
2639                                                 "From: " . MAIL_FROM . "\n".
2640                                                 "Content-Type: text/plain; charset=\"utf-8\"\n".
2641                                                 "Content-Transfer-Encoding: 8bit\n");
2642                                         print "RC=$rc\n";
2643                                         db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW() 
2644                                                         WHERE id = " . $line["id"]);
2645                                 } else {
2646                                         print "No headlines\n";
2647                                 }
2648                         }
2649                 }
2650
2651 //              $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2652
2653         }
2654
2655         function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2656                 $tmp =  __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";       
2657                 $tmp .= "=======================================================\n\n";
2658
2659                 if (DB_TYPE == "pgsql") {
2660                         $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2661                 } else if (DB_TYPE == "mysql") {
2662                         $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2663                 }
2664
2665                 $result = db_query($link, "SELECT ttrss_entries.title,
2666                                 ttrss_feeds.title AS feed_title,
2667                                 date_entered,
2668                                 link,
2669                                 SUBSTRING(last_updated,1,19) AS last_updated
2670                         FROM 
2671                                 ttrss_user_entries,ttrss_entries,ttrss_feeds 
2672                         WHERE 
2673                                 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id 
2674                                 AND include_in_digest = true
2675                                 AND $interval_query
2676                                 AND ttrss_user_entries.owner_uid = $user_id
2677                                 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2678                         LIMIT $limit");
2679
2680                 $cur_feed_title = "";
2681
2682                 $headlines_count = db_num_rows($result);
2683
2684                 while ($line = db_fetch_assoc($result)) {
2685                         $updated = smart_date_time(strtotime($line["last_updated"]));
2686                         $feed_title = $line["feed_title"];
2687
2688                         if ($cur_feed_title != $feed_title) {
2689                                 $cur_feed_title = $feed_title;
2690
2691                                 $tmp .= "$feed_title\n\n";
2692                         }
2693
2694                         $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2695                         $tmp .= "   " . trim($line["link"]) . "\n";
2696                         $tmp .= "\n";
2697                 }
2698
2699                 $tmp .= "--- \n";
2700                 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") . 
2701                         DIGEST_HOSTNAME . "\n".
2702                         __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2703                         
2704
2705                 return array($tmp, $headlines_count);
2706         }
2707
2708         function check_for_update($link, $brief_fmt = true) {
2709                 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2710
2711                 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
2712                         return;
2713                 }
2714
2715                 error_reporting(0);
2716                 $rss = fetch_rss($releases_feed);
2717                 error_reporting (DEFAULT_ERROR_LEVEL);
2718
2719                 if ($rss) {
2720
2721                         $items = $rss->items;
2722
2723                         if (!$items || !is_array($items)) $items = $rss->entries;
2724                         if (!$items || !is_array($items)) $items = $rss;
2725
2726                         if (!is_array($items) || count($items) == 0) {
2727                                 return;
2728                         }                       
2729
2730                         $latest_item = $items[0];
2731
2732                         $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2733
2734                         $release_url = sanitize_rss($latest_item["link"]);
2735                         $content = sanitize_rss($latest_item["description"]);
2736
2737                         if (version_compare(VERSION, $latest_version) == -1) {
2738                                 if ($brief_fmt) {
2739                                         return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">      
2740                                                 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2741                                                 <div id=\"milestoneDetails\">$content</div>");
2742                                 } else {
2743                                         return "New version of Tiny-Tiny RSS ($latest_version) is available:
2744                                                 <div class='milestoneDetails'>$content</div>
2745                                                 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2746                                                 download and update information.";      
2747                                 }
2748
2749                         }                       
2750                 }
2751         }
2752
2753         function markArticlesById($link, $ids, $cmode) {
2754
2755                 $tmp_ids = array();
2756
2757                 foreach ($ids as $id) {
2758                         array_push($tmp_ids, "ref_id = '$id'");
2759                 }
2760
2761                 $ids_qpart = join(" OR ", $tmp_ids);
2762
2763                 if ($cmode == 0) {
2764                         db_query($link, "UPDATE ttrss_user_entries SET 
2765                         marked = false,last_read = NOW()
2766                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2767                 } else if ($cmode == 1) {
2768                         db_query($link, "UPDATE ttrss_user_entries SET 
2769                         marked = true
2770                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2771                 } else {
2772                         db_query($link, "UPDATE ttrss_user_entries SET 
2773                         marked = NOT marked,last_read = NOW()
2774                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2775                 }
2776         }
2777
2778         function catchupArticlesById($link, $ids, $cmode) {
2779
2780                 $tmp_ids = array();
2781
2782                 foreach ($ids as $id) {
2783                         array_push($tmp_ids, "ref_id = '$id'");
2784                 }
2785
2786                 $ids_qpart = join(" OR ", $tmp_ids);
2787
2788                 if ($cmode == 0) {
2789                         db_query($link, "UPDATE ttrss_user_entries SET 
2790                         unread = false,last_read = NOW()
2791                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2792                 } else if ($cmode == 1) {
2793                         db_query($link, "UPDATE ttrss_user_entries SET 
2794                         unread = true
2795                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2796                 } else {
2797                         db_query($link, "UPDATE ttrss_user_entries SET 
2798                         unread = NOT unread,last_read = NOW()
2799                         WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2800                 }
2801         }
2802
2803         function escape_for_form($s) {
2804                 return htmlspecialchars(db_unescape_string($s));
2805         }
2806
2807         function make_guid_from_title($title) {
2808                 return preg_replace("/[ \"\',.:;]/", "-", 
2809                         mb_strtolower(strip_tags($title)));
2810         }
2811
2812         function print_headline_subtoolbar($link, $feed_site_url, $feed_title, 
2813                         $bottom = false, $rtl_content = false, $feed_id = 0,
2814                         $is_cat = false, $search = false, $match_on = false,
2815                         $search_mode = false, $offset = 0, $limit = 0) {
2816
2817                         $user_page_offset = $offset + 1;
2818
2819                         if (!$bottom) {
2820                                 $class = "headlinesSubToolbar";
2821                                 $tid = "headlineActionsTop";
2822                         } else {
2823                                 $class = "headlinesSubToolbar";
2824                                 $tid = "headlineActionsBottom";
2825                         }
2826
2827                         print "<table class=\"$class\" id=\"$tid\"
2828                                 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
2829
2830                         if ($rtl_content) {
2831                                 $rtl_cpart = "RTL";
2832                         } else {
2833                                 $rtl_cpart = "";
2834                         }
2835
2836                         $page_prev_link = "javascript:viewFeedGoPage(-1)";
2837                         $page_next_link = "javascript:viewFeedGoPage(1)";
2838                         $page_first_link = "javascript:viewFeedGoPage(0)";
2839
2840                         $catchup_page_link = "javascript:catchupPage()";
2841                         $catchup_feed_link = "javascript:catchupCurrentFeed()";
2842
2843                         if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2844
2845                                 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
2846                                 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
2847                                 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
2848
2849                                 $tog_unread_link = "javascript:selectionToggleUnread()";
2850                                 $tog_marked_link = "javascript:selectionToggleMarked()";
2851
2852                         } else {
2853
2854                                 $sel_all_link = "javascript:cdmSelectArticles('all')";
2855                                 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
2856                                 $sel_none_link = "javascript:cdmSelectArticles('none')";
2857
2858                                 $tog_unread_link = "javascript:selectionToggleUnread(true)";
2859                                 $tog_marked_link = "javascript:selectionToggleMarked(true)";
2860
2861                         }
2862
2863                         if (!strstr($_SESSION["client.userAgent"], "MSIE")) {
2864
2865                                 print "<td class=\"headlineActions$rtl_cpart\">
2866                                         <ul class=\"headlineDropdownMenu\">
2867                                         <li class=\"top2\">
2868                                         ".__('Select:')."
2869                                                 <a href=\"$sel_all_link\">".__('All')."</a>,
2870                                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2871                                                 <a href=\"$sel_none_link\">".__('None')."</a></li>
2872                                         <li class=\"vsep\">&nbsp;</li>
2873                                         <li class=\"top\">Toggle<ul>
2874                                                 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
2875                                                 <li onclick=\"$tog_marked_link\">".__('Starred')."</li></ul></li>
2876                                         <li class=\"vsep\">&nbsp;</li>
2877                                         <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
2878                                                 <li onclick=\"$catchup_page_link\">".__('This page')."</li>
2879                                                 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
2880                                         <li class=\"vsep\">&nbsp;</li>";
2881
2882                                         if ($limit != 0) {
2883                                                 print "
2884                                                 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
2885                                                         <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
2886                                                         <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
2887                                                         </ul>";
2888                                         }
2889
2890                                         print " 
2891                                         </td>"; 
2892
2893                         } else {
2894                         // old style subtoolbar:
2895
2896                                 print "<td class=\"headlineActions$rtl_cpart\">".
2897                                         __('Select:')."
2898                                                                 <a href=\"$sel_all_link\">".__('All')."</a>,
2899                                                                 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2900                                                                 <a href=\"$sel_none_link\">".__('None')."</a>
2901                                                 &nbsp;&nbsp;".
2902                                                 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
2903                                                         <a href=\"$tog_marked_link\">".__('Starred')."</a>
2904                                                 &nbsp;&nbsp;".
2905                                                 __('Mark as read:')."
2906                                                         <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
2907                                                         <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
2908                                 print "</td>";  
2909
2910                         }
2911
2912                         if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
2913                                 print "<td class=\"headlineActions$rtl_cpart\">
2914                                         <a href=\"javascript:labelFromSearch('$search', '$search_mode',
2915                                                         '$match_on', '$feed_id', '$is_cat');\">
2916                                                 ".__('Convert to Label')."</a></td>";
2917                         }
2918
2919                         print "<td class=\"headlineTitle$rtl_cpart\">";
2920                 
2921                         if ($feed_site_url) {
2922                                 if (!$bottom) {
2923                                         $target = "target=\"_blank\"";
2924                                 }
2925                                 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
2926                         } else {
2927                                 print $feed_title;
2928                         }
2929
2930                         if ($search) {
2931                                 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
2932                         }
2933
2934                         if ($user_page_offset > 1) {
2935                                 print " [$user_page_offset] ";
2936                         }
2937
2938                         if (!$bottom) {
2939                                 print "
2940                                         <a target=\"_new\" 
2941                                                 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
2942                                                 <img class=\"noborder\" 
2943                                                         alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
2944                                         </a>";
2945                         }
2946                                 
2947                         print "</td>";
2948                         print "</tr></table>";
2949
2950                 }
2951
2952         function outputFeedList($link, $tags = false) {
2953
2954                 print "<ul class=\"feedList\" id=\"feedList\">\n";
2955
2956                 $owner_uid = $_SESSION["uid"];
2957
2958                 /* virtual feeds */
2959
2960                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2961                         print "<li class=\"feedCat\">".__('Special')."</li>";
2962                         print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
2963                 }
2964
2965                 $num_starred = getFeedUnread($link, -1);
2966
2967                 $class = "virt";
2968
2969                 if ($num_starred > 0) $class .= "Unread";
2970
2971                 printFeedEntry(-1, $class, __("Starred articles"), $num_starred, 
2972                         "images/mark_set.png", $link);
2973
2974                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
2975                         print "</ul>\n";
2976                 }
2977
2978                 if (!$tags) {
2979
2980                         if (GLOBAL_ENABLE_LABELS && get_pref($link, 'ENABLE_LABELS')) {
2981         
2982                                 $result = db_query($link, "SELECT id,sql_exp,description FROM
2983                                         ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
2984                 
2985                                 if (db_num_rows($result) > 0) {
2986                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
2987                                                 print "<li class=\"feedCat\">".__('Labels')."</li>";
2988                                                 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
2989                                         } else {
2990                                                 print "<li><hr></li>";
2991                                         }
2992                                 }
2993                 
2994                                 while ($line = db_fetch_assoc($result)) {
2995         
2996                                         error_reporting (0);
2997
2998                                         $label_id = -$line['id'] - 11;
2999                                         $count = getFeedUnread($link, $label_id);
3000
3001                                         $class = "label";
3002         
3003                                         if ($count > 0) {
3004                                                 $class .= "Unread";
3005                                         }
3006                                         
3007                                         error_reporting (DEFAULT_ERROR_LEVEL);
3008         
3009                                         printFeedEntry($label_id, 
3010                                                 $class, db_unescape_string($line["description"]), 
3011                                                 $count, "images/label.png", $link);
3012                 
3013                                 }
3014
3015                                 if (db_num_rows($result) > 0) {
3016                                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3017                                                 print "</ul>";
3018                                         }
3019                                 }
3020
3021                         }
3022
3023                         if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3024                                 print "<li><hr></li>";
3025                         }
3026
3027                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3028                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3029                                         $order_by_qpart = "category,unread DESC,title";
3030                                 } else {
3031                                         $order_by_qpart = "category,title";
3032                                 }
3033                         } else {
3034                                 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3035                                         $order_by_qpart = "unread DESC,title";
3036                                 } else {                
3037                                         $order_by_qpart = "title";
3038                                 }
3039                         }
3040
3041                         $result = db_query($link, "SELECT ttrss_feeds.*,
3042                                 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3043                                 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3044                                         WHERE feed_id = ttrss_feeds.id AND unread = true
3045                                                 AND ttrss_user_entries.ref_id = ttrss_entries.id
3046                                                 AND owner_uid = '$owner_uid') as unread,
3047                                 cat_id,last_error,
3048                                 ttrss_feed_categories.title AS category,
3049                                 ttrss_feed_categories.collapsed 
3050                                 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories 
3051                                         ON (ttrss_feed_categories.id = cat_id)                          
3052                                 WHERE 
3053                                         ttrss_feeds.hidden = false AND
3054                                         ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3055                                 ORDER BY $order_by_qpart"); 
3056
3057                         $actid = $_GET["actid"];
3058         
3059                         /* real feeds */
3060         
3061                         $lnum = 0;
3062         
3063                         $total_unread = 0;
3064
3065                         $category = "";
3066
3067                         $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3068         
3069                         while ($line = db_fetch_assoc($result)) {
3070                         
3071                                 $feed = db_unescape_string($line["title"]);
3072                                 $feed_id = $line["id"];   
3073         
3074                                 $subop = $_GET["subop"];
3075                                 
3076                                 $unread = $line["unread"];
3077
3078                                 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3079                                         $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3080                                 } else {
3081                                         $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3082                                 }
3083
3084                                 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3085
3086                                 if ($rtl_content) {
3087                                         $rtl_tag = "dir=\"RTL\"";
3088                                 } else {
3089                                         $rtl_tag = "";
3090                                 }
3091
3092                                 $tmp_result = db_query($link,
3093                                         "SELECT id,COUNT(unread) AS unread
3094                                         FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
3095                                                 ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
3096                                         WHERE parent_feed = '$feed_id' AND unread = true 
3097                                         GROUP BY ttrss_feeds.id");
3098                         
3099                                 if (db_num_rows($tmp_result) > 0) {                             
3100                                         while ($l = db_fetch_assoc($tmp_result)) {
3101                                                 $unread += $l["unread"];
3102                                         }
3103                                 }
3104
3105                                 $cat_id = $line["cat_id"];
3106
3107                                 $tmp_category = $line["category"];
3108
3109                                 if (!$tmp_category) {
3110                                         $tmp_category = __("Uncategorized");
3111                                 }
3112                                 
3113         //                      $class = ($lnum % 2) ? "even" : "odd";
3114
3115                                 if ($line["last_error"]) {
3116                                         $class = "error";
3117                                 } else {
3118                                         $class = "feed";
3119                                 }
3120         
3121                                 if ($unread > 0) $class .= "Unread";
3122         
3123                                 if ($actid == $feed_id) {
3124                                         $class .= "Selected";
3125                                 }
3126         
3127                                 $total_unread += $unread;
3128
3129                                 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3130                                 
3131                                         if ($category) {
3132                                                 print "</ul></li>";
3133                                         }
3134                                 
3135                                         $category = $tmp_category;
3136
3137                                         $collapsed = $line["collapsed"];
3138
3139                                         // workaround for NULL category
3140                                         if ($category == __("Uncategorized")) {
3141                                                 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3142                                                         $collapsed = "t";
3143                                                 }
3144                                         }
3145
3146                                         if ($collapsed == "t" || $collapsed == "1") {
3147                                                 $holder_class = "invisible";
3148                                                 $ellipsis = "...";
3149                                         } else {
3150                                                 $holder_class = "";
3151                                                 $ellipsis = "";
3152                                         }
3153
3154                                         $cat_id = sprintf("%d", $cat_id);
3155
3156                                         $cat_unread = getCategoryUnread($link, $cat_id);
3157
3158                                         $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3159
3160                                         print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3161                                                 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3162                                                         <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3163                                                         <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\" 
3164                                                         class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3165                                                         </a></li>";
3166
3167                                         // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3168                                         // -> keyboard navigation, etc.
3169                                         print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3170                                 }
3171         
3172                                 printFeedEntry($feed_id, $class, $feed, $unread, 
3173                                         ICONS_DIR."/$feed_id.ico", $link, $rtl_content, 
3174                                         $last_updated, $line["last_error"]);
3175         
3176                                 ++$lnum;
3177                         }
3178
3179                         if (db_num_rows($result) == 0) {
3180                                 print "<li>".__('No feeds to display.')."</li>";
3181                         }
3182
3183                 } else {
3184
3185                         // tags
3186
3187 /*                      $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3188                                 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3189                                 post_int_id = ttrss_user_entries.int_id AND 
3190                                 unread = true AND ref_id = ttrss_entries.id
3191                                 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name       
3192                         UNION
3193                                 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3194                         ORDER BY tag_name"); */
3195
3196                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3197                                 print "<li class=\"feedCat\">".__('Tags')."</li>";
3198                                 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3199                         }
3200
3201                         $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
3202                                 FROM ttrss_user_entries WHERE int_id = post_int_id 
3203                                         AND unread = true)) AS count FROM ttrss_tags 
3204                                 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3205
3206                         $tags = array();
3207         
3208                         while ($line = db_fetch_assoc($result)) {
3209                                 $tags[$line["tag_name"]] += $line["count"];
3210                         }
3211         
3212                         foreach (array_keys($tags) as $tag) {
3213         
3214                                 $unread = $tags[$tag];
3215         
3216                                 $class = "tag";
3217         
3218                                 if ($unread > 0) {
3219                                         $class .= "Unread";
3220                                 }
3221         
3222                                 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3223         
3224                         } 
3225
3226                         if (db_num_rows($result) == 0) {
3227                                 print "<li>No tags to display.</li>";
3228                         }
3229
3230                         if (get_pref($link, 'ENABLE_FEED_CATS')) {
3231                                 print "</ul>\n";
3232                         }
3233
3234                 }
3235
3236                 print "</ul>";
3237
3238         }
3239
3240         function get_article_tags($link, $id) {
3241
3242                 $a_id = db_escape_string($id);
3243
3244                 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3245                         ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3246                                 ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
3247
3248                 $tags = array();        
3249         
3250                 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3251                         array_push($tags, $tmp_line["tag_name"]);                               
3252                 }
3253
3254                 return $tags;
3255         }
3256
3257         function trim_value(&$value) {
3258                 $value = trim($value);
3259         }       
3260
3261         function trim_array($array) {
3262                 $tmp = $array;
3263                 array_walk($tmp, 'trim_value');
3264                 return $tmp;
3265         }
3266
3267         function tag_is_valid($tag) {
3268                 if ($tag == '') return false;
3269                 if (preg_match("/^[0-9]*$/", $tag)) return false;
3270
3271                 $tag = iconv("utf-8", "utf-8", $tag);
3272                 if (!$tag) return false;
3273
3274                 return true;
3275         }
3276
3277         function render_login_form($link, $mobile = false) {
3278                 if (!$mobile) {
3279                         require_once "login_form.php";
3280                 } else {
3281                         require_once "mobile/login_form.php";
3282                 }
3283         }
3284
3285         // from http://developer.apple.com/internet/safari/faq.html
3286         function no_cache_incantation() {
3287                 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3288                 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3289                 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3290                 header("Cache-Control: post-check=0, pre-check=0", false);
3291                 header("Pragma: no-cache"); // HTTP/1.0
3292         }
3293
3294         function format_warning($msg, $id = "") {
3295                 return "<div class=\"warning\" id=\"$id\"> 
3296                         <img src=\"images/sign_excl.png\">$msg</div>";
3297         }
3298
3299         function format_notice($msg) {
3300                 return "<div class=\"notice\"> 
3301                         <img src=\"images/sign_info.png\">$msg</div>";
3302         }
3303
3304         function print_notice($msg) {
3305                 return print format_notice($msg);
3306         }
3307
3308         function print_warning($msg) {
3309                 return print format_warning($msg);
3310         }
3311
3312         function T_sprintf() {
3313                 $args = func_get_args();
3314                 return vsprintf(__(array_shift($args)), $args);
3315         }
3316
3317 ?>