]> git.wh0rd.org - tt-rss.git/blob - functions.php
69decc65cb34157ef09cdb6c0f57fed3abd44005
[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 || !is_array($iterator)) $iterator = $rss->entries;
305 if (!$iterator || !is_array($iterator)) $iterator = $rss;
306
307 if (!is_array($iterator)) {
308 db_query($link, "UPDATE ttrss_feeds
309 SET last_error = 'CrazyBug 001: Can\'t find iterator :('
310 WHERE id = '$feed'");
311 return; // WTF?
312 }
313
314 foreach ($iterator as $item) {
315
316 $entry_guid = $item["id"];
317
318 if (!$entry_guid) $entry_guid = $item["guid"];
319 if (!$entry_guid) $entry_guid = $item["link"];
320
321 if (!$entry_guid) continue;
322
323 $entry_timestamp = "";
324
325 $rss_2_date = $item['pubdate'];
326 $rss_1_date = $item['dc']['date'];
327 $atom_date = $item['issued'];
328 if (!$atom_date) $atom_date = $item['updated'];
329
330 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
331 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
332 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
333
334 if ($entry_timestamp == "") {
335 $entry_timestamp = time();
336 $no_orig_date = 'true';
337 } else {
338 $no_orig_date = 'false';
339 }
340
341 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
342
343 $entry_title = $item["title"];
344
345 // strange Magpie workaround
346 $entry_link = $item["link_"];
347 if (!$entry_link) $entry_link = $item["link"];
348
349 if (!$entry_title) continue;
350 if (!$entry_link) continue;
351
352 $entry_content = $item["content:escaped"];
353
354 if (!$entry_content) $entry_content = $item["content:encoded"];
355 if (!$entry_content) $entry_content = $item["content"];
356 if (!$entry_content) $entry_content = $item["summary"];
357 if (!$entry_content) $entry_content = $item["description"];
358
359 // if (!$entry_content) continue;
360
361 // WTF
362 if (is_array($entry_content)) {
363 $entry_content = $entry_content["encoded"];
364 if (!$entry_content) $entry_content = $entry_content["escaped"];
365 }
366
367 // print_r($item);
368 // print_r(htmlspecialchars($entry_content));
369 // print "<br>";
370
371 $entry_content_unescaped = $entry_content;
372 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
373
374 $entry_comments = $item["comments"];
375
376 $entry_author = db_escape_string($item['dc']['creator']);
377
378 $entry_guid = db_escape_string($entry_guid);
379
380 $result = db_query($link, "SELECT id FROM ttrss_entries
381 WHERE guid = '$entry_guid'");
382
383 $entry_content = db_escape_string($entry_content);
384 $entry_title = db_escape_string($entry_title);
385 $entry_link = db_escape_string($entry_link);
386 $entry_comments = db_escape_string($entry_comments);
387
388 $num_comments = db_escape_string($item["slash"]["comments"]);
389
390 if (!$num_comments) $num_comments = 0;
391
392 if (db_num_rows($result) == 0) {
393
394 // base post entry does not exist, create it
395
396 $result = db_query($link,
397 "INSERT INTO ttrss_entries
398 (title,
399 guid,
400 link,
401 updated,
402 content,
403 content_hash,
404 no_orig_date,
405 date_entered,
406 comments,
407 num_comments,
408 author)
409 VALUES
410 ('$entry_title',
411 '$entry_guid',
412 '$entry_link',
413 '$entry_timestamp_fmt',
414 '$entry_content',
415 '$content_hash',
416 $no_orig_date,
417 NOW(),
418 '$entry_comments',
419 '$num_comments',
420 '$entry_author')");
421 } else {
422 // we keep encountering the entry in feeds, so we need to
423 // update date_entered column so that we don't get horrible
424 // dupes when the entry gets purged and reinserted again e.g.
425 // in the case of SLOW SLOW OMG SLOW updating feeds
426
427 $base_entry_id = db_fetch_result($result, 0, "id");
428
429 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
430 WHERE id = '$base_entry_id'");
431 }
432
433 // now it should exist, if not - bad luck then
434
435 $result = db_query($link, "SELECT
436 id,content_hash,no_orig_date,title,
437 substring(date_entered,1,19) as date_entered,
438 substring(updated,1,19) as updated,
439 num_comments
440 FROM
441 ttrss_entries
442 WHERE guid = '$entry_guid'");
443
444 if (db_num_rows($result) == 1) {
445
446 // this will be used below in update handler
447 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
448 $orig_title = db_fetch_result($result, 0, "title");
449 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
450 $orig_date_entered = strtotime(db_fetch_result($result,
451 0, "date_entered"));
452
453 $ref_id = db_fetch_result($result, 0, "id");
454
455 // check for user post link to main table
456
457 // do we allow duplicate posts with same GUID in different feeds?
458 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid)) {
459 $dupcheck_qpart = "AND feed_id = '$feed'";
460 } else {
461 $dupcheck_qpart = "";
462 }
463
464 // error_reporting(0);
465
466 $filter_name = get_filter_name($entry_title, $entry_content,
467 $entry_link, $filters);
468
469 if ($filter_name == "filter") {
470 continue;
471 }
472
473 // error_reporting (DEFAULT_ERROR_LEVEL);
474
475 $result = db_query($link,
476 "SELECT ref_id FROM ttrss_user_entries WHERE
477 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
478 $dupcheck_qpart");
479
480 // okay it doesn't exist - create user entry
481 if (db_num_rows($result) == 0) {
482
483 if ($filter_name != 'catchup') {
484 $unread = 'true';
485 $last_read_qpart = 'NULL';
486 } else {
487 $unread = 'false';
488 $last_read_qpart = 'NOW()';
489 }
490
491 $result = db_query($link,
492 "INSERT INTO ttrss_user_entries
493 (ref_id, owner_uid, feed_id, unread, last_read)
494 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
495 $last_read_qpart)");
496 }
497
498 $post_needs_update = false;
499
500 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid) &&
501 ($content_hash != $orig_content_hash)) {
502 $post_needs_update = true;
503 }
504
505 if ($orig_title != $entry_title) {
506 $post_needs_update = true;
507 }
508
509 if ($orig_num_comments != $num_comments) {
510 $post_needs_update = true;
511 }
512
513 // this doesn't seem to be very reliable
514 //
515 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
516 // $post_needs_update = true;
517 // }
518
519 // if post needs update, update it and mark all user entries
520 // linking to this post as updated
521 if ($post_needs_update) {
522
523 // print "<!-- post $orig_title needs update : $post_needs_update -->";
524
525 db_query($link, "UPDATE ttrss_entries
526 SET title = '$entry_title', content = '$entry_content',
527 num_comments = '$num_comments'
528 WHERE id = '$ref_id'");
529
530 db_query($link, "UPDATE ttrss_user_entries
531 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
532
533 }
534 }
535
536 /* taaaags */
537 // <a href="http://technorati.com/tag/Xorg" rel="tag">Xorg</a>, //
538
539 $entry_tags = null;
540
541 preg_match_all("/<a.*?href=.http:\/\/.*?technorati.com\/tag\/([^\"\'>]+)/i",
542 $entry_content_unescaped, $entry_tags);
543
544 // print "<br>$entry_title : $entry_content_unescaped<br>";
545 // print_r($entry_tags);
546 // print "<br>";
547
548 $entry_tags = $entry_tags[1];
549
550 if (count($entry_tags) > 0) {
551
552 $result = db_query($link, "SELECT id,int_id
553 FROM ttrss_entries,ttrss_user_entries
554 WHERE guid = '$entry_guid'
555 AND feed_id = '$feed' AND ref_id = id
556 AND owner_uid = '$owner_uid'");
557
558 if (db_num_rows($result) == 1) {
559
560 $entry_id = db_fetch_result($result, 0, "id");
561 $entry_int_id = db_fetch_result($result, 0, "int_id");
562
563 foreach ($entry_tags as $tag) {
564 $tag = db_escape_string(strtolower($tag));
565
566 $tag = str_replace("+", " ", $tag);
567 $tag = str_replace("technorati tag: ", "", $tag);
568
569 $result = db_query($link, "SELECT id FROM ttrss_tags
570 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
571 owner_uid = '$owner_uid' LIMIT 1");
572
573 // print db_fetch_result($result, 0, "id");
574
575 if ($result && db_num_rows($result) == 0) {
576
577 // print "tagging $entry_id as $tag<br>";
578
579 db_query($link, "INSERT INTO ttrss_tags
580 (owner_uid,tag_name,post_int_id)
581 VALUES ('$owner_uid','$tag', '$entry_int_id')");
582 }
583 }
584 }
585 }
586 }
587
588 db_query($link, "UPDATE ttrss_feeds
589 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
590
591 db_query($link, "COMMIT");
592
593 } else {
594 $error_msg = db_escape_string(magpie_error());
595 db_query($link,
596 "UPDATE ttrss_feeds SET last_error = '$error_msg',
597 last_updated = NOW() WHERE id = '$feed'");
598 }
599
600 }
601
602 function print_select($id, $default, $values, $attributes = "") {
603 print "<select id=\"$id\" $attributes>";
604 foreach ($values as $v) {
605 if ($v == $default)
606 $sel = " selected";
607 else
608 $sel = "";
609
610 print "<option$sel>$v</option>";
611 }
612 print "</select>";
613 }
614
615 function get_filter_name($title, $content, $link, $filters) {
616
617 if ($filters["title"]) {
618 foreach ($filters["title"] as $filter) {
619 $reg_exp = $filter["reg_exp"];
620 if (preg_match("/$reg_exp/i", $title)) {
621 return $filter["action"];
622 }
623 }
624 }
625
626 if ($filters["content"]) {
627 foreach ($filters["content"] as $filter) {
628 $reg_exp = $filter["reg_exp"];
629 if (preg_match("/$reg_exp/i", $content)) {
630 return $filter["action"];
631 }
632 }
633 }
634
635 if ($filters["both"]) {
636 foreach ($filters["both"] as $filter) {
637 $reg_exp = $filter["reg_exp"];
638 if (preg_match("/$reg_exp/i", $title) ||
639 preg_match("/$reg_exp/i", $content)) {
640 return $filter["action"];
641 }
642 }
643 }
644
645 if ($filters["link"]) {
646 $reg_exp = $filter["reg_exp"];
647 foreach ($filters["link"] as $filter) {
648 $reg_exp = $filter["reg_exp"];
649 if (preg_match("/$reg_exp/i", $link)) {
650 return $filter["action"];
651 }
652 }
653 }
654
655 return false;
656 }
657
658 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link) {
659
660 if (file_exists($icon_file) && filesize($icon_file) > 0) {
661 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
662 } else {
663 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
664 }
665
666 $feed = "<a href=\"javascript:viewfeed('$feed_id', 0);\">$feed_title</a>";
667
668 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
669 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
670 print "$feed_icon";
671 }
672
673 print "<span id=\"FEEDN-$feed_id\">$feed</span>";
674
675 if ($unread != 0) {
676 $fctr_class = "";
677 } else {
678 $fctr_class = "class=\"invisible\"";
679 }
680
681 print "<span $fctr_class id=\"FEEDCTR-$feed_id\">
682 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
683
684 print "</li>";
685
686 }
687
688 function getmicrotime() {
689 list($usec, $sec) = explode(" ",microtime());
690 return ((float)$usec + (float)$sec);
691 }
692
693 function print_radio($id, $default, $values, $attributes = "") {
694 foreach ($values as $v) {
695
696 if ($v == $default)
697 $sel = "checked";
698 else
699 $sel = "";
700
701 if ($v == "Yes") {
702 $sel .= " value=\"1\"";
703 } else {
704 $sel .= " value=\"0\"";
705 }
706
707 print "<input class=\"noborder\"
708 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
709
710 }
711 }
712
713 function initialize_user_prefs($link, $uid) {
714
715 $uid = db_escape_string($uid);
716
717 db_query($link, "BEGIN");
718
719 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
720
721 $u_result = db_query($link, "SELECT pref_name
722 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
723
724 $active_prefs = array();
725
726 while ($line = db_fetch_assoc($u_result)) {
727 array_push($active_prefs, $line["pref_name"]);
728 }
729
730 while ($line = db_fetch_assoc($result)) {
731 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
732 // print "adding " . $line["pref_name"] . "<br>";
733
734 db_query($link, "INSERT INTO ttrss_user_prefs
735 (owner_uid,pref_name,value) VALUES
736 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
737
738 }
739 }
740
741 db_query($link, "COMMIT");
742
743 }
744
745 function authenticate_user($link, $login, $password) {
746
747 $pwd_hash = 'SHA1:' . sha1($password);
748
749 $result = db_query($link, "SELECT id,login,access_level FROM ttrss_users WHERE
750 login = '$login' AND pwd_hash = '$pwd_hash'");
751
752 if (db_num_rows($result) == 1) {
753 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
754 $_SESSION["name"] = db_fetch_result($result, 0, "login");
755 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
756
757 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
758 $_SESSION["uid"]);
759
760 $user_theme = get_user_theme_path($link);
761
762 $_SESSION["theme"] = $user_theme;
763 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
764
765 initialize_user_prefs($link, $_SESSION["uid"]);
766
767 return true;
768 }
769
770 return false;
771
772 }
773
774 function make_password($length = 8) {
775
776 $password = "";
777 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
778
779 $i = 0;
780
781 while ($i < $length) {
782 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
783
784 if (!strstr($password, $char)) {
785 $password .= $char;
786 $i++;
787 }
788 }
789 return $password;
790 }
791
792 // this is called after user is created to initialize default feeds, labels
793 // or whatever else
794
795 // user preferences are checked on every login, not here
796
797 function initialize_user($link, $uid) {
798
799 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
800 values ('$uid','unread = true', 'Unread articles')");
801
802 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
803 values ('$uid','last_read is null and unread = false', 'Updated articles')");
804
805 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
806 values ('$uid', 'Tiny Tiny RSS: New Releases',
807 'http://tt-rss.spb.ru/releases.rss')");
808
809 }
810
811 function logout_user() {
812 session_destroy();
813 if (isset($_COOKIE[session_name()])) {
814 setcookie(session_name(), '', time()-42000, '/');
815 }
816 }
817
818 function get_script_urlpath() {
819 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
820 }
821
822 function get_login_redirect() {
823 $server = $_SERVER["SERVER_NAME"];
824
825 if (ENABLE_LOGIN_SSL) {
826 $protocol = "https";
827 } else {
828 $protocol = "http";
829 }
830
831 $url_path = get_script_urlpath();
832
833 $redirect_uri = "$protocol://$server$url_path/login.php";
834
835 return $redirect_uri;
836 }
837
838 function validate_session($link) {
839 if (SESSION_CHECK_ADDRESS && !DATABASE_BACKED_SESSIONS && $_SESSION["uid"]) {
840 if ($_SESSION["ip_address"]) {
841 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
842 return false;
843 }
844 }
845 }
846 return true;
847 }
848
849 function basic_nosid_redirect_check() {
850 if (!SINGLE_USER_MODE) {
851 if (!$_COOKIE["ttrss_sid"]) {
852 $redirect_uri = get_login_redirect();
853 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
854 header("Location: $redirect_uri?rt=$return_to");
855 exit;
856 }
857 }
858 }
859
860 function login_sequence($link) {
861 if (!SINGLE_USER_MODE) {
862
863 if (!validate_session($link)) {
864 logout_user();
865 $redirect_uri = get_login_redirect();
866 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
867 header("Location: $redirect_uri?rt=$return_to");
868 exit;
869 }
870
871 if (!USE_HTTP_AUTH) {
872 if (!$_SESSION["uid"]) {
873 $redirect_uri = get_login_redirect();
874 $return_to = preg_replace('/.*?\//', '', $_SERVER["REQUEST_URI"]);
875 header("Location: $redirect_uri?rt=$return_to");
876 exit;
877 }
878 } else {
879 if (!$_SESSION["uid"]) {
880 if (!$_SERVER["PHP_AUTH_USER"]) {
881
882 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
883 header('HTTP/1.0 401 Unauthorized');
884 exit;
885
886 } else {
887 $auth_result = authenticate_user($link,
888 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
889
890 if (!$auth_result) {
891 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS"');
892 header('HTTP/1.0 401 Unauthorized');
893 exit;
894 }
895 }
896 }
897 }
898 } else {
899 $_SESSION["uid"] = 1;
900 $_SESSION["name"] = "admin";
901 initialize_user_prefs($link, 1);
902 }
903 }
904
905 function truncate_string($str, $max_len) {
906 if (mb_strlen($str, "utf-8") > $max_len - 3) {
907 return mb_substr($str, 0, $max_len, "utf-8") . "...";
908 } else {
909 return $str;
910 }
911 }
912
913 function get_user_theme_path($link) {
914 $result = db_query($link, "SELECT theme_path
915 FROM
916 ttrss_themes,ttrss_users
917 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
918 if (db_num_rows($result) != 0) {
919 return db_fetch_result($result, 0, "theme_path");
920 } else {
921 return null;
922 }
923 }
924
925 function smart_date_time($timestamp) {
926 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
927 return date("G:i", $timestamp);
928 } else if (date("Y", $timestamp) == date("Y")) {
929 return date("M d, G:i", $timestamp);
930 } else {
931 return date("Y/m/d G:i", $timestamp);
932 }
933 }
934
935 function smart_date($timestamp) {
936 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
937 return "Today";
938 } else if (date("Y", $timestamp) == date("Y")) {
939 return date("D m", $timestamp);
940 } else {
941 return date("Y/m/d", $timestamp);
942 }
943 }
944
945 function sql_bool_to_string($s) {
946 if ($s == "t" || $s == "1") {
947 return "true";
948 } else {
949 return "false";
950 }
951 }
952
953 function sql_bool_to_bool($s) {
954 if ($s == "t" || $s == "1") {
955 return true;
956 } else {
957 return false;
958 }
959 }
960
961
962 function toggleEvenOdd($a) {
963 if ($a == "even")
964 return "odd";
965 else
966 return "even";
967 }
968
969 function sanity_check($link) {
970
971 $error_code = 0;
972 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
973 $schema_version = db_fetch_result($result, 0, "schema_version");
974
975 if ($schema_version != SCHEMA_VERSION) {
976 $error_code = 5;
977 }
978
979 if ($error_code != 0) {
980 print "<error error-code='$error_code'/>";
981 return false;
982 } else {
983 return true;
984 }
985 }
986
987 function file_is_locked($filename) {
988 error_reporting(0);
989 $fp = fopen($filename, "r");
990 error_reporting(DEFAULT_ERROR_LEVEL);
991 if ($fp) {
992 if (flock($fp, LOCK_EX | LOCK_NB)) {
993 flock($fp, LOCK_UN);
994 fclose($fp);
995 return false;
996 }
997 fclose($fp);
998 return true;
999 }
1000 return false;
1001 }
1002
1003 function make_lockfile($filename) {
1004 $fp = fopen($filename, "w");
1005
1006 if (flock($fp, LOCK_EX | LOCK_NB)) {
1007 return $fp;
1008 } else {
1009 return false;
1010 }
1011 }
1012
1013 ?>