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