]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
move some cookies to init-params
[tt-rss.git] / functions.php
1 <?
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         require_once 'magpierss/rss_utils.inc';
16
17         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
18
19         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
20
21                 $rows = -1;
22
23                 if (DB_TYPE == "pgsql") {
24 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
25                                 marked = false AND feed_id = '$feed_id' AND
26                                 (SELECT date_entered FROM ttrss_entries WHERE
27                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
28
29                         $pg_version = get_pgsql_version($link);
30
31                         if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
32
33                                 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE 
34                                         ttrss_entries.id = ref_id AND 
35                                         marked = false AND 
36                                         feed_id = '$feed_id' AND 
37                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
38
39                         } else {
40
41                                 $result = db_query($link, "DELETE FROM ttrss_user_entries 
42                                         USING ttrss_entries 
43                                         WHERE ttrss_entries.id = ref_id AND 
44                                         marked = false AND 
45                                         feed_id = '$feed_id' AND 
46                                         ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
47                         }
48
49                         $rows = pg_affected_rows($result);
50                         
51                 } else {
52                 
53 /*                      $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
54                                 marked = false AND feed_id = '$feed_id' AND
55                                 (SELECT date_entered FROM ttrss_entries WHERE 
56                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
57
58                         $result = db_query($link, "DELETE FROM ttrss_user_entries 
59                                 USING ttrss_user_entries, ttrss_entries 
60                                 WHERE ttrss_entries.id = ref_id AND 
61                                 marked = false AND 
62                                 feed_id = '$feed_id' AND 
63                                 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
64                                         
65                         $rows = mysql_affected_rows($link);
66
67                 }
68
69                 if ($debug) {
70                         print "Purged feed $feed_id ($purge_interval): deleted $rows articles\n";
71                 }
72         }
73
74         function global_purge_old_posts($link, $do_output = false, $limit = false) {
75
76                 $random_qpart = sql_random_function();
77
78                 if ($limit) {
79                         $limit_qpart = "LIMIT $limit";
80                 } else {
81                         $limit_qpart = "";
82                 }
83                 
84                 $result = db_query($link, 
85                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds 
86                                 ORDER BY $random_qpart $limit_qpart");
87
88                 while ($line = db_fetch_assoc($result)) {
89
90                         $feed_id = $line["id"];
91                         $purge_interval = $line["purge_interval"];
92                         $owner_uid = $line["owner_uid"];
93
94                         if ($purge_interval == 0) {
95                         
96                                 $tmp_result = db_query($link, 
97                                         "SELECT value FROM ttrss_user_prefs WHERE
98                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
99
100                                 if (db_num_rows($tmp_result) != 0) {                    
101                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
102                                 }
103                         }
104
105                         if ($do_output) {
106 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
107                         }
108
109                         if ($purge_interval > 0) {
110                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
111                         }
112                 }       
113
114                 // purge orphaned posts in main content table
115                 db_query($link, "DELETE FROM ttrss_entries WHERE 
116                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
117
118         }
119
120         function purge_old_posts($link) {
121
122                 $user_id = $_SESSION["uid"];
123         
124                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
125                         WHERE owner_uid = '$user_id'");
126
127                 while ($line = db_fetch_assoc($result)) {
128
129                         $feed_id = $line["id"];
130                         $purge_interval = $line["purge_interval"];
131
132                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
133
134                         if ($purge_interval > 0) {
135                                 purge_feed($link, $feed_id, $purge_interval);
136                         }
137                 }       
138
139                 // purge orphaned posts in main content table
140                 db_query($link, "DELETE FROM ttrss_entries WHERE 
141                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
142         }
143
144         function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
145
146                 if (WEB_DEMO_MODE) return;
147
148                 if (!$user_id) {
149                         $user_id = $_SESSION["uid"];
150                         purge_old_posts($link);
151                 }
152
153 //              db_query($link, "BEGIN");
154
155                 if (MAX_UPDATE_TIME > 0) {
156                         if (DB_TYPE == "mysql") {
157                                 $q_order = "RAND()";
158                         } else {
159                                 $q_order = "RANDOM()";
160                         }
161                 } else {
162                         $q_order = "last_updated DESC";
163                 }
164
165                 $result = db_query($link, "SELECT feed_url,id,
166                         SUBSTRING(last_updated,1,19) AS last_updated,
167                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
168                         ORDER BY $q_order");
169
170                 $upd_start = time();
171
172                 while ($line = db_fetch_assoc($result)) {
173                         $upd_intl = $line["update_interval"];
174
175                         if (!$upd_intl || $upd_intl == 0) {
176                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id);
177                         }
178
179                         if ($upd_intl < 0) { 
180                                 // Updates for this feed are disabled
181                                 continue; 
182                         }
183
184                         if ($fetch || (!$line["last_updated"] || 
185                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
186
187 //                              print "<!-- feed: ".$line["feed_url"]." -->";
188
189                                 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
190
191                                 $upd_elapsed = time() - $upd_start;
192
193                                 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
194                                         return;
195                                 }
196                         }
197                 }
198
199 //              db_query($link, "COMMIT");
200
201         }
202
203         function check_feed_favicon($feed_url, $feed, $link) {
204                 $feed_url = str_replace("http://", "", $feed_url);
205                 $feed_url = preg_replace("/\/.*$/", "", $feed_url);
206                 
207                 $icon_url = "http://$feed_url/favicon.ico";
208                 $icon_file = ICONS_DIR . "/$feed.ico";
209
210                 if (!file_exists($icon_file)) {
211                                 
212                         error_reporting(0);
213                         $r = fopen($icon_url, "r");
214                         error_reporting (DEFAULT_ERROR_LEVEL);
215
216                         if ($r) {
217                                 $tmpfname = tempnam(TMP_DIRECTORY, "ttrssicon");
218                         
219                                 $t = fopen($tmpfname, "w");
220                                 
221                                 while (!feof($r)) {
222                                         $buf = fread($r, 16384);
223                                         fwrite($t, $buf);
224                                 }
225                                 
226                                 fclose($r);
227                                 fclose($t);
228
229                                 error_reporting(0);
230                                 if (!rename($tmpfname, $icon_file)) {
231                                         unlink($tmpfname);
232                                 }
233
234                                 chmod($icon_file, 0644);
235                                 
236                                 error_reporting (DEFAULT_ERROR_LEVEL);
237
238                         }       
239                 }
240         }
241
242         function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
243
244                 if (WEB_DEMO_MODE) return;
245
246                 if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
247                         return;                 
248                 }
249
250                 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
251                         FROM ttrss_feeds WHERE id = '$feed'");
252
253                 $auth_login = db_fetch_result($result, 0, "auth_login");
254                 $auth_pass = db_fetch_result($result, 0, "auth_pass");
255
256                 $update_interval = db_fetch_result($result, 0, "update_interval");
257
258                 if ($update_interval < 0) { return; }
259
260                 $feed = db_escape_string($feed);
261
262                 $fetch_url = $feed_url;
263
264                 if ($auth_login && $auth_pass) {
265                         $url_parts = array();
266                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
267
268                         if ($url_parts[1] && $url_parts[2]) {
269                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
270                         }
271
272                 }
273                 error_reporting(0);
274                 $rss = fetch_rss($fetch_url);
275
276                 error_reporting (DEFAULT_ERROR_LEVEL);
277
278                 $feed = db_escape_string($feed);
279
280                 if ($rss) {
281
282 //                      db_query($link, "BEGIN");
283
284                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
285                                 FROM ttrss_feeds WHERE id = '$feed'");
286
287                         $registered_title = db_fetch_result($result, 0, "title");
288                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
289                         $orig_site_url = db_fetch_result($result, 0, "site_url");
290
291                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
292
293                         if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid)) { 
294                                 check_feed_favicon($feed_url, $feed, $link);
295                         }
296
297                         if (!$registered_title || $registered_title == "[Unknown]") {
298                                 $feed_title = db_escape_string($rss->channel["title"]);
299                                 db_query($link, "UPDATE ttrss_feeds SET 
300                                         title = '$feed_title' WHERE id = '$feed'");
301                         }
302
303                         $site_url = $rss->channel["link"];
304                         // weird, weird Magpie
305                         if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
306
307                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
308                                 db_query($link, "UPDATE ttrss_feeds SET 
309                                         site_url = '$site_url' WHERE id = '$feed'");
310                         }
311
312 //                      print "I: " . $rss->channel["image"]["url"];
313
314                         $icon_url = $rss->image["url"];
315
316                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
317                                 $icon_url = db_escape_string($icon_url);
318                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
319                         }
320
321
322                         $filters = array();
323
324                         $result = db_query($link, "SELECT reg_exp,
325                                 ttrss_filter_types.name AS name,
326                                 ttrss_filter_actions.name AS action
327                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
328                                         owner_uid = $owner_uid AND
329                                         ttrss_filter_types.id = filter_type AND
330                                         ttrss_filter_actions.id = action_id AND
331                                 (feed_id IS NULL OR feed_id = '$feed')");
332
333                         while ($line = db_fetch_assoc($result)) {
334                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
335
336                                 $filter["reg_exp"] = $line["reg_exp"];
337                                 $filter["action"] = $line["action"];
338                                 
339                                 array_push($filters[$line["name"]], $filter);
340                         }
341
342                         $iterator = $rss->items;
343
344                         if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
345                         if (!$iterator || !is_array($iterator)) $iterator = $rss;
346
347                         if (!is_array($iterator)) {
348                                 db_query($link, "UPDATE ttrss_feeds 
349                                         SET last_error = 'Parse error: can\'t find any articles.'
350                                                 WHERE id = '$feed'");
351                                 return; // WTF?
352                         }
353
354                         foreach ($iterator as $item) {
355         
356                                 $entry_guid = $item["id"];
357         
358                                 if (!$entry_guid) $entry_guid = $item["guid"];
359                                 if (!$entry_guid) $entry_guid = $item["link"];
360
361                                 if (!$entry_guid) continue;
362
363                                 $entry_timestamp = "";
364
365                                 $rss_2_date = $item['pubdate'];
366                                 $rss_1_date = $item['dc']['date'];
367                                 $atom_date = $item['issued'];
368                                 if (!$atom_date) $atom_date = $item['updated'];
369                         
370                                 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
371                                 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
372                                 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
373                                 
374                                 if ($entry_timestamp == "") {
375                                         $entry_timestamp = time();
376                                         $no_orig_date = 'true';
377                                 } else {
378                                         $no_orig_date = 'false';
379                                 }
380
381                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
382
383                                 $entry_title = $item["title"];
384
385                                 // strange Magpie workaround
386                                 $entry_link = $item["link_"];
387                                 if (!$entry_link) $entry_link = $item["link"];
388
389                                 if (!$entry_title) continue;
390                                 if (!$entry_link) continue;
391
392                                 $entry_content = $item["content:escaped"];
393
394                                 if (!$entry_content) $entry_content = $item["content:encoded"];
395                                 if (!$entry_content) $entry_content = $item["content"];
396                                 if (!$entry_content) $entry_content = $item["summary"];
397                                 if (!$entry_content) $entry_content = $item["description"];
398
399 //                              if (!$entry_content) continue;
400
401                                 // WTF
402                                 if (is_array($entry_content)) {
403                                         $entry_content = $entry_content["encoded"];
404                                         if (!$entry_content) $entry_content = $entry_content["escaped"];
405                                 }
406
407 //                              print_r($item);
408 //                              print_r(htmlspecialchars($entry_content));
409 //                              print "<br>";
410
411                                 $entry_content_unescaped = $entry_content;
412                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
413
414                                 $entry_comments = $item["comments"];
415
416                                 $entry_author = db_escape_string($item['dc']['creator']);
417
418                                 $entry_guid = db_escape_string($entry_guid);
419
420                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
421                                         WHERE guid = '$entry_guid'");
422
423                                 $entry_content = db_escape_string($entry_content);
424                                 $entry_title = db_escape_string($entry_title);
425                                 $entry_link = db_escape_string($entry_link);
426                                 $entry_comments = db_escape_string($entry_comments);
427
428                                 $num_comments = db_escape_string($item["slash"]["comments"]);
429
430                                 if (!$num_comments) $num_comments = 0;
431
432                                 db_query($link, "BEGIN");
433
434                                 if (db_num_rows($result) == 0) {
435
436                                         // base post entry does not exist, create it
437
438                                         $result = db_query($link,
439                                                 "INSERT INTO ttrss_entries 
440                                                         (title,
441                                                         guid,
442                                                         link,
443                                                         updated,
444                                                         content,
445                                                         content_hash,
446                                                         no_orig_date,
447                                                         date_entered,
448                                                         comments,
449                                                         num_comments,
450                                                         author)
451                                                 VALUES
452                                                         ('$entry_title', 
453                                                         '$entry_guid', 
454                                                         '$entry_link',
455                                                         '$entry_timestamp_fmt', 
456                                                         '$entry_content', 
457                                                         '$content_hash',
458                                                         $no_orig_date, 
459                                                         NOW(), 
460                                                         '$entry_comments',
461                                                         '$num_comments',
462                                                         '$entry_author')");
463                                 } else {
464                                         // we keep encountering the entry in feeds, so we need to
465                                         // update date_entered column so that we don't get horrible
466                                         // dupes when the entry gets purged and reinserted again e.g.
467                                         // in the case of SLOW SLOW OMG SLOW updating feeds
468
469                                         $base_entry_id = db_fetch_result($result, 0, "id");
470
471                                         db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
472                                                 WHERE id = '$base_entry_id'");
473                                 }
474
475                                 // now it should exist, if not - bad luck then
476
477                                 $result = db_query($link, "SELECT 
478                                                 id,content_hash,no_orig_date,title,
479                                                 substring(date_entered,1,19) as date_entered,
480                                                 substring(updated,1,19) as updated,
481                                                 num_comments
482                                         FROM 
483                                                 ttrss_entries 
484                                         WHERE guid = '$entry_guid'");
485
486                                 if (db_num_rows($result) == 1) {
487
488                                         // this will be used below in update handler
489                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
490                                         $orig_title = db_fetch_result($result, 0, "title");
491                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
492                                         $orig_date_entered = strtotime(db_fetch_result($result, 
493                                                 0, "date_entered"));
494
495                                         $ref_id = db_fetch_result($result, 0, "id");
496
497                                         // check for user post link to main table
498
499                                         // do we allow duplicate posts with same GUID in different feeds?
500                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid)) {
501                                                 $dupcheck_qpart = "AND feed_id = '$feed'";
502                                         } else { 
503                                                 $dupcheck_qpart = "";
504                                         }
505
506 //                                      error_reporting(0);
507
508                                         $filter_name = get_filter_name($entry_title, $entry_content, 
509                                                 $entry_link, $filters);
510
511                                         if ($filter_name == "filter") {
512                                                 continue;
513                                         }
514
515 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
516
517                                         $result = db_query($link,
518                                                 "SELECT ref_id FROM ttrss_user_entries WHERE
519                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
520                                                         $dupcheck_qpart");
521                                                         
522                                         // okay it doesn't exist - create user entry
523                                         if (db_num_rows($result) == 0) {
524
525                                                 if ($filter_name != 'catchup') {
526                                                         $unread = 'true';
527                                                         $last_read_qpart = 'NULL';
528                                                 } else {
529                                                         $unread = 'false';
530                                                         $last_read_qpart = 'NOW()';
531                                                 }                                               
532
533                                                 if ($filter_name == 'mark') {
534                                                         $marked = 'true';
535                                                 } else {
536                                                         $marked = 'false';
537                                                 }
538                                                 
539                                                 $result = db_query($link,
540                                                         "INSERT INTO ttrss_user_entries 
541                                                                 (ref_id, owner_uid, feed_id, unread, last_read, marked) 
542                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
543                                                                 $last_read_qpart, $marked)");
544                                         }
545                                         
546                                         $post_needs_update = false;
547
548                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid) &&
549                                                 ($content_hash != $orig_content_hash)) {
550                                                 $post_needs_update = true;
551                                         }
552
553                                         if ($orig_title != $entry_title) {
554                                                 $post_needs_update = true;
555                                         }
556
557                                         if ($orig_num_comments != $num_comments) {
558                                                 $post_needs_update = true;
559                                         }
560
561 //                                      this doesn't seem to be very reliable
562 //
563 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
564 //                                              $post_needs_update = true;
565 //                                      }
566
567                                         // if post needs update, update it and mark all user entries 
568                                         // linking to this post as updated                                      
569                                         if ($post_needs_update) {
570
571 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
572
573                                                 db_query($link, "UPDATE ttrss_entries 
574                                                         SET title = '$entry_title', content = '$entry_content',
575                                                                 num_comments = '$num_comments'
576                                                         WHERE id = '$ref_id'");
577
578                                                 db_query($link, "UPDATE ttrss_user_entries 
579                                                         SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
580
581                                         }
582                                 }
583
584                                 db_query($link, "COMMIT");
585
586                                 /* taaaags */
587                                 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
588
589                                 $entry_tags = null;
590
591                                 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i", 
592                                         $entry_content_unescaped, $entry_tags);
593
594 //                              print "<br>$entry_title : $entry_content_unescaped<br>";
595 //                              print_r($entry_tags);
596 //                              print "<br>";
597
598                                 $entry_tags = $entry_tags[1];
599
600                                 if (count($entry_tags) > 0) {
601                                 
602                                         db_query($link, "BEGIN");
603                         
604                                         $result = db_query($link, "SELECT id,int_id 
605                                                 FROM ttrss_entries,ttrss_user_entries 
606                                                 WHERE guid = '$entry_guid' 
607                                                 AND feed_id = '$feed' AND ref_id = id
608                                                 AND owner_uid = '$owner_uid'");
609
610                                         if (db_num_rows($result) == 1) {
611
612                                                 $entry_id = db_fetch_result($result, 0, "id");
613                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
614                                                 
615                                                 foreach ($entry_tags as $tag) {
616                                                         $tag = db_escape_string(strtolower($tag));
617
618                                                         $tag = str_replace("+", " ", $tag);     
619                                                         $tag = str_replace("technorati tag: ", "", $tag);
620         
621                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
622                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
623                                                                 owner_uid = '$owner_uid' LIMIT 1");
624         
625         //                                              print db_fetch_result($result, 0, "id");
626         
627                                                         if ($result && db_num_rows($result) == 0) {
628                                                                 
629         //                                                      print "tagging $entry_id as $tag<br>";
630         
631                                                                 db_query($link, "INSERT INTO ttrss_tags 
632                                                                         (owner_uid,tag_name,post_int_id)
633                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
634                                                         }                                                       
635                                                 }
636                                         }
637                                         db_query($link, "COMMIT");
638                                 } 
639                         } 
640
641                         db_query($link, "UPDATE ttrss_feeds 
642                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
643
644 //                      db_query($link, "COMMIT");
645
646                 } else {
647                         $error_msg = db_escape_string(magpie_error());
648                         db_query($link, 
649                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
650                                         last_updated = NOW() WHERE id = '$feed'");
651                 }
652
653         }
654
655         function print_select($id, $default, $values, $attributes = "") {
656                 print "<select name=\"$id\" id=\"$id\" $attributes>";
657                 foreach ($values as $v) {
658                         if ($v == $default)
659                                 $sel = " selected";
660                          else
661                                 $sel = "";
662                         
663                         print "<option$sel>$v</option>";
664                 }
665                 print "</select>";
666         }
667
668         function print_select_hash($id, $default, $values, $attributes = "") {
669                 print "<select name=\"$id\" id='$id' $attributes>";
670                 foreach (array_keys($values) as $v) {
671                         if ($v == $default)
672                                 $sel = "selected";
673                          else
674                                 $sel = "";
675                         
676                         print "<option $sel value=\"$v\">".$values[$v]."</option>";
677                 }
678
679                 print "</select>";
680         }
681
682         function get_filter_name($title, $content, $link, $filters) {
683
684                 if ($filters["title"]) {
685                         foreach ($filters["title"] as $filter) {
686                                 $reg_exp = $filter["reg_exp"];                  
687                                 if (preg_match("/$reg_exp/i", $title)) {
688                                         return $filter["action"];
689                                 }
690                         }
691                 }
692
693                 if ($filters["content"]) {
694                         foreach ($filters["content"] as $filter) {
695                                 $reg_exp = $filter["reg_exp"];                  
696                                 if (preg_match("/$reg_exp/i", $content)) {
697                                         return $filter["action"];
698                                 }               
699                         }
700                 }
701
702                 if ($filters["both"]) {
703                         foreach ($filters["both"] as $filter) {                 
704                                 $reg_exp = $filter["reg_exp"];          
705                                 if (preg_match("/$reg_exp/i", $title) || 
706                                         preg_match("/$reg_exp/i", $content)) {
707                                         return $filter["action"];
708                                 }
709                         }
710                 }
711
712                 if ($filters["link"]) {
713                         $reg_exp = $filter["reg_exp"];
714                         foreach ($filters["link"] as $filter) {
715                                 $reg_exp = $filter["reg_exp"];
716                                 if (preg_match("/$reg_exp/i", $link)) {
717                                         return $filter["action"];
718                                 }
719                         }
720                 }
721
722                 return false;
723         }
724
725         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
726                 $rtl_content = false, $last_updated = false, $last_error = false) {
727
728                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
729                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
730                 } else {
731                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
732                 }
733
734                 if ($rtl_content) {
735                         $rtl_tag = "dir=\"rtl\"";
736                 } else {
737                         $rtl_tag = "dir=\"ltr\"";
738                 }
739
740                 if ($last_error) {
741                         $link_title = "Error: $last_error ($last_updated)";
742                 } else if ($last_updated) {
743                         $link_title = "Updated: $last_updated";
744                 }
745
746                 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\" href=\"javascript:viewfeed('$feed_id', 0);\">$feed_title</a>";
747
748                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
749                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
750                         print "$feed_icon";
751                 }
752
753                 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
754
755                 if ($unread != 0) {
756                         $fctr_class = "";
757                 } else {
758                         $fctr_class = "class=\"invisible\"";
759                 }
760
761                 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
762                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
763                 
764                 print "</li>";
765
766         }
767
768         function getmicrotime() {
769                 list($usec, $sec) = explode(" ",microtime());
770                 return ((float)$usec + (float)$sec);
771         }
772
773         function print_radio($id, $default, $values, $attributes = "") {
774                 foreach ($values as $v) {
775                 
776                         if ($v == $default)
777                                 $sel = "checked";
778                          else
779                                 $sel = "";
780
781                         if ($v == "Yes") {
782                                 $sel .= " value=\"1\"";
783                         } else {
784                                 $sel .= " value=\"0\"";
785                         }
786                         
787                         print "<input class=\"noborder\" 
788                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
789
790                 }
791         }
792
793         function initialize_user_prefs($link, $uid) {
794
795                 $uid = db_escape_string($uid);
796
797                 db_query($link, "BEGIN");
798
799                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
800                 
801                 $u_result = db_query($link, "SELECT pref_name 
802                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
803
804                 $active_prefs = array();
805
806                 while ($line = db_fetch_assoc($u_result)) {
807                         array_push($active_prefs, $line["pref_name"]);                  
808                 }
809
810                 while ($line = db_fetch_assoc($result)) {
811                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
812 //                              print "adding " . $line["pref_name"] . "<br>";
813
814                                 db_query($link, "INSERT INTO ttrss_user_prefs
815                                         (owner_uid,pref_name,value) VALUES 
816                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
817
818                         }
819                 }
820
821                 db_query($link, "COMMIT");
822
823         }
824
825         function lookup_user_id($link, $user) {
826
827                 $result = db_query($link, "SELECT id FROM ttrss_users WHERE 
828                         login = '$login'");
829
830                 if (db_num_rows($result) == 1) {
831                         return db_fetch_result($result, 0, "id");
832                 } else {
833                         return false;
834                 }
835         }
836
837         function authenticate_user($link, $login, $password) {
838
839                 $pwd_hash = 'SHA1:' . sha1($password);
840
841                 $result = db_query($link, "SELECT id,login,access_level FROM ttrss_users WHERE 
842                         login = '$login' AND pwd_hash = '$pwd_hash'");
843
844                 if (db_num_rows($result) == 1) {
845                         $_SESSION["uid"] = db_fetch_result($result, 0, "id");
846                         $_SESSION["name"] = db_fetch_result($result, 0, "login");
847                         $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
848
849                         db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
850                                 $_SESSION["uid"]);
851
852                         $user_theme = get_user_theme_path($link);
853
854                         $_SESSION["theme"] = $user_theme;
855                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
856
857                         initialize_user_prefs($link, $_SESSION["uid"]);
858
859                         return true;
860                 }
861
862                 return false;
863
864         }
865
866         function make_password($length = 8) {
867
868                 $password = "";
869                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
870                 
871         $i = 0; 
872     
873                 while ($i < $length) { 
874                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
875         
876                         if (!strstr($password, $char)) { 
877                                 $password .= $char;
878                                 $i++;
879                         }
880                 }
881                 return $password;
882         }
883
884         // this is called after user is created to initialize default feeds, labels
885         // or whatever else
886         
887         // user preferences are checked on every login, not here
888
889         function initialize_user($link, $uid) {
890
891                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
892                         values ('$uid','unread = true', 'Unread articles')");
893
894                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
895                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
896                 
897                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
898                         values ('$uid', 'Tiny Tiny RSS: New Releases',
899                         'http://tt-rss.spb.ru/releases.rss')");
900
901         }
902
903         function logout_user() {
904                 session_destroy();
905                 if (isset($_COOKIE[session_name()])) {
906                    setcookie(session_name(), '', time()-42000, '/');
907                 }
908         }
909
910         function get_script_urlpath() {
911                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
912         }
913
914         function get_login_redirect() {
915                 $server = $_SERVER["SERVER_NAME"];
916
917                 if (ENABLE_LOGIN_SSL) {
918                         $protocol = "https";
919                 } else {
920                         $protocol = "http";
921                 }               
922
923                 $url_path = get_script_urlpath();
924
925                 $redirect_uri = "$protocol://$server$url_path/login.php";
926
927                 return $redirect_uri;
928         }
929
930         function validate_session($link) {
931                 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
932                         if ($_SESSION["ip_address"]) {
933                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
934                                         return false;
935                                 }
936                         }
937                 }
938                 return true;
939         }
940
941         function basic_nosid_redirect_check() {
942                 if (!SINGLE_USER_MODE) {
943                         if (!$_COOKIE[get_session_cookie_name()]) {
944                                 $redirect_uri = get_login_redirect();
945                                 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
946                                 header("Location: $redirect_uri?rt=$return_to");
947                                 exit;
948                         }
949                 }
950         }
951
952         function login_sequence($link) {
953                 if (!SINGLE_USER_MODE) {
954
955                         if (!validate_session($link)) {
956                                 logout_user();
957                                 $redirect_uri = get_login_redirect();
958                                 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
959                                 header("Location: $redirect_uri?rt=$return_to");
960                                 exit;
961                         }
962
963                         if (!USE_HTTP_AUTH) {
964                                 if (!$_SESSION["uid"]) {
965                                         $redirect_uri = get_login_redirect();
966                                         $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
967                                         header("Location: $redirect_uri?rt=$return_to");
968                                         exit;
969                                 }
970                         } else {
971                                 if (!$_SESSION["uid"]) {
972                                         if (!$_SERVER["PHP_AUTH_USER"]) {
973
974                                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
975                                                 header('HTTP/1.0 401 Unauthorized');
976                                                 exit;
977                                                 
978                                         } else {
979                                                 $auth_result = authenticate_user($link, 
980                                                         $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
981
982                                                 if (!$auth_result) {
983                                                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
984                                                         header('HTTP/1.0 401 Unauthorized');
985                                                         exit;
986                                                 }
987                                         }
988                                 }                               
989                         }
990                 } else {
991                         $_SESSION["uid"] = 1;
992                         $_SESSION["name"] = "admin";
993                         initialize_user_prefs($link, 1); 
994                 }
995         }
996
997         function truncate_string($str, $max_len) {
998                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
999                         return mb_substr($str, 0, $max_len, "utf-8") . "...";
1000                 } else {
1001                         return $str;
1002                 }
1003         }
1004
1005         function get_user_theme_path($link) {
1006                 $result = db_query($link, "SELECT theme_path 
1007                         FROM 
1008                                 ttrss_themes,ttrss_users
1009                         WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1010                 if (db_num_rows($result) != 0) {
1011                         return db_fetch_result($result, 0, "theme_path");
1012                 } else {
1013                         return null;
1014                 }
1015         }
1016
1017         function smart_date_time($timestamp) {
1018                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1019                         return date("G:i", $timestamp);
1020                 } else if (date("Y", $timestamp) == date("Y")) {
1021                         return date("M d, G:i", $timestamp);
1022                 } else {
1023                         return date("Y/m/d G:i", $timestamp);
1024                 }
1025         }
1026
1027         function smart_date($timestamp) {
1028                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1029                         return "Today";
1030                 } else if (date("Y", $timestamp) == date("Y")) {
1031                         return date("D m", $timestamp);
1032                 } else {
1033                         return date("Y/m/d", $timestamp);
1034                 }
1035         }
1036
1037         function sql_bool_to_string($s) {
1038                 if ($s == "t" || $s == "1") {
1039                         return "true";
1040                 } else {
1041                         return "false";
1042                 }
1043         }
1044
1045         function sql_bool_to_bool($s) {
1046                 if ($s == "t" || $s == "1") {
1047                         return true;
1048                 } else {
1049                         return false;
1050                 }
1051         }
1052         
1053
1054         function toggleEvenOdd($a) {
1055                 if ($a == "even") 
1056                         return "odd";
1057                 else
1058                         return "even";
1059         }
1060
1061         function sanity_check($link) {
1062
1063                 $error_code = 0;
1064                 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1065                 $schema_version = db_fetch_result($result, 0, "schema_version");
1066
1067                 if ($schema_version != SCHEMA_VERSION) {
1068                         $error_code = 5;
1069                 }
1070
1071                 if ($error_code != 0) {
1072                         print_error_xml(5);
1073                         return false;
1074                 } else {
1075                         return true;
1076                 } 
1077         }
1078
1079         function file_is_locked($filename) {
1080                 error_reporting(0);
1081                 $fp = fopen($filename, "r");
1082                 error_reporting(DEFAULT_ERROR_LEVEL);
1083                 if ($fp) {
1084                         if (flock($fp, LOCK_EX | LOCK_NB)) {
1085                                 flock($fp, LOCK_UN);
1086                                 fclose($fp);
1087                                 return false;
1088                         }
1089                         fclose($fp);
1090                         return true;
1091                 }
1092                 return false;
1093         }
1094
1095         function make_lockfile($filename) {
1096                 $fp = fopen($filename, "w");
1097
1098                 if (flock($fp, LOCK_EX | LOCK_NB)) {            
1099                         return $fp;
1100                 } else {
1101                         return false;
1102                 }
1103         }
1104
1105         function sql_random_function() {
1106                 if (DB_TYPE == "mysql") {
1107                         return "RAND()";
1108                 } else {
1109                         return "RANDOM()";
1110                 }
1111         }
1112
1113         function catchup_feed($link, $feed, $cat_view) {
1114                         if (preg_match("/^[0-9][0-9]*$/", $feed) != false && $feed >= 0) {
1115                         
1116                                 if ($cat_view) {
1117
1118                                         if ($feed > 0) {
1119                                                 $cat_qpart = "cat_id = '$feed'";
1120                                         } else {
1121                                                 $cat_qpart = "cat_id IS NULL";
1122                                         }
1123                                         
1124                                         $tmp_result = db_query($link, "SELECT id 
1125                                                 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " . 
1126                                                 $_SESSION["uid"]);
1127
1128                                         while ($tmp_line = db_fetch_assoc($tmp_result)) {
1129
1130                                                 $tmp_feed = $tmp_line["id"];
1131
1132                                                 db_query($link, "UPDATE ttrss_user_entries 
1133                                                         SET unread = false,last_read = NOW() 
1134                                                         WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1135                                         }
1136
1137                                 } else if ($feed > 0) {
1138
1139                                         $tmp_result = db_query($link, "SELECT id 
1140                                                 FROM ttrss_feeds WHERE parent_feed = '$feed'
1141                                                 ORDER BY cat_id,title");
1142
1143                                         $parent_ids = array();
1144
1145                                         if (db_num_rows($tmp_result) > 0) {
1146                                                 while ($p = db_fetch_assoc($tmp_result)) {
1147                                                         array_push($parent_ids, "feed_id = " . $p["id"]);
1148                                                 }
1149
1150                                                 $children_qpart = implode(" OR ", $parent_ids);
1151                                                 
1152                                                 db_query($link, "UPDATE ttrss_user_entries 
1153                                                         SET unread = false,last_read = NOW() 
1154                                                         WHERE (feed_id = '$feed' OR $children_qpart) 
1155                                                         AND owner_uid = " . $_SESSION["uid"]);
1156
1157                                         } else {                                                
1158                                                 db_query($link, "UPDATE ttrss_user_entries 
1159                                                         SET unread = false,last_read = NOW() 
1160                                                         WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1161                                         }
1162                                                 
1163                                 } else if ($feed < 0 && $feed > -10) { // special, like starred
1164
1165                                         if ($feed == -1) {
1166                                                 db_query($link, "UPDATE ttrss_user_entries 
1167                                                         SET unread = false,last_read = NOW()
1168                                                         WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1169                                         }
1170                         
1171                                 } else if ($feed < -10) { // label
1172
1173                                         // TODO make this more efficient
1174
1175                                         $label_id = -$feed - 11;
1176
1177                                         $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1178                                                 WHERE id = '$label_id'");                                       
1179
1180                                         if ($tmp_result) {
1181                                                 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1182
1183                                                 db_query($link, "BEGIN");
1184
1185                                                 $tmp2_result = db_query($link,
1186                                                         "SELECT 
1187                                                                 int_id 
1188                                                         FROM 
1189                                                                 ttrss_user_entries,ttrss_entries 
1190                                                         WHERE
1191                                                                 ref_id = id AND 
1192                                                                 $sql_exp AND
1193                                                                 owner_uid = " . $_SESSION["uid"]);
1194
1195                                                 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1196                                                         db_query($link, "UPDATE 
1197                                                                 ttrss_user_entries 
1198                                                         SET 
1199                                                                 unread = false, last_read = NOW()
1200                                                         WHERE
1201                                                                 int_id = " . $tmp_line["int_id"]);
1202                                                 }
1203                                                                 
1204                                                 db_query($link, "COMMIT");
1205
1206 /*                                              db_query($link, "UPDATE ttrss_user_entries,ttrss_entries 
1207                                                         SET unread = false,last_read = NOW()
1208                                                         WHERE $sql_exp
1209                                                         AND ref_id = id
1210                                                         AND owner_uid = ".$_SESSION["uid"]); */
1211                                         }
1212                                 }
1213                         } else { // tag
1214                                 db_query($link, "BEGIN");
1215
1216                                 $tag_name = db_escape_string($feed);
1217
1218                                 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1219                                         WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1220
1221                                 while ($line = db_fetch_assoc($result)) {
1222                                         db_query($link, "UPDATE ttrss_user_entries SET
1223                                                 unread = false, last_read = NOW() 
1224                                                 WHERE int_id = " . $line["post_int_id"]);
1225                                 }
1226                                 db_query($link, "COMMIT");
1227                         }
1228         }
1229
1230         function update_generic_feed($link, $feed, $cat_view) {
1231                         if ($cat_view) {
1232
1233                                 if ($feed > 0) {
1234                                         $cat_qpart = "cat_id = '$feed'";
1235                                 } else {
1236                                         $cat_qpart = "cat_id IS NULL";
1237                                 }
1238                                 
1239                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1240                                         WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1241
1242                                 while ($tmp_line = db_fetch_assoc($tmp_result)) {                                       
1243                                         $feed_url = $tmp_line["feed_url"];
1244                                         update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1245                                 }
1246
1247                         } else {
1248                                 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1249                                         WHERE id = '$feed'");
1250                                 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");                                
1251                                 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1252                         }
1253         }
1254
1255         function getAllCounters($link) {
1256                 getLabelCounters($link);
1257                 getFeedCounters($link);
1258                 getTagCounters($link);
1259                 getGlobalCounters($link);
1260                 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1261                         getCategoryCounters($link);
1262                 }
1263         }       
1264
1265         function getCategoryCounters($link) {
1266                 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id) 
1267                                 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id 
1268                                         AND unread = true)) AS unread FROM ttrss_feeds 
1269                         WHERE 
1270                                 owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1271
1272                 while ($line = db_fetch_assoc($result)) {
1273                         $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1274                         print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1275                                 $line["unread"]."\"/>";
1276                 }
1277         }
1278
1279         function getFeedUnread($link, $feed) {
1280                 $n_feed = sprintf("%d", $feed);
1281         
1282                 if ($n_feed == -1) {
1283                         $match_part = "marked = true";
1284                 } else if ($feed > 0) {
1285                         $match_part = "feed_id = '$n_feed'";
1286                 } else if ($feed < -10) {
1287                         $label_id = -$feed - 11;
1288
1289                         $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1290                                 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1291
1292                         $match_part = db_fetch_result($result, 0, "sql_exp");
1293                 }
1294
1295                 if ($match_part) {
1296                 
1297                         $result = db_query($link, "SELECT count(int_id) AS unread 
1298                                 FROM ttrss_user_entries 
1299                                 WHERE   unread = true AND $match_part AND owner_uid = " . $_SESSION["uid"]);
1300                                 
1301                 } else {
1302                 
1303                         $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1304                                 FROM ttrss_tags,ttrss_user_entries 
1305                                 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1306                                         ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1307                 }
1308                 
1309                 $unread = db_fetch_result($result, 0, "unread");
1310                 return $unread;
1311         }
1312
1313         /* FIXME this needs reworking */
1314
1315         function getGlobalUnread($link) {
1316                 $result = db_query($link, "SELECT count(id) as c_id FROM ttrss_entries,ttrss_user_entries
1317                         WHERE unread = true AND 
1318                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1319                         owner_uid = " . $_SESSION["uid"]);
1320                 $c_id = db_fetch_result($result, 0, "c_id");
1321                 return $c_id;
1322         }
1323
1324         function getGlobalCounters($link, $global_unread = -1) {
1325                 if ($global_unread == -1) {     
1326                         $global_unread = getGlobalUnread($link);
1327                 }
1328                 print "<counter type=\"global\" id='global-unread' counter='$global_unread'/>";
1329         }
1330
1331         function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1332
1333                 if ($smart_mode) {
1334                         if (!$_SESSION["tctr_last_value"]) {
1335                                 $_SESSION["tctr_last_value"] = array();
1336                         }
1337                 }
1338
1339                 $old_counters = $_SESSION["tctr_last_value"];
1340
1341                 $tctrs_modified = false;
1342
1343 /*              $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1344                         FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1345                         ttrss_user_entries.ref_id = ttrss_entries.id AND 
1346                         ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1347                         post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name 
1348                 UNION
1349                         select tag_name,0 as count FROM ttrss_tags
1350                         WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1351
1352                 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id) 
1353                         FROM ttrss_user_entries WHERE int_id = post_int_id 
1354                                 AND unread = true)) AS count FROM ttrss_tags 
1355                         WHERE owner_uid = 2 GROUP BY tag_name ORDER BY tag_name");
1356                         
1357                 $tags = array();
1358
1359                 while ($line = db_fetch_assoc($result)) {
1360                         $tags[$line["tag_name"]] += $line["count"];
1361                 }
1362
1363                 foreach (array_keys($tags) as $tag) {
1364                         $unread = $tags[$tag];                  
1365
1366                         $tag = htmlspecialchars($tag);
1367
1368                         if (!$smart_mode || $old_counters[$tag] != $unread) {                   
1369                                 $old_counters[$tag] = $unread;
1370                                 $tctrs_modified = true;
1371                                 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1372                         }
1373
1374                 } 
1375
1376                 if ($smart_mode && $tctrs_modified) {
1377                         $_SESSION["tctr_last_value"] = $old_counters;
1378                 }
1379
1380         }
1381
1382         function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1383
1384                 if ($smart_mode) {
1385                         if (!$_SESSION["lctr_last_value"]) {
1386                                 $_SESSION["lctr_last_value"] = array();
1387                         }
1388                 }
1389
1390                 $old_counters = $_SESSION["lctr_last_value"];
1391                 $lctrs_modified = false;
1392
1393                 $result = db_query($link, "SELECT count(id) as count FROM ttrss_entries,ttrss_user_entries
1394                         WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND 
1395                         unread = true AND owner_uid = ".$_SESSION["uid"]);
1396
1397                 $count = db_fetch_result($result, 0, "count");
1398
1399                 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1400
1401                 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1402                         ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1403         
1404                 while ($line = db_fetch_assoc($result)) {
1405
1406                         $id = -$line["id"] - 11;
1407
1408                         error_reporting (0);
1409
1410                         $tmp_result = db_query($link, "SELECT count(id) as count FROM ttrss_user_entries,ttrss_entries
1411                                 WHERE (" . $line["sql_exp"] . ") AND unread = true AND 
1412                                 ttrss_user_entries.ref_id = ttrss_entries.id AND 
1413                                 owner_uid = ".$_SESSION["uid"]);
1414
1415                         $count = db_fetch_result($tmp_result, 0, "count");
1416
1417                         if (!$smart_mode || $old_counters[$id] != $count) {     
1418                                 $old_counters[$id] = $count;
1419                                 $lctrs_modified = true;
1420                                 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1421                         }
1422
1423                         error_reporting (DEFAULT_ERROR_LEVEL);
1424                 }
1425
1426                 if ($smart_mode && $lctrs_modified) {
1427                         $_SESSION["lctr_last_value"] = $old_counters;
1428                 }
1429         }
1430
1431 /*      function getFeedCounter($link, $id) {
1432         
1433                 $result = db_query($link, "SELECT 
1434                                 count(id) as count,last_error
1435                         FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1436                         WHERE feed_id = '$id' AND unread = true
1437                         AND ttrss_user_entries.feed_id = ttrss_feeds.id
1438                         AND ttrss_user_entries.ref_id = ttrss_entries.id");
1439         
1440                         $count = db_fetch_result($result, 0, "count");
1441                         $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1442                         
1443                         print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";           
1444         } */
1445
1446         function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1447
1448                 if ($smart_mode) {
1449                         if (!$_SESSION["fctr_last_value"]) {
1450                                 $_SESSION["fctr_last_value"] = array();
1451                         }
1452                 }
1453
1454                 $old_counters = $_SESSION["fctr_last_value"];
1455
1456                 $result = db_query($link, "SELECT id,last_error,parent_feed,
1457                         SUBSTRING(last_updated,1,19) AS last_updated,
1458                         (SELECT count(id) 
1459                                 FROM ttrss_entries,ttrss_user_entries 
1460                                 WHERE feed_id = ttrss_feeds.id AND 
1461                                         ttrss_user_entries.ref_id = ttrss_entries.id
1462                                 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1463                         FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1464                                 AND parent_feed IS NULL");
1465
1466                 $fctrs_modified = false;
1467
1468                 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1469
1470                 while ($line = db_fetch_assoc($result)) {
1471                 
1472                         $id = $line["id"];
1473                         $count = $line["count"];
1474                         $last_error = htmlspecialchars($line["last_error"]);
1475
1476                         if (get_pref($link, 'HEADLINES_SMART_DATE')) {
1477                                 $last_updated = smart_date_time(strtotime($line["last_updated"]));
1478                         } else {
1479                                 $last_updated = date($short_date, strtotime($line["last_updated"]));
1480                         }                               
1481
1482                         $has_img = is_file(ICONS_DIR . "/$id.ico");
1483
1484                         $tmp_result = db_query($link,
1485                                 "SELECT id,COUNT(unread) AS unread
1486                                 FROM ttrss_feeds LEFT JOIN ttrss_user_entries 
1487                                         ON (ttrss_feeds.id = ttrss_user_entries.feed_id) 
1488                                 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
1489                         
1490                         if (db_num_rows($tmp_result) > 0) {                             
1491                                 while ($l = db_fetch_assoc($tmp_result)) {
1492                                         $count += $l["unread"];
1493                                 }
1494                         }
1495
1496                         if (!$smart_mode || $old_counters[$id] != $count) {
1497                                 $old_counters[$id] = $count;
1498                                 $fctrs_modified = true;
1499
1500                                 if ($last_error) {
1501                                         $error_part = "error=\"$last_error\"";
1502                                 } else {
1503                                         $error_part = "";
1504                                 }
1505
1506                                 if ($has_img) {
1507                                         $has_img_part = "hi=\"$has_img\"";
1508                                 } else {
1509                                         $has_img_part = "";
1510                                 }                               
1511
1512                                 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
1513                         }
1514                 }
1515
1516                 if ($smart_mode && $fctrs_modified) {
1517                         $_SESSION["fctr_last_value"] = $old_counters;
1518                 }
1519         }
1520
1521         function get_script_dt_add() {
1522                 if (strpos(VERSION, "99") === false) {
1523                         return VERSION;
1524                 } else {
1525                         return time();
1526                 }
1527         }
1528
1529         function get_pgsql_version($link) {
1530                 $result = db_query($link, "SELECT version() AS version");
1531                 $version = split(" ", db_fetch_result($result, 0, "version"));
1532                 return $version[1];
1533         }
1534
1535         function print_error_xml($code, $add_msg = "") {
1536                 global $ERRORS;
1537
1538                 $error_msg = $ERRORS[$code];
1539                 
1540                 if ($add_msg) {
1541                         $error_msg = "$error_msg; $add_msg";
1542                 }
1543                 
1544                 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
1545         }
1546
1547         function subscribe_to_feed($link, $feed_link, $cat_id = 0) {
1548         
1549                 if ($cat_id == "0" || !$cat_id) {
1550                         $cat_qpart = "NULL";
1551                 } else {
1552                         $cat_qpart = "'$cat_id'";
1553                 }
1554         
1555                 $result = db_query($link,
1556                         "SELECT id FROM ttrss_feeds 
1557                         WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
1558         
1559                 if (db_num_rows($result) == 0) {
1560                         
1561                         $result = db_query($link,
1562                                 "INSERT INTO ttrss_feeds (owner_uid,feed_url,title,cat_id) 
1563                                 VALUES ('".$_SESSION["uid"]."', '$feed_link', 
1564                                 '[Unknown]', $cat_qpart)");
1565         
1566                         $result = db_query($link,
1567                                 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link' 
1568                                 AND owner_uid = " . $_SESSION["uid"]);
1569         
1570                         $feed_id = db_fetch_result($result, 0, "id");
1571         
1572                         if ($feed_id) {
1573                                 update_rss_feed($link, $feed_link, $feed_id, true);
1574                         }
1575
1576                         return true;
1577                 } else {
1578                         return false;
1579                 }
1580         }
1581
1582         function print_feed_select($link, $id, $default_id = "", 
1583                 $attributes = "", $include_all_feeds = true) {
1584
1585                 print "<select id=\"$id\" name=\"$id\" $attributes>";
1586                 if ($include_all_feeds) { 
1587                         print "<option value=\"0\">All feeds</option>";
1588                 }
1589         
1590                 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1591                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1592
1593                 if (db_num_rows($result) > 0 && $include_all_feeds) {
1594                         print "<option disabled>--------</option>";
1595                 }
1596
1597                 while ($line = db_fetch_assoc($result)) {
1598                         if ($line["id"] == $default_id) {
1599                                 $is_selected = "selected";
1600                         } else {
1601                                 $is_selected = "";
1602                         }
1603                         printf("<option $is_selected value='%d'>%s</option>", 
1604                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
1605                 }
1606         
1607                 print "</select>";
1608         }
1609
1610         function print_feed_cat_select($link, $id, $default_id = "", 
1611                 $attributes = "", $include_all_cats = true) {
1612                 
1613                 print "<select id=\"$id\" name=\"$id\" $attributes>";
1614
1615                 if ($include_all_cats) {
1616                         print "<option value=\"0\">Uncategorized</option>";
1617                 }
1618
1619                 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
1620                         WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1621
1622                 if (db_num_rows($result) > 0 && $include_all_cats) {
1623                         print "<option disabled>--------</option>";
1624                 }
1625
1626                 while ($line = db_fetch_assoc($result)) {
1627                         if ($line["id"] == $default_id) {
1628                                 $is_selected = "selected";
1629                         } else {
1630                                 $is_selected = "";
1631                         }
1632                         printf("<option $is_selected value='%d'>%s</option>", 
1633                                 $line["id"], htmlspecialchars(db_unescape_string($line["title"])));
1634                 }
1635
1636                 print "</select>";
1637         }
1638         
1639         function checkbox_to_sql_bool($val) {
1640                 return ($val == "on") ? "true" : "false";
1641         }
1642
1643         function getFeedCatTitle($link, $id) {
1644                 if ($id == -1) {
1645                         return "Special";
1646                 } else if ($id < -10) {
1647                         return "Labels";
1648                 } else if ($id > 0) {
1649                         $result = db_query($link, "SELECT ttrss_feed_categories.title 
1650                                 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1651                                         cat_id = ttrss_feed_categories.id");
1652                         if (db_num_rows($result) == 1) {
1653                                 return db_fetch_result($result, 0, "title");
1654                         } else {
1655                                 return "Uncategorized";
1656                         }
1657                 } else {
1658                         return "getFeedCatTitle($id) failed";
1659                 }
1660
1661         }
1662
1663         function getFeedTitle($link, $id) {
1664                 if ($id == -1) {
1665                         return "Starred articles";
1666                 } else if ($id < -10) {
1667                         $label_id = -10 - $id;
1668                         $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
1669                         if (db_num_rows($result) == 1) {
1670                                 return db_fetch_result($result, 0, "description");
1671                         } else {
1672                                 return "Unknown label ($label_id)";
1673                         }
1674
1675                 } else if ($id > 0) {
1676                         $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1677                         if (db_num_rows($result) == 1) {
1678                                 return db_fetch_result($result, 0, "title");
1679                         } else {
1680                                 return "Unknown feed ($id)";
1681                         }
1682                 } else {
1683                         return "getFeedTitle($id) failed";
1684                 }
1685
1686         }
1687
1688         function get_session_cookie_name() {
1689                 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
1690         }
1691
1692         function print_init_params($link) {
1693                 print "<init-params>";
1694                 if ($_SESSION["stored-params"]) {
1695                         foreach (array_keys($_SESSION["stored-params"]) as $key) {
1696                                 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
1697                                 print "<param key=\"$key\" value=\"$value\"/>";
1698                         }
1699                 }
1700
1701                 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
1702                 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
1703
1704                 print "<param key=\"on_catchup_show_next_feed\" value=\"" . 
1705                         get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
1706
1707                 print "</init-params>";
1708         }
1709 ?>