]> git.wh0rd.org Git - tt-rss.git/blob - functions.php
fix prefs_init for single user mode
[tt-rss.git] / functions.php
1 <?
2         session_start();
3
4         require_once 'config.php';
5         require_once 'db-prefs.php';
6
7         define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
8
9         function purge_feed($link, $feed_id, $purge_interval) {
10
11                 if (DB_TYPE == "pgsql") {
12                         db_query($link, "DELETE FROM ttrss_user_entries WHERE
13                                 marked = false AND feed_id = '$feed_id' AND
14                                 (SELECT date_entered FROM ttrss_entries WHERE
15                                         id = ref_id) < NOW() - INTERVAL '$purge_interval days'");
16                 } else {
17                         db_query($link, "DELETE FROM ttrss_user_entries WHERE
18                                 marked = false AND feed_id = '$feed_id' AND
19                                 (SELECT date_entered FROM ttrss_entries WHERE 
20                                         id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
21                 }
22         }
23
24         function global_purge_old_posts($link, $do_output = false) {
25
26                 $result = db_query($link, 
27                         "SELECT id,purge_interval,owner_uid FROM ttrss_feeds");
28
29                 while ($line = db_fetch_assoc($result)) {
30
31                         $feed_id = $line["id"];
32                         $purge_interval = $line["purge_interval"];
33                         $owner_uid = $line["owner_uid"];
34
35                         if ($purge_interval == 0) {
36                         
37                                 $tmp_result = db_query($link, 
38                                         "SELECT value FROM ttrss_user_prefs WHERE
39                                                 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
40
41                                 if (db_num_rows($tmp_result) != 0) {                    
42                                         $purge_interval = db_fetch_result($tmp_result, 0, "value");
43                                 }
44                         }
45
46                         if ($do_output) {
47                                 print "<feed id='$feed_id' p_intl='$purge_interval'/>";
48                         }
49
50                         if ($purge_interval > 0) {
51                                 purge_feed($link, $feed_id, $purge_interval);
52                         }
53                 }       
54
55                 // purge orphaned posts in main content table
56                 db_query($link, "DELETE FROM ttrss_entries WHERE 
57                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
58
59         }
60
61         function purge_old_posts($link) {
62
63                 $user_id = $_SESSION["uid"];
64         
65                 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds 
66                         WHERE owner_uid = '$user_id'");
67
68                 while ($line = db_fetch_assoc($result)) {
69
70                         $feed_id = $line["id"];
71                         $purge_interval = $line["purge_interval"];
72
73                         if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
74
75                         if ($purge_interval > 0) {
76                                 purge_feed($link, $feed_id, $purge_interval);
77                         }
78                 }       
79
80                 // purge orphaned posts in main content table
81                 db_query($link, "DELETE FROM ttrss_entries WHERE 
82                         (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
83         }
84
85         function update_all_feeds($link, $fetch) {
86
87                 if (WEB_DEMO_MODE) return;
88
89                 if (get_pref($link, 'DAEMON_REFRESH_ONLY')) {
90                         if (!$_GET["daemon"]) {
91                                 return;
92                         }
93                 }
94
95                 db_query($link, "BEGIN");
96
97                 $user_id = $_SESSION["uid"];
98
99                 $result = db_query($link, "SELECT feed_url,id,
100                         substring(last_updated,1,19) as last_updated,
101                         update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'");
102
103                 while ($line = db_fetch_assoc($result)) {
104                         $upd_intl = $line["update_interval"];
105
106                         if (!$upd_intl || $upd_intl == 0) {
107                                 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL');
108                         }
109
110                         if ($fetch || (!$line["last_updated"] || 
111                                 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
112
113                                 update_rss_feed($link, $line["feed_url"], $line["id"]);
114                         }
115                 }
116
117                 purge_old_posts($link);
118
119                 db_query($link, "COMMIT");
120
121         }
122
123         function check_feed_favicon($feed_url, $feed, $link) {
124                 $feed_url = str_replace("http://", "", $feed_url);
125                 $feed_url = preg_replace("/\/.*$/", "", $feed_url);
126                 
127                 $icon_url = "http://$feed_url/favicon.ico";
128                 $icon_file = ICONS_DIR . "/$feed.ico";
129
130                 if (!file_exists($icon_file)) {
131                                 
132                         error_reporting(0);
133                         $r = fopen($icon_url, "r");
134                         error_reporting (E_ERROR | E_WARNING | E_PARSE);
135
136                         if ($r) {
137                                 $tmpfname = tempnam("/tmp", "ttrssicon");
138                         
139                                 $t = fopen($tmpfname, "w");
140                                 
141                                 while (!feof($r)) {
142                                         $buf = fread($r, 16384);
143                                         fwrite($t, $buf);
144                                 }
145                                 
146                                 fclose($r);
147                                 fclose($t);
148
149                                 error_reporting(0);
150                                 if (!rename($tmpfname, $icon_file)) {
151                                         unlink($tmpfname);
152                                 }
153
154                                 chmod($icon_file, 0644);
155                                 
156                                 error_reporting (E_ERROR | E_WARNING | E_PARSE);
157
158                         }       
159                 }
160         }
161
162         function update_rss_feed($link, $feed_url, $feed) {
163
164                 if (WEB_DEMO_MODE) return;
165
166                 $feed = db_escape_string($feed);
167
168                 error_reporting(0);
169                 $rss = fetch_rss($feed_url);
170
171                 error_reporting (E_ERROR | E_WARNING | E_PARSE);
172
173                 db_query($link, "BEGIN");
174
175                 $feed = db_escape_string($feed);
176
177                 if ($rss) {
178
179                         if (get_pref($link, 'ENABLE_FEED_ICONS')) {     
180                                 check_feed_favicon($feed_url, $feed, $link);
181                         }
182                 
183                         $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid 
184                                 FROM ttrss_feeds WHERE id = '$feed'");
185
186                         $registered_title = db_fetch_result($result, 0, "title");
187                         $orig_icon_url = db_fetch_result($result, 0, "icon_url");
188                         $orig_site_url = db_fetch_result($result, 0, "site_url");
189
190                         $owner_uid = db_fetch_result($result, 0, "owner_uid");
191
192                         if (!$registered_title) {
193                                 $feed_title = db_escape_string($rss->channel["title"]);
194                                 db_query($link, "UPDATE ttrss_feeds SET 
195                                         title = '$feed_title' WHERE id = '$feed'");
196                         }
197
198                         if (!$orig_site_url && $rss->channel["link"]) {
199                                 $site_url = db_escape_string($rss->channel["link"]);
200                                 db_query($link, "UPDATE ttrss_feeds SET 
201                                         site_url = '$site_url' WHERE id = '$feed'");
202                         }
203
204 //                      print "I: " . $rss->channel["image"]["url"];
205
206                         $icon_url = $rss->image["url"];
207
208                         if ($icon_url && !$orig_icon_url) {
209                                 $icon_url = db_escape_string($icon_url);
210                                 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
211                         }
212
213
214                         $filters = array();
215
216                         $result = db_query($link, "SELECT reg_exp,
217                                 (SELECT name FROM ttrss_filter_types
218                                         WHERE id = filter_type) as name
219                                 FROM ttrss_filters WHERE owner_uid = $owner_uid");
220
221                         while ($line = db_fetch_assoc($result)) {
222                                 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
223                                 array_push($filters[$line["name"]], $line["reg_exp"]);
224                         }
225
226                         foreach ($rss->items as $item) {
227         
228                                 $entry_guid = $item["id"];
229         
230                                 if (!$entry_guid) $entry_guid = $item["guid"];
231                                 if (!$entry_guid) $entry_guid = $item["link"];
232
233                                 if (!$entry_guid) continue;
234
235                                 $entry_timestamp = "";
236
237                                 $rss_2_date = $item['pubdate'];
238                                 $rss_1_date = $item['dc']['date'];
239                                 $atom_date = $item['issued'];
240                         
241                                 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
242                                 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
243                                 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
244                                 
245                                 if ($entry_timestamp == "") {
246                                         $entry_timestamp = time();
247                                         $no_orig_date = 'true';
248                                 } else {
249                                         $no_orig_date = 'false';
250                                 }
251
252                                 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
253
254                                 $entry_title = $item["title"];
255                                 $entry_link = $item["link"];
256
257                                 if (!$entry_title) continue;
258                                 if (!$entry_link) continue;
259
260                                 $entry_content = $item["content:escaped"];
261
262                                 if (!$entry_content) $entry_content = $item["content:encoded"];
263                                 if (!$entry_content) $entry_content = $item["content"];
264                                 if (!$entry_content) $entry_content = $item["description"];
265
266 //                              if (!$entry_content) continue;
267
268                                 // WTF
269                                 if (is_array($entry_content)) {
270                                         $entry_content = $entry_content["encoded"];
271                                         if (!$entry_content) $entry_content = $entry_content["escaped"];
272                                 }
273
274 //                              print_r($item);
275 //                              print_r($entry_content);
276
277                                 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
278
279                                 $entry_comments = $item["comments"];
280
281                                 $entry_guid = db_escape_string($entry_guid);
282
283                                 $result = db_query($link, "SELECT id FROM       ttrss_entries 
284                                         WHERE guid = '$entry_guid'");
285
286                                 $entry_content = db_escape_string($entry_content);
287                                 $entry_title = db_escape_string($entry_title);
288                                 $entry_link = db_escape_string($entry_link);
289                                 $entry_comments = db_escape_string($entry_comments);
290
291                                 if (db_num_rows($result) == 0) {
292
293                                         // base post entry does not exist, create it
294
295                                         error_reporting(0);
296                                         if (is_filtered($entry_title, $entry_content, $filters)) {
297                                                 continue;
298                                         }
299                                         error_reporting (E_ERROR | E_WARNING | E_PARSE);
300
301                                         $result = db_query($link,
302                                                 "INSERT INTO ttrss_entries 
303                                                         (title,
304                                                         guid,
305                                                         link,
306                                                         updated,
307                                                         content,
308                                                         content_hash,
309                                                         no_orig_date,
310                                                         date_entered,
311                                                         comments)
312                                                 VALUES
313                                                         ('$entry_title', 
314                                                         '$entry_guid', 
315                                                         '$entry_link',
316                                                         '$entry_timestamp_fmt', 
317                                                         '$entry_content', 
318                                                         '$content_hash',
319                                                         $no_orig_date, 
320                                                         NOW(), 
321                                                         '$entry_comments')");
322                                 }
323
324                                 // now it should exist, if not - bad luck then
325
326                                 $result = db_query($link, "SELECT 
327                                                 id,content_hash,no_orig_date,title,
328                                                 substring(updated,1,19) as updated
329                                         FROM 
330                                                 ttrss_entries 
331                                         WHERE guid = '$entry_guid'");
332
333                                 if (db_num_rows($result) == 1) {
334
335                                                 // this will be used below in update handler
336                                                 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
337 //                                              $orig_timestamp = strtotime(db_fetch_result($result, 0, "updated"));
338 //                                              $orig_no_orig_date = db_fetch_result($result, 0, "no_orig_date");
339                                                 $orig_title = db_fetch_result($result, 0, "title");
340
341                                                 $ref_id = db_fetch_result($result, 0, "id");
342
343                                                 // check for user post link to main table
344
345                                                 // do we allow duplicate posts with same GUID in different feeds?
346                                                 if (get_pref($link, "ALLOW_DUPLICATE_POSTS")) {
347                                                         $dupcheck_qpart = "AND feed_id = '$feed'";
348                                                 } else { 
349                                                         $dupcheck_qpart = "";
350                                                 }
351
352                                                 $result = db_query($link,
353                                                         "SELECT ref_id FROM ttrss_user_entries WHERE
354                                                                 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
355                                                                 $dupcheck_qpart");
356
357                                                 // okay it doesn't exist - create user entry
358                                                 if (db_num_rows($result) == 0) {
359                                                         $result = db_query($link,
360                                                                 "INSERT INTO ttrss_user_entries 
361                                                                         (ref_id, owner_uid, feed_id) 
362                                                                 VALUES ('$ref_id', '$owner_uid', '$feed')");
363                                                 }
364
365                                         $post_needs_update = false;
366
367                                         if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE") &&
368                                                 ($content_hash != $orig_content_hash)) {
369                                                 $post_needs_update = true;
370                                         }
371
372                                         if ($orig_title != $entry_title) {
373                                                 $post_needs_update = true;
374                                         }
375
376 //                                      this doesn't seem to be very reliable
377 //
378 //                                      if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
379 //                                              $post_needs_update = true;
380 //                                      }
381
382                                         // if post needs update, update it and mark all user entries 
383                                         // linking to this post as updated                                      
384                                         if ($post_needs_update) {
385
386 //                                              print "<!-- post $orig_title needs update : $post_needs_update -->";
387
388                                                 db_query($link, "UPDATE ttrss_entries 
389                                                         SET title = '$entry_title', content = '$entry_content'
390                                                         WHERE id = '$ref_id'");
391
392                                                 db_query($link, "UPDATE ttrss_user_entries 
393                                                         SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
394
395                                         }
396                                 }
397
398                                 /* taaaags */
399                                 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
400
401                                 $entry_tags = null;
402
403                                 preg_match_all("/<a.*?rel=.tag.*?>([^>]+)<\/a>/i", $entry_content,
404                                         $entry_tags);
405
406                                 $entry_tags = $entry_tags[1];
407
408                                 if (count($entry_tags) > 0) {
409                                 
410                                         $result = db_query($link, "SELECT id,int_id 
411                                                 FROM ttrss_entries,ttrss_user_entries 
412                                                 WHERE guid = '$entry_guid' 
413                                                 AND feed_id = '$feed' AND ref_id = id
414                                                 AND owner_uid = '$owner_uid'");
415
416                                         if (!$result || db_num_rows($result) != 1) {
417                                                 return;
418                                         }
419
420                                         $entry_id = db_fetch_result($result, 0, "id");
421                                         $entry_int_id = db_fetch_result($result, 0, "int_id");
422                                         
423                                         foreach ($entry_tags as $tag) {
424                                                 $tag = db_escape_string(strtolower($tag));
425
426                                                 $tag = str_replace("technorati tag: ", "", $tag);
427
428                                                 $result = db_query($link, "SELECT id FROM ttrss_tags            
429                                                         WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND 
430                                                         owner_uid = '$owner_uid' LIMIT 1");
431
432 //                                              print db_fetch_result($result, 0, "id");
433
434                                                 if ($result && db_num_rows($result) == 0) {
435                                                         
436 //                                                      print "tagging $entry_id as $tag<br>";
437
438                                                         db_query($link, "INSERT INTO ttrss_tags 
439                                                                 (owner_uid,tag_name,post_int_id)
440                                                                 VALUES ('$owner_uid','$tag', '$entry_int_id')");
441                                                 }                                                       
442                                         }
443                                 } 
444                         } 
445
446                         db_query($link, "UPDATE ttrss_feeds 
447                                 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
448
449                 } else {
450                         $error_msg = db_escape_string(magpie_error());
451                         db_query($link, 
452                                 "UPDATE ttrss_feeds SET last_error = '$error_msg', 
453                                         last_updated = NOW() WHERE id = '$feed'");
454                 }
455
456                 db_query($link, "COMMIT");
457
458         }
459
460         function print_select($id, $default, $values, $attributes = "") {
461                 print "<select id=\"$id\" $attributes>";
462                 foreach ($values as $v) {
463                         if ($v == $default)
464                                 $sel = " selected";
465                          else
466                                 $sel = "";
467                         
468                         print "<option$sel>$v</option>";
469                 }
470                 print "</select>";
471         }
472
473         function is_filtered($title, $content, $filters) {
474
475                 if ($filters["title"]) {
476                         foreach ($filters["title"] as $title_filter) {                  
477                                 if (preg_match("/$title_filter/i", $title)) 
478                                         return true;
479                         }
480                 }
481
482                 if ($filters["content"]) {
483                         foreach ($filters["content"] as $content_filter) {                      
484                                 if (preg_match("/$content_filter/i", $content)) 
485                                         return true;
486                         }
487                 }
488
489                 if ($filters["both"]) {
490                         foreach ($filters["both"] as $filter) {                 
491                                 if (preg_match("/$filter/i", $title) || preg_match("/$filter/i", $content)) 
492                                         return true;
493                         }
494                 }
495
496                 return false;
497         }
498
499         function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link) {
500
501                 if (file_exists($icon_file) && filesize($icon_file) > 0) {
502                                 $feed_icon = "<img src=\"$icon_file\">";
503                 } else {
504                         $feed_icon = "<img src=\"images/blank_icon.gif\">";
505                 }
506
507                 $feed = "<a href=\"javascript:viewfeed('$feed_id', 0);\">$feed_title</a>";
508
509                 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
510                 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
511                         print "$feed_icon";
512                 }
513
514                 print "<span id=\"FEEDN-$feed_id\">$feed</span>";
515
516                 if ($unread != 0) {
517                         $fctr_class = "";
518                 } else {
519                         $fctr_class = "class=\"invisible\"";
520                 }
521
522                 print "<span $fctr_class id=\"FEEDCTR-$feed_id\">
523                          (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
524                 
525                 print "</li>";
526
527         }
528
529         function getmicrotime() {
530                 list($usec, $sec) = explode(" ",microtime());
531                 return ((float)$usec + (float)$sec);
532         }
533
534         function print_radio($id, $default, $values, $attributes = "") {
535                 foreach ($values as $v) {
536                 
537                         if ($v == $default)
538                                 $sel = "checked";
539                          else
540                                 $sel = "";
541
542                         if ($v == "Yes") {
543                                 $sel .= " value=\"1\"";
544                         } else {
545                                 $sel .= " value=\"0\"";
546                         }
547                         
548                         print "<input type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
549
550                 }
551         }
552
553         function initialize_user_prefs($link, $uid) {
554
555                 $uid = db_escape_string($uid);
556
557                 db_query($link, "BEGIN");
558
559                 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
560                 
561                 $u_result = db_query($link, "SELECT pref_name 
562                         FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
563
564                 $active_prefs = array();
565
566                 while ($line = db_fetch_assoc($u_result)) {
567                         array_push($active_prefs, $line["pref_name"]);                  
568                 }
569
570                 while ($line = db_fetch_assoc($result)) {
571                         if (array_search($line["pref_name"], $active_prefs) === FALSE) {
572 //                              print "adding " . $line["pref_name"] . "<br>";
573
574                                 db_query($link, "INSERT INTO ttrss_user_prefs
575                                         (owner_uid,pref_name,value) VALUES 
576                                         ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
577
578                         }
579                 }
580
581                 db_query($link, "COMMIT");
582
583         }
584         
585         function authenticate_user($link, $login, $password) {
586
587                 $pwd_hash = 'SHA1:' . sha1($password);
588
589                 $result = db_query($link, "SELECT id,login,access_level FROM ttrss_users WHERE 
590                         login = '$login' AND (pwd_hash = '$password' OR pwd_hash = '$pwd_hash')");
591
592                 if (db_num_rows($result) == 1) {
593                         $_SESSION["uid"] = db_fetch_result($result, 0, "id");
594                         $_SESSION["name"] = db_fetch_result($result, 0, "login");
595                         $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
596
597                         db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " . 
598                                 $_SESSION["uid"]);
599
600                         return true;
601                 }
602
603                 return false;
604
605         }
606
607         function http_authenticate_user($link, $force_logout) {
608
609                 if (!$_SERVER['PHP_AUTH_USER'] || $force_logout) {
610
611                         if ($force_logout) logout_user();
612
613                         header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
614                         header('HTTP/1.0 401 Unauthorized');
615                         print "<h1>401 Unathorized</h1>";
616                         
617                         exit;
618                         
619                 } else {
620
621                         $login = db_escape_string($_SERVER['PHP_AUTH_USER']);
622                         $password = db_escape_string($_SERVER['PHP_AUTH_PW']);
623
624                         return authenticate_user($link, $login, $password);
625                 }
626         }
627
628         function make_password($length = 8) {
629
630                 $password = "";
631                 $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
632     
633                 $i = 0; 
634     
635                 while ($i < $length) { 
636                         $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
637         
638                         if (!strstr($password, $char)) { 
639                                 $password .= $char;
640                                 $i++;
641                         }
642                 }
643                 return $password;
644         }
645
646         // this is called after user is created to initialize default feeds, labels
647         // or whatever else
648         
649         // user preferences are checked on every login, not here
650
651         function initialize_user($link, $uid) {
652
653                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
654                         values ('$uid','unread = true', 'Unread articles')");
655
656                 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description) 
657                         values ('$uid','last_read is null and unread = false', 'Updated articles')");
658                 
659                 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
660                         values ('$uid', 'Tiny Tiny RSS Dev. Feed',
661                         'http://bah.spb.su/darcsweb/darcsweb.cgi?r=tt-rss;a=rss')");
662                 
663                 }
664
665         function logout_user() {
666                 $_SESSION["uid"] = null;
667                 $_SESSION["name"] = null;
668                 $_SESSION["access_level"] = null;
669                 session_destroy();
670         }
671
672         function login_sequence($link) {
673                 if (!SINGLE_USER_MODE) {
674         
675                         if (!USE_HTTP_AUTH) {
676                                 if (!$_SESSION["uid"]) {
677                                         header("Location: login.php?rt=tt-rss.php");
678                                         exit;
679                                 }
680                         } else {
681                                 if (!http_authenticate_user($link, false)) {
682                                         exit;
683                                 }
684                         }
685                 } else {
686                         $_SESSION["uid"] = 1;
687                         $_SESSION["name"] = "admin";
688                         initialize_user_prefs($link, 1); 
689                 }
690         }
691 ?>