]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
add experimental digest code
[tt-rss.git] / functions.php
1 <?php
2
3 /*      if ($_GET["debug"]) {
4                 define('DEFAULT_ERROR_LEVEL', E_ALL);
5         } else {
6                 define('DEFAULT_ERROR_LEVEL', E_ERROR | E_WARNING | E_PARSE);
7         } */
8
9         require_once 'config.php';
10         require_once 'db-prefs.php';
11         require_once 'compat.php';
12         require_once 'errors.php';
13         require_once 'version.php';
14
15         if (RSS_BACKEND_TYPE == "magpie") {     
16                 require_once "magpierss/rss_fetch.inc";
17                 require_once 'magpierss/rss_utils.inc';
18         } else if (RSS_BACKEND_TYPE == "simplepie") {
19                 require_once 'simplepie/simplepie.inc';
20         }
21
22         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
23
24         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
25
26                 $rows = -1;
27
28                 if (DB_TYPE == "pgsql") {
29 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
30                                 marked = false AND feed_id = '$feed_id' AND
31                                 (SELECT date_entered FROM ttrss_entries WHERE
32                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
33
34                         $pg_version = get_pgsql_version($link);
35
36                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
37
38                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE 
39                                         ttrss_entries.id = ref_id AND 
40                                         marked = false AND 
41                                         feed_id = '$feed_id' AND 
42                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
43
44                         } else {
45
46                                 $result = db_query($link, "DELETE FROM ttrss_user_entries 
47                                         USING ttrss_entries 
48                                         WHERE ttrss_entries.id = ref_id AND 
49                                         marked = false AND 
50                                         feed_id = '$feed_id' AND 
51                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
52                         }
53
54                         $rows = pg_affected_rows($result);
55                         
56                 } else {
57                 
58 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
59                                 marked = false AND feed_id = '$feed_id' AND
60                                 (SELECT date_entered FROM ttrss_entries WHERE 
61                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
62
63                         $result = db_query($link, "DELETE FROM ttrss_user_entries 
64                                 USING ttrss_user_entries, ttrss_entries 
65                                 WHERE ttrss_entries.id = ref_id AND 
66                                 marked = false AND 
67                                 feed_id = '$feed_id' AND 
68                                 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
69                                         
70                         $rows = mysql_affected_rows($link);
71
72                 }
73
74                 if ($debug) {
75                         print "Purged feed $feed_id ($purge_interval): deleted $rows articles\n";
76                 }
77         }
78
79         function global_purge_old_posts($link, $do_output = false, $limit = false) {
80
81                 $random_qpart = sql_random_function();
82
83                 if ($limit) {
84                         $limit_qpart = "LIMIT $limit";
85                 } else {
86                         $limit_qpart = "";
87                 }
88                 
89                 $result = db_query($link, 
90                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds 
91                                 ORDER BY $random_qpart $limit_qpart");
92
93                 while ($line = db_fetch_assoc($result)) {
94
95                         $feed_id = $line["id"];
96                         $purge_interval = $line["purge_interval"];
97                         $owner_uid = $line["owner_uid"];
98
99                         if ($purge_interval == 0) {
100                         
101                                 $tmp_result = db_query($link, 
102                                         "SELECT value FROM ttrss_user_prefs WHERE
103                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
104
105                                 if (db_num_rows($tmp_result) != 0) {                    
106                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
107                                 }
108                         }
109
110                         if ($do_output) {
111 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
112                         }
113
114                         if ($purge_interval > 0) {
115                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
116                         }
117                 }       
118
119                 // purge orphaned posts in main content table
120                 db_query($link, "DELETE FROM ttrss_entries WHERE 
121                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
122
123         }
124
125         function purge_old_posts($link) {
126
127                 $user_id = $_SESSION["uid"];
128         
129                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
130                         WHERE owner_uid = '$user_id'");
131
132                 while ($line = db_fetch_assoc($result)) {
133
134                         $feed_id = $line["id"];
135                         $purge_interval = $line["purge_interval"];
136
137                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
138
139                         if ($purge_interval > 0) {
140                                 purge_feed($link, $feed_id, $purge_interval);
141                         }
142                 }       
143
144                 // purge orphaned posts in main content table
145                 db_query($link, "DELETE FROM ttrss_entries WHERE 
146                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
147         }
148
149         function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
150
151                 if (WEB_DEMO_MODE) return;
152
153                 if (!$user_id) {
154                         $user_id = $_SESSION["uid"];
155                         purge_old_posts($link);
156                 }
157
158 //              db_query($link, "BEGIN");
159
160                 if (MAX_UPDATE_TIME > 0) {
161                         if (DB_TYPE == "mysql") {
162                                 $q_order = "RAND()";
163                         } else {
164                                 $q_order = "RANDOM()";
165                         }
166                 } else {
167                         $q_order = "last_updated DESC";
168                 }
169
170                 $result = db_query($link, "SELECT feed_url,id,
171                         SUBSTRING(last_updated,1,19) AS last_updated,
172                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
173                         ORDER BY $q_order");
174
175                 $upd_start = time();
176
177                 while ($line = db_fetch_assoc($result)) {
178                         $upd_intl = $line["update_interval"];
179
180                         if (!$upd_intl || $upd_intl == 0) {
181                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id);
182                         }
183
184                         if ($upd_intl < 0) { 
185                                 // Updates for this feed are disabled
186                                 continue; 
187                         }
188
189                         if ($fetch || (!$line["last_updated"] || 
190                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
191
192 //                              print "<!-- feed: ".$line["feed_url"]." -->";
193
194                                 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
195
196                                 $upd_elapsed = time() - $upd_start;
197
198                                 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
199                                         return;
200                                 }
201                         }
202                 }
203
204 //              db_query($link, "COMMIT");
205
206         }
207
208         function check_feed_favicon($feed_url, $feed, $link) {
209                 $feed_url = str_replace("http://", "", $feed_url);
210                 $feed_url = preg_replace("/\/.*$/", "", $feed_url);
211                 
212                 $icon_url = "http://$feed_url/favicon.ico";
213                 $icon_file = ICONS_DIR . "/$feed.ico";
214
215                 if (!file_exists($icon_file)) {
216
217                         if (USE_CURL_FOR_ICONS) {
218                                 error_reporting(0);
219
220                                 $ch = curl_init($icon_url);
221                                 $fp = fopen($icon_file, "w");
222
223                                 if ($fp) {
224                                         curl_setopt($ch, CURLOPT_FILE, $fp);
225                                         curl_setopt($ch, CURLOPT_FILE, $fp);
226
227                                         curl_exec($ch);
228                                         curl_close($ch);
229                                         fclose($fp);                                    
230                                 }
231
232                                 error_reporting (DEFAULT_ERROR_LEVEL);
233
234                         } else {
235
236                                 error_reporting(0);
237                                 $r = fopen($icon_url, "r");
238                                 error_reporting (DEFAULT_ERROR_LEVEL);
239         
240                                 if ($r) {
241                                         $tmpfname = tempnam(TMP_DIRECTORY, "ttrssicon");
242                                 
243                                         $t = fopen($tmpfname, "w");
244                                         
245                                         while (!feof($r)) {
246                                                 $buf = fread($r, 16384);
247                                                 fwrite($t, $buf);
248                                         }
249                                         
250                                         fclose($r);
251                                         fclose($t);
252         
253                                         error_reporting(0);
254                                         if (!rename($tmpfname, $icon_file)) {
255                                                 unlink($tmpfname);
256                                         }
257         
258                                         chmod($icon_file, 0644);
259                                         
260                                         error_reporting (DEFAULT_ERROR_LEVEL);
261                                 }
262
263                         }       
264                 }
265         }
266
267         function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
268
269                 if (WEB_DEMO_MODE) return;
270
271                 if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
272                         return;                 
273                 }
274
275                 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
276                         FROM ttrss_feeds WHERE id = '$feed'");
277
278                 $auth_login = db_unescape_string(db_fetch_result($result, 0, "auth_login"));
279                 $auth_pass = db_unescape_string(db_fetch_result($result, 0, "auth_pass"));
280
281                 $update_interval = db_fetch_result($result, 0, "update_interval");
282
283                 if ($update_interval < 0) { return; }
284
285                 $feed = db_escape_string($feed);
286
287                 $fetch_url = $feed_url;
288
289                 if ($auth_login && $auth_pass) {
290                         $url_parts = array();
291                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
292
293                         if ($url_parts[1] && $url_parts[2]) {
294                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
295                         }
296
297                 }
298
299                 if (RSS_BACKEND_TYPE == "magpie") {             
300                         error_reporting(0);
301                         $rss = fetch_rss($fetch_url);
302                         error_reporting (DEFAULT_ERROR_LEVEL);
303                 } else if (RSS_BACKEND_TYPE == "simplepie") {
304                         
305                         if (!file_exists(SIMPLEPIE_CACHE_DIR)) {
306                                         mkdir(SIMPLEPIE_CACHE_DIR);
307                         }
308
309                         $rss = new SimplePie();
310                         $rss->feed_url($fetch_url);
311                         $rss->cache_location(SIMPLEPIE_CACHE_DIR);
312                         $rss->init();
313                 }
314                 
315                 $feed = db_escape_string($feed);
316
317                 $rss_check = $rss;
318
319                 if (RSS_BACKEND_TYPE == "simplepie") {
320                         $rss_check = $rss->data;
321                 }
322                 
323                 if ($rss_check) {
324                         
325 //                      db_query($link, "BEGIN");
326
327                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
328                                 FROM ttrss_feeds WHERE id = '$feed'");
329
330                         $registered_title = db_fetch_result($result, 0, "title");
331                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
332                         $orig_site_url = db_fetch_result($result, 0, "site_url");
333
334                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
335
336                         if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {  
337                                 check_feed_favicon($feed_url, $feed, $link);
338                         }
339
340                         if (!$registered_title || $registered_title == "[Unknown]") {
341                         
342                                 if (RSS_BACKEND_TYPE == "magpie") {                             
343                                         $feed_title = db_escape_string($rss->channel["title"]);
344                                 } else {
345                                         $feed_title = $rss->get_feed_title();
346                                 }
347                                 
348                                 db_query($link, "UPDATE ttrss_feeds SET 
349                                         title = '$feed_title' WHERE id = '$feed'");
350                         }
351
352                         if (RSS_BACKEND_TYPE == "magpie") {                             
353                                 $site_url = $rss->channel["link"];
354                                 // weird, weird Magpie
355                                 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
356                         } else {
357                                 $site_url = $rss->get_feed_link();
358                         }
359
360                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
361                                 db_query($link, "UPDATE ttrss_feeds SET 
362                                         site_url = '$site_url' WHERE id = '$feed'");
363                         }
364
365 //                      print "I: " . $rss->channel["image"]["url"];
366
367                         if (RSS_BACKEND_TYPE == "magpie") {
368                                 $icon_url = $rss->image["url"];
369                         } else {
370                                 $icon_url = $rss->get_image_url(); # FIXME
371                         }
372
373                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
374                                 $icon_url = db_escape_string($icon_url);
375                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
376                         }
377
378
379                         $filters = array();
380
381                         $result = db_query($link, "SELECT reg_exp,
382                                 ttrss_filter_types.name AS name,
383                                 ttrss_filter_actions.name AS action
384                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
385                                         owner_uid = $owner_uid AND
386                                         ttrss_filter_types.id = filter_type AND
387                                         ttrss_filter_actions.id = action_id AND
388                                 (feed_id IS NULL OR feed_id = '$feed')");
389
390                         while ($line = db_fetch_assoc($result)) {
391                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
392
393                                 $filter["reg_exp"] = $line["reg_exp"];
394                                 $filter["action"] = $line["action"];
395                                 
396                                 array_push($filters[$line["name"]], $filter);
397                         }
398
399                         if (RSS_BACKEND_TYPE == "magpie") {                     
400                                 $iterator = $rss->items;
401
402                                 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
403                                 if (!$iterator || !is_array($iterator)) $iterator = $rss;
404
405                         } else {
406                                 $iterator = $rss->get_items();
407                         }
408
409                         if (!is_array($iterator)) {
410                                 /* db_query($link, "UPDATE ttrss_feeds 
411                                         SET last_error = 'Parse error: can\'t find any articles.'
412                                                 WHERE id = '$feed'"); */
413                                 return; // WTF?
414                         }
415
416                         foreach ($iterator as $item) {
417
418                                 if (RSS_BACKEND_TYPE == "magpie") {
419                                 
420                                         $entry_guid = $item["id"];
421                 
422                                         if (!$entry_guid) $entry_guid = $item["guid"];
423                                         if (!$entry_guid) $entry_guid = $item["link"];
424         
425                                         if (!$entry_guid) continue;
426         
427                                         $entry_timestamp = "";
428         
429                                         $rss_2_date = $item['pubdate'];
430                                         $rss_1_date = $item['dc']['date'];
431                                         $atom_date = $item['issued'];
432                                         if (!$atom_date) $atom_date = $item['updated'];
433                                 
434                                         if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
435                                         if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
436                                         if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
437                                         
438                                         if ($entry_timestamp == "") {
439                                                 $entry_timestamp = time();
440                                                 $no_orig_date = 'true';
441                                         } else {
442                                                 $no_orig_date = 'false';
443                                         }
444         
445                                         $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
446         
447                                         $entry_title = $item["title"];
448         
449                                         // strange Magpie workaround
450                                         $entry_link = $item["link_"];
451                                         if (!$entry_link) $entry_link = $item["link"];
452         
453                                         if (!$entry_title) continue;
454                                         if (!$entry_link) continue;
455         
456                                         $entry_content = $item["content:escaped"];
457         
458                                         if (!$entry_content) $entry_content = $item["content:encoded"];
459                                         if (!$entry_content) $entry_content = $item["content"];
460                                         if (!$entry_content) $entry_content = $item["atom_content"];
461                                         if (!$entry_content) $entry_content = $item["summary"];
462                                         if (!$entry_content) $entry_content = $item["description"];
463         
464         //                              if (!$entry_content) continue;
465         
466                                         // WTF
467                                         if (is_array($entry_content)) {
468                                                 $entry_content = $entry_content["encoded"];
469                                                 if (!$entry_content) $entry_content = $entry_content["escaped"];
470                                         }
471         
472         //                              print_r($item);
473         //                              print_r(htmlspecialchars($entry_content));
474         //                              print "<br>";
475         
476                                         $entry_content_unescaped = $entry_content;
477                                         $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
478         
479                                         $entry_comments = $item["comments"];
480         
481                                         $entry_author = db_escape_string($item['dc']['creator']);
482         
483                                         $entry_guid = db_escape_string($entry_guid);
484         
485                                         $result = db_query($link, "SELECT id FROM       ttrss_entries 
486                                                 WHERE guid = '$entry_guid'");
487         
488                                         $entry_content = db_escape_string($entry_content);
489                                         $entry_title = db_escape_string($entry_title);
490                                         $entry_link = db_escape_string($entry_link);
491                                         $entry_comments = db_escape_string($entry_comments);
492         
493                                         $num_comments = db_escape_string($item["slash"]["comments"]);
494         
495                                         if (!$num_comments) $num_comments = 0;
496
497                                 } else if (RSS_BACKEND_TYPE == "simplepie") {
498
499                                         $entry_guid = $item->get_id();
500
501                                         if (!$entry_guid) {
502                                                         $entry_guid = $item->get_permalink();
503                                         }
504         
505                                         if (!$entry_guid) continue;
506                                         
507                                         $entry_timestamp = $item->get_date("U");
508                                         
509                                         if ($entry_timestamp == "") {
510                                                 $entry_timestamp = time();
511                                                 $no_orig_date = 'true';
512                                         } else {
513                                                 $no_orig_date = 'false';
514                                         }
515         
516                                         $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
517         
518                                         $entry_title = $item->get_title();
519                                         $entry_link = $item->get_permalink();
520         
521                                         if (!$entry_title) continue;
522                                         if (!$entry_link) continue;
523
524                                         $entry_content = $item->get_description();
525                                                 
526 //                                      print_r(htmlspecialchars($entry_content));
527 //                                      print "<br>";
528         
529                                         $entry_content_unescaped = $entry_content;
530                                         $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
531         
532                                         $entry_comments = ""; # FIXME
533                                         
534                                         $entry_author = $item->get_author(0);
535
536                                         $entry_author = db_escape_string($entry_author->name);
537                                         
538                                         $entry_guid = db_escape_string($entry_guid);
539
540                                         $result = db_query($link, "SELECT id FROM       ttrss_entries 
541                                                 WHERE guid = '$entry_guid'");
542         
543                                         $entry_content = db_escape_string($entry_content);
544                                         $entry_title = db_escape_string($entry_title);
545                                         $entry_link = db_escape_string($entry_link);
546                                         $entry_comments = db_escape_string($entry_comments);
547         
548                                         $num_comments = 0; # FIXME
549         
550                                         if (!$num_comments) $num_comments = 0;
551
552                                 }
553
554                                 # sanitize content
555                                 
556                                 $entry_content = sanitize_rss($entry_content);
557                                 $entry_title = sanitize_rss($entry_title);
558                                 $entry_link = sanitize_rss($entry_link);
559                                 $entry_comments = sanitize_rss($entry_comments);
560
561                                 db_query($link, "BEGIN");
562
563                                 if (db_num_rows($result) == 0) {
564
565                                         // base post entry does not exist, create it
566
567                                         $result = db_query($link,
568                                                 "INSERT INTO ttrss_entries 
569                                                         (title,
570                                                         guid,
571                                                         link,
572                                                         updated,
573                                                         content,
574                                                         content_hash,
575                                                         no_orig_date,
576                                                         date_entered,
577                                                         comments,
578                                                         num_comments,
579                                                         author)
580                                                 VALUES
581                                                         ('$entry_title', 
582                                                         '$entry_guid', 
583                                                         '$entry_link',
584                                                         '$entry_timestamp_fmt', 
585                                                         '$entry_content', 
586                                                         '$content_hash',
587                                                         $no_orig_date, 
588                                                         NOW(), 
589                                                         '$entry_comments',
590                                                         '$num_comments',
591                                                         '$entry_author')");
592                                 } else {
593                                         // we keep encountering the entry in feeds, so we need to
594                                         // update date_entered column so that we don't get horrible
595                                         // dupes when the entry gets purged and reinserted again e.g.
596                                         // in the case of SLOW SLOW OMG SLOW updating feeds
597
598                                         $base_entry_id = db_fetch_result($result, 0, "id");
599
600                                         db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
601                                                 WHERE id = '$base_entry_id'");
602                                 }
603
604                                 // now it should exist, if not - bad luck then
605
606                                 $result = db_query($link, "SELECT 
607                                                 id,content_hash,no_orig_date,title,
608                                                 substring(date_entered,1,19) as date_entered,
609                                                 substring(updated,1,19) as updated,
610                                                 num_comments
611                                         FROM 
612                                                 ttrss_entries 
613                                         WHERE guid = '$entry_guid'");
614
615                                 if (db_num_rows($result) == 1) {
616
617                                         // this will be used below in update handler
618                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
619                                         $orig_title = db_fetch_result($result, 0, "title");
620                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
621                                         $orig_date_entered = strtotime(db_fetch_result($result, 
622                                                 0, "date_entered"));
623
624                                         $ref_id = db_fetch_result($result, 0, "id");
625
626                                         // check for user post link to main table
627
628                                         // do we allow duplicate posts with same GUID in different feeds?
629                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
630                                                 $dupcheck_qpart = "AND feed_id = '$feed'";
631                                         } else { 
632                                                 $dupcheck_qpart = "";
633                                         }
634
635 //                                      error_reporting(0);
636
637                                         $filter_name = get_filter_name($entry_title, $entry_content, 
638                                                 $entry_link, $filters);
639
640                                         if ($filter_name == "filter") {
641                                                 continue;
642                                         }
643
644 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
645
646                                         $result = db_query($link,
647                                                 "SELECT ref_id FROM ttrss_user_entries WHERE
648                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
649                                                         $dupcheck_qpart");
650                                                         
651                                         // okay it doesn't exist - create user entry
652                                         if (db_num_rows($result) == 0) {
653
654                                                 if ($filter_name != 'catchup') {
655                                                         $unread = 'true';
656                                                         $last_read_qpart = 'NULL';
657                                                 } else {
658                                                         $unread = 'false';
659                                                         $last_read_qpart = 'NOW()';
660                                                 }                                               
661
662                                                 if ($filter_name == 'mark') {
663                                                         $marked = 'true';
664                                                 } else {
665                                                         $marked = 'false';
666                                                 }
667                                                 
668                                                 $result = db_query($link,
669                                                         "INSERT INTO ttrss_user_entries 
670                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked) 
671                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
672                                                                 $last_read_qpart, $marked)");
673                                         }
674                                         
675                                         $post_needs_update = false;
676
677                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
678                                                 ($content_hash != $orig_content_hash)) {
679                                                 $post_needs_update = true;
680                                         }
681
682                                         if ($orig_title != $entry_title) {
683                                                 $post_needs_update = true;
684                                         }
685
686                                         if ($orig_num_comments != $num_comments) {
687                                                 $post_needs_update = true;
688                                         }
689
690 //                                      this doesn't seem to be very reliable
691 //
692 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
693 //                                              $post_needs_update = true;
694 //                                      }
695
696                                         // if post needs update, update it and mark all user entries 
697                                         // linking to this post as updated                                      
698                                         if ($post_needs_update) {
699
700 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
701
702                                                 db_query($link, "UPDATE ttrss_entries 
703                                                         SET title = '$entry_title', content = '$entry_content',
704                                                                 num_comments = '$num_comments'
705                                                         WHERE id = '$ref_id'");
706
707                                                 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
708                                                         db_query($link, "UPDATE ttrss_user_entries 
709                                                                 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
710                                                 } else {
711                                                         db_query($link, "UPDATE ttrss_user_entries 
712                                                                 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
713                                                 }
714
715                                         }
716                                 }
717
718                                 db_query($link, "COMMIT");
719
720                                 /* taaaags */
721                                 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
722
723                                 $entry_tags = null;
724
725                                 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i", 
726                                         $entry_content_unescaped, $entry_tags);
727
728 //                              print "<br>$entry_title : $entry_content_unescaped<br>";
729 //                              print_r($entry_tags);
730 //                              print "<br>";
731
732                                 $entry_tags = $entry_tags[1];
733
734                                 if (count($entry_tags) > 0) {
735                                 
736                                         db_query($link, "BEGIN");
737                         
738                                         $result = db_query($link, "SELECT id,int_id 
739                                                 FROM ttrss_entries,ttrss_user_entries 
740                                                 WHERE guid = '$entry_guid' 
741                                                 AND feed_id = '$feed' AND ref_id = id
742                                                 AND owner_uid = '$owner_uid'");
743
744                                         if (db_num_rows($result) == 1) {
745
746                                                 $entry_id = db_fetch_result($result, 0, "id");
747                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
748                                                 
749                                                 foreach ($entry_tags as $tag) {
750                                                         $tag = db_escape_string(strtolower($tag));
751
752                                                         $tag = str_replace("+", " ", $tag);     
753                                                         $tag = str_replace("technorati tag: ", "", $tag);
754         
755                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
756                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
757                                                                 owner_uid = '$owner_uid' LIMIT 1");
758         
759         //                                              print db_fetch_result($result, 0, "id");
760         
761                                                         if ($result && db_num_rows($result) == 0) {
762                                                                 
763         //                                                      print "tagging $entry_id as $tag<br>";
764         
765                                                                 db_query($link, "INSERT INTO ttrss_tags 
766                                                                         (owner_uid,tag_name,post_int_id)
767                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
768                                                         }                                                       
769                                                 }
770                                         }
771                                         db_query($link, "COMMIT");
772                                 } 
773                         } 
774
775                         db_query($link, "UPDATE ttrss_feeds 
776                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
777
778 //                      db_query($link, "COMMIT");
779
780                 } else {
781                         $error_msg = db_escape_string(magpie_error());
782                         db_query($link, 
783                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
784                                         last_updated = NOW() WHERE id = '$feed'");
785                 }
786
787         }
788
789         function print_select($id, $default, $values, $attributes = "") {
790                 print "<select name=\"$id\" id=\"$id\" $attributes>";
791                 foreach ($values as $v) {
792                         if ($v == $default)
793                                 $sel = " selected";
794                          else
795                                 $sel = "";
796                         
797                         print "<option$sel>$v</option>";
798                 }
799                 print "</select>";
800         }
801
802         function print_select_hash($id, $default, $values, $attributes = "") {
803                 print "<select name=\"$id\" id='$id' $attributes>";
804                 foreach (array_keys($values) as $v) {
805                         if ($v == $default)
806                                 $sel = "selected";
807                          else
808                                 $sel = "";
809                         
810                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
811                 }
812
813                 print "</select>";
814         }
815
816         function get_filter_name($title, $content, $link, $filters) {
817
818                 if ($filters["title"]) {
819                         foreach ($filters["title"] as $filter) {
820                                 $reg_exp = $filter["reg_exp"];                  
821                                 if (preg_match("/$reg_exp/i", $title)) {
822                                         return $filter["action"];
823                                 }
824                         }
825                 }
826
827                 if ($filters["content"]) {
828                         foreach ($filters["content"] as $filter) {
829                                 $reg_exp = $filter["reg_exp"];                  
830                                 if (preg_match("/$reg_exp/i", $content)) {
831                                         return $filter["action"];
832                                 }               
833                         }
834                 }
835
836                 if ($filters["both"]) {
837                         foreach ($filters["both"] as $filter) {                 
838                                 $reg_exp = $filter["reg_exp"];          
839                                 if (preg_match("/$reg_exp/i", $title) || 
840                                         preg_match("/$reg_exp/i", $content)) {
841                                         return $filter["action"];
842                                 }
843                         }
844                 }
845
846                 if ($filters["link"]) {
847                         $reg_exp = $filter["reg_exp"];
848                         foreach ($filters["link"] as $filter) {
849                                 $reg_exp = $filter["reg_exp"];
850                                 if (preg_match("/$reg_exp/i", $link)) {
851                                         return $filter["action"];
852                                 }
853                         }
854                 }
855
856                 return false;
857         }
858
859         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
860                 $rtl_content = false, $last_updated = false, $last_error = false) {
861
862                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
863                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
864                 } else {
865                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
866                 }
867
868                 if ($rtl_content) {
869                         $rtl_tag = "dir=\"rtl\"";
870                 } else {
871                         $rtl_tag = "dir=\"ltr\"";
872                 }
873
874                 $error_notify_msg = "";
875                 
876                 if ($last_error) {
877                         $link_title = "Error: $last_error ($last_updated)";
878                         $error_notify_msg = "(Error)";
879                 } else if ($last_updated) {
880                         $link_title = "Updated: $last_updated";
881                 }
882
883                 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\" href=\"javascript:viewfeed('$feed_id', '', false);\">$feed_title</a>";
884
885                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
886                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
887                         print "$feed_icon";
888                 }
889
890                 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
891
892                 if ($unread != 0) {
893                         $fctr_class = "";
894                 } else {
895                         $fctr_class = "class=\"invisible\"";
896                 }
897
898                 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
899                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
900
901                 if (get_pref($link, "EXTENDED_FEEDLIST")) {                      
902                         print "<div class=\"feedExtInfo\">
903                                 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
904                 }
905                          
906                 print "</li>";
907
908         }
909
910         function getmicrotime() {
911                 list($usec, $sec) = explode(" ",microtime());
912                 return ((float)$usec + (float)$sec);
913         }
914
915         function print_radio($id, $default, $values, $attributes = "") {
916                 foreach ($values as $v) {
917                 
918                         if ($v == $default)
919                                 $sel = "checked";
920                          else
921                                 $sel = "";
922
923                         if ($v == "Yes") {
924                                 $sel .= " value=\"1\"";
925                         } else {
926                                 $sel .= " value=\"0\"";
927                         }
928                         
929                         print "<input class=\"noborder\" 
930                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
931
932                 }
933         }
934
935         function initialize_user_prefs($link, $uid) {
936
937                 $uid = db_escape_string($uid);
938
939                 db_query($link, "BEGIN");
940
941                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
942                 
943                 $u_result = db_query($link, "SELECT pref_name 
944                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
945
946                 $active_prefs = array();
947
948                 while ($line = db_fetch_assoc($u_result)) {
949                         array_push($active_prefs, $line["pref_name"]);                  
950                 }
951
952                 while ($line = db_fetch_assoc($result)) {
953                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
954 //                              print "adding " . $line["pref_name"] . "<br>";
955
956                                 db_query($link, "INSERT INTO ttrss_user_prefs
957                                         (owner_uid,pref_name,value) VALUES 
958                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
959
960                         }
961                 }
962
963                 db_query($link, "COMMIT");
964
965         }
966
967         function lookup_user_id($link, $user) {
968
969                 $result = db_query($link, "SELECT id FROM ttrss_users WHERE 
970                         login = '$login'");
971
972                 if (db_num_rows($result) == 1) {
973                         return db_fetch_result($result, 0, "id");
974                 } else {
975                         return false;
976                 }
977         }
978
979         function http_authenticate_user($link) {
980
981                 if (!$_SERVER["PHP_AUTH_USER"]) {
982
983                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
984                         header('HTTP/1.0 401 Unauthorized');
985                         exit;
986                                         
987                 } else {
988                         $auth_result = authenticate_user($link, 
989                                 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
990
991                         if (!$auth_result) {
992                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
993                                 header('HTTP/1.0 401 Unauthorized');
994                                 exit;
995                         }
996                 }
997
998                 return true;
999         }
1000
1001         function authenticate_user($link, $login, $password) {
1002
1003                 if (!SINGLE_USER_MODE) {
1004
1005                         $pwd_hash = 'SHA1:' . sha1($password);
1006         
1007                         $result = db_query($link, "SELECT id,login,access_level FROM ttrss_users WHERE 
1008                                 login = '$login' AND pwd_hash = '$pwd_hash'");
1009         
1010                         if (db_num_rows($result) == 1) {
1011                                 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1012                                 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1013                                 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1014         
1015                                 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
1016                                         $_SESSION["uid"]);
1017         
1018                                 $user_theme = get_user_theme_path($link);
1019         
1020                                 $_SESSION["theme"] = $user_theme;
1021                                 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1022         
1023                                 initialize_user_prefs($link, $_SESSION["uid"]);
1024         
1025                                 return true;
1026                         }
1027         
1028                         return false;
1029
1030                 } else {
1031
1032                         $_SESSION["uid"] = 1;
1033                         $_SESSION["name"] = "admin";
1034
1035                         $user_theme = get_user_theme_path($link);
1036         
1037                         $_SESSION["theme"] = $user_theme;
1038                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1039         
1040                         initialize_user_prefs($link, $_SESSION["uid"]);
1041         
1042                         return true;
1043                 }
1044         }
1045
1046         function make_password($length = 8) {
1047
1048                 $password = "";
1049                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
1050                 
1051         $i = 0; 
1052     
1053                 while ($i < $length) { 
1054                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1055         
1056                         if (!strstr($password, $char)) { 
1057                                 $password .= $char;
1058                                 $i++;
1059                         }
1060                 }
1061                 return $password;
1062         }
1063
1064         // this is called after user is created to initialize default feeds, labels
1065         // or whatever else
1066         
1067         // user preferences are checked on every login, not here
1068
1069         function initialize_user($link, $uid) {
1070
1071                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1072                         values ('$uid','unread = true', 'Unread articles')");
1073
1074                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
1075                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
1076                 
1077                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1078                         values ('$uid', 'Tiny Tiny RSS: New Releases',
1079                         'http://tt-rss.spb.ru/releases.rss')");
1080
1081         }
1082
1083         function logout_user() {
1084                 session_destroy();
1085                 if (isset($_COOKIE[session_name()])) {
1086                    setcookie(session_name(), '', time()-42000, '/');
1087                 }
1088         }
1089
1090         function get_script_urlpath() {
1091                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1092         }
1093
1094         function get_login_redirect() {
1095                 $server = $_SERVER["SERVER_NAME"];
1096
1097                 if (ENABLE_LOGIN_SSL) {
1098                         $protocol = "https";
1099                 } else {
1100                         $protocol = "http";
1101                 }               
1102
1103                 $url_path = get_script_urlpath();
1104
1105                 $redirect_uri = "$protocol://$server$url_path/login.php";
1106
1107                 return $redirect_uri;
1108         }
1109
1110         function validate_session($link) {
1111                 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1112                         if ($_SESSION["ip_address"]) {
1113                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1114                                         return false;
1115                                 }
1116                         }
1117                 }
1118                 return true;
1119         }
1120
1121         function basic_nosid_redirect_check() {
1122                 if (!SINGLE_USER_MODE) {
1123                         if (!$_COOKIE[get_session_cookie_name()]) {
1124                                 $redirect_uri = get_login_redirect();
1125                                 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
1126                                 header("Location: $redirect_uri?rt=$return_to");
1127                                 exit;
1128                         }
1129                 }
1130         }
1131
1132         function login_sequence($link) {
1133                 if (!SINGLE_USER_MODE) {
1134
1135                         if (!validate_session($link)) {
1136                                 logout_user();
1137                                 $redirect_uri = get_login_redirect();
1138                                 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
1139                                 header("Location: $redirect_uri?rt=$return_to");
1140                                 exit;
1141                         }
1142
1143                         if (!USE_HTTP_AUTH) {
1144                                 if (!$_SESSION["uid"]) {
1145                                         $redirect_uri = get_login_redirect();
1146                                         $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
1147                                         header("Location: $redirect_uri?rt=$return_to");
1148                                         exit;
1149                                 }
1150                         } else {
1151                                 if (!$_SESSION["uid"]) {
1152                                         if (!$_SERVER["PHP_AUTH_USER"]) {
1153
1154                                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
1155                                                 header('HTTP/1.0 401 Unauthorized');
1156                                                 exit;
1157                                                 
1158                                         } else {
1159                                                 $auth_result = authenticate_user($link, 
1160                                                         $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1161
1162                                                 if (!$auth_result) {
1163                                                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
1164                                                         header('HTTP/1.0 401 Unauthorized');
1165                                                         exit;
1166                                                 }
1167                                         }
1168                                 }                               
1169                         }
1170                 } else {
1171                         return authenticate_user($link, "admin", null);
1172                 }
1173         }
1174
1175         function truncate_string($str, $max_len) {
1176                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1177                         return mb_substr($str, 0, $max_len, "utf-8") . "...";
1178                 } else {
1179                         return $str;
1180                 }
1181         }
1182
1183         function get_user_theme_path($link) {
1184                 $result = db_query($link, "SELECT theme_path 
1185                         FROM 
1186                                 ttrss_themes,ttrss_users
1187                         WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1188                 if (db_num_rows($result) != 0) {
1189                         return db_fetch_result($result, 0, "theme_path");
1190                 } else {
1191                         return null;
1192                 }
1193         }
1194
1195         function smart_date_time($timestamp) {
1196                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1197                         return date("G:i", $timestamp);
1198                 } else if (date("Y", $timestamp) == date("Y")) {
1199                         return date("M d, G:i", $timestamp);
1200                 } else {
1201                         return date("Y/m/d G:i", $timestamp);
1202                 }
1203         }
1204
1205         function smart_date($timestamp) {
1206                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1207                         return "Today";
1208                 } else if (date("Y", $timestamp) == date("Y")) {
1209                         return date("D m", $timestamp);
1210                 } else {
1211                         return date("Y/m/d", $timestamp);
1212                 }
1213         }
1214
1215         function sql_bool_to_string($s) {
1216                 if ($s == "t" || $s == "1") {
1217                         return "true";
1218                 } else {
1219                         return "false";
1220                 }
1221         }
1222
1223         function sql_bool_to_bool($s) {
1224                 if ($s == "t" || $s == "1") {
1225                         return true;
1226                 } else {
1227                         return false;
1228                 }
1229         }
1230         
1231
1232         function toggleEvenOdd($a) {
1233                 if ($a == "even") 
1234                         return "odd";
1235                 else
1236                         return "even";
1237         }
1238
1239         function sanity_check($link) {
1240
1241                 error_reporting(0);
1242
1243                 $error_code = 0;
1244                 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1245                 $schema_version = db_fetch_result($result, 0, "schema_version");
1246
1247                 if ($schema_version != SCHEMA_VERSION) {
1248                         $error_code = 5;
1249                 }
1250
1251                 if (DB_TYPE == "mysql") {
1252                         $result = db_query($link, "SELECT true", false);
1253                         if (db_num_rows($result) != 1) {
1254                                 $error_code = 10;
1255                         }
1256                 }
1257
1258                 error_reporting (DEFAULT_ERROR_LEVEL);
1259
1260                 if ($error_code != 0) {
1261                         print_error_xml($error_code);
1262                         return false;
1263                 } else {
1264                         return true;
1265                 } 
1266         }
1267
1268         function file_is_locked($filename) {
1269                 error_reporting(0);
1270                 $fp = fopen($filename, "r");
1271                 error_reporting(DEFAULT_ERROR_LEVEL);
1272                 if ($fp) {
1273                         if (flock($fp, LOCK_EX | LOCK_NB)) {
1274                                 flock($fp, LOCK_UN);
1275                                 fclose($fp);
1276                                 return false;
1277                         }
1278                         fclose($fp);
1279                         return true;
1280                 }
1281                 return false;
1282         }
1283
1284         function make_lockfile($filename) {
1285                 $fp = fopen($filename, "w");
1286
1287                 if (flock($fp, LOCK_EX | LOCK_NB)) {            
1288                         return $fp;
1289                 } else {
1290                         return false;
1291                 }
1292         }
1293
1294         function sql_random_function() {
1295                 if (DB_TYPE == "mysql") {
1296                         return "RAND()";
1297                 } else {
1298                         return "RANDOM()";
1299                 }
1300         }
1301
1302         function catchup_feed($link, $feed, $cat_view) {
1303
1304                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1305                         
1306                                 if ($cat_view) {
1307
1308                                         if ($feed > 0) {
1309                                                 $cat_qpart = "cat_id = '$feed'";
1310                                         } else {
1311                                                 $cat_qpart = "cat_id IS NULL";
1312                                         }
1313                                         
1314                                         $tmp_result = db_query($link, "SELECT id 
1315                                                 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " . 
1316                                                 $_SESSION["uid"]);
1317
1318                                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
1319
1320                                                 $tmp_feed = $tmp_line["id"];
1321
1322                                                 db_query($link, "UPDATE ttrss_user_entries 
1323                                                         SET unread = false,last_read = NOW() 
1324                                                         WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1325                                         }
1326
1327                                 } else if ($feed > 0) {
1328
1329                                         $tmp_result = db_query($link, "SELECT id 
1330                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
1331                                                 ORDER BY cat_id,title");
1332
1333                                         $parent_ids = array();
1334
1335                                         if (db_num_rows($tmp_result) > 0) {
1336                                                 while ($p = db_fetch_assoc($tmp_result)) {
1337                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
1338                                                 }
1339
1340                                                 $children_qpart = implode(" OR ", $parent_ids);
1341                                                 
1342                                                 db_query($link, "UPDATE ttrss_user_entries 
1343                                                         SET unread = false,last_read = NOW() 
1344                                                         WHERE (feed_id = '$feed' OR $children_qpart) 
1345                                                         AND owner_uid = " . $_SESSION["uid"]);
1346
1347                                         } else {                                                
1348                                                 db_query($link, "UPDATE ttrss_user_entries 
1349                                                         SET unread = false,last_read = NOW() 
1350                                                         WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1351                                         }
1352                                                 
1353                                 } else if ($feed < 0 && $feed > -10) { // special, like starred
1354
1355                                         if ($feed == -1) {
1356                                                 db_query($link, "UPDATE ttrss_user_entries 
1357                                                         SET unread = false,last_read = NOW()
1358                                                         WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1359                                         }
1360                         
1361                                 } else if ($feed < -10) { // label
1362
1363                                         // TODO make this more efficient
1364
1365                                         $label_id = -$feed - 11;
1366
1367                                         $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1368                                                 WHERE id = '$label_id'");                                       
1369
1370                                         if ($tmp_result) {
1371                                                 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1372
1373                                                 db_query($link, "BEGIN");
1374
1375                                                 $tmp2_result = db_query($link,
1376                                                         "SELECT 
1377                                                                 int_id 
1378                                                         FROM 
1379                                                                 ttrss_user_entries,ttrss_entries,ttrss_feeds
1380                                                         WHERE
1381                                                                 ref_id = ttrss_entries.id AND 
1382                                                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1383                                                                 $sql_exp AND
1384                                                                 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1385
1386                                                 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1387                                                         db_query($link, "UPDATE 
1388                                                                 ttrss_user_entries 
1389                                                         SET 
1390                                                                 unread = false, last_read = NOW()
1391                                                         WHERE
1392                                                                 int_id = " . $tmp_line["int_id"]);
1393                                                 }
1394                                                                 
1395                                                 db_query($link, "COMMIT");
1396
1397 /*                                              db_query($link, "UPDATE ttrss_user_entries,ttrss_entries 
1398                                                         SET unread = false,last_read = NOW()
1399                                                         WHERE $sql_exp
1400                                                         AND ref_id = id
1401                                                         AND owner_uid = ".$_SESSION["uid"]); */
1402                                         }
1403                                 }
1404                         } else { // tag
1405                                 db_query($link, "BEGIN");
1406
1407                                 $tag_name = db_escape_string($feed);
1408
1409                                 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1410                                         WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1411
1412                                 while ($line = db_fetch_assoc($result)) {
1413                                         db_query($link, "UPDATE ttrss_user_entries SET
1414                                                 unread = false, last_read = NOW() 
1415                                                 WHERE int_id = " . $line["post_int_id"]);
1416                                 }
1417                                 db_query($link, "COMMIT");
1418                         }
1419         }
1420
1421         function update_generic_feed($link, $feed, $cat_view) {
1422                         if ($cat_view) {
1423
1424                                 if ($feed > 0) {
1425                                         $cat_qpart = "cat_id = '$feed'";
1426                                 } else {
1427                                         $cat_qpart = "cat_id IS NULL";
1428                                 }
1429                                 
1430                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1431                                         WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1432
1433                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
1434                                         $feed_url = $tmp_line["feed_url"];
1435                                         update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1436                                 }
1437
1438                         } else {
1439                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1440                                         WHERE id = '$feed'");
1441                                 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");                                
1442                                 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1443                         }
1444         }
1445
1446         function getAllCounters($link) {
1447                 getLabelCounters($link);
1448                 getFeedCounters($link);
1449                 getTagCounters($link);
1450                 getGlobalCounters($link);
1451                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1452                         getCategoryCounters($link);
1453                 }
1454         }       
1455
1456         function getCategoryCounters($link) {
1457                 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id) 
1458                                 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id 
1459                                         AND unread = true)) AS unread FROM ttrss_feeds 
1460                         WHERE 
1461                                 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1462
1463                 while ($line = db_fetch_assoc($result)) {
1464                         $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1465                         print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1466                                 $line["unread"]."\"/>";
1467                 }
1468         }
1469
1470         function getCategoryUnread($link, $cat) {
1471
1472                 if ($cat != 0) {
1473                         $cat_query = "cat_id = '$cat'";
1474                 } else {
1475                         $cat_query = "cat_id IS NULL";
1476                 }
1477
1478                 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query 
1479                                 AND hidden = false
1480                                 AND owner_uid = " . $_SESSION["uid"]);
1481
1482                 $cat_feeds = array();
1483                 while ($line = db_fetch_assoc($result)) {
1484                         array_push($cat_feeds, "feed_id = " . $line["id"]);
1485                 }
1486
1487                 if (count($cat_feeds) == 0) return 0;
1488
1489                 $match_part = implode(" OR ", $cat_feeds);
1490
1491                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
1492                         FROM ttrss_user_entries 
1493                         WHERE   unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1494
1495                 $unread = 0;
1496
1497                 # this needs to be rewritten
1498                 while ($line = db_fetch_assoc($result)) {
1499                         $unread += $line["unread"];
1500                 }
1501
1502                 return $unread;
1503
1504         }
1505
1506         function getFeedUnread($link, $feed, $is_cat = false) {
1507                 $n_feed = sprintf("%d", $feed);
1508
1509                 if ($is_cat) {
1510                         return getCategoryUnread($link, $n_feed);               
1511                 } else if ($n_feed == -1) {
1512                         $match_part = "marked = true";
1513                 } else if ($n_feed > 0) {
1514
1515                         $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE parent_feed = '$n_feed'
1516                                         AND hidden = false
1517                                         AND owner_uid = " . $_SESSION["uid"]);
1518
1519                         if (db_num_rows($result) > 0) {
1520
1521                                 $linked_feeds = array();
1522                                 while ($line = db_fetch_assoc($result)) {
1523                                         array_push($linked_feeds, "feed_id = " . $line["id"]);
1524                                 }
1525                                 
1526                                 $match_part = implode(" OR ", $linked_feeds);
1527
1528                                 $result = db_query($link, "SELECT COUNT(int_id) AS unread 
1529                                         FROM ttrss_user_entries
1530                                         WHERE   unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1531
1532                                 $unread = 0;
1533
1534                                 # this needs to be rewritten
1535                                 while ($line = db_fetch_assoc($result)) {
1536                                         $unread += $line["unread"];
1537                                 }
1538
1539                                 return $unread;
1540
1541                         } else {
1542                                 $match_part = "feed_id = '$n_feed'";
1543                         }
1544                 } else if ($feed < -10) {
1545
1546                         $label_id = -$feed - 11;
1547
1548                         $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1549                                 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1550
1551                         $match_part = db_fetch_result($result, 0, "sql_exp");
1552                 }
1553
1554                 if ($match_part) {
1555                 
1556                         $result = db_query($link, "SELECT count(int_id) AS unread 
1557                                 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1558                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1559                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1560                                 ttrss_feeds.hidden = false AND
1561                                 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1562                                 
1563                 } else {
1564                 
1565                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1566                                 FROM ttrss_tags,ttrss_user_entries 
1567                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1568                                         ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1569                 }
1570                 
1571                 $unread = db_fetch_result($result, 0, "unread");
1572
1573                 return $unread;
1574         }
1575
1576         /* FIXME this needs reworking */
1577
1578         function getGlobalUnread($link, $user_id = false) {
1579
1580                 if (!$user_id) {
1581                         $user_id = $_SESSION["uid"];
1582                 }
1583
1584                 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1585                         WHERE unread = true AND 
1586                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
1587                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1588                         hidden = false AND
1589                         ttrss_user_entries.owner_uid = '$user_id'");
1590                 $c_id = db_fetch_result($result, 0, "c_id");
1591                 return $c_id;
1592         }
1593
1594         function getGlobalCounters($link, $global_unread = -1) {
1595                 if ($global_unread == -1) {     
1596                         $global_unread = getGlobalUnread($link);
1597                 }
1598                 print "<counter type=\"global\" id='global-unread' 
1599                         counter='$global_unread'/>";
1600
1601                 $result = db_query($link, "SELECT COUNT(id) AS fn FROM 
1602                         ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1603
1604                 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1605
1606                 print "<counter type=\"global\" id='subscribed-feeds' 
1607                         counter='$subscribed_feeds'/>";
1608
1609         }
1610
1611         function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1612
1613                 if ($smart_mode) {
1614                         if (!$_SESSION["tctr_last_value"]) {
1615                                 $_SESSION["tctr_last_value"] = array();
1616                         }
1617                 }
1618
1619                 $old_counters = $_SESSION["tctr_last_value"];
1620
1621                 $tctrs_modified = false;
1622
1623 /*              $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1624                         FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1625                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1626                         ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1627                         post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name 
1628                 UNION
1629                         select tag_name,0 as count FROM ttrss_tags
1630                         WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1631
1632                 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
1633                         FROM ttrss_user_entries WHERE int_id = post_int_id 
1634                                 AND unread = true)) AS count FROM ttrss_tags 
1635                         WHERE owner_uid = 2 GROUP BY tag_name ORDER BY tag_name");
1636                         
1637                 $tags = array();
1638
1639                 while ($line = db_fetch_assoc($result)) {
1640                         $tags[$line["tag_name"]] += $line["count"];
1641                 }
1642
1643                 foreach (array_keys($tags) as $tag) {
1644                         $unread = $tags[$tag];                  
1645
1646                         $tag = htmlspecialchars($tag);
1647
1648                         if (!$smart_mode || $old_counters[$tag] != $unread) {                   
1649                                 $old_counters[$tag] = $unread;
1650                                 $tctrs_modified = true;
1651                                 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1652                         }
1653
1654                 } 
1655
1656                 if ($smart_mode && $tctrs_modified) {
1657                         $_SESSION["tctr_last_value"] = $old_counters;
1658                 }
1659
1660         }
1661
1662         function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
1663
1664                 if ($smart_mode) {
1665                         if (!$_SESSION["lctr_last_value"]) {
1666                                 $_SESSION["lctr_last_value"] = array();
1667                         }
1668                 }
1669
1670                 $ret_arr = array();
1671                 
1672                 $old_counters = $_SESSION["lctr_last_value"];
1673                 $lctrs_modified = false;
1674
1675                 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1676                         WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND 
1677                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
1678                         unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1679
1680                 $count = db_fetch_result($result, 0, "count");
1681
1682                 if (!$ret_mode) {
1683                         print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1684                 } else {
1685                         $ret_arr["-1"]["counter"] = $count;
1686                         $ret_arr["-1"]["description"] = "Starred";
1687                 }
1688
1689                 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1690                         ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1691         
1692                 while ($line = db_fetch_assoc($result)) {
1693
1694                         $id = -$line["id"] - 11;
1695
1696                         $label_name = $line["description"];
1697
1698                         error_reporting (0);
1699
1700                         $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1701                                 WHERE (" . $line["sql_exp"] . ") AND unread = true AND 
1702                                 ttrss_feeds.hidden = false AND
1703                                 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1704                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1705                                 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1706
1707                         $count = db_fetch_result($tmp_result, 0, "count");
1708
1709                         if (!$smart_mode || $old_counters[$id] != $count) {     
1710                                 $old_counters[$id] = $count;
1711                                 $lctrs_modified = true;
1712                                 if (!$ret_mode) {
1713                                         print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1714                                 } else {
1715                                         $ret_arr[$id]["counter"] = $count;
1716                                         $ret_arr[$id]["description"] = $label_name;
1717                                 }
1718                         }
1719
1720                         error_reporting (DEFAULT_ERROR_LEVEL);
1721                 }
1722
1723                 if ($smart_mode && $lctrs_modified) {
1724                         $_SESSION["lctr_last_value"] = $old_counters;
1725                 }
1726
1727                 return $ret_arr;
1728         }
1729
1730 /*      function getFeedCounter($link, $id) {
1731         
1732                 $result = db_query($link, "SELECT 
1733                                 count(id) as count,last_error
1734                         FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1735                         WHERE feed_id = '$id' AND unread = true
1736                         AND ttrss_user_entries.feed_id = ttrss_feeds.id
1737                         AND ttrss_user_entries.ref_id = ttrss_entries.id");
1738         
1739                         $count = db_fetch_result($result, 0, "count");
1740                         $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1741                         
1742                         print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";           
1743         } */
1744
1745         function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1746
1747                 if ($smart_mode) {
1748                         if (!$_SESSION["fctr_last_value"]) {
1749                                 $_SESSION["fctr_last_value"] = array();
1750                         }
1751                 }
1752
1753                 $old_counters = $_SESSION["fctr_last_value"];
1754
1755                 $result = db_query($link, "SELECT id,last_error,parent_feed,
1756                         SUBSTRING(last_updated,1,19) AS last_updated,
1757                         (SELECT count(id) 
1758                                 FROM ttrss_entries,ttrss_user_entries 
1759                                 WHERE feed_id = ttrss_feeds.id AND 
1760                                         ttrss_user_entries.ref_id = ttrss_entries.id
1761                                 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1762                         FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1763                                 AND parent_feed IS NULL");
1764
1765                 $fctrs_modified = false;
1766
1767                 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1768
1769                 while ($line = db_fetch_assoc($result)) {
1770                 
1771                         $id = $line["id"];
1772                         $count = $line["count"];
1773                         $last_error = htmlspecialchars($line["last_error"]);
1774
1775                         if (get_pref($link, 'HEADLINES_SMART_DATE')) {
1776                                 $last_updated = smart_date_time(strtotime($line["last_updated"]));
1777                         } else {
1778                                 $last_updated = date($short_date, strtotime($line["last_updated"]));
1779                         }                               
1780
1781                         $has_img = is_file(ICONS_DIR . "/$id.ico");
1782
1783                         $tmp_result = db_query($link,
1784                                 "SELECT id,COUNT(unread) AS unread
1785                                 FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
1786                                         ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
1787                                 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
1788                         
1789                         if (db_num_rows($tmp_result) > 0) {                             
1790                                 while ($l = db_fetch_assoc($tmp_result)) {
1791                                         $count += $l["unread"];
1792                                 }
1793                         }
1794
1795                         if (!$smart_mode || $old_counters[$id] != $count) {
1796                                 $old_counters[$id] = $count;
1797                                 $fctrs_modified = true;
1798
1799                                 if ($last_error) {
1800                                         $error_part = "error=\"$last_error\"";
1801                                 } else {
1802                                         $error_part = "";
1803                                 }
1804
1805                                 if ($has_img) {
1806                                         $has_img_part = "hi=\"$has_img\"";
1807                                 } else {
1808                                         $has_img_part = "";
1809                                 }                               
1810
1811                                 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
1812                         }
1813                 }
1814
1815                 if ($smart_mode && $fctrs_modified) {
1816                         $_SESSION["fctr_last_value"] = $old_counters;
1817                 }
1818         }
1819
1820         function get_script_dt_add() {
1821                 if (strpos(VERSION, "99") === false) {
1822                         return VERSION;
1823                 } else {
1824                         return time();
1825                 }
1826         }
1827
1828         function get_pgsql_version($link) {
1829                 $result = db_query($link, "SELECT version() AS version");
1830                 $version = split(" ", db_fetch_result($result, 0, "version"));
1831                 return $version[1];
1832         }
1833
1834         function print_error_xml($code, $add_msg = "") {
1835                 global $ERRORS;
1836
1837                 $error_msg = $ERRORS[$code];
1838                 
1839                 if ($add_msg) {
1840                         $error_msg = "$error_msg; $add_msg";
1841                 }
1842                 
1843                 print "<rpc-reply>";
1844                 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
1845                 print "</rpc-reply>";
1846         }
1847
1848         function subscribe_to_feed($link, $feed_link, $cat_id = 0) {
1849         
1850                 if ($cat_id == "0" || !$cat_id) {
1851                         $cat_qpart = "NULL";
1852                 } else {
1853                         $cat_qpart = "'$cat_id'";
1854                 }
1855         
1856                 $result = db_query($link,
1857                         "SELECT id FROM ttrss_feeds 
1858                         WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
1859         
1860                 if (db_num_rows($result) == 0) {
1861                         
1862                         $result = db_query($link,
1863                                 "INSERT INTO ttrss_feeds (owner_uid,feed_url,title,cat_id) 
1864                                 VALUES ('".$_SESSION["uid"]."', '$feed_link', 
1865                                 '[Unknown]', $cat_qpart)");
1866         
1867                         $result = db_query($link,
1868                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link' 
1869                                 AND owner_uid = " . $_SESSION["uid"]);
1870         
1871                         $feed_id = db_fetch_result($result, 0, "id");
1872         
1873                         if ($feed_id) {
1874                                 update_rss_feed($link, $feed_link, $feed_id, true);
1875                         }
1876
1877                         return true;
1878                 } else {
1879                         return false;
1880                 }
1881         }
1882
1883         function print_feed_select($link, $id, $default_id = "", 
1884                 $attributes = "", $include_all_feeds = true) {
1885
1886                 print "<select id=\"$id\" name=\"$id\" $attributes>";
1887                 if ($include_all_feeds) { 
1888                         print "<option value=\"0\">All feeds</option>";
1889                 }
1890         
1891                 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1892                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1893
1894                 if (db_num_rows($result) > 0 && $include_all_feeds) {
1895                         print "<option disabled>--------</option>";
1896                 }
1897
1898                 while ($line = db_fetch_assoc($result)) {
1899                         if ($line["id"] == $default_id) {
1900                                 $is_selected = "selected";
1901                         } else {
1902                                 $is_selected = "";
1903                         }
1904                         printf("<option $is_selected value='%d'>%s</option>", 
1905                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
1906                 }
1907         
1908                 print "</select>";
1909         }
1910
1911         function print_feed_cat_select($link, $id, $default_id = "", 
1912                 $attributes = "", $include_all_cats = true) {
1913                 
1914                 print "<select id=\"$id\" name=\"$id\" $attributes>";
1915
1916                 if ($include_all_cats) {
1917                         print "<option value=\"0\">Uncategorized</option>";
1918                 }
1919
1920                 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
1921                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1922
1923                 if (db_num_rows($result) > 0 && $include_all_cats) {
1924                         print "<option disabled>--------</option>";
1925                 }
1926
1927                 while ($line = db_fetch_assoc($result)) {
1928                         if ($line["id"] == $default_id) {
1929                                 $is_selected = "selected";
1930                         } else {
1931                                 $is_selected = "";
1932                         }
1933                         printf("<option $is_selected value='%d'>%s</option>", 
1934                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
1935                 }
1936
1937                 print "</select>";
1938         }
1939         
1940         function checkbox_to_sql_bool($val) {
1941                 return ($val == "on") ? "true" : "false";
1942         }
1943
1944         function getFeedCatTitle($link, $id) {
1945                 if ($id == -1) {
1946                         return "Special";
1947                 } else if ($id < -10) {
1948                         return "Labels";
1949                 } else if ($id > 0) {
1950                         $result = db_query($link, "SELECT ttrss_feed_categories.title 
1951                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1952                                         cat_id = ttrss_feed_categories.id");
1953                         if (db_num_rows($result) == 1) {
1954                                 return db_fetch_result($result, 0, "title");
1955                         } else {
1956                                 return "Uncategorized";
1957                         }
1958                 } else {
1959                         return "getFeedCatTitle($id) failed";
1960                 }
1961
1962         }
1963
1964         function getFeedTitle($link, $id) {
1965                 if ($id == -1) {
1966                         return "Starred articles";
1967                 } else if ($id < -10) {
1968                         $label_id = -10 - $id;
1969                         $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
1970                         if (db_num_rows($result) == 1) {
1971                                 return db_fetch_result($result, 0, "description");
1972                         } else {
1973                                 return "Unknown label ($label_id)";
1974                         }
1975
1976                 } else if ($id > 0) {
1977                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1978                         if (db_num_rows($result) == 1) {
1979                                 return db_fetch_result($result, 0, "title");
1980                         } else {
1981                                 return "Unknown feed ($id)";
1982                         }
1983                 } else {
1984                         return "getFeedTitle($id) failed";
1985                 }
1986
1987         }
1988
1989         function get_session_cookie_name() {
1990                 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
1991         }
1992
1993         function print_init_params($link) {
1994                 print "<init-params>";
1995                 if ($_SESSION["stored-params"]) {
1996                         foreach (array_keys($_SESSION["stored-params"]) as $key) {
1997                                 if ($key) {
1998                                         $value = htmlspecialchars($_SESSION["stored-params"][$key]);
1999                                         print "<param key=\"$key\" value=\"$value\"/>";
2000                                 }
2001                         }
2002                 }
2003
2004                 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2005                 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2006                 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY . "\"/>";
2007
2008                 print "<param key=\"on_catchup_show_next_feed\" value=\"" . 
2009                         get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2010
2011                 print "<param key=\"hide_read_feeds\" value=\"" . 
2012                         sprintf("%d", get_pref($link, "HIDE_READ_FEEDS")) . "\"/>";
2013
2014                 print "<param key=\"feeds_sort_by_unread\" value=\"" . 
2015                         sprintf("%d", get_pref($link, "FEEDS_SORT_BY_UNREAD")) . "\"/>";
2016
2017                 print "</init-params>";
2018         }
2019
2020         function print_runtime_info($link) {
2021                 print "<runtime-info>";
2022                 if (ENABLE_UPDATE_DAEMON) {
2023                         print "<param key=\"daemon_is_running\" value=\"".
2024                                 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2025                 }
2026                 print "</runtime-info>";
2027         }
2028
2029         function getSearchSql($search, $match_on) {
2030
2031                 $search_query_part = "";
2032
2033                 $keywords = split(" ", $search);
2034                 $query_keywords = array();
2035
2036                 if ($match_on == "both") {
2037
2038                         foreach ($keywords as $k) {
2039                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2040                                         OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2041                         }
2042
2043                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2044
2045                 } else if ($match_on == "title") {
2046
2047                         foreach ($keywords as $k) {
2048                                 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2049                         }
2050
2051                         $search_query_part = implode("AND", $query_keywords) . " AND ";
2052
2053                 } else if ($match_on == "content") {
2054
2055                         foreach ($keywords as $k) {
2056                                 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2057                         }
2058                 }
2059
2060                 $search_query_part = implode("AND", $query_keywords);
2061
2062                 return $search_query_part;
2063         }
2064
2065         function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false) {
2066                         if ($search) {
2067                         
2068                                 $search_query_part = getSearchSql($search, $match_on);
2069                                 $search_query_part .= " AND ";
2070
2071                         } else {
2072                                 $search_query_part = "";
2073                         }
2074
2075                         $view_query_part = "";
2076         
2077                         if ($view_mode == "adaptive") {
2078                                 if ($search) {
2079                                         $view_query_part = " ";
2080                                 } else if ($feed != -1) {
2081                                         $unread = getFeedUnread($link, $feed, $cat_view);
2082                                         if ($unread > 0) {
2083                                                 $view_query_part = " unread = true AND ";
2084                                         }
2085                                 }
2086                         }
2087         
2088                         if ($view_mode == "marked") {
2089                                 $view_query_part = " marked = true AND ";
2090                         }
2091         
2092                         if ($view_mode == "unread") {
2093                                 $view_query_part = " unread = true AND ";
2094                         }
2095         
2096                         if ($limit > 0) {
2097                                 $limit_query_part = "LIMIT " . $limit;
2098                         } 
2099
2100                         $vfeed_query_part = "";
2101         
2102                         // override query strategy and enable feed display when searching globally
2103                         if ($search && $search_mode == "all_feeds") {
2104                                 $query_strategy_part = "ttrss_entries.id > 0";
2105                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
2106                         } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2107                                 $query_strategy_part = "ttrss_entries.id > 0";
2108                                 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2109                                         id = feed_id) as feed_title,";
2110                         } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2111         
2112                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";         
2113
2114                                 $tmp_result = false;
2115
2116                                 if ($cat_view) {
2117                                         $tmp_result = db_query($link, "SELECT id 
2118                                                 FROM ttrss_feeds WHERE cat_id = '$feed'");
2119                                 } else {
2120                                         $tmp_result = db_query($link, "SELECT id
2121                                                 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds 
2122                                                         WHERE id = '$feed') AND id != '$feed'");
2123                                 }
2124         
2125                                 $cat_siblings = array();
2126         
2127                                 if (db_num_rows($tmp_result) > 0) {
2128                                         while ($p = db_fetch_assoc($tmp_result)) {
2129                                                 array_push($cat_siblings, "feed_id = " . $p["id"]);
2130                                         }
2131         
2132                                         $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
2133                                                 $feed, implode(" OR ", $cat_siblings));
2134         
2135                                 } else {
2136                                         $query_strategy_part = "ttrss_entries.id > 0";
2137                                 }
2138                                 
2139                         } else if ($feed >= 0) {
2140         
2141                                 if ($cat_view) {
2142
2143                                         if ($feed > 0) {
2144                                                 $query_strategy_part = "cat_id = '$feed'";
2145                                         } else {
2146                                                 $query_strategy_part = "cat_id IS NULL";
2147                                         }
2148         
2149                                         $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2150
2151                                 } else {                
2152                                         $tmp_result = db_query($link, "SELECT id 
2153                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
2154                                                 ORDER BY cat_id,title");
2155                 
2156                                         $parent_ids = array();
2157                 
2158                                         if (db_num_rows($tmp_result) > 0) {
2159                                                 while ($p = db_fetch_assoc($tmp_result)) {
2160                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
2161                                                 }
2162                 
2163                                                 $query_strategy_part = sprintf("(feed_id = %d OR %s)", 
2164                                                         $feed, implode(" OR ", $parent_ids));
2165                 
2166                                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2167                                         } else {
2168                                                 $query_strategy_part = "feed_id = '$feed'";
2169                                         }
2170                                 }
2171                         } else if ($feed == -1) { // starred virtual feed
2172                                 $query_strategy_part = "marked = true";
2173                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2174                         } else if ($feed <= -10) { // labels
2175                                 $label_id = -$feed - 11;
2176         
2177                                 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2178                                         WHERE id = '$label_id'");
2179                         
2180                                 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2181                 
2182                                 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2183                         } else {
2184                                 $query_strategy_part = "id > 0"; // dumb
2185                         }
2186
2187                         if (get_pref($link, 'REVERSE_HEADLINES')) {
2188                                 $order_by = "updated";
2189                         } else {        
2190                                 $order_by = "updated DESC";
2191                         }
2192
2193                         if ($override_order) {
2194                                 $order_by = $override_order;
2195                         }
2196         
2197                         $feed_title = "";
2198
2199                         if ($search && $search_mode == "all_feeds") {
2200                                 $feed_title = "Global search results ($search)";
2201                         } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2202                                 $feed_title = "Tag search results ($search, $feed)";
2203                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2204                                 $feed_title = $feed;
2205                         } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2206         
2207                                 if ($cat_view) {
2208
2209                                         if ($feed != 0) {                       
2210                                                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2211                                                         WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2212                                                 $feed_title = db_fetch_result($result, 0, "title");
2213                                         } else {
2214                                                 $feed_title = "Uncategorized";
2215                                         }
2216
2217                                         if ($search) {
2218                                                 $feed_title = "Category search results ($search, $feed_title)";
2219                                         }
2220
2221                                 } else {
2222                                         
2223                                         $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds 
2224                                                 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2225                 
2226                                         $feed_title = db_fetch_result($result, 0, "title");
2227                                         $feed_site_url = db_fetch_result($result, 0, "site_url");
2228                                         $last_error = db_fetch_result($result, 0, "last_error");
2229
2230                                         if ($search) {
2231                                                 $feed_title = "Feed search results ($search, $feed_title)";
2232                                         }
2233                                 }
2234         
2235                         } else if ($feed == -1) {
2236                                 $feed_title = "Starred articles";
2237                         } else if ($feed < -10) {
2238                                 $label_id = -$feed - 11;
2239                                 $result = db_query($link, "SELECT description FROM ttrss_labels
2240                                         WHERE id = '$label_id'");
2241                                 $feed_title = db_fetch_result($result, 0, "description");
2242
2243                                 if ($search) {
2244                                         $feed_title = "Label search results ($search, $feed_title)";
2245                                 }
2246                         } else {
2247                                 $feed_title = "?";
2248                         }
2249
2250                         $feed_title = db_unescape_string($feed_title);
2251
2252                         if ($feed < -10) error_reporting (0);
2253
2254                         if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2255         
2256                                 if ($feed >= 0) {
2257                                         $feed_kind = "Feeds";
2258                                 } else {
2259                                         $feed_kind = "Labels";
2260                                 }
2261         
2262                                 $content_query_part = "content as content_preview,";
2263                                 
2264                                 $query = "SELECT 
2265                                                 ttrss_entries.id,ttrss_entries.title,
2266                                                 SUBSTRING(updated,1,16) as updated,
2267                                                 unread,feed_id,marked,link,last_read,
2268                                                 SUBSTRING(last_read,1,19) as last_read_noms,
2269                                                 $vfeed_query_part
2270                                                 $content_query_part
2271                                                 SUBSTRING(updated,1,19) as updated_noms
2272                                         FROM
2273                                                 ttrss_entries,ttrss_user_entries,ttrss_feeds
2274                                         WHERE
2275                                         ttrss_feeds.hidden = false AND
2276                                         ttrss_user_entries.feed_id = ttrss_feeds.id AND
2277                                         ttrss_user_entries.ref_id = ttrss_entries.id AND
2278                                         ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2279                                         $search_query_part
2280                                         $view_query_part
2281                                         $query_strategy_part ORDER BY $order_by
2282                                         $limit_query_part";
2283                                         
2284                                 $result = db_query($link, $query);
2285         
2286                                 if ($_GET["debug"]) print $query;
2287         
2288                         } else {
2289                                 // browsing by tag
2290         
2291                                 $feed_kind = "Tags";
2292         
2293                                 $result = db_query($link, "SELECT
2294                                         ttrss_entries.id as id,title,
2295                                         SUBSTRING(updated,1,16) as updated,
2296                                         unread,feed_id,
2297                                         marked,link,last_read,                          
2298                                         SUBSTRING(last_read,1,19) as last_read_noms,
2299                                         $vfeed_query_part
2300                                         $content_query_part
2301                                         SUBSTRING(updated,1,19) as updated_noms
2302                                         FROM
2303                                                 ttrss_entries,ttrss_user_entries,ttrss_tags
2304                                         WHERE
2305                                                 ref_id = ttrss_entries.id AND
2306                                                 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2307                                                 post_int_id = int_id AND tag_name = '$feed' AND
2308                                                 $view_query_part
2309                                                 $search_query_part
2310                                                 $query_strategy_part ORDER BY $order_by
2311                                         $limit_query_part");    
2312                         }
2313
2314                         return array($result, $feed_title, $feed_site_url, $last_error);
2315                         
2316         }
2317
2318         function generate_syndicated_feed($link, $feed, $is_cat,
2319                 $search, $search_mode, $match_on) {
2320
2321                 $qfh_ret = queryFeedHeadlines($link, $feed, 
2322                                 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2323
2324                 $result = $qfh_ret[0];
2325                 $feed_title = htmlspecialchars($qfh_ret[1]);
2326                 $feed_site_url = $qfh_ret[2];
2327                 $last_error = $qfh_ret[3];
2328
2329                 print "<rss version=\"2.0\">
2330                         <channel>
2331                         <title>$feed_title</title>
2332                         <link>$feed_site_url</link>
2333                         <generator>Tiny Tiny RSS v".VERSION."</generator>";
2334
2335                 while ($line = db_fetch_assoc($result)) {
2336                         print "<item>";
2337                         print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2338
2339                         $rfc822_date = date('r', strtotime($line["updated"]));
2340
2341                         print "<pubDate>$rfc822_date</pubDate>";
2342
2343                         print "<title>" . 
2344                                 htmlspecialchars($line["title"]) . "</title>";
2345
2346                         print "<description>" . 
2347                                 htmlspecialchars($line["content_preview"]) . "</description>";
2348
2349                         print "</item>";
2350                 }
2351
2352                 print "</channel></rss>";
2353
2354         }
2355
2356         function getCategoryTitle($link, $cat_id) {
2357
2358                 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2359                         id = '$cat_id'");
2360
2361                 if (db_num_rows($result) == 1) {
2362                         return db_fetch_result($result, 0, "title");
2363                 } else {
2364                         return "Uncategorized";
2365                 }
2366         }
2367
2368         function sanitize_rss($str) {
2369                 $res = "";
2370
2371                 $res = preg_replace('/<script.*?>/i', 
2372                                         "<p class=\"scriptWarn\">", $str);
2373
2374                 $res = preg_replace('/<\/script>/i', 
2375                         "</p>", $res);
2376
2377                 return $res;
2378         }
2379
2380         function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2381                 $tmp =  "New headlines for last 24 hours, as of " . date("Y/m/d H:m") . "\n";   
2382                 $tmp .= "=======================================================\n\n";
2383
2384                 if (DB_TYPE == "pgsql") {
2385                         $interval_query = "ttrss_entries.date_entered < NOW() - INTERVAL '$days days'";
2386                 } else if (DB_TYPE == "mysql") {
2387                         $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2388                 }
2389
2390                 $result = db_query($link, "SELECT ttrss_entries.title,
2391                                 ttrss_feeds.title AS feed_title,
2392                                 date_entered,
2393                                 link,
2394                                 SUBSTRING(last_updated,1,19) AS last_updated
2395                         FROM 
2396                                 ttrss_user_entries,ttrss_entries,ttrss_feeds 
2397                         WHERE 
2398                                 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id 
2399                                 AND $interval_query
2400                                 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2401                         LIMIT $limit");
2402
2403                 $cur_feed_title = "";
2404
2405                 while ($line = db_fetch_assoc($result)) {
2406                         $updated = smart_date_time(strtotime($line["last_updated"]));
2407                         $feed_title = $line["feed_title"];
2408
2409                         if ($cur_feed_title != $feed_title) {
2410                                 $cur_feed_title = $feed_title;
2411
2412                                 $tmp .= "$feed_title\n\n";
2413                         }
2414
2415                         $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2416                         $tmp .= "   " . trim($line["link"]) . "\n";
2417                         $tmp .= "\n";
2418                 }
2419
2420                 $tmp .= "--- \n";
2421                 $tmp .= "You have been sent this email because you have enabled\n".
2422                         "daily digests in Tiny Tiny RSS at " . DIGEST_HOSTNAME . "\n\n".
2423                         "To unsubscribe, visit your configuration options or contact\n".
2424                         "instance owner.\n";
2425                         
2426
2427                 return $tmp;
2428         }
2429
2430         function check_for_update($link) {
2431                 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2432
2433                 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
2434                         return;
2435                 }
2436
2437                 error_reporting(0);
2438                 $rss = fetch_rss($releases_feed);
2439                 error_reporting (DEFAULT_ERROR_LEVEL);
2440
2441                 if ($rss) {
2442
2443                         $items = $rss->items;
2444
2445                         if (!$items || !is_array($items)) $items = $rss->entries;
2446                         if (!$items || !is_array($items)) $items = $rss;
2447
2448                         if (!is_array($items) || count($items) == 0) {
2449                                 return;
2450                         }                       
2451
2452                         $last_item = $items[0];
2453
2454                         $last_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_item["title"]));
2455                         $cur_version = preg_replace("/\.99/", "", VERSION);
2456
2457                         $release_url = $last_item["link"];
2458
2459                         if ($cur_version != $last_version) {
2460                                 return "<div class=\"notice\"><a target=\"_new\" href=\"$release_url\">
2461                                                 New version of Tiny-Tiny RSS ($last_version) is available.</a></div>";
2462                         }                       
2463                 }
2464         }
2465 ?>