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