]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
tag display now works
[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
13         require_once 'magpierss/rss_utils.inc';
14
15         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
16
17         function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
18
19                 $rows = -1;
20
21                 if (DB_TYPE == "pgsql") {
22                         $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
23                                 marked = false AND feed_id = '$feed_id' AND
24                                 (SELECT date_entered FROM ttrss_entries WHERE
25                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'");
26
27                         $rows = pg_affected_rows($result);
28                         
29                 } else {
30                         $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
31                                 marked = false AND feed_id = '$feed_id' AND
32                                 (SELECT date_entered FROM ttrss_entries WHERE 
33                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
34                         $rows = mysql_affected_rows($link);
35
36                 }
37
38                 if ($debug) {
39                         print "Purged feed $feed_id ($purge_interval): deleted $rows articles\n";
40                 }
41         }
42
43         function global_purge_old_posts($link, $do_output = false) {
44
45                 $result = db_query($link, 
46                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds ORDER BY id");
47
48                 while ($line = db_fetch_assoc($result)) {
49
50                         $feed_id = $line["id"];
51                         $purge_interval = $line["purge_interval"];
52                         $owner_uid = $line["owner_uid"];
53
54                         if ($purge_interval == 0) {
55                         
56                                 $tmp_result = db_query($link, 
57                                         "SELECT value FROM ttrss_user_prefs WHERE
58                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
59
60                                 if (db_num_rows($tmp_result) != 0) {                    
61                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
62                                 }
63                         }
64
65                         if ($do_output) {
66 //                              print "Feed $feed_id: purge interval = $purge_interval\n";
67                         }
68
69                         if ($purge_interval > 0) {
70                                 purge_feed($link, $feed_id, $purge_interval, $do_output);
71                         }
72                 }       
73
74                 // purge orphaned posts in main content table
75                 db_query($link, "DELETE FROM ttrss_entries WHERE 
76                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
77
78         }
79
80         function purge_old_posts($link) {
81
82                 $user_id = $_SESSION["uid"];
83         
84                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
85                         WHERE owner_uid = '$user_id'");
86
87                 while ($line = db_fetch_assoc($result)) {
88
89                         $feed_id = $line["id"];
90                         $purge_interval = $line["purge_interval"];
91
92                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
93
94                         if ($purge_interval > 0) {
95                                 purge_feed($link, $feed_id, $purge_interval);
96                         }
97                 }       
98
99                 // purge orphaned posts in main content table
100                 db_query($link, "DELETE FROM ttrss_entries WHERE 
101                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
102         }
103
104         function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
105
106                 if (WEB_DEMO_MODE) return;
107
108                 if (!$user_id) {
109                         $user_id = $_SESSION["uid"];
110                         purge_old_posts($link);
111                 }
112
113 //              db_query($link, "BEGIN");
114
115                 if (MAX_UPDATE_TIME > 0) {
116                         if (DB_TYPE == "mysql") {
117                                 $q_order = "RAND()";
118                         } else {
119                                 $q_order = "RANDOM()";
120                         }
121                 } else {
122                         $q_order = "last_updated DESC";
123                 }
124
125                 $result = db_query($link, "SELECT feed_url,id,
126                         SUBSTRING(last_updated,1,19) AS last_updated,
127                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
128                         ORDER BY $q_order");
129
130                 $upd_start = time();
131
132                 while ($line = db_fetch_assoc($result)) {
133                         $upd_intl = $line["update_interval"];
134
135                         if (!$upd_intl || $upd_intl == 0) {
136                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id);
137                         }
138
139                         if ($upd_intl < 0) { 
140                                 // Updates for this feed are disabled
141                                 continue; 
142                         }
143
144                         if ($fetch || (!$line["last_updated"] || 
145                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
146
147 //                              print "<!-- feed: ".$line["feed_url"]." -->";
148
149                                 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
150
151                                 $upd_elapsed = time() - $upd_start;
152
153                                 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
154                                         return;
155                                 }
156                         }
157                 }
158
159 //              db_query($link, "COMMIT");
160
161         }
162
163         function check_feed_favicon($feed_url, $feed, $link) {
164                 $feed_url = str_replace("http://", "", $feed_url);
165                 $feed_url = preg_replace("/\/.*$/", "", $feed_url);
166                 
167                 $icon_url = "http://$feed_url/favicon.ico";
168                 $icon_file = ICONS_DIR . "/$feed.ico";
169
170                 if (!file_exists($icon_file)) {
171                                 
172                         error_reporting(0);
173                         $r = fopen($icon_url, "r");
174                         error_reporting (DEFAULT_ERROR_LEVEL);
175
176                         if ($r) {
177                                 $tmpfname = tempnam(TMP_DIRECTORY, "ttrssicon");
178                         
179                                 $t = fopen($tmpfname, "w");
180                                 
181                                 while (!feof($r)) {
182                                         $buf = fread($r, 16384);
183                                         fwrite($t, $buf);
184                                 }
185                                 
186                                 fclose($r);
187                                 fclose($t);
188
189                                 error_reporting(0);
190                                 if (!rename($tmpfname, $icon_file)) {
191                                         unlink($tmpfname);
192                                 }
193
194                                 chmod($icon_file, 0644);
195                                 
196                                 error_reporting (DEFAULT_ERROR_LEVEL);
197
198                         }       
199                 }
200         }
201
202         function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
203
204                 if (WEB_DEMO_MODE) return;
205
206                 if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
207                         return;                 
208                 }
209
210                 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass  
211                         FROM ttrss_feeds WHERE id = '$feed'");
212
213                 $auth_login = db_fetch_result($result, 0, "auth_login");
214                 $auth_pass = db_fetch_result($result, 0, "auth_pass");
215
216                 $update_interval = db_fetch_result($result, 0, "update_interval");
217
218                 if ($update_interval < 0) { return; }
219
220                 $feed = db_escape_string($feed);
221
222                 $fetch_url = $feed_url;
223
224                 if ($auth_login && $auth_pass) {
225                         $url_parts = array();
226                         preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
227
228                         if ($url_parts[1] && $url_parts[2]) {
229                                 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
230                         }
231
232                 }
233                 error_reporting(0);
234                 $rss = fetch_rss($fetch_url);
235
236                 error_reporting (DEFAULT_ERROR_LEVEL);
237
238                 $feed = db_escape_string($feed);
239
240                 if ($rss) {
241
242                         db_query($link, "BEGIN");
243
244                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
245                                 FROM ttrss_feeds WHERE id = '$feed'");
246
247                         $registered_title = db_fetch_result($result, 0, "title");
248                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
249                         $orig_site_url = db_fetch_result($result, 0, "site_url");
250
251                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
252
253                         if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid)) { 
254                                 check_feed_favicon($feed_url, $feed, $link);
255                         }
256
257                         if (!$registered_title || $registered_title == "[Unknown]") {
258                                 $feed_title = db_escape_string($rss->channel["title"]);
259                                 db_query($link, "UPDATE ttrss_feeds SET 
260                                         title = '$feed_title' WHERE id = '$feed'");
261                         }
262
263                         $site_url = $rss->channel["link"];
264                         // weird, weird Magpie
265                         if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
266
267                         if ($site_url && $orig_site_url != db_escape_string($site_url)) {
268                                 db_query($link, "UPDATE ttrss_feeds SET 
269                                         site_url = '$site_url' WHERE id = '$feed'");
270                         }
271
272 //                      print "I: " . $rss->channel["image"]["url"];
273
274                         $icon_url = $rss->image["url"];
275
276                         if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
277                                 $icon_url = db_escape_string($icon_url);
278                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
279                         }
280
281
282                         $filters = array();
283
284                         $result = db_query($link, "SELECT reg_exp,
285                                 ttrss_filter_types.name AS name,
286                                 ttrss_filter_actions.name AS action
287                                 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE                                        
288                                         owner_uid = $owner_uid AND
289                                         ttrss_filter_types.id = filter_type AND
290                                         ttrss_filter_actions.id = action_id AND
291                                 (feed_id IS NULL OR feed_id = '$feed')");
292
293                         while ($line = db_fetch_assoc($result)) {
294                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
295
296                                 $filter["reg_exp"] = $line["reg_exp"];
297                                 $filter["action"] = $line["action"];
298                                 
299                                 array_push($filters[$line["name"]], $filter);
300                         }
301
302                         $iterator = $rss->items;
303
304                         if (!$iterator) $iterator = $rss->entries;
305                         if (!$iterator) $iterator = $rss;                       
306
307                         foreach ($iterator as $item) {
308         
309                                 $entry_guid = $item["id"];
310         
311                                 if (!$entry_guid) $entry_guid = $item["guid"];
312                                 if (!$entry_guid) $entry_guid = $item["link"];
313
314                                 if (!$entry_guid) continue;
315
316                                 $entry_timestamp = "";
317
318                                 $rss_2_date = $item['pubdate'];
319                                 $rss_1_date = $item['dc']['date'];
320                                 $atom_date = $item['issued'];
321                                 if (!$atom_date) $atom_date = $item['updated'];
322                         
323                                 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
324                                 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
325                                 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
326                                 
327                                 if ($entry_timestamp == "") {
328                                         $entry_timestamp = time();
329                                         $no_orig_date = 'true';
330                                 } else {
331                                         $no_orig_date = 'false';
332                                 }
333
334                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
335
336                                 $entry_title = $item["title"];
337
338                                 // strange Magpie workaround
339                                 $entry_link = $item["link_"];
340                                 if (!$entry_link) $entry_link = $item["link"];
341
342                                 if (!$entry_title) continue;
343                                 if (!$entry_link) continue;
344
345                                 $entry_content = $item["content:escaped"];
346
347                                 if (!$entry_content) $entry_content = $item["content:encoded"];
348                                 if (!$entry_content) $entry_content = $item["content"];
349                                 if (!$entry_content) $entry_content = $item["summary"];
350                                 if (!$entry_content) $entry_content = $item["description"];
351
352 //                              if (!$entry_content) continue;
353
354                                 // WTF
355                                 if (is_array($entry_content)) {
356                                         $entry_content = $entry_content["encoded"];
357                                         if (!$entry_content) $entry_content = $entry_content["escaped"];
358                                 }
359
360 //                              print_r($item);
361 //                              print_r(htmlspecialchars($entry_content));
362 //                              print "<br>";
363
364                                 $entry_content_unescaped = $entry_content;
365                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
366
367                                 $entry_comments = $item["comments"];
368
369                                 $entry_author = db_escape_string($item['dc']['creator']);
370
371                                 $entry_guid = db_escape_string($entry_guid);
372
373                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
374                                         WHERE guid = '$entry_guid'");
375
376                                 $entry_content = db_escape_string($entry_content);
377                                 $entry_title = db_escape_string($entry_title);
378                                 $entry_link = db_escape_string($entry_link);
379                                 $entry_comments = db_escape_string($entry_comments);
380
381                                 $num_comments = db_escape_string($item["slash"]["comments"]);
382
383                                 if (!$num_comments) $num_comments = 0;
384
385                                 if (db_num_rows($result) == 0) {
386
387                                         // base post entry does not exist, create it
388
389                                         $result = db_query($link,
390                                                 "INSERT INTO ttrss_entries 
391                                                         (title,
392                                                         guid,
393                                                         link,
394                                                         updated,
395                                                         content,
396                                                         content_hash,
397                                                         no_orig_date,
398                                                         date_entered,
399                                                         comments,
400                                                         num_comments,
401                                                         author)
402                                                 VALUES
403                                                         ('$entry_title', 
404                                                         '$entry_guid', 
405                                                         '$entry_link',
406                                                         '$entry_timestamp_fmt', 
407                                                         '$entry_content', 
408                                                         '$content_hash',
409                                                         $no_orig_date, 
410                                                         NOW(), 
411                                                         '$entry_comments',
412                                                         '$num_comments',
413                                                         '$entry_author')");
414                                 } else {
415                                         // we keep encountering the entry in feeds, so we need to
416                                         // update date_entered column so that we don't get horrible
417                                         // dupes when the entry gets purged and reinserted again e.g.
418                                         // in the case of SLOW SLOW OMG SLOW updating feeds
419
420                                         $base_entry_id = db_fetch_result($result, 0, "id");
421
422                                         db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
423                                                 WHERE id = '$base_entry_id'");
424                                 }
425
426                                 // now it should exist, if not - bad luck then
427
428                                 $result = db_query($link, "SELECT 
429                                                 id,content_hash,no_orig_date,title,
430                                                 substring(date_entered,1,19) as date_entered,
431                                                 substring(updated,1,19) as updated,
432                                                 num_comments
433                                         FROM 
434                                                 ttrss_entries 
435                                         WHERE guid = '$entry_guid'");
436
437                                 if (db_num_rows($result) == 1) {
438
439                                         // this will be used below in update handler
440                                         $orig_content_hash = db_fetch_result($result, 0, "content_hash");
441                                         $orig_title = db_fetch_result($result, 0, "title");
442                                         $orig_num_comments = db_fetch_result($result, 0, "num_comments");
443                                         $orig_date_entered = strtotime(db_fetch_result($result, 
444                                                 0, "date_entered"));
445
446                                         $ref_id = db_fetch_result($result, 0, "id");
447
448                                         // check for user post link to main table
449
450                                         // do we allow duplicate posts with same GUID in different feeds?
451                                         if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid)) {
452                                                 $dupcheck_qpart = "AND feed_id = '$feed'";
453                                         } else { 
454                                                 $dupcheck_qpart = "";
455                                         }
456
457 //                                      error_reporting(0);
458
459                                         $filter_name = get_filter_name($entry_title, $entry_content, 
460                                                 $entry_link, $filters);
461
462                                         if ($filter_name == "filter") {
463                                                 continue;
464                                         }
465
466 //                                      error_reporting (DEFAULT_ERROR_LEVEL);
467
468                                         $result = db_query($link,
469                                                 "SELECT ref_id FROM ttrss_user_entries WHERE
470                                                         ref_id = '$ref_id' AND owner_uid = '$owner_uid'
471                                                         $dupcheck_qpart");
472                                                         
473                                         // okay it doesn't exist - create user entry
474                                         if (db_num_rows($result) == 0) {
475
476                                                 if ($filter_name != 'catchup') {
477                                                         $unread = 'true';
478                                                         $last_read_qpart = 'NULL';
479                                                 } else {
480                                                         $unread = 'false';
481                                                         $last_read_qpart = 'NOW()';
482                                                 }                                               
483                                                 
484                                                 $result = db_query($link,
485                                                         "INSERT INTO ttrss_user_entries 
486                                                                 (ref_id, owner_uid, feed_id, unread, last_read) 
487                                                         VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
488                                                                 $last_read_qpart)");
489                                         }
490                                         
491                                         $post_needs_update = false;
492
493                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid) &&
494                                                 ($content_hash != $orig_content_hash)) {
495                                                 $post_needs_update = true;
496                                         }
497
498                                         if ($orig_title != $entry_title) {
499                                                 $post_needs_update = true;
500                                         }
501
502                                         if ($orig_num_comments != $num_comments) {
503                                                 $post_needs_update = true;
504                                         }
505
506 //                                      this doesn't seem to be very reliable
507 //
508 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
509 //                                              $post_needs_update = true;
510 //                                      }
511
512                                         // if post needs update, update it and mark all user entries 
513                                         // linking to this post as updated                                      
514                                         if ($post_needs_update) {
515
516 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
517
518                                                 db_query($link, "UPDATE ttrss_entries 
519                                                         SET title = '$entry_title', content = '$entry_content',
520                                                                 num_comments = '$num_comments'
521                                                         WHERE id = '$ref_id'");
522
523                                                 db_query($link, "UPDATE ttrss_user_entries 
524                                                         SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
525
526                                         }
527                                 }
528
529                                 /* taaaags */
530                                 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
531
532                                 $entry_tags = null;
533
534                                 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i", 
535                                         $entry_content_unescaped, $entry_tags);
536
537 //                              print "<br>$entry_title : $entry_content_unescaped<br>";
538 //                              print_r($entry_tags);
539 //                              print "<br>";
540
541                                 $entry_tags = $entry_tags[1];
542
543                                 if (count($entry_tags) > 0) {
544                                 
545                                         $result = db_query($link, "SELECT id,int_id 
546                                                 FROM ttrss_entries,ttrss_user_entries 
547                                                 WHERE guid = '$entry_guid' 
548                                                 AND feed_id = '$feed' AND ref_id = id
549                                                 AND owner_uid = '$owner_uid'");
550
551                                         if (db_num_rows($result) == 1) {
552
553                                                 $entry_id = db_fetch_result($result, 0, "id");
554                                                 $entry_int_id = db_fetch_result($result, 0, "int_id");
555                                                 
556                                                 foreach ($entry_tags as $tag) {
557                                                         $tag = db_escape_string(strtolower($tag));
558
559                                                         $tag = str_replace("+", " ", $tag);     
560                                                         $tag = str_replace("technorati tag: ", "", $tag);
561         
562                                                         $result = db_query($link, "SELECT id FROM ttrss_tags            
563                                                                 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
564                                                                 owner_uid = '$owner_uid' LIMIT 1");
565         
566         //                                              print db_fetch_result($result, 0, "id");
567         
568                                                         if ($result && db_num_rows($result) == 0) {
569                                                                 
570         //                                                      print "tagging $entry_id as $tag<br>";
571         
572                                                                 db_query($link, "INSERT INTO ttrss_tags 
573                                                                         (owner_uid,tag_name,post_int_id)
574                                                                         VALUES ('$owner_uid','$tag', '$entry_int_id')");
575                                                         }                                                       
576                                                 }
577                                         }
578                                 } 
579                         } 
580
581                         db_query($link, "UPDATE ttrss_feeds 
582                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
583
584                         db_query($link, "COMMIT");
585
586                 } else {
587                         $error_msg = db_escape_string(magpie_error());
588                         db_query($link, 
589                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
590                                         last_updated = NOW() WHERE id = '$feed'");
591                 }
592
593         }
594
595         function print_select($id, $default, $values, $attributes = "") {
596                 print "<select id=\"$id\" $attributes>";
597                 foreach ($values as $v) {
598                         if ($v == $default)
599                                 $sel = " selected";
600                          else
601                                 $sel = "";
602                         
603                         print "<option$sel>$v</option>";
604                 }
605                 print "</select>";
606         }
607
608         function get_filter_name($title, $content, $link, $filters) {
609
610                 if ($filters["title"]) {
611                         foreach ($filters["title"] as $filter) {
612                                 $reg_exp = $filter["reg_exp"];                  
613                                 if (preg_match("/$reg_exp/i", $title)) {
614                                         return $filter["action"];
615                                 }
616                         }
617                 }
618
619                 if ($filters["content"]) {
620                         foreach ($filters["content"] as $filter) {
621                                 $reg_exp = $filter["reg_exp"];                  
622                                 if (preg_match("/$reg_exp/i", $content)) {
623                                         return $filter["action"];
624                                 }               
625                         }
626                 }
627
628                 if ($filters["both"]) {
629                         foreach ($filters["both"] as $filter) {                 
630                                 $reg_exp = $filter["reg_exp"];          
631                                 if (preg_match("/$reg_exp/i", $title) || 
632                                         preg_match("/$reg_exp/i", $content)) {
633                                         return $filter["action"];
634                                 }
635                         }
636                 }
637
638                 if ($filters["link"]) {
639                         $reg_exp = $filter["reg_exp"];
640                         foreach ($filters["link"] as $filter) {
641                                 $reg_exp = $filter["reg_exp"];
642                                 if (preg_match("/$reg_exp/i", $link)) {
643                                         return $filter["action"];
644                                 }
645                         }
646                 }
647
648                 return false;
649         }
650
651         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link) {
652
653                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
654                                 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
655                 } else {
656                         $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
657                 }
658
659                 $feed = "<a href=\"javascript:viewfeed('$feed_id', 0);\">$feed_title</a>";
660
661                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
662                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
663                         print "$feed_icon";
664                 }
665
666                 print "<span id=\"FEEDN-$feed_id\">$feed</span>";
667
668                 if ($unread != 0) {
669                         $fctr_class = "";
670                 } else {
671                         $fctr_class = "class=\"invisible\"";
672                 }
673
674                 print "<span $fctr_class id=\"FEEDCTR-$feed_id\">
675                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
676                 
677                 print "</li>";
678
679         }
680
681         function getmicrotime() {
682                 list($usec, $sec) = explode(" ",microtime());
683                 return ((float)$usec + (float)$sec);
684         }
685
686         function print_radio($id, $default, $values, $attributes = "") {
687                 foreach ($values as $v) {
688                 
689                         if ($v == $default)
690                                 $sel = "checked";
691                          else
692                                 $sel = "";
693
694                         if ($v == "Yes") {
695                                 $sel .= " value=\"1\"";
696                         } else {
697                                 $sel .= " value=\"0\"";
698                         }
699                         
700                         print "<input class=\"noborder\" 
701                                 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
702
703                 }
704         }
705
706         function initialize_user_prefs($link, $uid) {
707
708                 $uid = db_escape_string($uid);
709
710                 db_query($link, "BEGIN");
711
712                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
713                 
714                 $u_result = db_query($link, "SELECT pref_name 
715                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
716
717                 $active_prefs = array();
718
719                 while ($line = db_fetch_assoc($u_result)) {
720                         array_push($active_prefs, $line["pref_name"]);                  
721                 }
722
723                 while ($line = db_fetch_assoc($result)) {
724                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
725 //                              print "adding " . $line["pref_name"] . "<br>";
726
727                                 db_query($link, "INSERT INTO ttrss_user_prefs
728                                         (owner_uid,pref_name,value) VALUES 
729                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
730
731                         }
732                 }
733
734                 db_query($link, "COMMIT");
735
736         }
737         
738         function authenticate_user($link, $login, $password) {
739
740                 $pwd_hash = 'SHA1:' . sha1($password);
741
742                 $result = db_query($link, "SELECT id,login,access_level FROM ttrss_users WHERE 
743                         login = '$login' AND ((pwd_hash = '$password' AND '$password' = 'password')
744                                 OR pwd_hash = '$pwd_hash')");
745
746                 if (db_num_rows($result) == 1) {
747                         $_SESSION["uid"] = db_fetch_result($result, 0, "id");
748                         $_SESSION["name"] = db_fetch_result($result, 0, "login");
749                         $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
750
751                         db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
752                                 $_SESSION["uid"]);
753
754                         $user_theme = get_user_theme_path($link);
755
756                         $_SESSION["theme"] = $user_theme;
757                         $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
758
759                         initialize_user_prefs($link, $_SESSION["uid"]);
760
761                         return true;
762                 }
763
764                 return false;
765
766         }
767
768         function make_password($length = 8) {
769
770                 $password = "";
771                 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ"; 
772                 
773         $i = 0; 
774     
775                 while ($i < $length) { 
776                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
777         
778                         if (!strstr($password, $char)) { 
779                                 $password .= $char;
780                                 $i++;
781                         }
782                 }
783                 return $password;
784         }
785
786         // this is called after user is created to initialize default feeds, labels
787         // or whatever else
788         
789         // user preferences are checked on every login, not here
790
791         function initialize_user($link, $uid) {
792
793                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
794                         values ('$uid','unread = true', 'Unread articles')");
795
796                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
797                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
798                 
799                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
800                         values ('$uid', 'Tiny Tiny RSS: New Releases',
801                         'http://tt-rss.spb.ru/releases.rss')");
802
803         }
804
805         function logout_user() {
806                 session_destroy();
807                 if (isset($_COOKIE[session_name()])) {
808                    setcookie(session_name(), '', time()-42000, '/');
809                 }
810         }
811
812         function get_script_urlpath() {
813                 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
814         }
815
816         function get_login_redirect() {
817                 $server = $_SERVER["SERVER_NAME"];
818
819                 if (ENABLE_LOGIN_SSL) {
820                         $protocol = "https";
821                 } else {
822                         $protocol = "http";
823                 }               
824
825                 $url_path = get_script_urlpath();
826
827                 $redirect_uri = "$protocol://$server$url_path/login.php";
828
829                 return $redirect_uri;
830         }
831
832         function validate_session($link) {
833                 if (SESSION_CHECK_ADDRESS && !DATABASE_BACKED_SESSIONS && $_SESSION["uid"]) {
834                         if ($_SESSION["ip_address"]) {
835                                 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
836                                         return false;
837                                 }
838                         }
839                 }
840                 return true;
841         }
842
843         function login_sequence($link) {
844                 if (!SINGLE_USER_MODE) {
845
846                         if (!validate_session($link)) {
847                                 logout_user();
848                                 $redirect_uri = get_login_redirect();
849                                 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
850                                 header("Location: $redirect_uri?rt=$return_to");
851                                 exit;
852                         }
853
854                         if (!USE_HTTP_AUTH) {
855                                 if (!$_SESSION["uid"]) {
856                                         $redirect_uri = get_login_redirect();
857                                         $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
858                                         header("Location: $redirect_uri?rt=$return_to");
859                                         exit;
860                                 }
861                         } else {
862                                 if (!$_SESSION["uid"]) {
863                                         if (!$_SERVER["PHP_AUTH_USER"]) {
864
865                                                 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
866                                                 header('HTTP/1.0 401 Unauthorized');
867                                                 exit;
868                                                 
869                                         } else {
870                                                 $auth_result = authenticate_user($link, 
871                                                         $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
872
873                                                 if (!$auth_result) {
874                                                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
875                                                         header('HTTP/1.0 401 Unauthorized');
876                                                         exit;
877                                                 }
878                                         }
879                                 }                               
880                         }
881                 } else {
882                         $_SESSION["uid"] = 1;
883                         $_SESSION["name"] = "admin";
884                         initialize_user_prefs($link, 1); 
885                 }
886         }
887
888         function truncate_string($str, $max_len) {
889                 if (mb_strlen($str, "utf-8") > $max_len - 3) {
890                         return mb_substr($str, 0, $max_len, "utf-8") . "...";
891                 } else {
892                         return $str;
893                 }
894         }
895
896         function get_user_theme_path($link) {
897                 $result = db_query($link, "SELECT theme_path 
898                         FROM 
899                                 ttrss_themes,ttrss_users
900                         WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
901                 if (db_num_rows($result) != 0) {
902                         return db_fetch_result($result, 0, "theme_path");
903                 } else {
904                         return null;
905                 }
906         }
907
908         function smart_date_time($timestamp) {
909                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
910                         return date("G:i", $timestamp);
911                 } else if (date("Y", $timestamp) == date("Y")) {
912                         return date("M d, G:i", $timestamp);
913                 } else {
914                         return date("Y/m/d G:i", $timestamp);
915                 }
916         }
917
918         function smart_date($timestamp) {
919                 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
920                         return "Today";
921                 } else if (date("Y", $timestamp) == date("Y")) {
922                         return date("D m", $timestamp);
923                 } else {
924                         return date("Y/m/d", $timestamp);
925                 }
926         }
927
928         function sql_bool_to_string($s) {
929                 if ($s == "t" || $s == "1") {
930                         return "true";
931                 } else {
932                         return "false";
933                 }
934         }
935
936         function sql_bool_to_bool($s) {
937                 if ($s == "t" || $s == "1") {
938                         return true;
939                 } else {
940                         return false;
941                 }
942         }
943         
944
945         function toggleEvenOdd($a) {
946                 if ($a == "even") 
947                         return "odd";
948                 else
949                         return "even";
950         }
951
952         function sanity_check($link) {
953
954                 $error_code = 0;
955                 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
956                 $schema_version = db_fetch_result($result, 0, "schema_version");
957
958                 if ($schema_version != SCHEMA_VERSION) {
959                         $error_code = 5;
960                 }
961
962                 if ($error_code != 0) {
963                         print "<error error-code='$error_code'/>";
964                         return false;
965                 } else {
966                         return true;
967                 } 
968         }
969
970         function file_is_locked($filename) {
971                 error_reporting(0);
972                 $fp = fopen($filename, "r");
973                 error_reporting(DEFAULT_ERROR_LEVEL);
974                 if ($fp) {
975                         if (flock($fp, LOCK_EX | LOCK_NB)) {
976                                 flock($fp, LOCK_UN);
977                                 fclose($fp);
978                                 return false;
979                         }
980                         fclose($fp);
981                         return true;
982                 }
983                 return false;
984         }
985
986         function make_lockfile($filename) {
987                 $fp = fopen($filename, "w");
988
989                 if (flock($fp, LOCK_EX | LOCK_NB)) {            
990                         return $fp;
991                 } else {
992                         return false;
993                 }
994         }
995
996 ?>