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