]> git.wh0rd.org - tt-rss.git/blob - functions.php
remove db_unescape_string() hack
[tt-rss.git] / functions.php
1 <?php
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
11 if (ENABLE_TRANSLATIONS == true) {
12 require_once "accept-to-gettext.php";
13 require_once "gettext/gettext.inc";
14
15 function startup_gettext() {
16
17 # Get locale from Accept-Language header
18 $lang = al2gt(array("en_US", "ru_RU"), "text/html");
19
20 if ($lang) {
21 _setlocale(LC_MESSAGES, $lang);
22 _bindtextdomain("messages", "locale");
23 _textdomain("messages");
24 _bind_textdomain_codeset("messages", "UTF-8");
25 }
26 }
27
28 startup_gettext();
29
30 } else {
31 function __($msg) {
32 return $msg;
33 }
34 function startup_gettext() {
35 // no-op
36 return true;
37 }
38 }
39
40 require_once 'db-prefs.php';
41 require_once 'compat.php';
42 require_once 'errors.php';
43 require_once 'version.php';
44
45 define('MAGPIE_USER_AGENT_EXT', ' (Tiny Tiny RSS/' . VERSION . ')');
46 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
47
48 require_once "magpierss/rss_fetch.inc";
49 require_once 'magpierss/rss_utils.inc';
50
51 include_once "tw/tw-config.php";
52 include_once "tw/tw.php";
53 include_once TW_SETUP . "paranoya.php";
54
55 $tw_parser = new twParser();
56
57 function _debug($msg) {
58 $ts = strftime("%H:%M:%S", time());
59 print "[$ts] $msg\n";
60 }
61
62 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
63
64 $rows = -1;
65
66 if (DB_TYPE == "pgsql") {
67 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
68 marked = false AND feed_id = '$feed_id' AND
69 (SELECT date_entered FROM ttrss_entries WHERE
70 id = ref_id) < NOW() - INTERVAL '$purge_interval days'"); */
71
72 $pg_version = get_pgsql_version($link);
73
74 if (preg_match("/^7\./", $pg_version) || preg_match("/^8\.0/", $pg_version)) {
75
76 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
77 ttrss_entries.id = ref_id AND
78 marked = false AND
79 feed_id = '$feed_id' AND
80 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
81
82 } else {
83
84 $result = db_query($link, "DELETE FROM ttrss_user_entries
85 USING ttrss_entries
86 WHERE ttrss_entries.id = ref_id AND
87 marked = false AND
88 feed_id = '$feed_id' AND
89 ttrss_entries.date_entered < NOW() - INTERVAL '$purge_interval days'");
90 }
91
92 $rows = pg_affected_rows($result);
93
94 } else {
95
96 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
97 marked = false AND feed_id = '$feed_id' AND
98 (SELECT date_entered FROM ttrss_entries WHERE
99 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
100
101 $result = db_query($link, "DELETE FROM ttrss_user_entries
102 USING ttrss_user_entries, ttrss_entries
103 WHERE ttrss_entries.id = ref_id AND
104 marked = false AND
105 feed_id = '$feed_id' AND
106 ttrss_entries.date_entered < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
107
108 $rows = mysql_affected_rows($link);
109
110 }
111
112 if ($debug) {
113 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
114 }
115 }
116
117 function global_purge_old_posts($link, $do_output = false, $limit = false) {
118
119 $random_qpart = sql_random_function();
120
121 if ($limit) {
122 $limit_qpart = "LIMIT $limit";
123 } else {
124 $limit_qpart = "";
125 }
126
127 $result = db_query($link,
128 "SELECT id,purge_interval,owner_uid FROM ttrss_feeds
129 ORDER BY $random_qpart $limit_qpart");
130
131 while ($line = db_fetch_assoc($result)) {
132
133 $feed_id = $line["id"];
134 $purge_interval = $line["purge_interval"];
135 $owner_uid = $line["owner_uid"];
136
137 if ($purge_interval == 0) {
138
139 $tmp_result = db_query($link,
140 "SELECT value FROM ttrss_user_prefs WHERE
141 pref_name = 'PURGE_OLD_DAYS' AND owner_uid = '$owner_uid'");
142
143 if (db_num_rows($tmp_result) != 0) {
144 $purge_interval = db_fetch_result($tmp_result, 0, "value");
145 }
146 }
147
148 if ($do_output) {
149 // print "Feed $feed_id: purge interval = $purge_interval\n";
150 }
151
152 if ($purge_interval > 0) {
153 purge_feed($link, $feed_id, $purge_interval, $do_output);
154 }
155 }
156
157 // purge orphaned posts in main content table
158 db_query($link, "DELETE FROM ttrss_entries WHERE
159 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
160
161 }
162
163 function purge_old_posts($link) {
164
165 $user_id = $_SESSION["uid"];
166
167 $result = db_query($link, "SELECT id,purge_interval FROM ttrss_feeds
168 WHERE owner_uid = '$user_id'");
169
170 while ($line = db_fetch_assoc($result)) {
171
172 $feed_id = $line["id"];
173 $purge_interval = $line["purge_interval"];
174
175 if ($purge_interval == 0) $purge_interval = get_pref($link, 'PURGE_OLD_DAYS');
176
177 if ($purge_interval > 0) {
178 purge_feed($link, $feed_id, $purge_interval);
179 }
180 }
181
182 // purge orphaned posts in main content table
183 db_query($link, "DELETE FROM ttrss_entries WHERE
184 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
185 }
186
187 function update_all_feeds($link, $fetch, $user_id = false, $force_daemon = false) {
188
189 if (WEB_DEMO_MODE) return;
190
191 if (!$user_id) {
192 $user_id = $_SESSION["uid"];
193 purge_old_posts($link);
194 }
195
196 // db_query($link, "BEGIN");
197
198 if (MAX_UPDATE_TIME > 0) {
199 if (DB_TYPE == "mysql") {
200 $q_order = "RAND()";
201 } else {
202 $q_order = "RANDOM()";
203 }
204 } else {
205 $q_order = "last_updated DESC";
206 }
207
208 $result = db_query($link, "SELECT feed_url,id,
209 SUBSTRING(last_updated,1,19) AS last_updated,
210 update_interval FROM ttrss_feeds WHERE owner_uid = '$user_id'
211 ORDER BY $q_order");
212
213 $upd_start = time();
214
215 while ($line = db_fetch_assoc($result)) {
216 $upd_intl = $line["update_interval"];
217
218 if (!$upd_intl || $upd_intl == 0) {
219 $upd_intl = get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $user_id, false);
220 }
221
222 if ($upd_intl < 0) {
223 // Updates for this feed are disabled
224 continue;
225 }
226
227 if ($fetch || (!$line["last_updated"] ||
228 time() - strtotime($line["last_updated"]) > ($upd_intl * 60))) {
229
230 // print "<!-- feed: ".$line["feed_url"]." -->";
231
232 update_rss_feed($link, $line["feed_url"], $line["id"], $force_daemon);
233
234 $upd_elapsed = time() - $upd_start;
235
236 if (MAX_UPDATE_TIME > 0 && $upd_elapsed > MAX_UPDATE_TIME) {
237 return;
238 }
239 }
240 }
241
242 // db_query($link, "COMMIT");
243
244 }
245
246 function fetch_file_contents($url) {
247 if (USE_CURL_FOR_ICONS) {
248 $tmpfile = tempnam(TMP_DIRECTORY, "ttrss-tmp");
249
250 $ch = curl_init($url);
251 $fp = fopen($tmpfile, "w");
252
253 if ($fp) {
254 curl_setopt($ch, CURLOPT_FILE, $fp);
255 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
256 curl_setopt($ch, CURLOPT_TIMEOUT, 45);
257 curl_exec($ch);
258 curl_close($ch);
259 fclose($fp);
260 }
261
262 $contents = file_get_contents($tmpfile);
263 unlink($tmpfile);
264
265 return $contents;
266
267 } else {
268 return file_get_contents($url);
269 }
270
271 }
272
273 // adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
274 // http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
275
276 function get_favicon_url($url) {
277
278 if ($html = @fetch_file_contents($url)) {
279
280 if ( preg_match('/<link[^>]+rel="(?:shortcut )?icon"[^>]+?href="([^"]+?)"/si', $html, $matches)) {
281 // Attempt to grab a favicon link from their webpage url
282 $linkUrl = html_entity_decode($matches[1]);
283
284 if (substr($linkUrl, 0, 1) == '/') {
285 $urlParts = parse_url($url);
286 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].$linkUrl;
287 } else if (substr($linkUrl, 0, 7) == 'http://') {
288 $faviconURL = $linkUrl;
289 } else if (substr($url, -1, 1) == '/') {
290 $faviconURL = $url.$linkUrl;
291 } else {
292 $faviconURL = $url.'/'.$linkUrl;
293 }
294
295 } else {
296 // If unsuccessful, attempt to "guess" the favicon location
297 $urlParts = parse_url($url);
298 $faviconURL = $urlParts['scheme'].'://'.$urlParts['host'].'/favicon.ico';
299 }
300 }
301
302 // Run a test to see if what we have attempted to get actually exists.
303 if(USE_CURL_FOR_ICONS || url_validate($faviconURL)) {
304 return $faviconURL;
305 } else {
306 return false;
307 }
308 }
309
310 function url_validate($link) {
311
312 $url_parts = @parse_url($link);
313
314 if ( empty( $url_parts["host"] ) )
315 return false;
316
317 if ( !empty( $url_parts["path"] ) ) {
318 $documentpath = $url_parts["path"];
319 } else {
320 $documentpath = "/";
321 }
322
323 if ( !empty( $url_parts["query"] ) )
324 $documentpath .= "?" . $url_parts["query"];
325
326 $host = $url_parts["host"];
327 $port = $url_parts["port"];
328
329 if ( empty($port) )
330 $port = "80";
331
332 $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
333
334 if ( !$socket )
335 return false;
336
337 fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
338
339 $http_response = fgets( $socket, 22 );
340
341 $responses = "/(200 OK)|(30[0-9] Moved)/";
342 if ( preg_match($responses, $http_response) ) {
343 fclose($socket);
344 return true;
345 } else {
346 return false;
347 }
348
349 }
350
351 function check_feed_favicon($site_url, $feed, $link) {
352 $favicon_url = get_favicon_url($site_url);
353
354 # print "FAVICON [$site_url]: $favicon_url\n";
355
356 error_reporting(0);
357
358 $icon_file = ICONS_DIR . "/$feed.ico";
359
360 if ($favicon_url && !file_exists($icon_file)) {
361 $contents = fetch_file_contents($favicon_url);
362
363 $fp = fopen($icon_file, "w");
364
365 if ($fp) {
366 fwrite($fp, $contents);
367 fclose($fp);
368 chmod($icon_file, 0644);
369 }
370 }
371
372 error_reporting(DEFAULT_ERROR_LEVEL);
373
374 }
375
376 function update_rss_feed($link, $feed_url, $feed, $ignore_daemon = false) {
377
378 if (DAEMON_REFRESH_ONLY && !$_GET["daemon"] && !$ignore_daemon) {
379 return;
380 }
381
382 if (defined('DAEMON_EXTENDED_DEBUG')) {
383 _debug("update_rss_feed: start");
384 }
385
386 $result = db_query($link, "SELECT update_interval,auth_login,auth_pass
387 FROM ttrss_feeds WHERE id = '$feed'");
388
389 $auth_login = db_fetch_result($result, 0, "auth_login");
390 $auth_pass = db_fetch_result($result, 0, "auth_pass");
391
392 $update_interval = db_fetch_result($result, 0, "update_interval");
393
394 if ($update_interval < 0) { return; }
395
396 $feed = db_escape_string($feed);
397
398 $fetch_url = $feed_url;
399
400 if ($auth_login && $auth_pass) {
401 $url_parts = array();
402 preg_match("/(^[^:]*):\/\/(.*)/", $fetch_url, $url_parts);
403
404 if ($url_parts[1] && $url_parts[2]) {
405 $fetch_url = $url_parts[1] . "://$auth_login:$auth_pass@" . $url_parts[2];
406 }
407
408 }
409
410 if (defined('DAEMON_EXTENDED_DEBUG')) {
411 _debug("update_rss_feed: fetching...");
412 }
413
414 if (!defined('DAEMON_EXTENDED_DEBUG')) {
415 error_reporting(0);
416 }
417
418 $rss = fetch_rss($fetch_url);
419
420 if (defined('DAEMON_EXTENDED_DEBUG')) {
421 _debug("update_rss_feed: fetch done, parsing...");
422 } else {
423 error_reporting (DEFAULT_ERROR_LEVEL);
424 }
425
426 $feed = db_escape_string($feed);
427
428 if ($rss) {
429
430 if (defined('DAEMON_EXTENDED_DEBUG')) {
431 _debug("update_rss_feed: processing feed data...");
432 }
433
434 // db_query($link, "BEGIN");
435
436 $result = db_query($link, "SELECT title,icon_url,site_url,owner_uid
437 FROM ttrss_feeds WHERE id = '$feed'");
438
439 $registered_title = db_fetch_result($result, 0, "title");
440 $orig_icon_url = db_fetch_result($result, 0, "icon_url");
441 $orig_site_url = db_fetch_result($result, 0, "site_url");
442
443 $owner_uid = db_fetch_result($result, 0, "owner_uid");
444
445 if (get_pref($link, 'ENABLE_FEED_ICONS', $owner_uid, false)) {
446 if (defined('DAEMON_EXTENDED_DEBUG')) {
447 _debug("update_rss_feed: checking favicon...");
448 }
449 check_feed_favicon($rss->channel["link"], $feed, $link);
450 }
451
452 if (!$registered_title || $registered_title == "[Unknown]") {
453
454 $feed_title = db_escape_string($rss->channel["title"]);
455
456 db_query($link, "UPDATE ttrss_feeds SET
457 title = '$feed_title' WHERE id = '$feed'");
458 }
459
460 $site_url = $rss->channel["link"];
461 // weird, weird Magpie
462 if (!$site_url) $site_url = db_escape_string($rss->channel["link_"]);
463
464 if ($site_url && $orig_site_url != db_escape_string($site_url)) {
465 db_query($link, "UPDATE ttrss_feeds SET
466 site_url = '$site_url' WHERE id = '$feed'");
467 }
468
469 // print "I: " . $rss->channel["image"]["url"];
470
471 $icon_url = $rss->image["url"];
472
473 if ($icon_url && !$orig_icon_url != db_escape_string($icon_url)) {
474 $icon_url = db_escape_string($icon_url);
475 db_query($link, "UPDATE ttrss_feeds SET icon_url = '$icon_url' WHERE id = '$feed'");
476 }
477
478 if (defined('DAEMON_EXTENDED_DEBUG')) {
479 _debug("update_rss_feed: loading filters...");
480 }
481
482 $filters = array();
483
484 $result = db_query($link, "SELECT reg_exp,
485 ttrss_filter_types.name AS name,
486 ttrss_filter_actions.name AS action,
487 inverse,
488 action_param
489 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
490 enabled = true AND
491 owner_uid = $owner_uid AND
492 ttrss_filter_types.id = filter_type AND
493 ttrss_filter_actions.id = action_id AND
494 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
495
496 while ($line = db_fetch_assoc($result)) {
497 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
498
499 $filter["reg_exp"] = $line["reg_exp"];
500 $filter["action"] = $line["action"];
501 $filter["action_param"] = $line["action_param"];
502 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
503
504 array_push($filters[$line["name"]], $filter);
505 }
506
507 $iterator = $rss->items;
508
509 if (!$iterator || !is_array($iterator)) $iterator = $rss->entries;
510 if (!$iterator || !is_array($iterator)) $iterator = $rss;
511
512 if (!is_array($iterator)) {
513 /* db_query($link, "UPDATE ttrss_feeds
514 SET last_error = 'Parse error: can\'t find any articles.'
515 WHERE id = '$feed'"); */
516
517 // clear any errors and mark feed as updated if fetched okay
518 // even if it's blank
519
520 db_query($link, "UPDATE ttrss_feeds
521 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
522
523 return; // no articles
524 }
525
526 if (defined('DAEMON_EXTENDED_DEBUG')) {
527 _debug("update_rss_feed: processing articles...");
528 }
529
530 foreach ($iterator as $item) {
531
532 $entry_guid = $item["id"];
533
534 if (!$entry_guid) $entry_guid = $item["guid"];
535 if (!$entry_guid) $entry_guid = $item["link"];
536 if (!$entry_guid) $entry_guid = make_guid_from_title($item["title"]);
537
538 if (defined('DAEMON_EXTENDED_DEBUG')) {
539 _debug("update_rss_feed: guid $entry_guid");
540 }
541
542 if (!$entry_guid) continue;
543
544 $entry_timestamp = "";
545
546 $rss_2_date = $item['pubdate'];
547 $rss_1_date = $item['dc']['date'];
548 $atom_date = $item['issued'];
549 if (!$atom_date) $atom_date = $item['updated'];
550
551 if ($atom_date != "") $entry_timestamp = parse_w3cdtf($atom_date);
552 if ($rss_1_date != "") $entry_timestamp = parse_w3cdtf($rss_1_date);
553 if ($rss_2_date != "") $entry_timestamp = strtotime($rss_2_date);
554
555 if ($entry_timestamp == "" || $entry_timestamp == -1 || !$entry_timestamp) {
556 $entry_timestamp = time();
557 $no_orig_date = 'true';
558 } else {
559 $no_orig_date = 'false';
560 }
561
562 $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
563
564 $entry_title = trim(strip_tags($item["title"]));
565
566 // strange Magpie workaround
567 $entry_link = $item["link_"];
568 if (!$entry_link) $entry_link = $item["link"];
569
570 if (!$entry_title) continue;
571 # if (!$entry_link) continue;
572
573 $entry_link = strip_tags($entry_link);
574
575 $entry_content = $item["content:escaped"];
576
577 if (!$entry_content) $entry_content = $item["content:encoded"];
578 if (!$entry_content) $entry_content = $item["content"];
579 if (!$entry_content) $entry_content = $item["atom_content"];
580 if (!$entry_content) $entry_content = $item["summary"];
581 if (!$entry_content) $entry_content = $item["description"];
582
583 // if (!$entry_content) continue;
584
585 // WTF
586 if (is_array($entry_content)) {
587 $entry_content = $entry_content["encoded"];
588 if (!$entry_content) $entry_content = $entry_content["escaped"];
589 }
590
591 // print_r($item);
592 // print_r(htmlspecialchars($entry_content));
593 // print "<br>";
594
595 $entry_content_unescaped = $entry_content;
596
597 $entry_comments = strip_tags($item["comments"]);
598
599 $entry_author = db_escape_string(strip_tags($item['dc']['creator']));
600
601 if ($item['author']) {
602
603 if (is_array($item['author'])) {
604
605 if (!$entry_author) {
606 $entry_author = db_escape_string(strip_tags($item['author']['name']));
607 }
608
609 if (!$entry_author) {
610 $entry_author = db_escape_string(strip_tags($item['author']['email']));
611 }
612 }
613
614 if (!$entry_author) {
615 $entry_author = db_escape_string(strip_tags($item['author']));
616 }
617 }
618
619 if (preg_match('/^[\t\n\r ]*$/', $entry_author)) $entry_author = '';
620
621 $entry_guid = db_escape_string(strip_tags($entry_guid));
622
623 $result = db_query($link, "SELECT id FROM ttrss_entries
624 WHERE guid = '$entry_guid'");
625
626 $entry_content = db_escape_string($entry_content);
627
628 $content_hash = "SHA1:" . sha1(strip_tags($entry_content));
629
630 $entry_title = db_escape_string($entry_title);
631 $entry_link = db_escape_string($entry_link);
632 $entry_comments = db_escape_string($entry_comments);
633
634 $num_comments = db_escape_string($item["slash"]["comments"]);
635
636 if (!$num_comments) $num_comments = 0;
637
638 // parse <category> entries into tags
639
640 $t_ctr = $item['category#'];
641
642 $additional_tags = false;
643
644 if ($t_ctr == 0) {
645 $additional_tags = false;
646 } else if ($t_ctr == 1) {
647 $additional_tags = array($item['category']);
648 } else {
649 $additional_tags = array();
650 for ($i = 0; $i <= $t_ctr; $i++ ) {
651 if ($item["category#$i"]) {
652 array_push($additional_tags, $item["category#$i"]);
653 }
654 }
655 }
656
657 // parse <dc:subject> elements
658
659 $t_ctr = $item['dc']['subject#'];
660
661 if ($t_ctr == 1) {
662 $additional_tags = array($item['dc']['subject']);
663 } else if ($t_ctr > 1) {
664 $additional_tags = array();
665 for ($i = 0; $i <= $t_ctr; $i++ ) {
666 if ($item['dc']["subject#$i"]) {
667 array_push($additional_tags, $item['dc']["subject#$i"]);
668 }
669 }
670 }
671
672 # sanitize content
673
674 // $entry_content = sanitize_rss($entry_content);
675
676 if (defined('DAEMON_EXTENDED_DEBUG')) {
677 _debug("update_rss_feed: done collecting data [TITLE:$entry_title]");
678 }
679
680 db_query($link, "BEGIN");
681
682 if (db_num_rows($result) == 0) {
683
684 if (defined('DAEMON_EXTENDED_DEBUG')) {
685 _debug("update_rss_feed: base guid not found");
686 }
687
688 // base post entry does not exist, create it
689
690 $result = db_query($link,
691 "INSERT INTO ttrss_entries
692 (title,
693 guid,
694 link,
695 updated,
696 content,
697 content_hash,
698 no_orig_date,
699 date_entered,
700 comments,
701 num_comments,
702 author)
703 VALUES
704 ('$entry_title',
705 '$entry_guid',
706 '$entry_link',
707 '$entry_timestamp_fmt',
708 '$entry_content',
709 '$content_hash',
710 $no_orig_date,
711 NOW(),
712 '$entry_comments',
713 '$num_comments',
714 '$entry_author')");
715 } else {
716 // we keep encountering the entry in feeds, so we need to
717 // update date_entered column so that we don't get horrible
718 // dupes when the entry gets purged and reinserted again e.g.
719 // in the case of SLOW SLOW OMG SLOW updating feeds
720
721 $base_entry_id = db_fetch_result($result, 0, "id");
722
723 db_query($link, "UPDATE ttrss_entries SET date_entered = NOW()
724 WHERE id = '$base_entry_id'");
725 }
726
727 // now it should exist, if not - bad luck then
728
729 $result = db_query($link, "SELECT
730 id,content_hash,no_orig_date,title,
731 substring(date_entered,1,19) as date_entered,
732 substring(updated,1,19) as updated,
733 num_comments
734 FROM
735 ttrss_entries
736 WHERE guid = '$entry_guid'");
737
738 if (db_num_rows($result) == 1) {
739
740 if (defined('DAEMON_EXTENDED_DEBUG')) {
741 _debug("update_rss_feed: base guid found, checking for user record");
742 }
743
744 // this will be used below in update handler
745 $orig_content_hash = db_fetch_result($result, 0, "content_hash");
746 $orig_title = db_fetch_result($result, 0, "title");
747 $orig_num_comments = db_fetch_result($result, 0, "num_comments");
748 $orig_date_entered = strtotime(db_fetch_result($result,
749 0, "date_entered"));
750
751 $ref_id = db_fetch_result($result, 0, "id");
752
753 // check for user post link to main table
754
755 // do we allow duplicate posts with same GUID in different feeds?
756 if (get_pref($link, "ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
757 $dupcheck_qpart = "AND feed_id = '$feed'";
758 } else {
759 $dupcheck_qpart = "";
760 }
761
762 // error_reporting(0);
763
764 $article_filters = get_article_filters($filters, $entry_title,
765 $entry_content, $entry_link);
766
767 if (defined('DAEMON_EXTENDED_DEBUG')) {
768 _debug("update_rss_feed: article filters: ");
769 if (count($article_filters) != 0) {
770 print_r($article_filters);
771 }
772 }
773
774 if (find_article_filter($article_filters, "filter")) {
775 continue;
776 }
777
778 // error_reporting (DEFAULT_ERROR_LEVEL);
779
780 $result = db_query($link,
781 "SELECT ref_id FROM ttrss_user_entries WHERE
782 ref_id = '$ref_id' AND owner_uid = '$owner_uid'
783 $dupcheck_qpart");
784
785 // okay it doesn't exist - create user entry
786 if (db_num_rows($result) == 0) {
787
788 if (defined('DAEMON_EXTENDED_DEBUG')) {
789 _debug("update_rss_feed: user record not found, creating...");
790 }
791
792 if (!find_article_filter($article_filters, 'catchup')) {
793 $unread = 'true';
794 $last_read_qpart = 'NULL';
795 } else {
796 $unread = 'false';
797 $last_read_qpart = 'NOW()';
798 }
799
800 if (find_article_filter($article_filters, 'mark')) {
801 $marked = 'true';
802 } else {
803 $marked = 'false';
804 }
805
806 $result = db_query($link,
807 "INSERT INTO ttrss_user_entries
808 (ref_id, owner_uid, feed_id, unread, last_read, marked)
809 VALUES ('$ref_id', '$owner_uid', '$feed', $unread,
810 $last_read_qpart, $marked)");
811 }
812
813 $post_needs_update = false;
814
815 if (get_pref($link, "UPDATE_POST_ON_CHECKSUM_CHANGE", $owner_uid, false) &&
816 ($content_hash != $orig_content_hash)) {
817 // print "<!-- [$entry_title] $content_hash vs $orig_content_hash -->";
818 $post_needs_update = true;
819 }
820
821 if (db_escape_string($orig_title) != $entry_title) {
822 $post_needs_update = true;
823 }
824
825 if ($orig_num_comments != $num_comments) {
826 $post_needs_update = true;
827 }
828
829 // this doesn't seem to be very reliable
830 //
831 // if ($orig_timestamp != $entry_timestamp && !$orig_no_orig_date) {
832 // $post_needs_update = true;
833 // }
834
835 // if post needs update, update it and mark all user entries
836 // linking to this post as updated
837 if ($post_needs_update) {
838
839 if (defined('DAEMON_EXTENDED_DEBUG')) {
840 _debug("update_rss_feed: post $entry_guid needs update...");
841 }
842
843 // print "<!-- post $orig_title needs update : $post_needs_update -->";
844
845 db_query($link, "UPDATE ttrss_entries
846 SET title = '$entry_title', content = '$entry_content',
847 content_hash = '$content_hash',
848 num_comments = '$num_comments'
849 WHERE id = '$ref_id'");
850
851 if (get_pref($link, "MARK_UNREAD_ON_UPDATE", $owner_uid, false)) {
852 db_query($link, "UPDATE ttrss_user_entries
853 SET last_read = null, unread = true WHERE ref_id = '$ref_id'");
854 } else {
855 db_query($link, "UPDATE ttrss_user_entries
856 SET last_read = null WHERE ref_id = '$ref_id' AND unread = false");
857 }
858
859 }
860 }
861
862 db_query($link, "COMMIT");
863
864 if (defined('DAEMON_EXTENDED_DEBUG')) {
865 _debug("update_rss_feed: looking for tags...");
866 }
867
868 /* taaaags */
869 // <a href="..." rel="tag">Xorg</a>, //
870
871 $entry_tags = null;
872
873 preg_match_all("/<a.*?rel=['\"]tag['\"].*?>([^<]+)<\/a>/i",
874 $entry_content_unescaped, $entry_tags);
875
876 /* print "<p><br/>$entry_title : $entry_content_unescaped<br>";
877 print_r($entry_tags);
878 print "<br/></p>"; */
879
880 $entry_tags = $entry_tags[1];
881
882 # check for manual tags
883
884 $tag_filter = find_article_filter($article_filters, "tag");
885
886 if ($tag_filter) {
887
888 $manual_tags = trim_array(split(",", $tag_filter[1]));
889
890 foreach ($manual_tags as $tag) {
891 if (tag_is_valid($tag)) {
892 array_push($entry_tags, $tag);
893 }
894 }
895 }
896
897 $boring_tags = trim_array(split(",", mb_strtolower(get_pref($link,
898 'BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
899
900 if ($additional_tags && is_array($additional_tags)) {
901 foreach ($additional_tags as $tag) {
902 if (tag_is_valid($tag) &&
903 array_search($tag, $boring_tags) === FALSE) {
904 array_push($entry_tags, $tag);
905 }
906 }
907 }
908
909 // print "<p>TAGS: "; print_r($entry_tags); print "</p>";
910
911 if (count($entry_tags) > 0) {
912
913 db_query($link, "BEGIN");
914
915 $result = db_query($link, "SELECT id,int_id
916 FROM ttrss_entries,ttrss_user_entries
917 WHERE guid = '$entry_guid'
918 AND feed_id = '$feed' AND ref_id = id
919 AND owner_uid = '$owner_uid'");
920
921 if (db_num_rows($result) == 1) {
922
923 $entry_id = db_fetch_result($result, 0, "id");
924 $entry_int_id = db_fetch_result($result, 0, "int_id");
925
926 foreach ($entry_tags as $tag) {
927
928 $tag = sanitize_tag($tag);
929 $tag = db_escape_string($tag);
930
931 if (!tag_is_valid($tag)) continue;
932
933 $result = db_query($link, "SELECT id FROM ttrss_tags
934 WHERE tag_name = '$tag' AND post_int_id = '$entry_int_id' AND
935 owner_uid = '$owner_uid' LIMIT 1");
936
937 // print db_fetch_result($result, 0, "id");
938
939 if ($result && db_num_rows($result) == 0) {
940
941 db_query($link, "INSERT INTO ttrss_tags
942 (owner_uid,tag_name,post_int_id)
943 VALUES ('$owner_uid','$tag', '$entry_int_id')");
944 }
945 }
946 }
947 db_query($link, "COMMIT");
948 }
949 }
950
951 db_query($link, "UPDATE ttrss_feeds
952 SET last_updated = NOW(), last_error = '' WHERE id = '$feed'");
953
954 // db_query($link, "COMMIT");
955
956 } else {
957 $error_msg = db_escape_string(magpie_error());
958 db_query($link,
959 "UPDATE ttrss_feeds SET last_error = '$error_msg',
960 last_updated = NOW() WHERE id = '$feed'");
961 }
962
963 if (defined('DAEMON_EXTENDED_DEBUG')) {
964 _debug("update_rss_feed: done");
965 }
966
967 }
968
969 function print_select($id, $default, $values, $attributes = "") {
970 print "<select name=\"$id\" id=\"$id\" $attributes>";
971 foreach ($values as $v) {
972 if ($v == $default)
973 $sel = " selected";
974 else
975 $sel = "";
976
977 print "<option$sel>$v</option>";
978 }
979 print "</select>";
980 }
981
982 function print_select_hash($id, $default, $values, $attributes = "") {
983 print "<select name=\"$id\" id='$id' $attributes>";
984 foreach (array_keys($values) as $v) {
985 if ($v == $default)
986 $sel = "selected";
987 else
988 $sel = "";
989
990 print "<option $sel value=\"$v\">".$values[$v]."</option>";
991 }
992
993 print "</select>";
994 }
995
996 function get_article_filters($filters, $title, $content, $link) {
997 $matches = array();
998
999 if ($filters["title"]) {
1000 foreach ($filters["title"] as $filter) {
1001 $reg_exp = $filter["reg_exp"];
1002 $inverse = $filter["inverse"];
1003 if ((!$inverse && preg_match("/$reg_exp/i", $title)) ||
1004 ($inverse && !preg_match("/$reg_exp/i", $title))) {
1005
1006 array_push($matches, array($filter["action"], $filter["action_param"]));
1007 }
1008 }
1009 }
1010
1011 if ($filters["content"]) {
1012 foreach ($filters["content"] as $filter) {
1013 $reg_exp = $filter["reg_exp"];
1014 $inverse = $filter["inverse"];
1015
1016 if ((!$inverse && preg_match("/$reg_exp/i", $content)) ||
1017 ($inverse && !preg_match("/$reg_exp/i", $content))) {
1018
1019 array_push($matches, array($filter["action"], $filter["action_param"]));
1020 }
1021 }
1022 }
1023
1024 if ($filters["both"]) {
1025 foreach ($filters["both"] as $filter) {
1026 $reg_exp = $filter["reg_exp"];
1027 $inverse = $filter["inverse"];
1028
1029 if ($inverse) {
1030 if (!preg_match("/$reg_exp/i", $title) || !preg_match("/$reg_exp/i", $content)) {
1031 array_push($matches, array($filter["action"], $filter["action_param"]));
1032 }
1033 } else {
1034 if (preg_match("/$reg_exp/i", $title) || preg_match("/$reg_exp/i", $content)) {
1035 array_push($matches, array($filter["action"], $filter["action_param"]));
1036 }
1037 }
1038 }
1039 }
1040
1041 if ($filters["link"]) {
1042 $reg_exp = $filter["reg_exp"];
1043 foreach ($filters["link"] as $filter) {
1044 $reg_exp = $filter["reg_exp"];
1045 $inverse = $filter["inverse"];
1046
1047 if ((!$inverse && preg_match("/$reg_exp/i", $link)) ||
1048 ($inverse && !preg_match("/$reg_exp/i", $link))) {
1049
1050 array_push($matches, array($filter["action"], $filter["action_param"]));
1051 }
1052 }
1053 }
1054
1055 return $matches;
1056 }
1057
1058 function find_article_filter($filters, $filter_name) {
1059 foreach ($filters as $f) {
1060 if ($f[0] == $filter_name) {
1061 return $f;
1062 };
1063 }
1064 return false;
1065 }
1066
1067 function printFeedEntry($feed_id, $class, $feed_title, $unread, $icon_file, $link,
1068 $rtl_content = false, $last_updated = false, $last_error = false) {
1069
1070 if (file_exists($icon_file) && filesize($icon_file) > 0) {
1071 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"$icon_file\">";
1072 } else {
1073 $feed_icon = "<img id=\"FIMG-$feed_id\" src=\"images/blank_icon.gif\">";
1074 }
1075
1076 if ($rtl_content) {
1077 $rtl_tag = "dir=\"rtl\"";
1078 } else {
1079 $rtl_tag = "dir=\"ltr\"";
1080 }
1081
1082 $error_notify_msg = "";
1083
1084 if ($last_error) {
1085 $link_title = "Error: $last_error ($last_updated)";
1086 $error_notify_msg = "(Error)";
1087 } else if ($last_updated) {
1088 $link_title = "Updated: $last_updated";
1089 }
1090
1091 $feed = "<a title=\"$link_title\" id=\"FEEDL-$feed_id\"
1092 href=\"javascript:viewfeed('$feed_id', '', false, '', false, 0);\">$feed_title</a>";
1093
1094 print "<li id=\"FEEDR-$feed_id\" class=\"$class\">";
1095 if (get_pref($link, 'ENABLE_FEED_ICONS')) {
1096 print "$feed_icon";
1097 }
1098
1099 print "<span $rtl_tag id=\"FEEDN-$feed_id\">$feed</span>";
1100
1101 if ($unread != 0) {
1102 $fctr_class = "";
1103 } else {
1104 $fctr_class = "class=\"invisible\"";
1105 }
1106
1107 print " <span $rtl_tag $fctr_class id=\"FEEDCTR-$feed_id\">
1108 (<span id=\"FEEDU-$feed_id\">$unread</span>)</span>";
1109
1110 if (get_pref($link, "EXTENDED_FEEDLIST")) {
1111 print "<div class=\"feedExtInfo\">
1112 <span id=\"FLUPD-$feed_id\">$last_updated $error_notify_msg</span></div>";
1113 }
1114
1115 print "</li>";
1116
1117 }
1118
1119 function getmicrotime() {
1120 list($usec, $sec) = explode(" ",microtime());
1121 return ((float)$usec + (float)$sec);
1122 }
1123
1124 function print_radio($id, $default, $values, $attributes = "") {
1125 foreach ($values as $v) {
1126
1127 if ($v == $default)
1128 $sel = "checked";
1129 else
1130 $sel = "";
1131
1132 if ($v == "Yes") {
1133 $sel .= " value=\"1\"";
1134 } else {
1135 $sel .= " value=\"0\"";
1136 }
1137
1138 print "<input class=\"noborder\"
1139 type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
1140
1141 }
1142 }
1143
1144 function initialize_user_prefs($link, $uid) {
1145
1146 $uid = db_escape_string($uid);
1147
1148 db_query($link, "BEGIN");
1149
1150 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
1151
1152 $u_result = db_query($link, "SELECT pref_name
1153 FROM ttrss_user_prefs WHERE owner_uid = '$uid'");
1154
1155 $active_prefs = array();
1156
1157 while ($line = db_fetch_assoc($u_result)) {
1158 array_push($active_prefs, $line["pref_name"]);
1159 }
1160
1161 while ($line = db_fetch_assoc($result)) {
1162 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
1163 // print "adding " . $line["pref_name"] . "<br>";
1164
1165 db_query($link, "INSERT INTO ttrss_user_prefs
1166 (owner_uid,pref_name,value) VALUES
1167 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
1168
1169 }
1170 }
1171
1172 db_query($link, "COMMIT");
1173
1174 }
1175
1176 function lookup_user_id($link, $user) {
1177
1178 $result = db_query($link, "SELECT id FROM ttrss_users WHERE
1179 login = '$login'");
1180
1181 if (db_num_rows($result) == 1) {
1182 return db_fetch_result($result, 0, "id");
1183 } else {
1184 return false;
1185 }
1186 }
1187
1188 function http_authenticate_user($link) {
1189
1190 if (!$_SERVER["PHP_AUTH_USER"]) {
1191
1192 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1193 header('HTTP/1.0 401 Unauthorized');
1194 exit;
1195
1196 } else {
1197 $auth_result = authenticate_user($link,
1198 $_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
1199
1200 if (!$auth_result) {
1201 header('WWW-Authenticate: Basic realm="Tiny Tiny RSS RSSGen"');
1202 header('HTTP/1.0 401 Unauthorized');
1203 exit;
1204 }
1205 }
1206
1207 return true;
1208 }
1209
1210 function authenticate_user($link, $login, $password, $force_auth = false) {
1211
1212 if (!SINGLE_USER_MODE) {
1213
1214 $pwd_hash = 'SHA1:' . sha1($password);
1215
1216 if ($force_auth && defined('_DEBUG_USER_SWITCH')) {
1217 $query = "SELECT id,login,access_level
1218 FROM ttrss_users WHERE
1219 login = '$login'";
1220 } else {
1221 $query = "SELECT id,login,access_level
1222 FROM ttrss_users WHERE
1223 login = '$login' AND pwd_hash = '$pwd_hash'";
1224 }
1225
1226 $result = db_query($link, $query);
1227
1228 if (db_num_rows($result) == 1) {
1229 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
1230 $_SESSION["name"] = db_fetch_result($result, 0, "login");
1231 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
1232
1233 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1234 $_SESSION["uid"]);
1235
1236 $user_theme = get_user_theme_path($link);
1237
1238 $_SESSION["theme"] = $user_theme;
1239 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1240
1241 initialize_user_prefs($link, $_SESSION["uid"]);
1242
1243 return true;
1244 }
1245
1246 return false;
1247
1248 } else {
1249
1250 $_SESSION["uid"] = 1;
1251 $_SESSION["name"] = "admin";
1252
1253 $user_theme = get_user_theme_path($link);
1254
1255 $_SESSION["theme"] = $user_theme;
1256 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
1257
1258 initialize_user_prefs($link, $_SESSION["uid"]);
1259
1260 return true;
1261 }
1262 }
1263
1264 function make_password($length = 8) {
1265
1266 $password = "";
1267 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
1268
1269 $i = 0;
1270
1271 while ($i < $length) {
1272 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
1273
1274 if (!strstr($password, $char)) {
1275 $password .= $char;
1276 $i++;
1277 }
1278 }
1279 return $password;
1280 }
1281
1282 // this is called after user is created to initialize default feeds, labels
1283 // or whatever else
1284
1285 // user preferences are checked on every login, not here
1286
1287 function initialize_user($link, $uid) {
1288
1289 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1290 values ('$uid','unread = true', 'Unread articles')");
1291
1292 db_query($link, "insert into ttrss_labels (owner_uid,sql_exp,description)
1293 values ('$uid','last_read is null and unread = false', 'Updated articles')");
1294
1295 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1296 values ('$uid', 'Tiny Tiny RSS: New Releases',
1297 'http://tt-rss.spb.ru/releases.rss')");
1298
1299 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
1300 values ('$uid', 'Tiny Tiny RSS: Forum',
1301 'http://tt-rss.spb.ru/forum/rss.php')");
1302 }
1303
1304 function logout_user() {
1305 session_destroy();
1306 if (isset($_COOKIE[session_name()])) {
1307 setcookie(session_name(), '', time()-42000, '/');
1308 }
1309 }
1310
1311 function get_script_urlpath() {
1312 return preg_replace('/\/[^\/]*$/', "", $_SERVER["REQUEST_URI"]);
1313 }
1314
1315 function validate_session($link) {
1316 if (SESSION_CHECK_ADDRESS && $_SESSION["uid"]) {
1317 if ($_SESSION["ip_address"]) {
1318 if ($_SESSION["ip_address"] != $_SERVER["REMOTE_ADDR"]) {
1319 $_SESSION["login_error_msg"] = "Session failed to validate (incorrect IP)";
1320 return false;
1321 }
1322 }
1323 }
1324
1325 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
1326
1327 //print_r($_SESSION);
1328
1329 if (time() > $_SESSION["cookie_lifetime"]) {
1330 return false;
1331 }
1332 } */
1333
1334 return true;
1335 }
1336
1337 function login_sequence($link, $mobile = false) {
1338 if (!SINGLE_USER_MODE) {
1339
1340 if (defined('_DEBUG_USER_SWITCH') && $_SESSION["uid"]) {
1341 $swu = db_escape_string($_REQUEST["swu"]);
1342 if ($swu) {
1343 $_SESSION["prefs_cache"] = false;
1344 return authenticate_user($link, $swu, null, true);
1345 }
1346 }
1347
1348 $login_action = $_POST["login_action"];
1349
1350 # try to authenticate user if called from login form
1351 if ($login_action == "do_login") {
1352 $login = $_POST["login"];
1353 $password = $_POST["password"];
1354 $remember_me = $_POST["remember_me"];
1355
1356 if (authenticate_user($link, $login, $password)) {
1357 $_POST["password"] = "";
1358
1359 header("Location: " . $_SERVER["REQUEST_URI"]);
1360 exit;
1361
1362 return;
1363 } else {
1364 $_SESSION["login_error_msg"] = "Incorrect username or password";
1365 }
1366 }
1367
1368 // print session_id();
1369 // print_r($_SESSION);
1370
1371 if (!$_SESSION["uid"] || !validate_session($link)) {
1372 render_login_form($link, $mobile);
1373 exit;
1374 } else {
1375 /* bump login timestamp */
1376 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
1377 $_SESSION["uid"]);
1378 }
1379
1380 } else {
1381 return authenticate_user($link, "admin", null);
1382 }
1383 }
1384
1385 function truncate_string($str, $max_len) {
1386 if (mb_strlen($str, "utf-8") > $max_len - 3) {
1387 return mb_substr($str, 0, $max_len, "utf-8") . "...";
1388 } else {
1389 return $str;
1390 }
1391 }
1392
1393 function get_user_theme_path($link) {
1394 $result = db_query($link, "SELECT theme_path
1395 FROM
1396 ttrss_themes,ttrss_users
1397 WHERE ttrss_themes.id = theme_id AND ttrss_users.id = " . $_SESSION["uid"]);
1398 if (db_num_rows($result) != 0) {
1399 return db_fetch_result($result, 0, "theme_path");
1400 } else {
1401 return null;
1402 }
1403 }
1404
1405 function smart_date_time($timestamp) {
1406 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1407 return date("G:i", $timestamp);
1408 } else if (date("Y", $timestamp) == date("Y")) {
1409 return date("M d, G:i", $timestamp);
1410 } else {
1411 return date("Y/m/d, G:i", $timestamp);
1412 }
1413 }
1414
1415 function smart_date($timestamp) {
1416 if (date("Y.m.d", $timestamp) == date("Y.m.d")) {
1417 return "Today";
1418 } else if (date("Y", $timestamp) == date("Y")) {
1419 return date("D m", $timestamp);
1420 } else {
1421 return date("Y/m/d", $timestamp);
1422 }
1423 }
1424
1425 function sql_bool_to_string($s) {
1426 if ($s == "t" || $s == "1") {
1427 return "true";
1428 } else {
1429 return "false";
1430 }
1431 }
1432
1433 function sql_bool_to_bool($s) {
1434 if ($s == "t" || $s == "1") {
1435 return true;
1436 } else {
1437 return false;
1438 }
1439 }
1440
1441
1442 function toggleEvenOdd($a) {
1443 if ($a == "even")
1444 return "odd";
1445 else
1446 return "even";
1447 }
1448
1449 function sanity_check($link) {
1450
1451 error_reporting(0);
1452
1453 $error_code = 0;
1454 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1455 $schema_version = db_fetch_result($result, 0, "schema_version");
1456
1457 if ($schema_version != SCHEMA_VERSION) {
1458 $error_code = 5;
1459 }
1460
1461 if (DB_TYPE == "mysql") {
1462 $result = db_query($link, "SELECT true", false);
1463 if (db_num_rows($result) != 1) {
1464 $error_code = 10;
1465 }
1466 }
1467
1468 error_reporting (DEFAULT_ERROR_LEVEL);
1469
1470 if ($error_code != 0) {
1471 print_error_xml($error_code);
1472 return false;
1473 } else {
1474 return true;
1475 }
1476 }
1477
1478 function file_is_locked($filename) {
1479 error_reporting(0);
1480 $fp = fopen($filename, "r");
1481 error_reporting(DEFAULT_ERROR_LEVEL);
1482 if ($fp) {
1483 if (flock($fp, LOCK_EX | LOCK_NB)) {
1484 flock($fp, LOCK_UN);
1485 fclose($fp);
1486 return false;
1487 }
1488 fclose($fp);
1489 return true;
1490 }
1491 return false;
1492 }
1493
1494 function make_lockfile($filename) {
1495 $fp = fopen($filename, "w");
1496
1497 if (flock($fp, LOCK_EX | LOCK_NB)) {
1498 return $fp;
1499 } else {
1500 return false;
1501 }
1502 }
1503
1504 function sql_random_function() {
1505 if (DB_TYPE == "mysql") {
1506 return "RAND()";
1507 } else {
1508 return "RANDOM()";
1509 }
1510 }
1511
1512 function catchup_feed($link, $feed, $cat_view) {
1513
1514 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1515
1516 if ($cat_view) {
1517
1518 if ($feed > 0) {
1519 $cat_qpart = "cat_id = '$feed'";
1520 } else {
1521 $cat_qpart = "cat_id IS NULL";
1522 }
1523
1524 $tmp_result = db_query($link, "SELECT id
1525 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = " .
1526 $_SESSION["uid"]);
1527
1528 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1529
1530 $tmp_feed = $tmp_line["id"];
1531
1532 db_query($link, "UPDATE ttrss_user_entries
1533 SET unread = false,last_read = NOW()
1534 WHERE feed_id = '$tmp_feed' AND owner_uid = " . $_SESSION["uid"]);
1535 }
1536
1537 } else if ($feed > 0) {
1538
1539 $tmp_result = db_query($link, "SELECT id
1540 FROM ttrss_feeds WHERE parent_feed = '$feed'
1541 ORDER BY cat_id,title");
1542
1543 $parent_ids = array();
1544
1545 if (db_num_rows($tmp_result) > 0) {
1546 while ($p = db_fetch_assoc($tmp_result)) {
1547 array_push($parent_ids, "feed_id = " . $p["id"]);
1548 }
1549
1550 $children_qpart = implode(" OR ", $parent_ids);
1551
1552 db_query($link, "UPDATE ttrss_user_entries
1553 SET unread = false,last_read = NOW()
1554 WHERE (feed_id = '$feed' OR $children_qpart)
1555 AND owner_uid = " . $_SESSION["uid"]);
1556
1557 } else {
1558 db_query($link, "UPDATE ttrss_user_entries
1559 SET unread = false,last_read = NOW()
1560 WHERE feed_id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
1561 }
1562
1563 } else if ($feed < 0 && $feed > -10) { // special, like starred
1564
1565 if ($feed == -1) {
1566 db_query($link, "UPDATE ttrss_user_entries
1567 SET unread = false,last_read = NOW()
1568 WHERE marked = true AND owner_uid = ".$_SESSION["uid"]);
1569 }
1570
1571 } else if ($feed < -10) { // label
1572
1573 // TODO make this more efficient
1574
1575 $label_id = -$feed - 11;
1576
1577 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
1578 WHERE id = '$label_id'");
1579
1580 if ($tmp_result) {
1581 $sql_exp = db_fetch_result($tmp_result, 0, "sql_exp");
1582
1583 db_query($link, "BEGIN");
1584
1585 $tmp2_result = db_query($link,
1586 "SELECT
1587 int_id
1588 FROM
1589 ttrss_user_entries,ttrss_entries,ttrss_feeds
1590 WHERE
1591 ref_id = ttrss_entries.id AND
1592 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1593 $sql_exp AND
1594 ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1595
1596 while ($tmp_line = db_fetch_assoc($tmp2_result)) {
1597 db_query($link, "UPDATE
1598 ttrss_user_entries
1599 SET
1600 unread = false, last_read = NOW()
1601 WHERE
1602 int_id = " . $tmp_line["int_id"]);
1603 }
1604
1605 db_query($link, "COMMIT");
1606
1607 /* db_query($link, "UPDATE ttrss_user_entries,ttrss_entries
1608 SET unread = false,last_read = NOW()
1609 WHERE $sql_exp
1610 AND ref_id = id
1611 AND owner_uid = ".$_SESSION["uid"]); */
1612 }
1613 }
1614 } else { // tag
1615 db_query($link, "BEGIN");
1616
1617 $tag_name = db_escape_string($feed);
1618
1619 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1620 WHERE tag_name = '$tag_name' AND owner_uid = " . $_SESSION["uid"]);
1621
1622 while ($line = db_fetch_assoc($result)) {
1623 db_query($link, "UPDATE ttrss_user_entries SET
1624 unread = false, last_read = NOW()
1625 WHERE int_id = " . $line["post_int_id"]);
1626 }
1627 db_query($link, "COMMIT");
1628 }
1629 }
1630
1631 function update_generic_feed($link, $feed, $cat_view) {
1632 if ($cat_view) {
1633
1634 if ($feed > 0) {
1635 $cat_qpart = "cat_id = '$feed'";
1636 } else {
1637 $cat_qpart = "cat_id IS NULL";
1638 }
1639
1640 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1641 WHERE $cat_qpart AND owner_uid = " . $_SESSION["uid"]);
1642
1643 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1644 $feed_url = $tmp_line["feed_url"];
1645 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1646 }
1647
1648 } else {
1649 $tmp_result = db_query($link, "SELECT feed_url FROM ttrss_feeds
1650 WHERE id = '$feed'");
1651 $feed_url = db_fetch_result($tmp_result, 0, "feed_url");
1652 update_rss_feed($link, $feed_url, $feed, ENABLE_UPDATE_DAEMON);
1653 }
1654 }
1655
1656 function getAllCounters($link, $omode = "tflc") {
1657 /* getLabelCounters($link);
1658 getFeedCounters($link);
1659 getTagCounters($link);
1660 getGlobalCounters($link);
1661 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1662 getCategoryCounters($link);
1663 } */
1664
1665 if (!$omode) $omode = "tflc";
1666
1667 getGlobalCounters($link);
1668
1669 if (strchr($omode, "l")) getLabelCounters($link);
1670 if (strchr($omode, "f")) getFeedCounters($link);
1671 if (strchr($omode, "t")) getTagCounters($link);
1672 if (strchr($omode, "c")) {
1673 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1674 getCategoryCounters($link);
1675 }
1676 }
1677 }
1678
1679 function getCategoryCounters($link) {
1680 $result = db_query($link, "SELECT cat_id,SUM((SELECT COUNT(int_id)
1681 FROM ttrss_user_entries WHERE feed_id = ttrss_feeds.id
1682 AND unread = true)) AS unread FROM ttrss_feeds
1683 WHERE
1684 hidden = false AND owner_uid = ".$_SESSION["uid"]." GROUP BY cat_id");
1685
1686 while ($line = db_fetch_assoc($result)) {
1687 $line["cat_id"] = sprintf("%d", $line["cat_id"]);
1688 print "<counter type=\"category\" id=\"".$line["cat_id"]."\" counter=\"".
1689 $line["unread"]."\"/>";
1690 }
1691 }
1692
1693 function getCategoryUnread($link, $cat) {
1694
1695 if ($cat != 0) {
1696 $cat_query = "cat_id = '$cat'";
1697 } else {
1698 $cat_query = "cat_id IS NULL";
1699 }
1700
1701 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1702 AND hidden = false
1703 AND owner_uid = " . $_SESSION["uid"]);
1704
1705 $cat_feeds = array();
1706 while ($line = db_fetch_assoc($result)) {
1707 array_push($cat_feeds, "feed_id = " . $line["id"]);
1708 }
1709
1710 if (count($cat_feeds) == 0) return 0;
1711
1712 $match_part = implode(" OR ", $cat_feeds);
1713
1714 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1715 FROM ttrss_user_entries
1716 WHERE unread = true AND ($match_part) AND owner_uid = " . $_SESSION["uid"]);
1717
1718 $unread = 0;
1719
1720 # this needs to be rewritten
1721 while ($line = db_fetch_assoc($result)) {
1722 $unread += $line["unread"];
1723 }
1724
1725 return $unread;
1726
1727 }
1728
1729 function getFeedUnread($link, $feed, $is_cat = false) {
1730 $n_feed = sprintf("%d", $feed);
1731
1732 if ($is_cat) {
1733 return getCategoryUnread($link, $n_feed);
1734 } else if ($n_feed == -1) {
1735 $match_part = "marked = true";
1736 } else if ($n_feed > 0) {
1737
1738 $result = db_query($link, "SELECT id FROM ttrss_feeds
1739 WHERE parent_feed = '$n_feed'
1740 AND hidden = false
1741 AND owner_uid = " . $_SESSION["uid"]);
1742
1743 if (db_num_rows($result) > 0) {
1744
1745 $linked_feeds = array();
1746 while ($line = db_fetch_assoc($result)) {
1747 array_push($linked_feeds, "feed_id = " . $line["id"]);
1748 }
1749
1750 array_push($linked_feeds, "feed_id = $n_feed");
1751
1752 $match_part = implode(" OR ", $linked_feeds);
1753
1754 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1755 FROM ttrss_user_entries
1756 WHERE unread = true AND ($match_part)
1757 AND owner_uid = " . $_SESSION["uid"]);
1758
1759 $unread = 0;
1760
1761 # this needs to be rewritten
1762 while ($line = db_fetch_assoc($result)) {
1763 $unread += $line["unread"];
1764 }
1765
1766 return $unread;
1767
1768 } else {
1769 $match_part = "feed_id = '$n_feed'";
1770 }
1771 } else if ($feed < -10) {
1772
1773 $label_id = -$feed - 11;
1774
1775 $result = db_query($link, "SELECT sql_exp FROM ttrss_labels WHERE
1776 id = '$label_id' AND owner_uid = " . $_SESSION["uid"]);
1777
1778 $match_part = db_fetch_result($result, 0, "sql_exp");
1779 }
1780
1781 if ($match_part) {
1782
1783 $result = db_query($link, "SELECT count(int_id) AS unread
1784 FROM ttrss_user_entries,ttrss_feeds,ttrss_entries WHERE
1785 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1786 ttrss_user_entries.ref_id = ttrss_entries.id AND
1787 ttrss_feeds.hidden = false AND
1788 unread = true AND ($match_part) AND ttrss_user_entries.owner_uid = " . $_SESSION["uid"]);
1789
1790 } else {
1791
1792 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1793 FROM ttrss_tags,ttrss_user_entries
1794 WHERE tag_name = '$feed' AND post_int_id = int_id AND unread = true AND
1795 ttrss_tags.owner_uid = " . $_SESSION["uid"]);
1796 }
1797
1798 $unread = db_fetch_result($result, 0, "unread");
1799
1800 return $unread;
1801 }
1802
1803 /* FIXME this needs reworking */
1804
1805 function getGlobalUnread($link, $user_id = false) {
1806
1807 if (!$user_id) {
1808 $user_id = $_SESSION["uid"];
1809 }
1810
1811 $result = db_query($link, "SELECT count(ttrss_entries.id) as c_id FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1812 WHERE unread = true AND
1813 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1814 ttrss_user_entries.ref_id = ttrss_entries.id AND
1815 hidden = false AND
1816 ttrss_user_entries.owner_uid = '$user_id'");
1817 $c_id = db_fetch_result($result, 0, "c_id");
1818 return $c_id;
1819 }
1820
1821 function getGlobalCounters($link, $global_unread = -1) {
1822 if ($global_unread == -1) {
1823 $global_unread = getGlobalUnread($link);
1824 }
1825 print "<counter type=\"global\" id='global-unread'
1826 counter='$global_unread'/>";
1827
1828 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1829 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1830
1831 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1832
1833 print "<counter type=\"global\" id='subscribed-feeds'
1834 counter='$subscribed_feeds'/>";
1835
1836 }
1837
1838 function getTagCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1839
1840 if ($smart_mode) {
1841 if (!$_SESSION["tctr_last_value"]) {
1842 $_SESSION["tctr_last_value"] = array();
1843 }
1844 }
1845
1846 $old_counters = $_SESSION["tctr_last_value"];
1847
1848 $tctrs_modified = false;
1849
1850 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
1851 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
1852 ttrss_user_entries.ref_id = ttrss_entries.id AND
1853 ttrss_tags.owner_uid = ".$_SESSION["uid"]." AND
1854 post_int_id = ttrss_user_entries.int_id AND unread = true GROUP BY tag_name
1855 UNION
1856 select tag_name,0 as count FROM ttrss_tags
1857 WHERE ttrss_tags.owner_uid = ".$_SESSION["uid"]); */
1858
1859 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1860 FROM ttrss_user_entries WHERE int_id = post_int_id
1861 AND unread = true)) AS count FROM ttrss_tags
1862 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
1863
1864 $tags = array();
1865
1866 while ($line = db_fetch_assoc($result)) {
1867 $tags[$line["tag_name"]] += $line["count"];
1868 }
1869
1870 foreach (array_keys($tags) as $tag) {
1871 $unread = $tags[$tag];
1872
1873 $tag = htmlspecialchars($tag);
1874
1875 if (!$smart_mode || $old_counters[$tag] != $unread) {
1876 $old_counters[$tag] = $unread;
1877 $tctrs_modified = true;
1878 print "<counter type=\"tag\" id=\"$tag\" counter=\"$unread\"/>";
1879 }
1880
1881 }
1882
1883 if ($smart_mode && $tctrs_modified) {
1884 $_SESSION["tctr_last_value"] = $old_counters;
1885 }
1886
1887 }
1888
1889 function getLabelCounters($link, $smart_mode = SMART_RPC_COUNTERS, $ret_mode = false) {
1890
1891 if ($smart_mode) {
1892 if (!$_SESSION["lctr_last_value"]) {
1893 $_SESSION["lctr_last_value"] = array();
1894 }
1895 }
1896
1897 $ret_arr = array();
1898
1899 $old_counters = $_SESSION["lctr_last_value"];
1900 $lctrs_modified = false;
1901
1902 $result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1903 WHERE marked = true AND ttrss_user_entries.ref_id = ttrss_entries.id AND
1904 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1905 unread = true AND ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1906
1907 $count = db_fetch_result($result, 0, "count");
1908
1909 if (!$ret_mode) {
1910 print "<counter type=\"label\" id=\"-1\" counter=\"$count\"/>";
1911 } else {
1912 $ret_arr["-1"]["counter"] = $count;
1913 $ret_arr["-1"]["description"] = "Starred";
1914 }
1915
1916 $result = db_query($link, "SELECT owner_uid,id,sql_exp,description FROM
1917 ttrss_labels WHERE owner_uid = ".$_SESSION["uid"]." ORDER by description");
1918
1919 while ($line = db_fetch_assoc($result)) {
1920
1921 $id = -$line["id"] - 11;
1922
1923 $label_name = $line["description"];
1924
1925 error_reporting (0);
1926
1927 $tmp_result = db_query($link, "SELECT count(ttrss_entries.id) as count FROM ttrss_user_entries,ttrss_entries,ttrss_feeds
1928 WHERE (" . $line["sql_exp"] . ") AND unread = true AND
1929 ttrss_feeds.hidden = false AND
1930 ttrss_user_entries.feed_id = ttrss_feeds.id AND
1931 ttrss_user_entries.ref_id = ttrss_entries.id AND
1932 ttrss_user_entries.owner_uid = ".$_SESSION["uid"]);
1933
1934 $count = db_fetch_result($tmp_result, 0, "count");
1935
1936 if (!$smart_mode || $old_counters[$id] != $count) {
1937 $old_counters[$id] = $count;
1938 $lctrs_modified = true;
1939 if (!$ret_mode) {
1940 print "<counter type=\"label\" id=\"$id\" counter=\"$count\"/>";
1941 } else {
1942 $ret_arr[$id]["counter"] = $count;
1943 $ret_arr[$id]["description"] = $label_name;
1944 }
1945 }
1946
1947 error_reporting (DEFAULT_ERROR_LEVEL);
1948 }
1949
1950 if ($smart_mode && $lctrs_modified) {
1951 $_SESSION["lctr_last_value"] = $old_counters;
1952 }
1953
1954 return $ret_arr;
1955 }
1956
1957 /* function getFeedCounter($link, $id) {
1958
1959 $result = db_query($link, "SELECT
1960 count(id) as count,last_error
1961 FROM ttrss_entries,ttrss_user_entries,ttrss_feeds
1962 WHERE feed_id = '$id' AND unread = true
1963 AND ttrss_user_entries.feed_id = ttrss_feeds.id
1964 AND ttrss_user_entries.ref_id = ttrss_entries.id");
1965
1966 $count = db_fetch_result($result, 0, "count");
1967 $last_error = htmlspecialchars(db_fetch_result($result, 0, "last_error"));
1968
1969 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" error=\"$last_error\"/>";
1970 } */
1971
1972 function getFeedCounters($link, $smart_mode = SMART_RPC_COUNTERS) {
1973
1974 if ($smart_mode) {
1975 if (!$_SESSION["fctr_last_value"]) {
1976 $_SESSION["fctr_last_value"] = array();
1977 }
1978 }
1979
1980 $old_counters = $_SESSION["fctr_last_value"];
1981
1982 $result = db_query($link, "SELECT id,last_error,parent_feed,
1983 SUBSTRING(last_updated,1,19) AS last_updated,
1984 (SELECT count(id)
1985 FROM ttrss_entries,ttrss_user_entries
1986 WHERE feed_id = ttrss_feeds.id AND
1987 ttrss_user_entries.ref_id = ttrss_entries.id
1988 AND unread = true AND owner_uid = ".$_SESSION["uid"].") as count
1989 FROM ttrss_feeds WHERE owner_uid = ".$_SESSION["uid"] . "
1990 AND parent_feed IS NULL");
1991
1992 $fctrs_modified = false;
1993
1994 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
1995
1996 while ($line = db_fetch_assoc($result)) {
1997
1998 $id = $line["id"];
1999 $count = $line["count"];
2000 $last_error = htmlspecialchars($line["last_error"]);
2001
2002 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
2003 $last_updated = smart_date_time(strtotime($line["last_updated"]));
2004 } else {
2005 $last_updated = date($short_date, strtotime($line["last_updated"]));
2006 }
2007
2008 $has_img = is_file(ICONS_DIR . "/$id.ico");
2009
2010 $tmp_result = db_query($link,
2011 "SELECT id,COUNT(unread) AS unread
2012 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
2013 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
2014 WHERE parent_feed = '$id' AND unread = true GROUP BY ttrss_feeds.id");
2015
2016 if (db_num_rows($tmp_result) > 0) {
2017 while ($l = db_fetch_assoc($tmp_result)) {
2018 $count += $l["unread"];
2019 }
2020 }
2021
2022 if (!$smart_mode || $old_counters[$id] != $count) {
2023 $old_counters[$id] = $count;
2024 $fctrs_modified = true;
2025
2026 if ($last_error) {
2027 $error_part = "error=\"$last_error\"";
2028 } else {
2029 $error_part = "";
2030 }
2031
2032 if ($has_img) {
2033 $has_img_part = "hi=\"$has_img\"";
2034 } else {
2035 $has_img_part = "";
2036 }
2037
2038 print "<counter type=\"feed\" id=\"$id\" counter=\"$count\" $has_img_part $error_part updated=\"$last_updated\"/>";
2039 }
2040 }
2041
2042 if ($smart_mode && $fctrs_modified) {
2043 $_SESSION["fctr_last_value"] = $old_counters;
2044 }
2045 }
2046
2047 function get_script_dt_add() {
2048 if (strpos(VERSION, ".99") === false) {
2049 return VERSION;
2050 } else {
2051 return time();
2052 }
2053 }
2054
2055 function get_pgsql_version($link) {
2056 $result = db_query($link, "SELECT version() AS version");
2057 $version = split(" ", db_fetch_result($result, 0, "version"));
2058 return $version[1];
2059 }
2060
2061 function print_error_xml($code, $add_msg = "") {
2062 global $ERRORS;
2063
2064 $error_msg = $ERRORS[$code];
2065
2066 if ($add_msg) {
2067 $error_msg = "$error_msg; $add_msg";
2068 }
2069
2070 print "<rpc-reply>";
2071 print "<error error-code=\"$code\" error-msg=\"$error_msg\"/>";
2072 print "</rpc-reply>";
2073 }
2074
2075 function subscribe_to_feed($link, $feed_link, $cat_id = 0,
2076 $auth_login = '', $auth_pass = '') {
2077
2078 # check for feed:http://url
2079 $feed_link = trim(preg_replace("/^feed:/", "", $feed_link));
2080
2081 # check for feed://URL
2082 if (strpos($feed_link, "//") === 0) {
2083 $feed_link = "http:$feed_link";
2084 }
2085
2086 if ($feed_link == "") return;
2087
2088 if ($cat_id == "0" || !$cat_id) {
2089 $cat_qpart = "NULL";
2090 } else {
2091 $cat_qpart = "'$cat_id'";
2092 }
2093
2094 $result = db_query($link,
2095 "SELECT id FROM ttrss_feeds
2096 WHERE feed_url = '$feed_link' AND owner_uid = ".$_SESSION["uid"]);
2097
2098 if (db_num_rows($result) == 0) {
2099
2100 $result = db_query($link,
2101 "INSERT INTO ttrss_feeds
2102 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass)
2103 VALUES ('".$_SESSION["uid"]."', '$feed_link',
2104 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass')");
2105
2106 $result = db_query($link,
2107 "SELECT id FROM ttrss_feeds WHERE feed_url = '$feed_link'
2108 AND owner_uid = " . $_SESSION["uid"]);
2109
2110 $feed_id = db_fetch_result($result, 0, "id");
2111
2112 if ($feed_id) {
2113 update_rss_feed($link, $feed_link, $feed_id, true);
2114 }
2115
2116 return true;
2117 } else {
2118 return false;
2119 }
2120 }
2121
2122 function print_feed_select($link, $id, $default_id = "",
2123 $attributes = "", $include_all_feeds = true) {
2124
2125 print "<select id=\"$id\" name=\"$id\" $attributes>";
2126 if ($include_all_feeds) {
2127 print "<option value=\"0\">All feeds</option>";
2128 }
2129
2130 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
2131 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2132
2133 if (db_num_rows($result) > 0 && $include_all_feeds) {
2134 print "<option disabled>--------</option>";
2135 }
2136
2137 while ($line = db_fetch_assoc($result)) {
2138 if ($line["id"] == $default_id) {
2139 $is_selected = "selected";
2140 } else {
2141 $is_selected = "";
2142 }
2143 printf("<option $is_selected value='%d'>%s</option>",
2144 $line["id"], htmlspecialchars($line["title"]));
2145 }
2146
2147 print "</select>";
2148 }
2149
2150 function print_feed_cat_select($link, $id, $default_id = "",
2151 $attributes = "", $include_all_cats = true) {
2152
2153 print "<select id=\"$id\" name=\"$id\" $attributes>";
2154
2155 if ($include_all_cats) {
2156 print "<option value=\"0\">".__('Uncategorized')."</option>";
2157 }
2158
2159 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
2160 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
2161
2162 if (db_num_rows($result) > 0 && $include_all_cats) {
2163 print "<option disabled>--------</option>";
2164 }
2165
2166 while ($line = db_fetch_assoc($result)) {
2167 if ($line["id"] == $default_id) {
2168 $is_selected = "selected";
2169 } else {
2170 $is_selected = "";
2171 }
2172 printf("<option $is_selected value='%d'>%s</option>",
2173 $line["id"], htmlspecialchars($line["title"]));
2174 }
2175
2176 print "</select>";
2177 }
2178
2179 function checkbox_to_sql_bool($val) {
2180 return ($val == "on") ? "true" : "false";
2181 }
2182
2183 function getFeedCatTitle($link, $id) {
2184 if ($id == -1) {
2185 return __("Special");
2186 } else if ($id < -10) {
2187 return __("Labels");
2188 } else if ($id > 0) {
2189 $result = db_query($link, "SELECT ttrss_feed_categories.title
2190 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
2191 cat_id = ttrss_feed_categories.id");
2192 if (db_num_rows($result) == 1) {
2193 return db_fetch_result($result, 0, "title");
2194 } else {
2195 return __("Uncategorized");
2196 }
2197 } else {
2198 return "getFeedCatTitle($id) failed";
2199 }
2200
2201 }
2202
2203 function getFeedTitle($link, $id) {
2204 if ($id == -1) {
2205 return __("Starred articles");
2206 } else if ($id < -10) {
2207 $label_id = -10 - $id;
2208 $result = db_query($link, "SELECT description FROM ttrss_labels WHERE id = '$label_id'");
2209 if (db_num_rows($result) == 1) {
2210 return db_fetch_result($result, 0, "description");
2211 } else {
2212 return "Unknown label ($label_id)";
2213 }
2214
2215 } else if ($id > 0) {
2216 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2217 if (db_num_rows($result) == 1) {
2218 return db_fetch_result($result, 0, "title");
2219 } else {
2220 return "Unknown feed ($id)";
2221 }
2222 } else {
2223 return "getFeedTitle($id) failed";
2224 }
2225
2226 }
2227
2228 function get_session_cookie_name() {
2229 return ((!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME);
2230 }
2231
2232 function print_init_params($link) {
2233 print "<init-params>";
2234 if ($_SESSION["stored-params"]) {
2235 foreach (array_keys($_SESSION["stored-params"]) as $key) {
2236 if ($key) {
2237 $value = htmlspecialchars($_SESSION["stored-params"][$key]);
2238 print "<param key=\"$key\" value=\"$value\"/>";
2239 }
2240 }
2241 }
2242
2243 print "<param key=\"daemon_enabled\" value=\"" . ENABLE_UPDATE_DAEMON . "\"/>";
2244 print "<param key=\"feeds_frame_refresh\" value=\"" . FEEDS_FRAME_REFRESH . "\"/>";
2245 print "<param key=\"daemon_refresh_only\" value=\"" . DAEMON_REFRESH_ONLY . "\"/>";
2246
2247 print "<param key=\"on_catchup_show_next_feed\" value=\"" .
2248 get_pref($link, "ON_CATCHUP_SHOW_NEXT_FEED") . "\"/>";
2249
2250 print "<param key=\"hide_read_feeds\" value=\"" .
2251 (int) get_pref($link, "HIDE_READ_FEEDS") . "\"/>";
2252
2253 print "<param key=\"feeds_sort_by_unread\" value=\"" .
2254 (int) get_pref($link, "FEEDS_SORT_BY_UNREAD") . "\"/>";
2255
2256 print "<param key=\"confirm_feed_catchup\" value=\"" .
2257 (int) get_pref($link, "CONFIRM_FEED_CATCHUP") . "\"/>";
2258
2259 print "<param key=\"cdm_auto_catchup\" value=\"" .
2260 (int) get_pref($link, "CDM_AUTO_CATCHUP") . "\"/>";
2261
2262 print "<param key=\"icons_url\" value=\"" . ICONS_URL . "\"/>";
2263
2264 print "<param key=\"cookie_lifetime\" value=\"" . SESSION_COOKIE_LIFETIME . "\"/>";
2265
2266 print "<param key=\"default_view_mode\" value=\"" .
2267 get_pref($link, "_DEFAULT_VIEW_MODE") . "\"/>";
2268
2269 print "<param key=\"default_view_limit\" value=\"" .
2270 (int) get_pref($link, "_DEFAULT_VIEW_LIMIT") . "\"/>";
2271
2272 print "<param key=\"prefs_active_tab\" value=\"" .
2273 get_pref($link, "_PREFS_ACTIVE_TAB") . "\"/>";
2274
2275 print "<param key=\"infobox_disable_overlay\" value=\"" .
2276 get_pref($link, "_INFOBOX_DISABLE_OVERLAY") . "\"/>";
2277
2278 print "</init-params>";
2279 }
2280
2281 function print_runtime_info($link) {
2282 print "<runtime-info>";
2283 if (ENABLE_UPDATE_DAEMON) {
2284 print "<param key=\"daemon_is_running\" value=\"".
2285 sprintf("%d", file_is_locked("update_daemon.lock")) . "\"/>";
2286 }
2287 if (CHECK_FOR_NEW_VERSION && $_SESSION["access_level"] >= 10) {
2288
2289 if ($_SESSION["last_version_check"] + 600 < time()) {
2290 $new_version_details = check_for_update($link);
2291
2292 print "<param key=\"new_version_available\" value=\"".
2293 sprintf("%d", $new_version_details != ""). "\"/>";
2294
2295 $_SESSION["last_version_check"] = time();
2296 }
2297 }
2298
2299 print "</runtime-info>";
2300 }
2301
2302 function getSearchSql($search, $match_on) {
2303
2304 $search_query_part = "";
2305
2306 $keywords = split(" ", $search);
2307 $query_keywords = array();
2308
2309 if ($match_on == "both") {
2310
2311 foreach ($keywords as $k) {
2312 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%')
2313 OR UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2314 }
2315
2316 $search_query_part = implode("AND", $query_keywords) . " AND ";
2317
2318 } else if ($match_on == "title") {
2319
2320 foreach ($keywords as $k) {
2321 array_push($query_keywords, "(UPPER(ttrss_entries.title) LIKE UPPER('%$k%'))");
2322 }
2323
2324 $search_query_part = implode("AND", $query_keywords) . " AND ";
2325
2326 } else if ($match_on == "content") {
2327
2328 foreach ($keywords as $k) {
2329 array_push($query_keywords, "(UPPER(ttrss_entries.content) LIKE UPPER('%$k%'))");
2330 }
2331 }
2332
2333 $search_query_part = implode("AND", $query_keywords);
2334
2335 return $search_query_part;
2336 }
2337
2338 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0) {
2339
2340 if ($search) {
2341
2342 $search_query_part = getSearchSql($search, $match_on);
2343 $search_query_part .= " AND ";
2344
2345 } else {
2346 $search_query_part = "";
2347 }
2348
2349 $view_query_part = "";
2350
2351 if ($view_mode == "adaptive") {
2352 if ($search) {
2353 $view_query_part = " ";
2354 } else if ($feed != -1) {
2355 $unread = getFeedUnread($link, $feed, $cat_view);
2356 if ($unread > 0) {
2357 $view_query_part = " unread = true AND ";
2358 }
2359 }
2360 }
2361
2362 if ($view_mode == "marked") {
2363 $view_query_part = " marked = true AND ";
2364 }
2365
2366 if ($view_mode == "unread") {
2367 $view_query_part = " unread = true AND ";
2368 }
2369
2370 if ($limit > 0) {
2371 $limit_query_part = "LIMIT " . $limit;
2372 }
2373
2374 $vfeed_query_part = "";
2375
2376 // override query strategy and enable feed display when searching globally
2377 if ($search && $search_mode == "all_feeds") {
2378 $query_strategy_part = "ttrss_entries.id > 0";
2379 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2380 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2381 $query_strategy_part = "ttrss_entries.id > 0";
2382 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2383 id = feed_id) as feed_title,";
2384 } else if ($feed >= 0 && $search && $search_mode == "this_cat") {
2385
2386 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2387
2388 $tmp_result = false;
2389
2390 if ($cat_view) {
2391 $tmp_result = db_query($link, "SELECT id
2392 FROM ttrss_feeds WHERE cat_id = '$feed'");
2393 } else {
2394 $tmp_result = db_query($link, "SELECT id
2395 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2396 WHERE id = '$feed') AND id != '$feed'");
2397 }
2398
2399 $cat_siblings = array();
2400
2401 if (db_num_rows($tmp_result) > 0) {
2402 while ($p = db_fetch_assoc($tmp_result)) {
2403 array_push($cat_siblings, "feed_id = " . $p["id"]);
2404 }
2405
2406 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2407 $feed, implode(" OR ", $cat_siblings));
2408
2409 } else {
2410 $query_strategy_part = "ttrss_entries.id > 0";
2411 }
2412
2413 } else if ($feed >= 0) {
2414
2415 if ($cat_view) {
2416
2417 if ($feed > 0) {
2418 $query_strategy_part = "cat_id = '$feed'";
2419 } else {
2420 $query_strategy_part = "cat_id IS NULL";
2421 }
2422
2423 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2424
2425 } else {
2426 $tmp_result = db_query($link, "SELECT id
2427 FROM ttrss_feeds WHERE parent_feed = '$feed'
2428 ORDER BY cat_id,title");
2429
2430 $parent_ids = array();
2431
2432 if (db_num_rows($tmp_result) > 0) {
2433 while ($p = db_fetch_assoc($tmp_result)) {
2434 array_push($parent_ids, "feed_id = " . $p["id"]);
2435 }
2436
2437 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2438 $feed, implode(" OR ", $parent_ids));
2439
2440 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2441 } else {
2442 $query_strategy_part = "feed_id = '$feed'";
2443 }
2444 }
2445 } else if ($feed == -1) { // starred virtual feed
2446 $query_strategy_part = "marked = true";
2447 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2448 } else if ($feed <= -10) { // labels
2449 $label_id = -$feed - 11;
2450
2451 $tmp_result = db_query($link, "SELECT sql_exp FROM ttrss_labels
2452 WHERE id = '$label_id'");
2453
2454 $query_strategy_part = db_fetch_result($tmp_result, 0, "sql_exp");
2455
2456 if (!$query_strategy_part) {
2457 return false;
2458 }
2459
2460 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2461 } else {
2462 $query_strategy_part = "id > 0"; // dumb
2463 }
2464
2465 if (get_pref($link, 'REVERSE_HEADLINES')) {
2466 $order_by = "updated";
2467 } else {
2468 $order_by = "updated DESC";
2469 }
2470
2471 if ($override_order) {
2472 $order_by = $override_order;
2473 }
2474
2475 $feed_title = "";
2476
2477 if ($search && $search_mode == "all_feeds") {
2478 $feed_title = __("Search results")." ($search)";
2479 } else if ($search && preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2480 $feed_title = __("Search results")." ($search, $feed)";
2481 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) == false) {
2482 $feed_title = $feed;
2483 } else if (preg_match('/^-?[0-9][0-9]*$/', $feed) != false && $feed >= 0) {
2484
2485 if ($cat_view) {
2486
2487 if ($feed != 0) {
2488 $result = db_query($link, "SELECT title FROM ttrss_feed_categories
2489 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2490 $feed_title = db_fetch_result($result, 0, "title");
2491 } else {
2492 $feed_title = __("Uncategorized");
2493 }
2494
2495 if ($search) {
2496 $feed_title = __("Searched for")." $search ($feed_title)";
2497 }
2498
2499 } else {
2500
2501 $result = db_query($link, "SELECT title,site_url,last_error FROM ttrss_feeds
2502 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
2503
2504 $feed_title = db_fetch_result($result, 0, "title");
2505 $feed_site_url = db_fetch_result($result, 0, "site_url");
2506 $last_error = db_fetch_result($result, 0, "last_error");
2507
2508 if ($search) {
2509 $feed_title = __("Searched for") . " $search ($feed_title)";
2510 }
2511 }
2512
2513 } else if ($feed == -1) {
2514 $feed_title = __("Starred articles");
2515 } else if ($feed < -10) {
2516 $label_id = -$feed - 11;
2517 $result = db_query($link, "SELECT description FROM ttrss_labels
2518 WHERE id = '$label_id'");
2519 $feed_title = db_fetch_result($result, 0, "description");
2520
2521 if ($search) {
2522 $feed_title = __("Searched for") . " $search ($feed_title)";
2523 }
2524 } else {
2525 $feed_title = "?";
2526 }
2527
2528 if ($feed < -10) error_reporting (0);
2529
2530 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2531
2532 if ($feed >= 0) {
2533 $feed_kind = "Feeds";
2534 } else {
2535 $feed_kind = "Labels";
2536 }
2537
2538 $content_query_part = "content as content_preview,";
2539
2540 if ($limit_query_part) {
2541 $offset_query_part = "OFFSET $offset";
2542 }
2543
2544 $query = "SELECT
2545 guid,
2546 ttrss_entries.id,ttrss_entries.title,
2547 updated,
2548 unread,feed_id,marked,link,last_read,
2549 SUBSTRING(last_read,1,19) as last_read_noms,
2550 $vfeed_query_part
2551 $content_query_part
2552 SUBSTRING(updated,1,19) as updated_noms,
2553 author
2554 FROM
2555 ttrss_entries,ttrss_user_entries,ttrss_feeds
2556 WHERE
2557 ttrss_feeds.hidden = false AND
2558 ttrss_user_entries.feed_id = ttrss_feeds.id AND
2559 ttrss_user_entries.ref_id = ttrss_entries.id AND
2560 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2561 $search_query_part
2562 $view_query_part
2563 $query_strategy_part ORDER BY $order_by
2564 $limit_query_part $offset_query_part";
2565
2566 $result = db_query($link, $query);
2567
2568 if ($_GET["debug"]) print $query;
2569
2570 } else {
2571 // browsing by tag
2572
2573 $feed_kind = "Tags";
2574
2575 $result = db_query($link, "SELECT
2576 guid,
2577 ttrss_entries.id as id,title,
2578 updated,
2579 unread,feed_id,
2580 marked,link,last_read,
2581 SUBSTRING(last_read,1,19) as last_read_noms,
2582 $vfeed_query_part
2583 $content_query_part
2584 SUBSTRING(updated,1,19) as updated_noms
2585 FROM
2586 ttrss_entries,ttrss_user_entries,ttrss_tags
2587 WHERE
2588 ref_id = ttrss_entries.id AND
2589 ttrss_user_entries.owner_uid = '".$_SESSION["uid"]."' AND
2590 post_int_id = int_id AND tag_name = '$feed' AND
2591 $view_query_part
2592 $search_query_part
2593 $query_strategy_part ORDER BY $order_by
2594 $limit_query_part");
2595 }
2596
2597 return array($result, $feed_title, $feed_site_url, $last_error);
2598
2599 }
2600
2601 function generate_syndicated_feed($link, $feed, $is_cat,
2602 $search, $search_mode, $match_on) {
2603
2604 $qfh_ret = queryFeedHeadlines($link, $feed,
2605 30, false, $is_cat, $search, $search_mode, $match_on, "updated DESC");
2606
2607 $result = $qfh_ret[0];
2608 $feed_title = htmlspecialchars($qfh_ret[1]);
2609 $feed_site_url = $qfh_ret[2];
2610 $last_error = $qfh_ret[3];
2611
2612 print "<rss version=\"2.0\">
2613 <channel>
2614 <title>$feed_title</title>
2615 <link>$feed_site_url</link>
2616 <generator>Tiny Tiny RSS v".VERSION."</generator>";
2617
2618 while ($line = db_fetch_assoc($result)) {
2619 print "<item>";
2620 print "<id>" . htmlspecialchars($line["guid"]) . "</id>";
2621 print "<link>" . htmlspecialchars($line["link"]) . "</link>";
2622
2623 $rfc822_date = date('r', strtotime($line["updated"]));
2624
2625 print "<pubDate>$rfc822_date</pubDate>";
2626
2627 print "<title>" .
2628 htmlspecialchars($line["title"]) . "</title>";
2629
2630 print "<description>" .
2631 htmlspecialchars($line["content_preview"]) . "</description>";
2632
2633 print "</item>";
2634 }
2635
2636 print "</channel></rss>";
2637
2638 }
2639
2640 function getCategoryTitle($link, $cat_id) {
2641
2642 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
2643 id = '$cat_id'");
2644
2645 if (db_num_rows($result) == 1) {
2646 return db_fetch_result($result, 0, "title");
2647 } else {
2648 return "Uncategorized";
2649 }
2650 }
2651
2652 // http://ru2.php.net/strip-tags
2653
2654 function strip_tags_long($textstring, $allowed){
2655 while($textstring != strip_tags($textstring, $allowed))
2656 {
2657 while (strlen($textstring) != 0)
2658 {
2659 if (strlen($textstring) > 1024) {
2660 $otherlen = 1024;
2661 } else {
2662 $otherlen = strlen($textstring);
2663 }
2664 $temptext = strip_tags(substr($textstring,0,$otherlen), $allowed);
2665 $safetext .= $temptext;
2666 $textstring = substr_replace($textstring,'',0,$otherlen);
2667 }
2668 $textstring = $safetext;
2669 }
2670 return $textstring;
2671 }
2672
2673
2674 function sanitize_rss($link, $str, $force_strip_tags = false) {
2675 $res = $str;
2676
2677 if (get_pref($link, "STRIP_UNSAFE_TAGS") || $force_strip_tags) {
2678 global $tw_parser;
2679 global $tw_paranoya_setup;
2680
2681 $res = $tw_parser->strip_tags($res, $tw_paranoya_setup);
2682
2683 // $res = preg_replace("/\r\n|\n|\r/", "", $res);
2684 // $res = strip_tags_long($res, "<p><a><i><em><b><strong><blockquote><br><img><div><span>");
2685 }
2686
2687 return $res;
2688 }
2689
2690 function send_headlines_digests($link, $limit = 100) {
2691
2692 if (!DIGEST_ENABLE) return false;
2693
2694 $user_limit = DIGEST_EMAIL_LIMIT;
2695 $days = 1;
2696
2697 print "Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit\n\n";
2698
2699 if (DB_TYPE == "pgsql") {
2700 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2701 } else if (DB_TYPE == "mysql") {
2702 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2703 }
2704
2705 $result = db_query($link, "SELECT id,email FROM ttrss_users
2706 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2707
2708 while ($line = db_fetch_assoc($result)) {
2709 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2710 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2711
2712 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2713 $digest = $tuple[0];
2714 $headlines_count = $tuple[1];
2715
2716 if ($headlines_count > 0) {
2717 $rc = mail($line["login"] . " <" . $line["email"] . ">",
2718 "[tt-rss] New headlines for last 24 hours", $digest,
2719 "From: " . MAIL_FROM . "\n".
2720 "Content-Type: text/plain; charset=\"utf-8\"\n".
2721 "Content-Transfer-Encoding: 8bit\n");
2722 print "RC=$rc\n";
2723 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2724 WHERE id = " . $line["id"]);
2725 } else {
2726 print "No headlines\n";
2727 }
2728 }
2729 }
2730
2731 // $digest = prepare_headlines_digest($link, $user_id, $days, $limit);
2732
2733 }
2734
2735 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2736 $tmp = __("New headlines for last 24 hours, as of ") . date("Y/m/d H:m") . "\n";
2737 $tmp .= "=======================================================\n\n";
2738
2739 if (DB_TYPE == "pgsql") {
2740 $interval_query = "ttrss_entries.date_entered > NOW() - INTERVAL '$days days'";
2741 } else if (DB_TYPE == "mysql") {
2742 $interval_query = "ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL $days DAY)";
2743 }
2744
2745 $result = db_query($link, "SELECT ttrss_entries.title,
2746 ttrss_feeds.title AS feed_title,
2747 date_entered,
2748 link,
2749 SUBSTRING(last_updated,1,19) AS last_updated
2750 FROM
2751 ttrss_user_entries,ttrss_entries,ttrss_feeds
2752 WHERE
2753 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2754 AND include_in_digest = true
2755 AND $interval_query
2756 AND ttrss_user_entries.owner_uid = $user_id
2757 AND unread = true ORDER BY ttrss_feeds.title, date_entered DESC
2758 LIMIT $limit");
2759
2760 $cur_feed_title = "";
2761
2762 $headlines_count = db_num_rows($result);
2763
2764 while ($line = db_fetch_assoc($result)) {
2765 $updated = smart_date_time(strtotime($line["last_updated"]));
2766 $feed_title = $line["feed_title"];
2767
2768 if ($cur_feed_title != $feed_title) {
2769 $cur_feed_title = $feed_title;
2770
2771 $tmp .= "$feed_title\n\n";
2772 }
2773
2774 $tmp .= " * " . trim($line["title"]) . " - $updated\n";
2775 $tmp .= " " . trim($line["link"]) . "\n";
2776 $tmp .= "\n";
2777 }
2778
2779 $tmp .= "--- \n";
2780 $tmp .= __("You have been sent this email because you have enabled daily digests in Tiny Tiny RSS at ") .
2781 DIGEST_HOSTNAME . "\n".
2782 __("To unsubscribe, visit your configuration options or contact instance owner.\n");
2783
2784
2785 return array($tmp, $headlines_count);
2786 }
2787
2788 function check_for_update($link, $brief_fmt = true) {
2789 $releases_feed = "http://tt-rss.spb.ru/releases.rss";
2790
2791 if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
2792 return;
2793 }
2794
2795 error_reporting(0);
2796 $rss = fetch_rss($releases_feed);
2797 error_reporting (DEFAULT_ERROR_LEVEL);
2798
2799 if ($rss) {
2800
2801 $items = $rss->items;
2802
2803 if (!$items || !is_array($items)) $items = $rss->entries;
2804 if (!$items || !is_array($items)) $items = $rss;
2805
2806 if (!is_array($items) || count($items) == 0) {
2807 return;
2808 }
2809
2810 $latest_item = $items[0];
2811
2812 $latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $latest_item["title"]));
2813
2814 $release_url = sanitize_rss($link, $latest_item["link"]);
2815 $content = sanitize_rss($link, $latest_item["description"]);
2816
2817 if (version_compare(VERSION, $latest_version) == -1) {
2818 if ($brief_fmt) {
2819 return format_notice("<a href=\"javascript:showBlockElement('milestoneDetails')\">
2820 New version of Tiny-Tiny RSS ($latest_version) is available (click for details)</a>
2821 <div id=\"milestoneDetails\">$content</div>");
2822 } else {
2823 return "New version of Tiny-Tiny RSS ($latest_version) is available:
2824 <div class='milestoneDetails'>$content</div>
2825 Visit <a target=\"_new\" href=\"http://tt-rss.spb.ru/\">official site</a> for
2826 download and update information.";
2827 }
2828
2829 }
2830 }
2831 }
2832
2833 function markArticlesById($link, $ids, $cmode) {
2834
2835 $tmp_ids = array();
2836
2837 foreach ($ids as $id) {
2838 array_push($tmp_ids, "ref_id = '$id'");
2839 }
2840
2841 $ids_qpart = join(" OR ", $tmp_ids);
2842
2843 if ($cmode == 0) {
2844 db_query($link, "UPDATE ttrss_user_entries SET
2845 marked = false,last_read = NOW()
2846 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2847 } else if ($cmode == 1) {
2848 db_query($link, "UPDATE ttrss_user_entries SET
2849 marked = true
2850 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2851 } else {
2852 db_query($link, "UPDATE ttrss_user_entries SET
2853 marked = NOT marked,last_read = NOW()
2854 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2855 }
2856 }
2857
2858 function catchupArticlesById($link, $ids, $cmode) {
2859
2860 $tmp_ids = array();
2861
2862 foreach ($ids as $id) {
2863 array_push($tmp_ids, "ref_id = '$id'");
2864 }
2865
2866 $ids_qpart = join(" OR ", $tmp_ids);
2867
2868 if ($cmode == 0) {
2869 db_query($link, "UPDATE ttrss_user_entries SET
2870 unread = false,last_read = NOW()
2871 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2872 } else if ($cmode == 1) {
2873 db_query($link, "UPDATE ttrss_user_entries SET
2874 unread = true
2875 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2876 } else {
2877 db_query($link, "UPDATE ttrss_user_entries SET
2878 unread = NOT unread,last_read = NOW()
2879 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2880 }
2881 }
2882
2883 function catchupArticleById($link, $id, $cmode) {
2884
2885 if ($cmode == 0) {
2886 db_query($link, "UPDATE ttrss_user_entries SET
2887 unread = false,last_read = NOW()
2888 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2889 } else if ($cmode == 1) {
2890 db_query($link, "UPDATE ttrss_user_entries SET
2891 unread = true
2892 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2893 } else {
2894 db_query($link, "UPDATE ttrss_user_entries SET
2895 unread = NOT unread,last_read = NOW()
2896 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2897 }
2898 }
2899
2900 function make_guid_from_title($title) {
2901 return preg_replace("/[ \"\',.:;]/", "-",
2902 mb_strtolower(strip_tags($title), 'utf-8'));
2903 }
2904
2905 function print_headline_subtoolbar($link, $feed_site_url, $feed_title,
2906 $bottom = false, $rtl_content = false, $feed_id = 0,
2907 $is_cat = false, $search = false, $match_on = false,
2908 $search_mode = false, $offset = 0, $limit = 0) {
2909
2910 $user_page_offset = $offset + 1;
2911
2912 if (!$bottom) {
2913 $class = "headlinesSubToolbar";
2914 $tid = "headlineActionsTop";
2915 } else {
2916 $class = "headlinesSubToolbar";
2917 $tid = "headlineActionsBottom";
2918 }
2919
2920 print "<table class=\"$class\" id=\"$tid\"
2921 width=\"100%\" cellspacing=\"0\" cellpadding=\"0\"><tr>";
2922
2923 if ($rtl_content) {
2924 $rtl_cpart = "RTL";
2925 } else {
2926 $rtl_cpart = "";
2927 }
2928
2929 $page_prev_link = "javascript:viewFeedGoPage(-1)";
2930 $page_next_link = "javascript:viewFeedGoPage(1)";
2931 $page_first_link = "javascript:viewFeedGoPage(0)";
2932
2933 $catchup_page_link = "javascript:catchupPage()";
2934 $catchup_feed_link = "javascript:catchupCurrentFeed()";
2935
2936 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
2937
2938 $sel_all_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, '', true)";
2939 $sel_unread_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', true, 'Unread', true)";
2940 $sel_none_link = "javascript:selectTableRowsByIdPrefix('headlinesList', 'RROW-', 'RCHK-', false)";
2941
2942 $tog_unread_link = "javascript:selectionToggleUnread()";
2943 $tog_marked_link = "javascript:selectionToggleMarked()";
2944
2945 } else {
2946
2947 $sel_all_link = "javascript:cdmSelectArticles('all')";
2948 $sel_unread_link = "javascript:cdmSelectArticles('unread')";
2949 $sel_none_link = "javascript:cdmSelectArticles('none')";
2950
2951 $tog_unread_link = "javascript:selectionToggleUnread(true)";
2952 $tog_marked_link = "javascript:selectionToggleMarked(true)";
2953
2954 }
2955
2956 if (strpos($_SESSION["client.userAgent"], "MSIE") === false) {
2957
2958 print "<td class=\"headlineActions$rtl_cpart\">
2959 <ul class=\"headlineDropdownMenu\">
2960 <li class=\"top2\">
2961 ".__('Select:')."
2962 <a href=\"$sel_all_link\">".__('All')."</a>,
2963 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2964 <a href=\"$sel_none_link\">".__('None')."</a></li>
2965 <li class=\"vsep\">&nbsp;</li>
2966 <li class=\"top\">Toggle<ul>
2967 <li onclick=\"$tog_unread_link\">".__('Unread')."</li>
2968 <li onclick=\"$tog_marked_link\">".__('Starred')."</li></ul></li>
2969 <li class=\"vsep\">&nbsp;</li>
2970 <li class=\"top\"><a href=\"$catchup_page_link\">".__('Mark as read')."</a><ul>
2971 <li onclick=\"$catchup_page_link\">".__('This page')."</li>
2972 <li onclick=\"$catchup_feed_link\">".__('Entire feed')."</li></ul></li>
2973 <li class=\"vsep\">&nbsp;</li>";
2974
2975 if ($limit != 0 && !$search) {
2976 print "
2977 <li class=\"top\"><a href=\"$page_next_link\">".__('Next page')."</a><ul>
2978 <li onclick=\"$page_prev_link\">".__('Previous page')."</li>
2979 <li onclick=\"$page_first_link\">".__('First page')."</li></ul></li>
2980 </ul>";
2981 }
2982
2983 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
2984 print "<li class=\"top3\">
2985 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
2986 '$match_on', '$feed_id', '$is_cat');\">
2987 ".__('Convert to label')."</a></td>";
2988 }
2989 print "
2990 </td>";
2991
2992 } else {
2993 // old style subtoolbar:
2994
2995 print "<td class=\"headlineActions$rtl_cpart\">".
2996 __('Select:')."
2997 <a href=\"$sel_all_link\">".__('All')."</a>,
2998 <a href=\"$sel_unread_link\">".__('Unread')."</a>,
2999 <a href=\"$sel_none_link\">".__('None')."</a>
3000 &nbsp;&nbsp;".
3001 __('Toggle:')." <a href=\"$tog_unread_link\">".__('Unread')."</a>,
3002 <a href=\"$tog_marked_link\">".__('Starred')."</a>
3003 &nbsp;&nbsp;".
3004 __('Mark as read:')."
3005 <a href=\"#\" onclick=\"$catchup_page_link\">".__('Page')."</a>,
3006 <a href=\"#\" onclick=\"$catchup_feed_link\">".__('Feed')."</a>";
3007
3008 if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3009
3010 print "&nbsp;&nbsp;
3011 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3012 '$match_on', '$feed_id', '$is_cat');\">
3013 ".__('Convert to label')."</a>";
3014 }
3015
3016 print "</td>";
3017
3018 }
3019
3020 /* if ($search && $feed_id >= 0 && get_pref($link, 'ENABLE_LABELS') && GLOBAL_ENABLE_LABELS) {
3021 print "<td class=\"headlineActions$rtl_cpart\">
3022 <a href=\"javascript:labelFromSearch('$search', '$search_mode',
3023 '$match_on', '$feed_id', '$is_cat');\">
3024 ".__('Convert to Label')."</a></td>";
3025 } */
3026
3027 print "<td class=\"headlineTitle$rtl_cpart\">";
3028
3029 if ($feed_site_url) {
3030 if (!$bottom) {
3031 $target = "target=\"_blank\"";
3032 }
3033 print "<a $target href=\"$feed_site_url\">$feed_title</a>";
3034 } else {
3035 print $feed_title;
3036 }
3037
3038 if ($search) {
3039 $search_q = "&q=$search&m=$match_on&smode=$search_mode";
3040 }
3041
3042 if ($user_page_offset > 1) {
3043 print " [$user_page_offset] ";
3044 }
3045
3046 if (!$bottom) {
3047 print "
3048 <a target=\"_new\"
3049 href=\"backend.php?op=rss&id=$feed_id&is_cat=$is_cat$search_q\">
3050 <img class=\"noborder\"
3051 alt=\"".__('Generated feed')."\" src=\"images/feed-icon-12x12.png\">
3052 </a>";
3053 }
3054
3055 print "</td>";
3056 print "</tr></table>";
3057
3058 }
3059
3060 function outputFeedList($link, $tags = false) {
3061
3062 print "<ul class=\"feedList\" id=\"feedList\">";
3063
3064 $owner_uid = $_SESSION["uid"];
3065
3066 /* virtual feeds */
3067
3068 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3069 print "<li class=\"feedCat\">".__('Special')."</li>";
3070 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3071 }
3072
3073 $num_starred = getFeedUnread($link, -1);
3074
3075 $class = "virt";
3076
3077 if ($num_starred > 0) $class .= "Unread";
3078
3079 printFeedEntry(-1, $class, __("Starred articles"), $num_starred,
3080 "images/mark_set.png", $link);
3081
3082 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3083 print "</ul>";
3084 }
3085
3086 if (!$tags) {
3087
3088 if (GLOBAL_ENABLE_LABELS && get_pref($link, 'ENABLE_LABELS')) {
3089
3090 $result = db_query($link, "SELECT id,sql_exp,description FROM
3091 ttrss_labels WHERE owner_uid = '$owner_uid' ORDER by description");
3092
3093 if (db_num_rows($result) > 0) {
3094 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3095 print "<li class=\"feedCat\">".__('Labels')."</li>";
3096 print "<li id=\"feedCatHolder\" class=\"feedCatHolder\"><ul class=\"feedCatList\">";
3097 } else {
3098 print "<li><hr></li>";
3099 }
3100 }
3101
3102 while ($line = db_fetch_assoc($result)) {
3103
3104 error_reporting (0);
3105
3106 $label_id = -$line['id'] - 11;
3107 $count = getFeedUnread($link, $label_id);
3108
3109 $class = "label";
3110
3111 if ($count > 0) {
3112 $class .= "Unread";
3113 }
3114
3115 error_reporting (DEFAULT_ERROR_LEVEL);
3116
3117 printFeedEntry($label_id,
3118 $class, $line["description"],
3119 $count, "images/label.png", $link);
3120
3121 }
3122
3123 if (db_num_rows($result) > 0) {
3124 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3125 print "</ul>";
3126 }
3127 }
3128
3129 }
3130
3131 if (!get_pref($link, 'ENABLE_FEED_CATS')) {
3132 print "<li><hr></li>";
3133 }
3134
3135 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3136 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3137 $order_by_qpart = "category,unread DESC,title";
3138 } else {
3139 $order_by_qpart = "category,title";
3140 }
3141 } else {
3142 if (get_pref($link, "FEEDS_SORT_BY_UNREAD")) {
3143 $order_by_qpart = "unread DESC,title";
3144 } else {
3145 $order_by_qpart = "title";
3146 }
3147 }
3148
3149 $result = db_query($link, "SELECT ttrss_feeds.*,
3150 SUBSTRING(last_updated,1,19) AS last_updated_noms,
3151 (SELECT COUNT(id) FROM ttrss_entries,ttrss_user_entries
3152 WHERE feed_id = ttrss_feeds.id AND unread = true
3153 AND ttrss_user_entries.ref_id = ttrss_entries.id
3154 AND owner_uid = '$owner_uid') as unread,
3155 cat_id,last_error,
3156 ttrss_feed_categories.title AS category,
3157 ttrss_feed_categories.collapsed
3158 FROM ttrss_feeds LEFT JOIN ttrss_feed_categories
3159 ON (ttrss_feed_categories.id = cat_id)
3160 WHERE
3161 ttrss_feeds.hidden = false AND
3162 ttrss_feeds.owner_uid = '$owner_uid' AND parent_feed IS NULL
3163 ORDER BY $order_by_qpart");
3164
3165 $actid = $_GET["actid"];
3166
3167 /* real feeds */
3168
3169 $lnum = 0;
3170
3171 $total_unread = 0;
3172
3173 $category = "";
3174
3175 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3176
3177 while ($line = db_fetch_assoc($result)) {
3178
3179 $feed = trim($line["title"]);
3180
3181 if (!$feed) $feed = "[Untitled]";
3182
3183 $feed_id = $line["id"];
3184
3185 $subop = $_GET["subop"];
3186
3187 $unread = $line["unread"];
3188
3189 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3190 $last_updated = smart_date_time(strtotime($line["last_updated_noms"]));
3191 } else {
3192 $last_updated = date($short_date, strtotime($line["last_updated_noms"]));
3193 }
3194
3195 $rtl_content = sql_bool_to_bool($line["rtl_content"]);
3196
3197 if ($rtl_content) {
3198 $rtl_tag = "dir=\"RTL\"";
3199 } else {
3200 $rtl_tag = "";
3201 }
3202
3203 $tmp_result = db_query($link,
3204 "SELECT id,COUNT(unread) AS unread
3205 FROM ttrss_feeds LEFT JOIN ttrss_user_entries
3206 ON (ttrss_feeds.id = ttrss_user_entries.feed_id)
3207 WHERE parent_feed = '$feed_id' AND unread = true
3208 GROUP BY ttrss_feeds.id");
3209
3210 if (db_num_rows($tmp_result) > 0) {
3211 while ($l = db_fetch_assoc($tmp_result)) {
3212 $unread += $l["unread"];
3213 }
3214 }
3215
3216 $cat_id = $line["cat_id"];
3217
3218 $tmp_category = $line["category"];
3219
3220 if (!$tmp_category) {
3221 $tmp_category = __("Uncategorized");
3222 }
3223
3224 // $class = ($lnum % 2) ? "even" : "odd";
3225
3226 if ($line["last_error"]) {
3227 $class = "error";
3228 } else {
3229 $class = "feed";
3230 }
3231
3232 if ($unread > 0) $class .= "Unread";
3233
3234 if ($actid == $feed_id) {
3235 $class .= "Selected";
3236 }
3237
3238 $total_unread += $unread;
3239
3240 if ($category != $tmp_category && get_pref($link, 'ENABLE_FEED_CATS')) {
3241
3242 if ($category) {
3243 print "</ul></li>";
3244 }
3245
3246 $category = $tmp_category;
3247
3248 $collapsed = $line["collapsed"];
3249
3250 // workaround for NULL category
3251 if ($category == __("Uncategorized")) {
3252 if ($_COOKIE["ttrss_vf_uclps"] == 1) {
3253 $collapsed = "t";
3254 }
3255 }
3256
3257 if ($collapsed == "t" || $collapsed == "1") {
3258 $holder_class = "invisible";
3259 $ellipsis = "...";
3260 } else {
3261 $holder_class = "feedCatHolder";
3262 $ellipsis = "";
3263 }
3264
3265 $cat_id = sprintf("%d", $cat_id);
3266
3267 $cat_unread = getCategoryUnread($link, $cat_id);
3268
3269 $catctr_class = ($cat_unread > 0) ? "catCtrHasUnread" : "catCtrNoUnread";
3270
3271 print "<li class=\"feedCat\" id=\"FCAT-$cat_id\">
3272 <a id=\"FCATN-$cat_id\" href=\"javascript:toggleCollapseCat($cat_id)\">$tmp_category</a>
3273 <a href=\"#\" onclick=\"javascript:viewCategory($cat_id)\" id=\"FCAP-$cat_id\">
3274 <span id=\"FCATCTR-$cat_id\" title=\"Click to browse category\"
3275 class=\"$catctr_class\">($cat_unread)</span> $ellipsis
3276 </a></li>";
3277
3278 // !!! NO SPACE before <ul...feedCatList - breaks firstChild DOM function
3279 // -> keyboard navigation, etc.
3280 print "<li id=\"feedCatHolder\" class=\"$holder_class\"><ul class=\"feedCatList\" id=\"FCATLIST-$cat_id\">";
3281 }
3282
3283 printFeedEntry($feed_id, $class, $feed, $unread,
3284 ICONS_DIR."/$feed_id.ico", $link, $rtl_content,
3285 $last_updated, $line["last_error"]);
3286
3287 ++$lnum;
3288 }
3289
3290 if (db_num_rows($result) == 0) {
3291 print "<li>".__('No feeds to display.')."</li>";
3292 }
3293
3294 } else {
3295
3296 // tags
3297
3298 /* $result = db_query($link, "SELECT tag_name,count(ttrss_entries.id) AS count
3299 FROM ttrss_tags,ttrss_entries,ttrss_user_entries WHERE
3300 post_int_id = ttrss_user_entries.int_id AND
3301 unread = true AND ref_id = ttrss_entries.id
3302 AND ttrss_tags.owner_uid = '$owner_uid' GROUP BY tag_name
3303 UNION
3304 select tag_name,0 as count FROM ttrss_tags WHERE owner_uid = '$owner_uid'
3305 ORDER BY tag_name"); */
3306
3307 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3308 print "<li class=\"feedCat\">".__('Tags')."</li>";
3309 print "<li id=\"feedCatHolder\"><ul class=\"feedCatList\">";
3310 }
3311
3312 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
3313 FROM ttrss_user_entries WHERE int_id = post_int_id
3314 AND unread = true)) AS count FROM ttrss_tags
3315 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name ORDER BY tag_name");
3316
3317 $tags = array();
3318
3319 while ($line = db_fetch_assoc($result)) {
3320 $tags[$line["tag_name"]] += $line["count"];
3321 }
3322
3323 foreach (array_keys($tags) as $tag) {
3324
3325 $unread = $tags[$tag];
3326
3327 $class = "tag";
3328
3329 if ($unread > 0) {
3330 $class .= "Unread";
3331 }
3332
3333 printFeedEntry($tag, $class, $tag, $unread, "images/tag.png", $link);
3334
3335 }
3336
3337 if (db_num_rows($result) == 0) {
3338 print "<li>No tags to display.</li>";
3339 }
3340
3341 if (get_pref($link, 'ENABLE_FEED_CATS')) {
3342 print "</ul>";
3343 }
3344
3345 }
3346
3347 print "</ul>";
3348
3349 }
3350
3351 function get_article_tags($link, $id) {
3352
3353 $a_id = db_escape_string($id);
3354
3355 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3356 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
3357 ref_id = '$a_id' AND owner_uid = '".$_SESSION["uid"]."' LIMIT 1) ORDER BY tag_name");
3358
3359 $tags = array();
3360
3361 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3362 array_push($tags, $tmp_line["tag_name"]);
3363 }
3364
3365 return $tags;
3366 }
3367
3368 function trim_value(&$value) {
3369 $value = trim($value);
3370 }
3371
3372 function trim_array($array) {
3373 $tmp = $array;
3374 array_walk($tmp, 'trim_value');
3375 return $tmp;
3376 }
3377
3378 function tag_is_valid($tag) {
3379 if ($tag == '') return false;
3380 if (preg_match("/^[0-9]*$/", $tag)) return false;
3381
3382 $tag = iconv("utf-8", "utf-8", $tag);
3383 if (!$tag) return false;
3384
3385 return true;
3386 }
3387
3388 function render_login_form($link, $mobile = false) {
3389 if (!$mobile) {
3390 require_once "login_form.php";
3391 } else {
3392 require_once "mobile/login_form.php";
3393 }
3394 }
3395
3396 // from http://developer.apple.com/internet/safari/faq.html
3397 function no_cache_incantation() {
3398 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3399 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3400 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3401 header("Cache-Control: post-check=0, pre-check=0", false);
3402 header("Pragma: no-cache"); // HTTP/1.0
3403 }
3404
3405 function format_warning($msg, $id = "") {
3406 return "<div class=\"warning\" id=\"$id\">
3407 <img src=\"images/sign_excl.png\">$msg</div>";
3408 }
3409
3410 function format_notice($msg) {
3411 return "<div class=\"notice\">
3412 <img src=\"images/sign_info.png\">$msg</div>";
3413 }
3414
3415 function format_error($msg) {
3416 return "<div class=\"error\">
3417 <img src=\"images/sign_excl.png\">$msg</div>";
3418 }
3419
3420 function print_notice($msg) {
3421 return print format_notice($msg);
3422 }
3423
3424 function print_warning($msg) {
3425 return print format_warning($msg);
3426 }
3427
3428 function print_error($msg) {
3429 return print format_error($msg);
3430 }
3431
3432
3433 function T_sprintf() {
3434 $args = func_get_args();
3435 return vsprintf(__(array_shift($args)), $args);
3436 }
3437
3438 function outputArticleXML($link, $id, $feed_id, $mark_as_read = true) {
3439
3440 /* we can figure out feed_id from article id anyway, why do we
3441 * pass feed_id here? */
3442
3443 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3444 WHERE ref_id = '$id'");
3445
3446 $feed_id = db_fetch_result($result, 0, "feed_id");
3447
3448 print "<article id='$id'><![CDATA[";
3449
3450 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3451 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
3452
3453 if (db_num_rows($result) == 1) {
3454 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3455 } else {
3456 $rtl_content = false;
3457 }
3458
3459 if ($rtl_content) {
3460 $rtl_tag = "dir=\"RTL\"";
3461 $rtl_class = "RTL";
3462 } else {
3463 $rtl_tag = "";
3464 $rtl_class = "";
3465 }
3466
3467 if ($mark_as_read) {
3468 $result = db_query($link, "UPDATE ttrss_user_entries
3469 SET unread = false,last_read = NOW()
3470 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3471 }
3472
3473 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3474 SUBSTRING(updated,1,16) as updated,
3475 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3476 num_comments,
3477 author
3478 FROM ttrss_entries,ttrss_user_entries
3479 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
3480
3481 if ($result) {
3482
3483 $link_target = "";
3484
3485 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3486 $link_target = "target=\"_new\"";
3487 }
3488
3489 $line = db_fetch_assoc($result);
3490
3491 if ($line["icon_url"]) {
3492 $feed_icon = "<img class=\"feedIcon\" src=\"" . $line["icon_url"] . "\">";
3493 } else {
3494 $feed_icon = "&nbsp;";
3495 }
3496
3497 /* if ($line["comments"] && $line["link"] != $line["comments"]) {
3498 $entry_comments = "(<a href=\"".$line["comments"]."\">Comments</a>)";
3499 } else {
3500 $entry_comments = "";
3501 } */
3502
3503 $num_comments = $line["num_comments"];
3504 $entry_comments = "";
3505
3506 if ($num_comments > 0) {
3507 if ($line["comments"]) {
3508 $comments_url = $line["comments"];
3509 } else {
3510 $comments_url = $line["link"];
3511 }
3512 $entry_comments = "<a $link_target href=\"$comments_url\">$num_comments comments</a>";
3513 } else {
3514 if ($line["comments"] && $line["link"] != $line["comments"]) {
3515 $entry_comments = "<a $link_target href=\"".$line["comments"]."\">comments</a>";
3516 }
3517 }
3518
3519 print "<div class=\"postReply\">";
3520
3521 print "<div class=\"postHeader\">";
3522
3523 $entry_author = $line["author"];
3524
3525 if ($entry_author) {
3526 $entry_author = __(" - by ") . $entry_author;
3527 }
3528
3529 $parsed_updated = date(get_pref($link, 'LONG_DATE_FORMAT'),
3530 strtotime($line["updated"]));
3531
3532 print "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3533
3534 if ($line["link"]) {
3535 print "<div clear='both'><a $link_target href=\"" . $line["link"] . "\">" .
3536 $line["title"] . "</a>$entry_author</div>";
3537 } else {
3538 print "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3539 }
3540
3541 $tmp_result = db_query($link, "SELECT DISTINCT tag_name FROM
3542 ttrss_tags WHERE post_int_id = " . $line["int_id"] . "
3543 ORDER BY tag_name");
3544
3545 $tags_str = "";
3546 $f_tags_str = "";
3547
3548 $num_tags = 0;
3549
3550 while ($tmp_line = db_fetch_assoc($tmp_result)) {
3551 $num_tags++;
3552 $tag = $tmp_line["tag_name"];
3553 $tag_escaped = str_replace("'", "\\'", $tag);
3554
3555 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>, ";
3556
3557 if ($num_tags == 6) {
3558 $tags_str .= "<a href=\"javascript:showBlockElement('allEntryTags')\">...</a>";
3559 } else if ($num_tags < 6) {
3560 $tags_str .= $tag_str;
3561 }
3562 $f_tags_str .= $tag_str;
3563 }
3564
3565 $tags_str = preg_replace("/, $/", "", $tags_str);
3566 $f_tags_str = preg_replace("/, $/", "", $f_tags_str);
3567
3568 if (!$entry_comments) $entry_comments = "&nbsp;"; # placeholder
3569
3570 if (!$tags_str) $tags_str = '<span class="tagList">'.__('no tags').'</span>';
3571
3572 print "<div style='float : right'>$tags_str
3573 <a title=\"Edit tags for this article\"
3574 href=\"javascript:editArticleTags($id, $feed_id)\">(+)</a></div>
3575 <div clear='both'>$entry_comments</div>";
3576
3577 print "</div>";
3578
3579 print "<div class=\"postIcon\">" . $feed_icon . "</div>";
3580 print "<div class=\"postContent\">";
3581
3582 if (db_num_rows($tmp_result) > 0) {
3583 print "<div id=\"allEntryTags\">".__('Tags:')." $f_tags_str</div>";
3584 }
3585
3586 if (get_pref($link, 'OPEN_LINKS_IN_NEW_WINDOW')) {
3587 $line["content"] = preg_replace("/href=/i", "target=\"_new\" href=", $line["content"]);
3588 }
3589
3590 $line["content"] = sanitize_rss($link, $line["content"]);
3591
3592 print $line["content"] . "</div>";
3593
3594 print "</div>";
3595
3596 }
3597
3598 print "]]></article>";
3599
3600 }
3601
3602 function outputHeadlinesList($link, $feed, $subop, $view_mode, $limit, $cat_view,
3603 $next_unread_feed, $offset) {
3604
3605 $timing_info = getmicrotime();
3606
3607 $topmost_article_ids = array();
3608
3609 if (!$offset) $offset = 0;
3610
3611 if ($subop == "undefined") $subop = "";
3612
3613 if ($subop == "CatchupSelected") {
3614 $ids = split(",", db_escape_string($_GET["ids"]));
3615 $cmode = sprintf("%d", $_GET["cmode"]);
3616
3617 catchupArticlesById($link, $ids, $cmode);
3618 }
3619
3620 if ($subop == "ForceUpdate" && sprintf("%d", $feed) > 0) {
3621 update_generic_feed($link, $feed, $cat_view);
3622 }
3623
3624 if ($subop == "MarkAllRead") {
3625 catchup_feed($link, $feed, $cat_view);
3626
3627 if (get_pref($link, 'ON_CATCHUP_SHOW_NEXT_FEED')) {
3628 if ($next_unread_feed) {
3629 $feed = $next_unread_feed;
3630 }
3631 }
3632 }
3633
3634 if ($feed_id > 0) {
3635 $result = db_query($link,
3636 "SELECT id FROM ttrss_feeds WHERE id = '$feed' LIMIT 1");
3637
3638 if (db_num_rows($result) == 0) {
3639 print "<div align='center'>".__('Feed not found.')."</div>";
3640 return;
3641 }
3642 }
3643
3644 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
3645
3646 $result = db_query($link, "SELECT rtl_content FROM ttrss_feeds
3647 WHERE id = '$feed' AND owner_uid = " . $_SESSION["uid"]);
3648
3649 if (db_num_rows($result) == 1) {
3650 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3651 } else {
3652 $rtl_content = false;
3653 }
3654
3655 if ($rtl_content) {
3656 $rtl_tag = "dir=\"RTL\"";
3657 } else {
3658 $rtl_tag = "";
3659 }
3660 } else {
3661 $rtl_tag = "";
3662 $rtl_content = false;
3663 }
3664
3665 $script_dt_add = get_script_dt_add();
3666
3667 /// START /////////////////////////////////////////////////////////////////////////////////
3668
3669 $search = db_escape_string($_GET["query"]);
3670 $search_mode = db_escape_string($_GET["search_mode"]);
3671 $match_on = db_escape_string($_GET["match_on"]);
3672
3673 if (!$match_on) {
3674 $match_on = "both";
3675 }
3676
3677 $real_offset = $offset * $limit;
3678
3679 if ($_GET["debug"]) $timing_info = print_checkpoint("H0", $timing_info);
3680
3681 $qfh_ret = queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view,
3682 $search, $search_mode, $match_on, false, $real_offset);
3683
3684 if ($_GET["debug"]) $timing_info = print_checkpoint("H1", $timing_info);
3685
3686 $result = $qfh_ret[0];
3687 $feed_title = $qfh_ret[1];
3688 $feed_site_url = $qfh_ret[2];
3689 $last_error = $qfh_ret[3];
3690
3691 /// STOP //////////////////////////////////////////////////////////////////////////////////
3692
3693 print "<div id=\"headlinesContainer\" $rtl_tag>";
3694
3695 if (!$result) {
3696 print "<div align='center'>".__("Could not display feed (query failed). Please check label match syntax or local configuration.")."</div>";
3697 return;
3698 }
3699
3700 print_headline_subtoolbar($link, $feed_site_url, $feed_title, false,
3701 $rtl_content, $feed, $cat_view, $search, $match_on, $search_mode,
3702 $offset, $limit);
3703
3704 print "<div id=\"headlinesInnerContainer\">";
3705
3706 if (db_num_rows($result) > 0) {
3707
3708 # print "\{$offset}";
3709
3710 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3711 print "<table class=\"headlinesList\" id=\"headlinesList\"
3712 cellspacing=\"0\">";
3713 }
3714
3715 $lnum = 0;
3716
3717 error_reporting (DEFAULT_ERROR_LEVEL);
3718
3719 $num_unread = 0;
3720
3721 while ($line = db_fetch_assoc($result)) {
3722
3723 $class = ($lnum % 2) ? "even" : "odd";
3724
3725 $id = $line["id"];
3726 $feed_id = $line["feed_id"];
3727
3728 if (count($topmost_article_ids) < 5) {
3729 array_push($topmost_article_ids, $id);
3730 }
3731
3732 if ($line["last_read"] == "" &&
3733 ($line["unread"] != "t" && $line["unread"] != "1")) {
3734
3735 $update_pic = "<img id='FUPDPIC-$id' src=\"images/updated.png\"
3736 alt=\"Updated\">";
3737 } else {
3738 $update_pic = "<img id='FUPDPIC-$id' src=\"images/blank_icon.gif\"
3739 alt=\"Updated\">";
3740 }
3741
3742 if ($line["unread"] == "t" || $line["unread"] == "1") {
3743 $class .= "Unread";
3744 ++$num_unread;
3745 $is_unread = true;
3746 } else {
3747 $is_unread = false;
3748 }
3749
3750 if ($line["marked"] == "t" || $line["marked"] == "1") {
3751 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_set.png\"
3752 class=\"markedPic\"
3753 alt=\"Reset mark\" onclick='javascript:tMark($id)'>";
3754 } else {
3755 $marked_pic = "<img id=\"FMPIC-$id\" src=\"images/mark_unset.png\"
3756 class=\"markedPic\"
3757 alt=\"Set mark\" onclick='javascript:tMark($id)'>";
3758 }
3759
3760 # $content_link = "<a target=\"_new\" href=\"".$line["link"]."\">" .
3761 # $line["title"] . "</a>";
3762
3763 $content_link = "<a href=\"javascript:view($id,$feed_id);\">" .
3764 $line["title"] . "</a>";
3765
3766 # $content_link = "<a href=\"javascript:viewContentUrl('".$line["link"]."');\">" .
3767 # $line["title"] . "</a>";
3768
3769 if (get_pref($link, 'HEADLINES_SMART_DATE')) {
3770 $updated_fmt = smart_date_time(strtotime($line["updated_noms"]));
3771 } else {
3772 $short_date = get_pref($link, 'SHORT_DATE_FORMAT');
3773 $updated_fmt = date($short_date, strtotime($line["updated_noms"]));
3774 }
3775
3776 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3777 $content_preview = truncate_string(strip_tags($line["content_preview"]),
3778 100);
3779 }
3780
3781 $entry_author = $line["author"];
3782
3783 if ($entry_author) {
3784 $entry_author = " - by $entry_author";
3785 }
3786
3787 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3788
3789 print "<tr class='$class' id='RROW-$id'>";
3790
3791 print "<td class='hlUpdPic'>$update_pic</td>";
3792
3793 print "<td class='hlSelectRow'>
3794 <input type=\"checkbox\" onclick=\"tSR(this)\"
3795 id=\"RCHK-$id\">
3796 </td>";
3797
3798 print "<td class='hlMarkedPic'>$marked_pic</td>";
3799
3800 if ($line["feed_title"]) {
3801 print "<td class='hlContent'>$content_link</td>";
3802 print "<td class='hlFeed'>
3803 <a href=\"javascript:viewfeed($feed_id, '', false)\">".
3804 $line["feed_title"]."</a>&nbsp;</td>";
3805 } else {
3806 print "<td class='hlContent' valign='middle'>";
3807
3808 print "<a href=\"javascript:view($id,$feed_id);\">" .
3809 $line["title"];
3810
3811 if (get_pref($link, 'SHOW_CONTENT_PREVIEW')) {
3812 if ($content_preview) {
3813 print "<span class=\"contentPreview\"> - $content_preview</span>";
3814 }
3815 }
3816
3817 print "</a>";
3818 print "</td>";
3819 }
3820
3821 print "<td class=\"hlUpdated\"><nobr>$updated_fmt&nbsp;</nobr></td>";
3822
3823 print "</tr>";
3824
3825 } else {
3826
3827 if ($is_unread) {
3828 $add_class = "Unread";
3829 } else {
3830 $add_class = "";
3831 }
3832
3833 print "<div class=\"cdmArticle$add_class\" id=\"RROW-$id\">";
3834
3835 print "<div class=\"cdmHeader\">";
3836
3837 print "<div class=\"articleUpdated\">$updated_fmt</div>";
3838
3839 print "<a class=\"title\"
3840 onclick=\"javascript:toggleUnread($id, 0)\"
3841 target=\"new\" href=\"".$line["link"]."\">".$line["title"]."</a>";
3842
3843 print $entry_author;
3844
3845 if ($line["feed_title"]) {
3846 print "&nbsp;(<a href='javascript:viewfeed($feed_id)'>".$line["feed_title"]."</a>)";
3847 }
3848
3849 print "</div>";
3850
3851 print "<div class=\"cdmContent\">" . $line["content_preview"] . "</div><br clear=\"all\">";
3852
3853 print "<div class=\"cdmFooter\">";
3854
3855 print "$marked_pic";
3856
3857 print "<input type=\"checkbox\" onclick=\"toggleSelectRowById(this,
3858 'RROW-$id')\" class=\"feedCheckBox\" id=\"RCHK-$id\">";
3859
3860 $tags = get_article_tags($link, $id);
3861
3862 $tags_str = "";
3863
3864 foreach ($tags as $tag) {
3865 $num_tags++;
3866 $tags_str .= "<a href=\"javascript:viewfeed('$tag')\">$tag</a>, ";
3867 }
3868
3869 $tags_str = preg_replace("/, $/", "", $tags_str);
3870
3871 if ($tags_str == "") $tags_str = "no tags";
3872
3873 print " $tags_str <a title=\"Edit tags for this article\"
3874 href=\"javascript:editArticleTags($id, $feed_id, true)\">(+)</a>";
3875
3876 print "</div>";
3877
3878 # print "<div align=\"center\"><a class=\"cdmToggleLink\"
3879 # href=\"javascript:toggleUnread($id)\">
3880 # Toggle unread</a></div>";
3881
3882 print "</div>";
3883
3884 }
3885
3886 ++$lnum;
3887 }
3888
3889 if (!get_pref($link, 'COMBINED_DISPLAY_MODE')) {
3890 print "</table>";
3891 }
3892
3893 // print_headline_subtoolbar($link,
3894 // "javascript:catchupPage()", "Mark page as read", true, $rtl_content);
3895
3896
3897 } else {
3898 print "<div class='whiteBox'>".__('No articles found.')."</div>";
3899 }
3900
3901 print "</div>";
3902
3903 print "</div>";
3904
3905 return $topmost_article_ids;
3906 }
3907
3908 // from here: http://www.roscripts.com/Create_tag_cloud-71.html
3909
3910 function printTagCloud($link) {
3911
3912 /* get first ref_id to count from */
3913
3914 /*
3915
3916 $query = "";
3917
3918 if (DB_TYPE == "pgsql") {
3919 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
3920 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3921 AND date_entered > NOW() - INTERVAL '30 days'";
3922 } else {
3923 $query = "SELECT MIN(id) AS id FROM ttrss_user_entries, ttrss_entries
3924 WHERE int_id = id AND owner_uid = ".$_SESSION["uid"]."
3925 AND date_entered > DATE_SUB(NOW(), INTERVAL 30 DAY)";
3926 }
3927
3928 $result = db_query($link, $query);
3929 $first_id = db_fetch_result($result, 0, "id"); */
3930
3931 //AND post_int_id >= '$first_id'
3932 $query = "SELECT tag_name, COUNT(post_int_id) AS count
3933 FROM ttrss_tags WHERE owner_uid = ".$_SESSION["uid"]."
3934 GROUP BY tag_name ORDER BY count DESC LIMIT 50";
3935
3936 $result = db_query($link, $query);
3937
3938 $tags = array();
3939
3940 while ($line = db_fetch_assoc($result)) {
3941 $tags[$line["tag_name"]] = $line["count"];
3942 }
3943
3944 ksort($tags);
3945
3946 $max_size = 32; // max font size in pixels
3947 $min_size = 11; // min font size in pixels
3948
3949 // largest and smallest array values
3950 $max_qty = max(array_values($tags));
3951 $min_qty = min(array_values($tags));
3952
3953 // find the range of values
3954 $spread = $max_qty - $min_qty;
3955 if ($spread == 0) { // we don't want to divide by zero
3956 $spread = 1;
3957 }
3958
3959 // set the font-size increment
3960 $step = ($max_size - $min_size) / ($spread);
3961
3962 // loop through the tag array
3963 foreach ($tags as $key => $value) {
3964 // calculate font-size
3965 // find the $value in excess of $min_qty
3966 // multiply by the font-size increment ($size)
3967 // and add the $min_size set above
3968 $size = round($min_size + (($value - $min_qty) * $step));
3969
3970 echo "<a href=\"javascript:viewfeed('$key') \" style=\"font-size: " .
3971 $size . "px\" title=\"$value articles tagged with " .
3972 $key . '">' . $key . '</a> ';
3973 }
3974 }
3975
3976 function print_checkpoint($n, $s) {
3977 $ts = getmicrotime();
3978 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3979 return $ts;
3980 }
3981
3982 function sanitize_tag($tag) {
3983 $tag = trim($tag);
3984
3985 $tag = mb_strtolower($tag, 'utf-8');
3986
3987 $tag = str_replace('\"', "", $tag);
3988 $tag = str_replace('"', "", $tag);
3989 $tag = str_replace("+", " ", $tag);
3990 $tag = str_replace("technorati tag: ", "", $tag);
3991
3992 return $tag;
3993 }
3994 ?>