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