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