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