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