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