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