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