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