2 date_default_timezone_set('UTC');
3 if (defined('E_DEPRECATED')) {
4 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
6 error_reporting(E_ALL
& ~E_NOTICE
);
9 require_once 'config.php';
11 if (DB_TYPE
== "pgsql") {
12 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
14 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
17 define('THEME_VERSION_REQUIRED', 1.1);
20 * Return available translations names.
23 * @return array A array of available translations.
25 function get_translations() {
27 "auto" => "Detect automatically",
32 "fr_FR" => "Français",
33 "hu_HU" => "Magyar (Hungarian)",
34 "it_IT" => "Italiano",
35 "ja_JP" => "日本語 (Japanese)",
36 "nb_NO" => "Norwegian bokmål",
38 "pt_BR" => "Portuguese/Brazil",
39 "zh_CN" => "Simplified Chinese");
44 require_once "lib/accept-to-gettext.php";
45 require_once "lib/gettext/gettext.inc";
47 function startup_gettext() {
49 # Get locale from Accept-Language header
50 $lang = al2gt(array_keys(get_translations()), "text/html");
52 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
53 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
56 if ($_COOKIE["ttrss_lang"] && $_COOKIE["ttrss_lang"] != "auto") {
57 $lang = $_COOKIE["ttrss_lang"];
60 /* In login action of mobile version */
61 if ($_POST["language"] && defined('MOBILE_VERSION')) {
62 $lang = $_POST["language"];
63 $_COOKIE["ttrss_lang"] = $lang;
67 if (defined('LC_MESSAGES')) {
68 _setlocale(LC_MESSAGES
, $lang);
69 } else if (defined('LC_ALL')) {
70 _setlocale(LC_ALL
, $lang);
73 if (defined('MOBILE_VERSION')) {
74 _bindtextdomain("messages", "../locale");
76 _bindtextdomain("messages", "locale");
79 _textdomain("messages");
80 _bind_textdomain_codeset("messages", "UTF-8");
86 if (defined('MEMCACHE_SERVER')) {
87 $memcache = new Memcache
;
88 $memcache->connect(MEMCACHE_SERVER
, 11211);
91 require_once 'db-prefs.php';
92 require_once 'version.php';
94 define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
96 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
97 define('MAGPIE_USER_AGENT', SELF_USER_AGENT
);
99 ini_set('user_agent', SELF_USER_AGENT
);
101 require_once 'lib/pubsubhubbub/publisher.php';
106 $utc_tz = new DateTimeZone('UTC');
107 $schema_version = false;
110 * Print a timestamped debug message.
112 * @param string $msg The debug message.
115 function _debug($msg) {
116 $ts = strftime("%H:%M:%S", time());
117 if (function_exists('posix_getpid')) {
118 $ts = "$ts/" . posix_getpid();
120 print "[$ts] $msg\n";
124 * Purge a feed old posts.
126 * @param mixed $link A database connection.
127 * @param mixed $feed_id The id of the purged feed.
128 * @param mixed $purge_interval Olderness of purged posts.
129 * @param boolean $debug Set to True to enable the debug. False by default.
133 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
135 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
139 $result = db_query($link,
140 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
144 if (db_num_rows($result) == 1) {
145 $owner_uid = db_fetch_result($result, 0, "owner_uid");
148 if ($purge_interval == -1 ||
!$purge_interval) {
150 ccache_update($link, $feed_id, $owner_uid);
155 if (!$owner_uid) return;
157 if (FORCE_ARTICLE_PURGE
== 0) {
158 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
161 $purge_unread = true;
162 $purge_interval = FORCE_ARTICLE_PURGE
;
165 if (!$purge_unread) $query_limit = " unread = false AND ";
167 if (DB_TYPE
== "pgsql") {
168 $pg_version = get_pgsql_version($link);
170 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
172 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
173 ttrss_entries.id = ref_id AND
175 feed_id = '$feed_id' AND
177 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
181 $result = db_query($link, "DELETE FROM ttrss_user_entries
183 WHERE ttrss_entries.id = ref_id AND
185 feed_id = '$feed_id' AND
187 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
190 $rows = pg_affected_rows($result);
194 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
195 marked = false AND feed_id = '$feed_id' AND
196 (SELECT date_updated FROM ttrss_entries WHERE
197 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
199 $result = db_query($link, "DELETE FROM ttrss_user_entries
200 USING ttrss_user_entries, ttrss_entries
201 WHERE ttrss_entries.id = ref_id AND
203 feed_id = '$feed_id' AND
205 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
207 $rows = mysql_affected_rows($link);
211 ccache_update($link, $feed_id, $owner_uid);
214 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
216 } // function purge_feed
218 function feed_purge_interval($link, $feed_id) {
220 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
221 WHERE id = '$feed_id'");
223 if (db_num_rows($result) == 1) {
224 $purge_interval = db_fetch_result($result, 0, "purge_interval");
225 $owner_uid = db_fetch_result($result, 0, "owner_uid");
227 if ($purge_interval == 0) $purge_interval = get_pref($link,
228 'PURGE_OLD_DAYS', $owner_uid);
230 return $purge_interval;
237 function purge_orphans($link, $do_output = false) {
239 // purge orphaned posts in main content table
240 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
241 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
244 $rows = db_affected_rows($link, $result);
245 _debug("Purged $rows orphaned posts.");
249 function get_feed_update_interval($link, $feed_id) {
250 $result = db_query($link, "SELECT owner_uid, update_interval FROM
251 ttrss_feeds WHERE id = '$feed_id'");
253 if (db_num_rows($result) == 1) {
254 $update_interval = db_fetch_result($result, 0, "update_interval");
255 $owner_uid = db_fetch_result($result, 0, "owner_uid");
257 if ($update_interval != 0) {
258 return $update_interval;
260 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
268 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
269 $login = urlencode($login);
270 $pass = urlencode($pass);
272 if (function_exists('curl_init') && !ini_get("open_basedir")) {
273 $ch = curl_init($url);
275 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
276 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
277 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
278 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
279 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
280 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
281 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
282 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
283 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
284 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
287 curl_setopt($ch, CURLOPT_POST
, true);
288 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
292 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
294 $contents = @curl_exec
($ch);
296 if ($contents === false) {
301 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
302 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
305 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
311 if ($login && $pass ){
312 $url_parts = array();
314 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
316 if ($url_parts[1] && $url_parts[2]) {
317 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
321 return @file_get_contents
($url);
327 * Try to determine the favicon URL for a feed.
328 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
329 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
331 * @param string $url A feed or page URL
333 * @return mixed The favicon URL, or false if none was found.
335 function get_favicon_url($url) {
337 $favicon_url = false;
339 if ($html = @fetch_file_contents
($url)) {
341 libxml_use_internal_errors(true);
343 $doc = new DOMDocument();
344 $doc->loadHTML($html);
345 $xpath = new DOMXPath($doc);
347 $base = $xpath->query('/html/head/base');
348 foreach ($base as $b) {
349 $url = $b->getAttribute("href");
353 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
354 if (count($entries) > 0) {
355 foreach ($entries as $entry) {
356 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
363 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
366 } // function get_favicon_url
368 function check_feed_favicon($site_url, $feed, $link) {
369 # print "FAVICON [$site_url]: $favicon_url\n";
371 $icon_file = ICONS_DIR
. "/$feed.ico";
373 if (!file_exists($icon_file)) {
374 $favicon_url = get_favicon_url($site_url);
377 $contents = fetch_file_contents($favicon_url, "image");
380 $fp = @fopen
($icon_file, "w");
383 fwrite($fp, $contents);
385 chmod($icon_file, 0644);
392 function print_select($id, $default, $values, $attributes = "") {
393 print "<select name=\"$id\" id=\"$id\" $attributes>";
394 foreach ($values as $v) {
396 $sel = "selected=\"1\"";
400 print "<option value=\"$v\" $sel>$v</option>";
405 function print_select_hash($id, $default, $values, $attributes = "") {
406 print "<select name=\"$id\" id='$id' $attributes>";
407 foreach (array_keys($values) as $v) {
409 $sel = 'selected="selected"';
413 print "<option $sel value=\"$v\">".$values[$v]."</option>";
419 function get_article_filters($filters, $title, $content, $link, $timestamp, $author, $tags) {
422 if ($filters["title"]) {
423 foreach ($filters["title"] as $filter) {
424 $reg_exp = $filter["reg_exp"];
425 $inverse = $filter["inverse"];
426 if ((!$inverse && @preg_match
("/$reg_exp/i", $title)) ||
427 ($inverse && !@preg_match
("/$reg_exp/i", $title))) {
429 array_push($matches, array($filter["action"], $filter["action_param"]));
434 if ($filters["content"]) {
435 foreach ($filters["content"] as $filter) {
436 $reg_exp = $filter["reg_exp"];
437 $inverse = $filter["inverse"];
439 if ((!$inverse && @preg_match
("/$reg_exp/i", $content)) ||
440 ($inverse && !@preg_match
("/$reg_exp/i", $content))) {
442 array_push($matches, array($filter["action"], $filter["action_param"]));
447 if ($filters["both"]) {
448 foreach ($filters["both"] as $filter) {
449 $reg_exp = $filter["reg_exp"];
450 $inverse = $filter["inverse"];
453 if (!@preg_match
("/$reg_exp/i", $title) && !preg_match("/$reg_exp/i", $content)) {
454 array_push($matches, array($filter["action"], $filter["action_param"]));
457 if (@preg_match
("/$reg_exp/i", $title) ||
preg_match("/$reg_exp/i", $content)) {
458 array_push($matches, array($filter["action"], $filter["action_param"]));
464 if ($filters["link"]) {
465 $reg_exp = $filter["reg_exp"];
466 foreach ($filters["link"] as $filter) {
467 $reg_exp = $filter["reg_exp"];
468 $inverse = $filter["inverse"];
470 if ((!$inverse && @preg_match
("/$reg_exp/i", $link)) ||
471 ($inverse && !@preg_match
("/$reg_exp/i", $link))) {
473 array_push($matches, array($filter["action"], $filter["action_param"]));
478 if ($filters["date"]) {
479 $reg_exp = $filter["reg_exp"];
480 foreach ($filters["date"] as $filter) {
481 $date_modifier = $filter["filter_param"];
482 $inverse = $filter["inverse"];
483 $check_timestamp = strtotime($filter["reg_exp"]);
485 # no-op when timestamp doesn't parse to prevent misfires
487 if ($check_timestamp) {
490 if ($date_modifier == "before" && $timestamp < $check_timestamp ||
491 $date_modifier == "after" && $timestamp > $check_timestamp) {
495 if ($inverse) $match_ok = !$match_ok;
498 array_push($matches, array($filter["action"], $filter["action_param"]));
504 if ($filters["author"]) {
505 foreach ($filters["author"] as $filter) {
506 $reg_exp = $filter["reg_exp"];
507 $inverse = $filter["inverse"];
508 if ((!$inverse && @preg_match
("/$reg_exp/i", $author)) ||
509 ($inverse && !@preg_match
("/$reg_exp/i", $author))) {
511 array_push($matches, array($filter["action"], $filter["action_param"]));
516 if ($filters["tag"]) {
518 $tag_string = join(",", $tags);
520 foreach ($filters["tag"] as $filter) {
521 $reg_exp = $filter["reg_exp"];
522 $inverse = $filter["inverse"];
524 if ((!$inverse && @preg_match
("/$reg_exp/i", $tag_string)) ||
525 ($inverse && !@preg_match
("/$reg_exp/i", $tag_string))) {
527 array_push($matches, array($filter["action"], $filter["action_param"]));
536 function find_article_filter($filters, $filter_name) {
537 foreach ($filters as $f) {
538 if ($f[0] == $filter_name) {
545 function calculate_article_score($filters) {
548 foreach ($filters as $f) {
549 if ($f[0] == "score") {
556 function assign_article_to_labels($link, $id, $filters, $owner_uid) {
557 foreach ($filters as $f) {
558 if ($f[0] == "label") {
559 label_add_article($link, $id, $f[1], $owner_uid);
564 function getmicrotime() {
565 list($usec, $sec) = explode(" ",microtime());
566 return ((float)$usec +
(float)$sec);
569 function print_radio($id, $default, $true_is, $values, $attributes = "") {
570 foreach ($values as $v) {
577 if ($v == $true_is) {
578 $sel .= " value=\"1\"";
580 $sel .= " value=\"0\"";
583 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
584 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
589 function initialize_user_prefs($link, $uid, $profile = false) {
591 $uid = db_escape_string($uid);
595 $profile_qpart = "AND profile IS NULL";
597 $profile_qpart = "AND profile = '$profile'";
600 if (get_schema_version($link) < 63) $profile_qpart = "";
602 db_query($link, "BEGIN");
604 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
606 $u_result = db_query($link, "SELECT pref_name
607 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
609 $active_prefs = array();
611 while ($line = db_fetch_assoc($u_result)) {
612 array_push($active_prefs, $line["pref_name"]);
615 while ($line = db_fetch_assoc($result)) {
616 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
617 // print "adding " . $line["pref_name"] . "<br>";
619 if (get_schema_version($link) < 63) {
620 db_query($link, "INSERT INTO ttrss_user_prefs
621 (owner_uid,pref_name,value) VALUES
622 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
625 db_query($link, "INSERT INTO ttrss_user_prefs
626 (owner_uid,pref_name,value, profile) VALUES
627 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
633 db_query($link, "COMMIT");
637 function get_ssl_certificate_id() {
638 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
639 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
640 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
641 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
642 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
647 function get_login_by_ssl_certificate($link) {
649 $cert_serial = db_escape_string(get_ssl_certificate_id());
652 $result = db_query($link, "SELECT login FROM ttrss_user_prefs, ttrss_users
653 WHERE pref_name = 'SSL_CERT_SERIAL' AND value = '$cert_serial' AND
654 owner_uid = ttrss_users.id");
656 if (db_num_rows($result) != 0) {
657 return db_escape_string(db_fetch_result($result, 0, "login"));
664 function get_remote_user($link) {
666 if (defined('ALLOW_REMOTE_USER_AUTH') && ALLOW_REMOTE_USER_AUTH
) {
667 return db_escape_string($_SERVER["REMOTE_USER"]);
670 return db_escape_string(get_login_by_ssl_certificate($link));
673 function get_remote_fakepass($link) {
674 if (get_remote_user($link))
680 function authenticate_user($link, $login, $password, $force_auth = false) {
682 if (!SINGLE_USER_MODE
) {
684 $pwd_hash1 = encrypt_password($password);
685 $pwd_hash2 = encrypt_password($password, $login);
686 $login = db_escape_string($login);
688 $remote_user = get_remote_user($link);
690 if ($remote_user && $remote_user == $login && $login != "admin") {
692 $login = $remote_user;
694 $query = "SELECT id,login,access_level,pwd_hash
695 FROM ttrss_users WHERE
698 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
699 && $_SERVER["REMOTE_USER"]) {
700 $result = db_query($link, $query);
703 if (db_num_rows($result) == 0) {
704 $query2 = "INSERT INTO ttrss_users
705 (login,access_level,last_login,created)
706 VALUES ('$login', 0, null, NOW())";
707 db_query($link, $query2);
712 $query = "SELECT id,login,access_level,pwd_hash
713 FROM ttrss_users WHERE
714 login = '$login' AND (pwd_hash = '$pwd_hash1' OR
715 pwd_hash = '$pwd_hash2')";
718 $result = db_query($link, $query);
720 if (db_num_rows($result) == 1) {
721 $_SESSION["uid"] = db_fetch_result($result, 0, "id");
722 $_SESSION["name"] = db_fetch_result($result, 0, "login");
723 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
724 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
726 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
730 // LemonLDAP can send user informations via HTTP HEADER
731 if (defined('AUTO_CREATE_USER') && AUTO_CREATE_USER
){
733 $fullname = $_SERVER['HTTP_USER_NAME'] ?
$_SERVER['HTTP_USER_NAME'] : $_SERVER['AUTHENTICATE_CN'];
735 $fullname = db_escape_string($fullname);
736 db_query($link, "UPDATE ttrss_users SET full_name = '$fullname' WHERE id = " .
740 $email = $_SERVER['HTTP_USER_MAIL'] ?
$_SERVER['HTTP_USER_MAIL'] : $_SERVER['AUTHENTICATE_MAIL'];
742 $email = db_escape_string($email);
743 db_query($link, "UPDATE ttrss_users SET email = '$email' WHERE id = " .
748 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
749 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
751 $_SESSION["last_version_check"] = time();
753 initialize_user_prefs($link, $_SESSION["uid"]);
762 $_SESSION["uid"] = 1;
763 $_SESSION["name"] = "admin";
765 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
767 initialize_user_prefs($link, $_SESSION["uid"]);
773 function make_password($length = 8) {
776 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
780 while ($i < $length) {
781 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
783 if (!strstr($password, $char)) {
791 // this is called after user is created to initialize default feeds, labels
794 // user preferences are checked on every login, not here
796 function initialize_user($link, $uid) {
798 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
799 values ('$uid', 'Tiny Tiny RSS: New Releases',
800 'http://tt-rss.org/releases.rss')");
802 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
803 values ('$uid', 'Tiny Tiny RSS: Forum',
804 'http://tt-rss.org/forum/rss.php')");
807 function logout_user() {
809 if (isset($_COOKIE[session_name()])) {
810 setcookie(session_name(), '', time()-42000, '/');
814 function validate_csrf($csrf_token) {
815 return $csrf_token == $_SESSION['csrf_token'];
818 function validate_session($link) {
819 if (SINGLE_USER_MODE
) return true;
821 $check_ip = $_SESSION['ip_address'];
823 switch (SESSION_CHECK_ADDRESS
) {
828 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
831 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
832 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
836 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
837 $_SESSION["login_error_msg"] =
838 __("Session failed to validate (incorrect IP)");
842 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
845 if ($_SESSION["uid"]) {
847 $result = db_query($link,
848 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
850 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
852 if ($pwd_hash != $_SESSION["pwd_hash"]) {
857 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
859 //print_r($_SESSION);
861 if (time() > $_SESSION["cookie_lifetime"]) {
869 function login_sequence($link, $mobile = false) {
870 $_SESSION["prefs_cache"] = array();
872 if (!SINGLE_USER_MODE
) {
874 $login_action = $_POST["login_action"];
876 # try to authenticate user if called from login form
877 if ($login_action == "do_login") {
878 $login = db_escape_string($_POST["login"]);
879 $password = $_POST["password"];
880 $remember_me = $_POST["remember_me"];
882 if (authenticate_user($link, $login, $password)) {
883 $_POST["password"] = "";
885 $_SESSION["language"] = $_POST["language"];
886 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
887 $_SESSION["bw_limit"] = !!$_POST["bw_limit"];
889 if ($_POST["profile"]) {
891 $profile = db_escape_string($_POST["profile"]);
893 $result = db_query($link, "SELECT id FROM ttrss_settings_profiles
894 WHERE id = '$profile' AND owner_uid = " . $_SESSION["uid"]);
896 if (db_num_rows($result) != 0) {
897 $_SESSION["profile"] = $profile;
898 $_SESSION["prefs_cache"] = array();
902 if ($_REQUEST['return']) {
903 header("Location: " . $_REQUEST['return']);
905 header("Location: " . $_SERVER["REQUEST_URI"]);
912 $_SESSION["login_error_msg"] = __("Incorrect username or password");
916 if (!$_SESSION["uid"] ||
!validate_session($link)) {
918 if (get_remote_user($link) && AUTO_LOGIN
) {
919 authenticate_user($link, get_remote_user($link), null);
920 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
922 render_login_form($link, $mobile);
923 //header("Location: login.php");
927 /* bump login timestamp */
928 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
931 if ($_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
932 setcookie("ttrss_lang", $_SESSION["language"],
933 time() + SESSION_COOKIE_LIFETIME
);
936 // try to remove possible duplicates from feed counter cache
937 // ccache_cleanup($link, $_SESSION["uid"]);
941 return authenticate_user($link, "admin", null);
945 function truncate_string($str, $max_len, $suffix = '…') {
946 if (mb_strlen($str, "utf-8") > $max_len - 3) {
947 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
953 function theme_image($link, $filename) {
955 $theme_path = get_user_theme_path($link);
957 if ($theme_path && is_file($theme_path.$filename)) {
958 return $theme_path.$filename;
967 function get_user_theme($link) {
969 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
970 $theme_name = get_pref($link, "_THEME_ID");
971 if (is_dir("themes/$theme_name")) {
982 function get_user_theme_path($link) {
985 if (get_schema_version($link) >= 63 && $_SESSION["uid"]) {
986 $theme_name = get_pref($link, "_THEME_ID");
988 if ($theme_name && is_dir("themes/$theme_name")) {
989 $theme_path = "themes/$theme_name/";
998 if (is_file("$theme_path/theme.ini")) {
999 $ini = parse_ini_file("$theme_path/theme.ini", true);
1000 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
) {
1008 function get_user_theme_options($link) {
1009 $t = get_user_theme_path($link);
1012 if (is_file("$t/theme.ini")) {
1013 $ini = parse_ini_file("$t/theme.ini", true);
1014 if ($ini['theme']['version']) {
1015 return $ini['theme']['options'];
1022 function print_theme_includes($link) {
1024 $t = get_user_theme_path($link);
1028 print "<link rel=\"stylesheet\" type=\"text/css\"
1029 href=\"$t/theme.css?$time \">";
1030 if (file_exists("$t/theme.js")) {
1031 print "<script type=\"text/javascript\" src=\"$t/theme.js?$time\">
1037 function get_all_themes() {
1038 $themes = glob("themes/*");
1044 foreach ($themes as $t) {
1045 if (is_file("$t/theme.ini")) {
1046 $ini = parse_ini_file("$t/theme.ini", true);
1047 if ($ini['theme']['version'] >= THEME_VERSION_REQUIRED
&&
1048 !$ini['theme']['disabled']) {
1050 $entry["path"] = $t;
1051 $entry["base"] = basename($t);
1052 $entry["name"] = $ini['theme']['name'];
1053 $entry["version"] = $ini['theme']['version'];
1054 $entry["author"] = $ini['theme']['author'];
1055 $entry["options"] = $ini['theme']['options'];
1056 array_push($rv, $entry);
1064 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
1067 $source_tz = new DateTimeZone($source_tz);
1068 } catch (Exception
$e) {
1069 $source_tz = new DateTimeZone('UTC');
1073 $dest_tz = new DateTimeZone($dest_tz);
1074 } catch (Exception
$e) {
1075 $dest_tz = new DateTimeZone('UTC');
1078 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
1079 return $dt->format('U') +
$dest_tz->getOffset($dt);
1082 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
1083 $no_smart_dt = false) {
1085 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1086 if (!$timestamp) $timestamp = '1970-01-01 0:00';
1091 # We store date in UTC internally
1092 $dt = new DateTime($timestamp, $utc_tz);
1094 if ($tz_offset == -1) {
1096 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
1099 $user_tz = new DateTimeZone($user_tz_string);
1100 } catch (Exception
$e) {
1104 $tz_offset = $user_tz->getOffset($dt);
1107 $user_timestamp = $dt->format('U') +
$tz_offset;
1109 if (!$no_smart_dt) {
1110 return smart_date_time($link, $user_timestamp,
1111 $tz_offset, $owner_uid);
1114 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1116 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1118 return date($format, $user_timestamp);
1122 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
1123 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1125 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
1126 return date("G:i", $timestamp);
1127 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
1128 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
1129 return date($format, $timestamp);
1131 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
1132 return date($format, $timestamp);
1136 function sql_bool_to_bool($s) {
1137 if ($s == "t" ||
$s == "1" ||
$s == "true") {
1144 function bool_to_sql_bool($s) {
1152 // Session caching removed due to causing wrong redirects to upgrade
1153 // script when get_schema_version() is called on an obsolete session
1154 // created on a previous schema version.
1155 function get_schema_version($link, $nocache = false) {
1156 global $schema_version;
1158 if (!$schema_version) {
1159 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
1160 $version = db_fetch_result($result, 0, "schema_version");
1161 $schema_version = $version;
1164 return $schema_version;
1168 function sanity_check($link) {
1169 require_once 'errors.php';
1172 $schema_version = get_schema_version($link, true);
1174 if ($schema_version != SCHEMA_VERSION
) {
1178 if (DB_TYPE
== "mysql") {
1179 $result = db_query($link, "SELECT true", false);
1180 if (db_num_rows($result) != 1) {
1185 if (db_escape_string("testTEST") != "testTEST") {
1189 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
1192 function file_is_locked($filename) {
1193 if (function_exists('flock')) {
1194 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
1196 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1197 flock($fp, LOCK_UN
);
1207 return true; // consider the file always locked and skip the test
1210 function make_lockfile($filename) {
1211 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1213 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1214 if (function_exists('posix_getpid')) {
1215 fwrite($fp, posix_getpid() . "\n");
1223 function make_stampfile($filename) {
1224 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
1226 if (flock($fp, LOCK_EX | LOCK_NB
)) {
1227 fwrite($fp, time() . "\n");
1228 flock($fp, LOCK_UN
);
1236 function sql_random_function() {
1237 if (DB_TYPE
== "mysql") {
1244 function catchup_feed($link, $feed, $cat_view, $owner_uid = false) {
1246 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
1248 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
1250 if (is_numeric($feed)) {
1256 $cat_qpart = "cat_id = '$feed'";
1258 $cat_qpart = "cat_id IS NULL";
1261 $tmp_result = db_query($link, "SELECT id
1262 FROM ttrss_feeds WHERE $cat_qpart AND owner_uid = $owner_uid");
1264 while ($tmp_line = db_fetch_assoc($tmp_result)) {
1266 $tmp_feed = $tmp_line["id"];
1268 db_query($link, "UPDATE ttrss_user_entries
1269 SET unread = false,last_read = NOW()
1270 WHERE feed_id = '$tmp_feed' AND owner_uid = $owner_uid");
1272 } else if ($feed == -2) {
1274 db_query($link, "UPDATE ttrss_user_entries
1275 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
1276 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
1277 AND unread = true AND owner_uid = $owner_uid");
1280 } else if ($feed > 0) {
1282 db_query($link, "UPDATE ttrss_user_entries
1283 SET unread = false,last_read = NOW()
1284 WHERE feed_id = '$feed' AND owner_uid = $owner_uid");
1286 } else if ($feed < 0 && $feed > -10) { // special, like starred
1289 db_query($link, "UPDATE ttrss_user_entries
1290 SET unread = false,last_read = NOW()
1291 WHERE marked = true AND owner_uid = $owner_uid");
1295 db_query($link, "UPDATE ttrss_user_entries
1296 SET unread = false,last_read = NOW()
1297 WHERE published = true AND owner_uid = $owner_uid");
1302 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1304 if (DB_TYPE
== "pgsql") {
1305 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1307 $match_part = "updated > DATE_SUB(NOW(),
1308 INTERVAL $intl HOUR) ";
1311 $result = db_query($link, "SELECT id FROM ttrss_entries,
1312 ttrss_user_entries WHERE $match_part AND
1314 ttrss_user_entries.ref_id = ttrss_entries.id AND
1315 owner_uid = $owner_uid");
1317 $affected_ids = array();
1319 while ($line = db_fetch_assoc($result)) {
1320 array_push($affected_ids, $line["id"]);
1323 catchupArticlesById($link, $affected_ids, 0);
1327 db_query($link, "UPDATE ttrss_user_entries
1328 SET unread = false,last_read = NOW()
1329 WHERE owner_uid = $owner_uid");
1332 } else if ($feed < -10) { // label
1334 $label_id = -$feed - 11;
1336 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1337 SET unread = false, last_read = NOW()
1338 WHERE label_id = '$label_id' AND unread = true
1339 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1343 ccache_update($link, $feed, $owner_uid, $cat_view);
1346 db_query($link, "BEGIN");
1348 $tag_name = db_escape_string($feed);
1350 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1351 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1353 while ($line = db_fetch_assoc($result)) {
1354 db_query($link, "UPDATE ttrss_user_entries SET
1355 unread = false, last_read = NOW()
1356 WHERE int_id = " . $line["post_int_id"]);
1358 db_query($link, "COMMIT");
1362 function getAllCounters($link, $omode = "flc", $active_feed = false) {
1364 if (!$omode) $omode = "flc";
1366 $data = getGlobalCounters($link);
1368 $data = array_merge($data, getVirtCounters($link));
1370 if (strchr($omode, "l")) $data = array_merge($data, getLabelCounters($link));
1371 if (strchr($omode, "f")) $data = array_merge($data, getFeedCounters($link, $active_feed));
1372 if (strchr($omode, "t")) $data = array_merge($data, getTagCounters($link));
1373 if (strchr($omode, "c")) $data = array_merge($data, getCategoryCounters($link));
1378 function getCategoryTitle($link, $cat_id) {
1380 if ($cat_id == -1) {
1381 return __("Special");
1382 } else if ($cat_id == -2) {
1383 return __("Labels");
1386 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1389 if (db_num_rows($result) == 1) {
1390 return db_fetch_result($result, 0, "title");
1392 return "Uncategorized";
1398 function getCategoryCounters($link) {
1401 /* Labels category */
1403 $cv = array("id" => -2, "kind" => "cat",
1404 "counter" => getCategoryUnread($link, -2));
1406 array_push($ret_arr, $cv);
1408 $age_qpart = getMaxAgeSubquery();
1410 $result = db_query($link, "SELECT id AS cat_id, value AS unread
1411 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1412 WHERE ttrss_cat_counters_cache.feed_id = id AND
1413 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1415 while ($line = db_fetch_assoc($result)) {
1416 $line["cat_id"] = (int) $line["cat_id"];
1418 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1419 "counter" => $line["unread"]);
1421 array_push($ret_arr, $cv);
1424 /* Special case: NULL category doesn't actually exist in the DB */
1426 $cv = array("id" => 0, "kind" => "cat",
1427 "counter" => ccache_find($link, 0, $_SESSION["uid"], true));
1429 array_push($ret_arr, $cv);
1434 function getCategoryUnread($link, $cat, $owner_uid = false) {
1436 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1441 $cat_query = "cat_id = '$cat'";
1443 $cat_query = "cat_id IS NULL";
1446 $age_qpart = getMaxAgeSubquery();
1448 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1449 AND owner_uid = " . $owner_uid);
1451 $cat_feeds = array();
1452 while ($line = db_fetch_assoc($result)) {
1453 array_push($cat_feeds, "feed_id = " . $line["id"]);
1456 if (count($cat_feeds) == 0) return 0;
1458 $match_part = implode(" OR ", $cat_feeds);
1460 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1461 FROM ttrss_user_entries,ttrss_entries
1462 WHERE unread = true AND ($match_part) AND id = ref_id
1463 AND $age_qpart AND owner_uid = " . $owner_uid);
1467 # this needs to be rewritten
1468 while ($line = db_fetch_assoc($result)) {
1469 $unread +
= $line["unread"];
1473 } else if ($cat == -1) {
1474 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1475 } else if ($cat == -2) {
1477 $result = db_query($link, "
1478 SELECT COUNT(unread) AS unread FROM
1479 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
1480 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
1481 ttrss_labels2.owner_uid = '$owner_uid'
1482 AND unread = true AND feed_id = ttrss_feeds.id
1483 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1485 $unread = db_fetch_result($result, 0, "unread");
1492 function getMaxAgeSubquery($days = COUNTERS_MAX_AGE
) {
1493 if (DB_TYPE
== "pgsql") {
1494 return "ttrss_entries.date_updated >
1495 NOW() - INTERVAL '$days days'";
1497 return "ttrss_entries.date_updated >
1498 DATE_SUB(NOW(), INTERVAL $days DAY)";
1502 function getFeedUnread($link, $feed, $is_cat = false) {
1503 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1506 function getLabelUnread($link, $label_id, $owner_uid = false) {
1507 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1509 $result = db_query($link, "
1510 SELECT COUNT(unread) AS unread FROM
1511 ttrss_user_entries, ttrss_labels2, ttrss_user_labels2, ttrss_feeds
1512 WHERE label_id = ttrss_labels2.id AND article_id = ref_id AND
1513 ttrss_labels2.owner_uid = '$owner_uid' AND ttrss_labels2.id = '$label_id'
1514 AND unread = true AND feed_id = ttrss_feeds.id
1515 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1517 if (db_num_rows($result) != 0) {
1518 return db_fetch_result($result, 0, "unread");
1524 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1525 $owner_uid = false) {
1527 $n_feed = (int) $feed;
1529 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1532 $unread_qpart = "unread = true";
1534 $unread_qpart = "true";
1537 $age_qpart = getMaxAgeSubquery();
1540 return getCategoryUnread($link, $n_feed, $owner_uid);
1541 } if ($feed != "0" && $n_feed == 0) {
1543 $feed = db_escape_string($feed);
1545 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1546 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1547 AND ref_id = id AND $age_qpart
1548 AND $unread_qpart)) AS count FROM ttrss_tags
1549 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1550 return db_fetch_result($result, 0, "count");
1552 } else if ($n_feed == -1) {
1553 $match_part = "marked = true";
1554 } else if ($n_feed == -2) {
1555 $match_part = "published = true";
1556 } else if ($n_feed == -3) {
1557 $match_part = "unread = true AND score >= 0";
1559 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1561 if (DB_TYPE
== "pgsql") {
1562 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1564 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1566 } else if ($n_feed == -4) {
1567 $match_part = "true";
1568 } else if ($n_feed >= 0) {
1571 $match_part = "feed_id = '$n_feed'";
1573 $match_part = "feed_id IS NULL";
1576 } else if ($feed < -10) {
1578 $label_id = -$feed - 11;
1580 return getLabelUnread($link, $label_id, $owner_uid);
1587 $from_qpart = "ttrss_user_entries,ttrss_feeds,ttrss_entries";
1588 $feeds_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
1590 $from_qpart = "ttrss_user_entries,ttrss_entries";
1594 $query = "SELECT count(int_id) AS unread
1595 FROM $from_qpart WHERE
1596 ttrss_user_entries.ref_id = ttrss_entries.id AND
1599 $unread_qpart AND ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1601 $result = db_query($link, $query);
1605 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1606 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1607 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1608 AND $unread_qpart AND $age_qpart AND
1609 ttrss_tags.owner_uid = " . $owner_uid);
1612 $unread = db_fetch_result($result, 0, "unread");
1617 function getGlobalUnread($link, $user_id = false) {
1620 $user_id = $_SESSION["uid"];
1623 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1624 WHERE owner_uid = '$user_id' AND feed_id > 0");
1626 $c_id = db_fetch_result($result, 0, "c_id");
1631 function getGlobalCounters($link, $global_unread = -1) {
1634 if ($global_unread == -1) {
1635 $global_unread = getGlobalUnread($link);
1638 $cv = array("id" => "global-unread",
1639 "counter" => $global_unread);
1641 array_push($ret_arr, $cv);
1643 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1644 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1646 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1648 $cv = array("id" => "subscribed-feeds",
1649 "counter" => $subscribed_feeds);
1651 array_push($ret_arr, $cv);
1656 function getTagCounters($link) {
1660 $age_qpart = getMaxAgeSubquery();
1662 $result = db_query($link, "SELECT tag_name,SUM((SELECT COUNT(int_id)
1663 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1664 AND ref_id = id AND $age_qpart
1665 AND unread = true)) AS count FROM ttrss_tags
1666 WHERE owner_uid = ".$_SESSION['uid']." GROUP BY tag_name
1667 ORDER BY count DESC LIMIT 55");
1671 while ($line = db_fetch_assoc($result)) {
1672 $tags[$line["tag_name"]] +
= $line["count"];
1675 foreach (array_keys($tags) as $tag) {
1676 $unread = $tags[$tag];
1677 $tag = htmlspecialchars($tag);
1679 $cv = array("id" => $tag,
1681 "counter" => $unread);
1683 array_push($ret_arr, $cv);
1689 function getVirtCounters($link) {
1693 for ($i = 0; $i >= -4; $i--) {
1695 $count = getFeedUnread($link, $i);
1697 $cv = array("id" => $i,
1698 "counter" => $count);
1700 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1701 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1703 array_push($ret_arr, $cv);
1709 function getLabelCounters($link, $descriptions = false) {
1713 $age_qpart = getMaxAgeSubquery();
1715 $owner_uid = $_SESSION["uid"];
1717 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1718 WHERE owner_uid = '$owner_uid'");
1720 while ($line = db_fetch_assoc($result)) {
1722 $id = -$line["id"] - 11;
1724 $label_name = $line["caption"];
1725 $count = getFeedUnread($link, $id);
1727 $cv = array("id" => $id,
1728 "counter" => $count);
1731 $cv["description"] = $label_name;
1733 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1734 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1736 array_push($ret_arr, $cv);
1742 function getFeedCounters($link, $active_feed = false) {
1746 $age_qpart = getMaxAgeSubquery();
1748 $query = "SELECT ttrss_feeds.id,
1750 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1751 last_error, value AS count
1752 FROM ttrss_feeds, ttrss_counters_cache
1753 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1754 AND ttrss_counters_cache.feed_id = id";
1756 $result = db_query($link, $query);
1757 $fctrs_modified = false;
1759 while ($line = db_fetch_assoc($result)) {
1762 $count = $line["count"];
1763 $last_error = htmlspecialchars($line["last_error"]);
1765 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1767 $has_img = feed_has_icon($id);
1769 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1772 $cv = array("id" => $id,
1773 "updated" => $last_updated,
1774 "counter" => $count,
1775 "has_img" => (int) $has_img);
1778 $cv["error"] = $last_error;
1780 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1781 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1783 if ($active_feed && $id == $active_feed)
1784 $cv["title"] = truncate_string($line["title"], 30);
1786 array_push($ret_arr, $cv);
1793 function get_pgsql_version($link) {
1794 $result = db_query($link, "SELECT version() AS version");
1795 $version = explode(" ", db_fetch_result($result, 0, "version"));
1800 * Subscribes the user to the given feed
1802 * @param resource $link Database connection
1803 * @param string $url Feed URL to subscribe to
1804 * @param integer $cat_id Category ID the feed shall be added to
1805 * @param string $auth_login (optional) Feed username
1806 * @param string $auth_pass (optional) Feed password
1808 * @return integer Status code:
1809 * 0 - OK, Feed already exists
1810 * 1 - OK, Feed added
1812 * 3 - URL content is HTML, no feeds available
1813 * 4 - URL content is HTML which contains multiple feeds.
1814 * Here you should call extractfeedurls in rpc-backend
1815 * to get all possible feeds.
1816 * 5 - Couldn't download the URL content.
1818 function subscribe_to_feed($link, $url, $cat_id = 0,
1819 $auth_login = '', $auth_pass = '') {
1821 require_once "include/rssfuncs.php";
1823 $url = fix_url($url);
1825 if (!$url ||
!validate_feed_url($url)) return 2;
1829 $result = db_query($link, "SELECT twitter_oauth FROM ttrss_users
1830 WHERE id = ".$_SESSION['uid']);
1832 $has_oauth = db_fetch_result($result, 0, 'twitter_oauth');
1834 if (!$has_oauth ||
strpos($url, '://api.twitter.com') === false) {
1835 if (!fetch_file_contents($url, false, $auth_login, $auth_pass)) return 5;
1837 if (url_is_html($url, $auth_login, $auth_pass)) {
1838 $feedUrls = get_feeds_from_html($url, $auth_login, $auth_pass);
1839 if (count($feedUrls) == 0) {
1841 } else if (count($feedUrls) > 1) {
1844 //use feed url as new URL
1845 $url = key($feedUrls);
1849 if (!fetch_twitter_rss($link, $url, $_SESSION['uid']))
1854 if ($cat_id == "0" ||
!$cat_id) {
1855 $cat_qpart = "NULL";
1857 $cat_qpart = "'$cat_id'";
1860 $result = db_query($link,
1861 "SELECT id FROM ttrss_feeds
1862 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1864 if (db_num_rows($result) == 0) {
1865 $result = db_query($link,
1866 "INSERT INTO ttrss_feeds
1867 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1868 VALUES ('".$_SESSION["uid"]."', '$url',
1869 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', '$update_method')");
1871 $result = db_query($link,
1872 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1873 AND owner_uid = " . $_SESSION["uid"]);
1875 $feed_id = db_fetch_result($result, 0, "id");
1878 update_rss_feed($link, $feed_id, true);
1887 function print_feed_select($link, $id, $default_id = "",
1888 $attributes = "", $include_all_feeds = true) {
1890 print "<select id=\"$id\" name=\"$id\" $attributes>";
1891 if ($include_all_feeds) {
1892 print "<option value=\"0\">".__('All feeds')."</option>";
1895 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1896 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1898 if (db_num_rows($result) > 0 && $include_all_feeds) {
1899 print "<option disabled>--------</option>";
1902 while ($line = db_fetch_assoc($result)) {
1903 if ($line["id"] == $default_id) {
1904 $is_selected = "selected=\"1\"";
1909 $title = truncate_string(htmlspecialchars($line["title"]), 40);
1911 printf("<option $is_selected value='%d'>%s</option>",
1912 $line["id"], $title);
1918 function print_feed_cat_select($link, $id, $default_id = "",
1919 $attributes = "", $include_all_cats = true) {
1921 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1923 if ($include_all_cats) {
1924 print "<option value=\"0\">".__('Uncategorized')."</option>";
1927 $result = db_query($link, "SELECT id,title FROM ttrss_feed_categories
1928 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1930 if (db_num_rows($result) > 0 && $include_all_cats) {
1931 print "<option disabled=\"1\">--------</option>";
1934 while ($line = db_fetch_assoc($result)) {
1935 if ($line["id"] == $default_id) {
1936 $is_selected = "selected=\"1\"";
1942 printf("<option $is_selected value='%d'>%s</option>",
1943 $line["id"], htmlspecialchars($line["title"]));
1946 # print "<option value=\"ADD_CAT\">" .__("Add category...") . "</option>";
1951 function checkbox_to_sql_bool($val) {
1952 return ($val == "on") ?
"true" : "false";
1955 function getFeedCatTitle($link, $id) {
1957 return __("Special");
1958 } else if ($id < -10) {
1959 return __("Labels");
1960 } else if ($id > 0) {
1961 $result = db_query($link, "SELECT ttrss_feed_categories.title
1962 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1963 cat_id = ttrss_feed_categories.id");
1964 if (db_num_rows($result) == 1) {
1965 return db_fetch_result($result, 0, "title");
1967 return __("Uncategorized");
1970 return "getFeedCatTitle($id) failed";
1975 function getFeedIcon($id) {
1978 return "images/archive.png";
1981 return "images/mark_set.png";
1984 return "images/pub_set.png";
1987 return "images/fresh.png";
1990 return "images/tag.png";
1994 return "images/label.png";
1996 if (file_exists(ICONS_DIR
. "/$id.ico"))
1997 return ICONS_URL
. "/$id.ico";
2003 function getFeedTitle($link, $id) {
2005 return __("Starred articles");
2006 } else if ($id == -2) {
2007 return __("Published articles");
2008 } else if ($id == -3) {
2009 return __("Fresh articles");
2010 } else if ($id == -4) {
2011 return __("All articles");
2012 } else if ($id === 0 ||
$id === "0") {
2013 return __("Archived articles");
2014 } else if ($id < -10) {
2015 $label_id = -$id - 11;
2016 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
2017 if (db_num_rows($result) == 1) {
2018 return db_fetch_result($result, 0, "caption");
2020 return "Unknown label ($label_id)";
2023 } else if (is_numeric($id) && $id > 0) {
2024 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
2025 if (db_num_rows($result) == 1) {
2026 return db_fetch_result($result, 0, "title");
2028 return "Unknown feed ($id)";
2035 function make_init_params($link) {
2038 $params["theme"] = get_user_theme($link);
2039 $params["theme_options"] = get_user_theme_options($link);
2041 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
2042 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
2043 $params["sign_excl"] = theme_image($link, "images/sign_excl.png");
2044 $params["sign_info"] = theme_image($link, "images/sign_info.png");
2046 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
2047 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
2048 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
2049 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
2051 $params[strtolower($param)] = (int) get_pref($link, $param);
2054 $params["icons_url"] = ICONS_URL
;
2055 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
2056 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
2057 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
2058 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
2059 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
2061 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2062 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2064 $max_feed_id = db_fetch_result($result, 0, "mid");
2065 $num_feeds = db_fetch_result($result, 0, "nf");
2067 $params["max_feed_id"] = (int) $max_feed_id;
2068 $params["num_feeds"] = (int) $num_feeds;
2070 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
2072 $params["csrf_token"] = $_SESSION["csrf_token"];
2077 function make_runtime_info($link) {
2080 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
2081 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
2083 $max_feed_id = db_fetch_result($result, 0, "mid");
2084 $num_feeds = db_fetch_result($result, 0, "nf");
2086 $data["max_feed_id"] = (int) $max_feed_id;
2087 $data["num_feeds"] = (int) $num_feeds;
2089 $data['last_article_id'] = getLastArticleId($link);
2090 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
2092 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
2094 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
2096 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
2098 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
2101 $stamp_delta = time() - $stamp;
2103 if ($stamp_delta > 1800) {
2107 $_SESSION["daemon_stamp_check"] = time();
2110 $data['daemon_stamp_ok'] = $stamp_check;
2112 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2114 $data['daemon_stamp'] = $stamp_fmt;
2119 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2120 $new_version_details = @check_for_update
($link);
2122 $data['new_version_available'] = (int) ($new_version_details != false);
2124 $_SESSION["last_version_check"] = time();
2130 function search_to_sql($link, $search, $match_on) {
2132 $search_query_part = "";
2134 $keywords = explode(" ", $search);
2135 $query_keywords = array();
2137 foreach ($keywords as $k) {
2138 if (strpos($k, "-") === 0) {
2145 $commandpair = explode(":", mb_strtolower($k), 2);
2147 if ($commandpair[0] == "note" && $commandpair[1]) {
2149 if ($commandpair[1] == "true")
2150 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2152 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2154 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2156 if ($commandpair[1] == "true")
2157 array_push($query_keywords, "($not (marked = true))");
2159 array_push($query_keywords, "($not (marked = false))");
2161 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2163 if ($commandpair[1] == "true")
2164 array_push($query_keywords, "($not (published = true))");
2166 array_push($query_keywords, "($not (published = false))");
2168 } else if (strpos($k, "@") === 0) {
2170 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2171 $orig_ts = strtotime(substr($k, 1));
2172 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2174 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2176 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2177 } else if ($match_on == "both") {
2178 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2179 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2180 } else if ($match_on == "title") {
2181 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2182 } else if ($match_on == "content") {
2183 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2187 $search_query_part = implode("AND", $query_keywords);
2189 return $search_query_part;
2193 function queryFeedHeadlines($link, $feed, $limit, $view_mode, $cat_view, $search, $search_mode, $match_on, $override_order = false, $offset = 0, $owner_uid = 0, $filter = false, $since_id = 0) {
2195 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2197 $ext_tables_part = "";
2201 if (SPHINX_ENABLED
) {
2202 $ids = join(",", @sphinx_search
($search, 0, 500));
2205 $search_query_part = "ref_id IN ($ids) AND ";
2207 $search_query_part = "ref_id = -1 AND ";
2210 $search_query_part = search_to_sql($link, $search, $match_on);
2211 $search_query_part .= " AND ";
2215 $search_query_part = "";
2219 $filter_query_part = filter_to_sql($filter);
2221 $filter_query_part = "";
2225 $since_id_part = "ttrss_entries.id > $since_id AND ";
2227 $since_id_part = "";
2230 $view_query_part = "";
2232 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2234 $view_query_part = " ";
2235 } else if ($feed != -1) {
2236 $unread = getFeedUnread($link, $feed, $cat_view);
2238 $view_query_part = " unread = true AND ";
2243 if ($view_mode == "marked") {
2244 $view_query_part = " marked = true AND ";
2247 if ($view_mode == "published") {
2248 $view_query_part = " published = true AND ";
2251 if ($view_mode == "unread") {
2252 $view_query_part = " unread = true AND ";
2255 if ($view_mode == "updated") {
2256 $view_query_part = " (last_read is null and unread = false) AND ";
2260 $limit_query_part = "LIMIT " . $limit;
2263 $vfeed_query_part = "";
2265 // override query strategy and enable feed display when searching globally
2266 if ($search && $search_mode == "all_feeds") {
2267 $query_strategy_part = "ttrss_entries.id > 0";
2268 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2270 } else if (preg_match("/^-?[0-9][0-9]*$/", $feed) == false) {
2271 $query_strategy_part = "ttrss_entries.id > 0";
2272 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2273 id = feed_id) as feed_title,";
2274 } else if ($feed > 0 && $search && $search_mode == "this_cat") {
2276 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2278 $tmp_result = false;
2281 $tmp_result = db_query($link, "SELECT id
2282 FROM ttrss_feeds WHERE cat_id = '$feed'");
2284 $tmp_result = db_query($link, "SELECT id
2285 FROM ttrss_feeds WHERE cat_id = (SELECT cat_id FROM ttrss_feeds
2286 WHERE id = '$feed') AND id != '$feed'");
2289 $cat_siblings = array();
2291 if (db_num_rows($tmp_result) > 0) {
2292 while ($p = db_fetch_assoc($tmp_result)) {
2293 array_push($cat_siblings, "feed_id = " . $p["id"]);
2296 $query_strategy_part = sprintf("(feed_id = %d OR %s)",
2297 $feed, implode(" OR ", $cat_siblings));
2300 $query_strategy_part = "ttrss_entries.id > 0";
2303 } else if ($feed > 0) {
2308 $query_strategy_part = "cat_id = '$feed'";
2310 $query_strategy_part = "cat_id IS NULL";
2313 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2316 $query_strategy_part = "feed_id = '$feed'";
2318 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2319 $query_strategy_part = "feed_id IS NULL";
2320 } else if ($feed == 0 && $cat_view) { // uncategorized
2321 $query_strategy_part = "cat_id IS NULL";
2322 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2323 } else if ($feed == -1) { // starred virtual feed
2324 $query_strategy_part = "marked = true";
2325 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2326 } else if ($feed == -2) { // published virtual feed OR labels category
2329 $query_strategy_part = "published = true";
2330 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2332 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2334 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2336 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2337 ttrss_user_labels2.article_id = ref_id";
2341 } else if ($feed == -3) { // fresh virtual feed
2342 $query_strategy_part = "unread = true AND score >= 0";
2344 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2346 if (DB_TYPE
== "pgsql") {
2347 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2349 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2352 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2353 } else if ($feed == -4) { // all articles virtual feed
2354 $query_strategy_part = "true";
2355 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2356 } else if ($feed <= -10) { // labels
2357 $label_id = -$feed - 11;
2359 $query_strategy_part = "label_id = '$label_id' AND
2360 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2361 ttrss_user_labels2.article_id = ref_id";
2363 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2364 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2367 $query_strategy_part = "id > 0"; // dumb
2370 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2371 $date_sort_field = "updated";
2373 $date_sort_field = "date_entered";
2376 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2377 $order_by = "$date_sort_field";
2379 $order_by = "$date_sort_field DESC";
2382 if ($view_mode != "noscores") {
2383 $order_by = "score DESC, $order_by";
2386 if ($override_order) {
2387 $order_by = $override_order;
2393 $feed_title = "Search results";
2396 $feed_title = getCategoryTitle($link, $feed);
2398 if (is_numeric($feed) && $feed > 0) {
2399 $result = db_query($link, "SELECT title,site_url,last_error
2400 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2402 $feed_title = db_fetch_result($result, 0, "title");
2403 $feed_site_url = db_fetch_result($result, 0, "site_url");
2404 $last_error = db_fetch_result($result, 0, "last_error");
2406 $feed_title = getFeedTitle($link, $feed);
2411 $content_query_part = "content as content_preview,";
2413 if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
2416 $feed_kind = "Feeds";
2418 $feed_kind = "Labels";
2421 if ($limit_query_part) {
2422 $offset_query_part = "OFFSET $offset";
2425 if ($vfeed_query_part && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2426 if (!$override_order) {
2427 $order_by = "ttrss_feeds.title, $order_by";
2432 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2433 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2436 $from_qpart = "ttrss_entries,ttrss_user_entries$ext_tables_part
2437 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2440 $query = "SELECT DISTINCT
2443 ttrss_entries.id,ttrss_entries.title,
2447 always_display_enclosures,
2453 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2454 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2457 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2463 ttrss_user_entries.ref_id = ttrss_entries.id AND
2464 ttrss_user_entries.owner_uid = '$owner_uid' AND
2469 $query_strategy_part ORDER BY $order_by
2470 $limit_query_part $offset_query_part";
2472 if ($_REQUEST["debug"]) print $query;
2474 $result = db_query($link, $query);
2479 $select_qpart = "SELECT DISTINCT " .
2483 "ttrss_entries.id as id," .
2496 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2499 $content_query_part .
2500 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2503 $feed_kind = "Tags";
2504 $all_tags = explode(",", $feed);
2505 if ($search_mode == 'any') {
2506 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2507 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2508 $where_qpart = " WHERE " .
2509 "ref_id = ttrss_entries.id AND " .
2510 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2511 "post_int_id = int_id AND $tag_sql AND " .
2513 $search_query_part .
2514 $query_strategy_part . " ORDER BY $order_by " .
2519 $sub_selects = array();
2520 $sub_ands = array();
2521 foreach ($all_tags as $term) {
2522 array_push($sub_selects, "(SELECT post_int_id from ttrss_tags WHERE tag_name = " . db_quote($term) . " AND owner_uid = $owner_uid) as A$i");
2529 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2534 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2535 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2536 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2537 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2539 // error_log("TAG SQL: " . $tag_sql);
2540 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2542 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2543 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2546 return array($result, $feed_title, $feed_site_url, $last_error);
2550 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2553 if (!$owner) $owner = $_SESSION["uid"];
2555 $res = trim($str); if (!$res) return '';
2557 // create global Purifier object if needed
2559 require_once 'lib/htmlpurifier/library/HTMLPurifier.auto.php';
2561 $config = HTMLPurifier_Config
::createDefault();
2563 $allowed = "p,a[href],i,em,b,strong,code,pre,blockquote,br,img[src|alt|title],ul,ol,li,h1,h2,h3,h4,s,object[classid|type|id|name|width|height|codebase],param[name|value],table,tr,td";
2565 $config->set('HTML.SafeObject', true);
2566 @$config->set('HTML', 'Allowed', $allowed);
2567 $config->set('Output.FlashCompat', true);
2568 $config->set('Attr.EnableID', true);
2569 if (!defined('MOBILE_VERSION')) {
2570 @$config->set('Cache', 'SerializerPath', CACHE_DIR
. "/htmlpurifier");
2572 @$config->set('Cache', 'SerializerPath', "../" . CACHE_DIR
. "/htmlpurifier");
2575 $purifier = new HTMLPurifier($config);
2578 $res = $purifier->purify($res);
2580 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2581 $res = preg_replace('/<img[^>]+>/is', '', $res);
2584 if (strpos($res, "href=") === false)
2585 $res = rewrite_urls($res);
2587 $charset_hack = '<head>
2588 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2591 $res = trim($res); if (!$res) return '';
2593 libxml_use_internal_errors(true);
2595 $doc = new DOMDocument();
2596 $doc->loadHTML($charset_hack . $res);
2597 $xpath = new DOMXPath($doc);
2599 $entries = $xpath->query('(//a[@href]|//img[@src])');
2602 foreach ($entries as $entry) {
2606 if ($entry->hasAttribute('href'))
2607 $entry->setAttribute('href',
2608 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2610 if ($entry->hasAttribute('src'))
2611 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2612 $entry->setAttribute('src',
2613 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2616 if (strtolower($entry->nodeName
) == "a") {
2617 $entry->setAttribute("target", "_blank");
2620 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2621 $br = $doc->createElement("br");
2623 if ($entry->parentNode
->nextSibling
) {
2624 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2631 $node = $doc->getElementsByTagName('body')->item(0);
2633 return $doc->saveXML($node);
2637 * Send by mail a digest of last articles.
2639 * @param mixed $link The database connection.
2640 * @param integer $limit The maximum number of articles by digest.
2641 * @return boolean Return false if digests are not enabled.
2643 function send_headlines_digests($link, $limit = 100, $debug = true) {
2645 require_once 'lib/phpmailer/class.phpmailer.php';
2647 $user_limit = 15; // amount of users to process (e.g. emails to send out)
2650 if ($debug) _debug("Sending digests, batch of max $user_limit users, days = $days, headline limit = $limit");
2652 if (DB_TYPE
== "pgsql") {
2653 $interval_query = "last_digest_sent < NOW() - INTERVAL '$days days'";
2654 } else if (DB_TYPE
== "mysql") {
2655 $interval_query = "last_digest_sent < DATE_SUB(NOW(), INTERVAL $days DAY)";
2658 $result = db_query($link, "SELECT id,email FROM ttrss_users
2659 WHERE email != '' AND (last_digest_sent IS NULL OR $interval_query)");
2661 while ($line = db_fetch_assoc($result)) {
2663 if (get_pref($link, 'DIGEST_ENABLE', $line['id'], false)) {
2664 print "Sending digest for UID:" . $line['id'] . " - " . $line["email"] . " ... ";
2666 $do_catchup = get_pref($link, 'DIGEST_CATCHUP', $line['id'], false);
2668 $tuple = prepare_headlines_digest($link, $line["id"], $days, $limit);
2669 $digest = $tuple[0];
2670 $headlines_count = $tuple[1];
2671 $affected_ids = $tuple[2];
2672 $digest_text = $tuple[3];
2674 if ($headlines_count > 0) {
2676 $mail = new PHPMailer();
2678 $mail->PluginDir
= "lib/phpmailer/";
2679 $mail->SetLanguage("en", "lib/phpmailer/language/");
2681 $mail->CharSet
= "UTF-8";
2683 $mail->From
= SMTP_FROM_ADDRESS
;
2684 $mail->FromName
= SMTP_FROM_NAME
;
2685 $mail->AddAddress($line["email"], $line["login"]);
2688 $mail->Host
= SMTP_HOST
;
2689 $mail->Mailer
= "smtp";
2690 $mail->SMTPAuth
= SMTP_LOGIN
!= '';
2691 $mail->Username
= SMTP_LOGIN
;
2692 $mail->Password
= SMTP_PASSWORD
;
2695 $mail->IsHTML(true);
2696 $mail->Subject
= DIGEST_SUBJECT
;
2697 $mail->Body
= $digest;
2698 $mail->AltBody
= $digest_text;
2700 $rc = $mail->Send();
2702 if (!$rc) print "ERROR: " . $mail->ErrorInfo
;
2706 if ($rc && $do_catchup) {
2707 print "Marking affected articles as read...\n";
2708 catchupArticlesById($link, $affected_ids, 0, $line["id"]);
2711 print "No headlines\n";
2714 db_query($link, "UPDATE ttrss_users SET last_digest_sent = NOW()
2715 WHERE id = " . $line["id"]);
2719 if ($debug) _debug("All done.");
2723 function prepare_headlines_digest($link, $user_id, $days = 1, $limit = 100) {
2725 require_once "lib/MiniTemplator.class.php";
2727 $tpl = new MiniTemplator
;
2728 $tpl_t = new MiniTemplator
;
2730 $tpl->readTemplateFromFile("templates/digest_template_html.txt");
2731 $tpl_t->readTemplateFromFile("templates/digest_template.txt");
2733 $tpl->setVariable('CUR_DATE', date('Y/m/d'));
2734 $tpl->setVariable('CUR_TIME', date('G:i'));
2736 $tpl_t->setVariable('CUR_DATE', date('Y/m/d'));
2737 $tpl_t->setVariable('CUR_TIME', date('G:i'));
2739 $affected_ids = array();
2741 if (DB_TYPE
== "pgsql") {
2742 $interval_query = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'";
2743 } else if (DB_TYPE
== "mysql") {
2744 $interval_query = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)";
2747 $result = db_query($link, "SELECT ttrss_entries.title,
2748 ttrss_feeds.title AS feed_title,
2750 ttrss_user_entries.ref_id,
2752 SUBSTRING(content, 1, 120) AS excerpt,
2753 ".SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
2755 ttrss_user_entries,ttrss_entries,ttrss_feeds
2757 ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id
2758 AND include_in_digest = true
2760 AND ttrss_user_entries.owner_uid = $user_id
2762 ORDER BY ttrss_feeds.title, date_updated DESC
2765 $cur_feed_title = "";
2767 $headlines_count = db_num_rows($result);
2769 $headlines = array();
2771 while ($line = db_fetch_assoc($result)) {
2772 array_push($headlines, $line);
2775 for ($i = 0; $i < sizeof($headlines); $i++
) {
2777 $line = $headlines[$i];
2779 array_push($affected_ids, $line["ref_id"]);
2781 $updated = make_local_datetime($link, $line['last_updated'], false,
2784 $tpl->setVariable('FEED_TITLE', $line["feed_title"]);
2785 $tpl->setVariable('ARTICLE_TITLE', $line["title"]);
2786 $tpl->setVariable('ARTICLE_LINK', $line["link"]);
2787 $tpl->setVariable('ARTICLE_UPDATED', $updated);
2788 $tpl->setVariable('ARTICLE_EXCERPT',
2789 truncate_string(strip_tags($line["excerpt"]), 100));
2791 $tpl->addBlock('article');
2793 $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]);
2794 $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]);
2795 $tpl_t->setVariable('ARTICLE_LINK', $line["link"]);
2796 $tpl_t->setVariable('ARTICLE_UPDATED', $updated);
2797 // $tpl_t->setVariable('ARTICLE_EXCERPT',
2798 // truncate_string(strip_tags($line["excerpt"]), 100));
2800 $tpl_t->addBlock('article');
2802 if ($headlines[$i]['feed_title'] != $headlines[$i+
1]['feed_title']) {
2803 $tpl->addBlock('feed');
2804 $tpl_t->addBlock('feed');
2809 $tpl->addBlock('digest');
2810 $tpl->generateOutputToString($tmp);
2812 $tpl_t->addBlock('digest');
2813 $tpl_t->generateOutputToString($tmp_t);
2815 return array($tmp, $headlines_count, $affected_ids, $tmp_t);
2818 function check_for_update($link) {
2819 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2820 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2822 $version_data = @fetch_file_contents
($version_url);
2824 if ($version_data) {
2825 $version_data = json_decode($version_data, true);
2826 if ($version_data && $version_data['version']) {
2828 if (version_compare(VERSION
, $version_data['version']) == -1) {
2829 return $version_data;
2837 function markArticlesById($link, $ids, $cmode) {
2841 foreach ($ids as $id) {
2842 array_push($tmp_ids, "ref_id = '$id'");
2845 $ids_qpart = join(" OR ", $tmp_ids);
2848 db_query($link, "UPDATE ttrss_user_entries SET
2849 marked = false,last_read = NOW()
2850 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2851 } else if ($cmode == 1) {
2852 db_query($link, "UPDATE ttrss_user_entries SET
2854 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2856 db_query($link, "UPDATE ttrss_user_entries SET
2857 marked = NOT marked,last_read = NOW()
2858 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2862 function publishArticlesById($link, $ids, $cmode) {
2866 foreach ($ids as $id) {
2867 array_push($tmp_ids, "ref_id = '$id'");
2870 $ids_qpart = join(" OR ", $tmp_ids);
2873 db_query($link, "UPDATE ttrss_user_entries SET
2874 published = false,last_read = NOW()
2875 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2876 } else if ($cmode == 1) {
2877 db_query($link, "UPDATE ttrss_user_entries SET
2879 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2881 db_query($link, "UPDATE ttrss_user_entries SET
2882 published = NOT published,last_read = NOW()
2883 WHERE ($ids_qpart) AND owner_uid = " . $_SESSION["uid"]);
2886 if (PUBSUBHUBBUB_HUB
) {
2887 $rss_link = get_self_url_prefix() .
2888 "/public.php?op=rss&id=-2&key=" .
2889 get_feed_access_key($link, -2, false);
2891 $p = new Publisher(PUBSUBHUBBUB_HUB
);
2893 $pubsub_result = $p->publish_update($rss_link);
2897 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2899 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2900 if (count($ids) == 0) return;
2904 foreach ($ids as $id) {
2905 array_push($tmp_ids, "ref_id = '$id'");
2908 $ids_qpart = join(" OR ", $tmp_ids);
2911 db_query($link, "UPDATE ttrss_user_entries SET
2912 unread = false,last_read = NOW()
2913 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2914 } else if ($cmode == 1) {
2915 db_query($link, "UPDATE ttrss_user_entries SET
2917 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2919 db_query($link, "UPDATE ttrss_user_entries SET
2920 unread = NOT unread,last_read = NOW()
2921 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2926 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2927 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2929 while ($line = db_fetch_assoc($result)) {
2930 ccache_update($link, $line["feed_id"], $owner_uid);
2934 function catchupArticleById($link, $id, $cmode) {
2937 db_query($link, "UPDATE ttrss_user_entries SET
2938 unread = false,last_read = NOW()
2939 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2940 } else if ($cmode == 1) {
2941 db_query($link, "UPDATE ttrss_user_entries SET
2943 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2945 db_query($link, "UPDATE ttrss_user_entries SET
2946 unread = NOT unread,last_read = NOW()
2947 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2950 $feed_id = getArticleFeed($link, $id);
2951 ccache_update($link, $feed_id, $_SESSION["uid"]);
2954 function make_guid_from_title($title) {
2955 return preg_replace("/[ \"\',.:;]/", "-",
2956 mb_strtolower(strip_tags($title), 'utf-8'));
2959 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2963 $a_id = db_escape_string($id);
2965 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2967 $query = "SELECT DISTINCT tag_name,
2968 owner_uid as owner FROM
2969 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2970 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2972 $obj_id = md5("TAGS:$owner_uid:$id");
2975 if ($memcache && $obj = $memcache->get($obj_id)) {
2978 /* check cache first */
2980 if ($tag_cache === false) {
2981 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2982 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
2984 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2988 $tags = explode(",", $tag_cache);
2991 /* do it the hard way */
2993 $tmp_result = db_query($link, $query);
2995 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2996 array_push($tags, $tmp_line["tag_name"]);
2999 /* update the cache */
3001 $tags_str = db_escape_string(join(",", $tags));
3003 db_query($link, "UPDATE ttrss_user_entries
3004 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
3005 AND owner_uid = " . $_SESSION["uid"]);
3008 if ($memcache) $memcache->add($obj_id, $tags, 0, 3600);
3014 function trim_array($array) {
3016 array_walk($tmp, 'trim');
3020 function tag_is_valid($tag) {
3021 if ($tag == '') return false;
3022 if (preg_match("/^[0-9]*$/", $tag)) return false;
3023 if (mb_strlen($tag) > 250) return false;
3025 if (function_exists('iconv')) {
3026 $tag = iconv("utf-8", "utf-8", $tag);
3029 if (!$tag) return false;
3034 function render_login_form($link, $mobile = 0) {
3037 require_once "login_form.php";
3040 require_once "mobile/login_form.php";
3043 require_once "mobile/classic/login_form.php";
3047 // from http://developer.apple.com/internet/safari/faq.html
3048 function no_cache_incantation() {
3049 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
3050 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
3051 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
3052 header("Cache-Control: post-check=0, pre-check=0", false);
3053 header("Pragma: no-cache"); // HTTP/1.0
3056 function format_warning($msg, $id = "") {
3058 return "<div class=\"warning\" id=\"$id\">
3059 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3062 function format_notice($msg, $id = "") {
3064 return "<div class=\"notice\" id=\"$id\">
3065 <img src=\"".theme_image($link, "images/sign_info.png")."\">$msg</div>";
3068 function format_error($msg, $id = "") {
3070 return "<div class=\"error\" id=\"$id\">
3071 <img src=\"".theme_image($link, "images/sign_excl.png")."\">$msg</div>";
3074 function print_notice($msg) {
3075 return print format_notice($msg);
3078 function print_warning($msg) {
3079 return print format_warning($msg);
3082 function print_error($msg) {
3083 return print format_error($msg);
3087 function T_sprintf() {
3088 $args = func_get_args();
3089 return vsprintf(__(array_shift($args)), $args);
3092 function format_inline_player($link, $url, $ctype) {
3096 if (strpos($ctype, "audio/") === 0) {
3098 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
3099 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
3100 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
3102 $id = 'AUDIO-' . uniqid();
3104 $entry .= "<audio id=\"$id\"\">
3105 <source src=\"$url\"></source>
3108 $entry .= "<span onclick=\"player(this)\"
3109 title=\"".__("Click to play")."\" status=\"0\"
3110 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
3114 $entry .= "<object type=\"application/x-shockwave-flash\"
3115 data=\"lib/button/musicplayer.swf?song_url=$url\"
3116 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
3117 <param name=\"movie\"
3118 value=\"lib/button/musicplayer.swf?song_url=$url\" />
3123 $filename = substr($url, strrpos($url, "/")+
1);
3125 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3126 $filename . " (" . $ctype . ")" . "</a>";
3131 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false) {
3137 /* we can figure out feed_id from article id anyway, why do we
3138 * pass feed_id here? let's ignore the argument :( */
3140 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3141 WHERE ref_id = '$id'");
3143 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
3145 $rv['feed_id'] = $feed_id;
3147 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
3149 $result = db_query($link, "SELECT rtl_content, always_display_enclosures FROM ttrss_feeds
3150 WHERE id = '$feed_id' AND owner_uid = " . $_SESSION["uid"]);
3152 if (db_num_rows($result) == 1) {
3153 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
3154 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
3156 $rtl_content = false;
3157 $always_display_enclosures = false;
3161 $rtl_tag = "dir=\"RTL\"";
3168 if ($mark_as_read) {
3169 $result = db_query($link, "UPDATE ttrss_user_entries
3170 SET unread = false,last_read = NOW()
3171 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3173 ccache_update($link, $feed_id, $_SESSION["uid"]);
3176 $result = db_query($link, "SELECT title,link,content,feed_id,comments,int_id,
3177 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
3178 (SELECT icon_url FROM ttrss_feeds WHERE id = feed_id) as icon_url,
3179 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
3185 FROM ttrss_entries,ttrss_user_entries
3186 WHERE id = '$id' AND ref_id = id AND owner_uid = " . $_SESSION["uid"]);
3190 $line = db_fetch_assoc($result);
3192 if ($line["icon_url"]) {
3193 $feed_icon = "<img src=\"" . $line["icon_url"] . "\">";
3195 $feed_icon = " ";
3198 $feed_site_url = $line['site_url'];
3200 $num_comments = $line["num_comments"];
3201 $entry_comments = "";
3203 if ($num_comments > 0) {
3204 if ($line["comments"]) {
3205 $comments_url = $line["comments"];
3207 $comments_url = $line["link"];
3209 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
3211 if ($line["comments"] && $line["link"] != $line["comments"]) {
3212 $entry_comments = "<a target='_blank' href=\"".$line["comments"]."\">comments</a>";
3217 header("Content-Type: text/html");
3218 $rv['content'] .= "<html><head>
3219 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
3220 <title>Tiny Tiny RSS - ".$line["title"]."</title>
3221 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
3225 $rv['content'] .= "<div id=\"PTITLE-$id\" style=\"display : none\">" .
3226 truncate_string(strip_tags($line['title']), 15) . "</div>";
3228 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
3230 $rv['content'] .= "<div onclick=\"return postClicked(event, $id)\"
3231 class=\"postHeader\" id=\"POSTHDR-$id\">";
3233 $entry_author = $line["author"];
3235 if ($entry_author) {
3236 $entry_author = __(" - ") . $entry_author;
3239 $parsed_updated = make_local_datetime($link, $line["updated"], true,
3242 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
3244 if ($line["link"]) {
3245 $rv['content'] .= "<div clear='both'><a target='_blank'
3246 title=\"".htmlspecialchars($line['title'])."\"
3248 $line["link"] . "\">" .
3249 truncate_string($line["title"], 100) .
3250 "<span class='author'>$entry_author</span></a></div>";
3252 $rv['content'] .= "<div clear='both'>" . $line["title"] . "$entry_author</div>";
3255 $tag_cache = $line["tag_cache"];
3258 $tags = get_article_tags($link, $id);
3260 $tags = explode(",", $tag_cache);
3262 $tags_str = format_tags_string($tags, $id);
3263 $tags_str_full = join(", ", $tags);
3265 if (!$tags_str_full) $tags_str_full = __("no tags");
3267 if (!$entry_comments) $entry_comments = " "; # placeholder
3269 $rv['content'] .= "<div style='float : right'>
3270 <img src='".theme_image($link, 'images/tag.png')."'
3271 class='tagsPic' alt='Tags' title='Tags'> ";
3274 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
3275 <a title=\"".__('Edit tags for this article')."\"
3276 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
3278 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
3279 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
3280 position=\"below\">$tags_str_full</div>";
3282 $rv['content'] .= "<img src=\"".theme_image($link, 'images/art-zoom.png')."\"
3283 class='tagsPic' style=\"cursor : pointer\"
3284 onclick=\"postOpenInNewTab(event, $id)\"
3285 alt='Zoom' title='".__('Open article in new tab')."'>";
3287 $button_plugins = explode(",", ARTICLE_BUTTON_PLUGINS
);
3289 foreach ($button_plugins as $p) {
3290 $pclass = trim("${p}_button");
3292 if (class_exists($pclass)) {
3293 $plugin = new $pclass($link);
3294 $rv['content'] .= $plugin->render($id, $line);
3298 $rv['content'] .= "<img src=\"".theme_image($link, 'images/digest_checkbox.png')."\"
3299 class='tagsPic' style=\"cursor : pointer\"
3300 onclick=\"closeArticlePanel($id)\"
3301 title='".__('Close article')."'>";
3304 $tags_str = strip_tags($tags_str);
3305 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
3307 $rv['content'] .= "</div>";
3308 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
3310 if ($line["orig_feed_id"]) {
3312 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
3313 WHERE id = ".$line["orig_feed_id"]);
3315 if (db_num_rows($tmp_result) != 0) {
3317 $rv['content'] .= "<div clear='both'>";
3318 $rv['content'] .= __("Originally from:");
3320 $rv['content'] .= " ";
3322 $tmp_line = db_fetch_assoc($tmp_result);
3324 $rv['content'] .= "<a target='_blank'
3325 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
3326 $tmp_line['title'] . "</a>";
3328 $rv['content'] .= " ";
3330 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
3331 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.gif'></a>";
3333 $rv['content'] .= "</div>";
3337 $rv['content'] .= "</div>";
3339 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3340 if ($line['note']) {
3341 $rv['content'] .= format_article_note($id, $line['note']);
3343 $rv['content'] .= "</div>";
3345 $rv['content'] .= "<div class=\"postIcon\">" .
3346 "<a target=\"_blank\" title=\"".__("Visit the website")."\"$
3347 href=\"".htmlspecialchars($feed_site_url)."\">".
3348 $feed_icon . "</a></div>";
3350 $rv['content'] .= "<div class=\"postContent\">";
3352 $article_content = sanitize($link, $line["content"], false, false,
3355 $rv['content'] .= $article_content;
3357 $rv['content'] .= format_article_enclosures($link, $id,
3358 $always_display_enclosures, $article_content);
3360 $rv['content'] .= "</div>";
3362 $rv['content'] .= "</div>";
3368 <div style=\"text-align : center\">
3369 <button onclick=\"return window.close()\">".
3370 __("Close this window")."</button></div>";
3371 $rv['content'] .= "</body></html>";
3378 function print_checkpoint($n, $s) {
3379 $ts = getmicrotime();
3380 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3384 function sanitize_tag($tag) {
3387 $tag = mb_strtolower($tag, 'utf-8');
3389 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3391 // $tag = str_replace('"', "", $tag);
3392 // $tag = str_replace("+", " ", $tag);
3393 $tag = str_replace("technorati tag: ", "", $tag);
3398 function get_self_url_prefix() {
3399 return SELF_URL_PATH
;
3402 function opml_publish_url($link){
3404 $url_path = get_self_url_prefix();
3405 $url_path .= "/opml.php?op=publish&key=" .
3406 get_feed_access_key($link, 'OPML:Publish', false, $_SESSION["uid"]);
3412 * Purge a feed contents, marked articles excepted.
3414 * @param mixed $link The database connection.
3415 * @param integer $id The id of the feed to purge.
3418 function clear_feed_articles($link, $id) {
3421 $result = db_query($link, "DELETE FROM ttrss_user_entries
3422 WHERE feed_id = '$id' AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3424 $result = db_query($link, "DELETE FROM ttrss_user_entries
3425 WHERE feed_id IS NULL AND marked = false AND owner_uid = " . $_SESSION["uid"]);
3428 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
3429 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
3431 ccache_update($link, $id, $_SESSION['uid']);
3432 } // function clear_feed_articles
3435 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3437 * @return string The Mozilla Firefox feed adding URL.
3439 function add_feed_url() {
3440 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3442 $url_path = get_self_url_prefix() .
3443 "/backend.php?op=pref-feeds&quiet=1&method=add&feed_url=%s";
3445 } // function add_feed_url
3448 * Encrypt a password in SHA1.
3450 * @param string $pass The password to encrypt.
3451 * @param string $login A optionnal login.
3452 * @return string The encrypted password.
3454 function encrypt_password($pass, $login = '') {
3456 return "SHA1X:" . sha1("$login:$pass");
3458 return "SHA1:" . sha1($pass);
3460 } // function encrypt_password
3463 function sanitize_article_content($text) {
3464 # we don't support CDATA sections in articles, they break our own escaping
3465 $text = preg_replace("/\[\[CDATA/", "", $text);
3466 $text = preg_replace("/\]\]\>/", "", $text);
3470 function load_filters($link, $feed, $owner_uid, $action_id = false) {
3475 $obj_id = md5("FILTER:$feed:$owner_uid:$action_id");
3477 if ($memcache && $obj = $memcache->get($obj_id)) {
3483 if ($action_id) $ftype_query_part = "action_id = '$action_id' AND";
3485 $result = db_query($link, "SELECT reg_exp,
3486 ttrss_filter_types.name AS name,
3487 ttrss_filter_actions.name AS action,
3491 FROM ttrss_filters,ttrss_filter_types,ttrss_filter_actions WHERE
3494 owner_uid = $owner_uid AND
3495 ttrss_filter_types.id = filter_type AND
3496 ttrss_filter_actions.id = action_id AND
3497 (feed_id IS NULL OR feed_id = '$feed') ORDER BY reg_exp");
3499 while ($line = db_fetch_assoc($result)) {
3500 if (!$filters[$line["name"]]) $filters[$line["name"]] = array();
3501 $filter["reg_exp"] = $line["reg_exp"];
3502 $filter["action"] = $line["action"];
3503 $filter["action_param"] = $line["action_param"];
3504 $filter["filter_param"] = $line["filter_param"];
3505 $filter["inverse"] = sql_bool_to_bool($line["inverse"]);
3507 array_push($filters[$line["name"]], $filter);
3510 if ($memcache) $memcache->add($obj_id, $filters, 0, 3600*8);
3516 function get_score_pic($score) {
3518 return "score_high.png";
3519 } else if ($score > 0) {
3520 return "score_half_high.png";
3521 } else if ($score < -100) {
3522 return "score_low.png";
3523 } else if ($score < 0) {
3524 return "score_half_low.png";
3526 return "score_neutral.png";
3530 function feed_has_icon($id) {
3531 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3534 function init_connection($link) {
3537 if (DB_TYPE
== "pgsql") {
3538 pg_query($link, "set client_encoding = 'UTF-8'");
3539 pg_set_client_encoding("UNICODE");
3540 pg_query($link, "set datestyle = 'ISO, european'");
3541 pg_query($link, "set TIME ZONE 0");
3543 db_query($link, "SET time_zone = '+0:0'");
3545 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3546 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3551 print "Unable to connect to database:" . db_last_error();
3556 /* function ccache_zero($link, $feed_id, $owner_uid) {
3557 db_query($link, "UPDATE ttrss_counters_cache SET
3558 value = 0, updated = NOW() WHERE
3559 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3562 function ccache_zero_all($link, $owner_uid) {
3563 db_query($link, "UPDATE ttrss_counters_cache SET
3564 value = 0 WHERE owner_uid = '$owner_uid'");
3566 db_query($link, "UPDATE ttrss_cat_counters_cache SET
3567 value = 0 WHERE owner_uid = '$owner_uid'");
3570 function ccache_remove($link, $feed_id, $owner_uid, $is_cat = false) {
3573 $table = "ttrss_counters_cache";
3575 $table = "ttrss_cat_counters_cache";
3578 db_query($link, "DELETE FROM $table WHERE
3579 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3583 function ccache_update_all($link, $owner_uid) {
3585 if (get_pref($link, 'ENABLE_FEED_CATS', $owner_uid)) {
3587 $result = db_query($link, "SELECT feed_id FROM ttrss_cat_counters_cache
3588 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3590 while ($line = db_fetch_assoc($result)) {
3591 ccache_update($link, $line["feed_id"], $owner_uid, true);
3594 /* We have to manually include category 0 */
3596 ccache_update($link, 0, $owner_uid, true);
3599 $result = db_query($link, "SELECT feed_id FROM ttrss_counters_cache
3600 WHERE feed_id > 0 AND owner_uid = '$owner_uid'");
3602 while ($line = db_fetch_assoc($result)) {
3603 print ccache_update($link, $line["feed_id"], $owner_uid);
3610 function ccache_find($link, $feed_id, $owner_uid, $is_cat = false,
3611 $no_update = false) {
3613 if (!is_numeric($feed_id)) return;
3616 $table = "ttrss_counters_cache";
3618 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3619 WHERE id = '$feed_id'");
3620 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3623 $table = "ttrss_cat_counters_cache";
3626 if (DB_TYPE
== "pgsql") {
3627 $date_qpart = "updated > NOW() - INTERVAL '15 minutes'";
3628 } else if (DB_TYPE
== "mysql") {
3629 $date_qpart = "updated > DATE_SUB(NOW(), INTERVAL 15 MINUTE)";
3632 $result = db_query($link, "SELECT value FROM $table
3633 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id'
3636 if (db_num_rows($result) == 1) {
3637 return db_fetch_result($result, 0, "value");
3642 return ccache_update($link, $feed_id, $owner_uid, $is_cat);
3648 function ccache_update($link, $feed_id, $owner_uid, $is_cat = false,
3649 $update_pcat = true) {
3651 if (!is_numeric($feed_id)) return;
3653 if (!$is_cat && $feed_id > 0) {
3654 $tmp_result = db_query($link, "SELECT owner_uid FROM ttrss_feeds
3655 WHERE id = '$feed_id'");
3656 $owner_uid = db_fetch_result($tmp_result, 0, "owner_uid");
3659 $prev_unread = ccache_find($link, $feed_id, $owner_uid, $is_cat, true);
3661 /* When updating a label, all we need to do is recalculate feed counters
3662 * because labels are not cached */
3665 ccache_update_all($link, $owner_uid);
3670 $table = "ttrss_counters_cache";
3672 $table = "ttrss_cat_counters_cache";
3675 if ($is_cat && $feed_id >= 0) {
3676 if ($feed_id != 0) {
3677 $cat_qpart = "cat_id = '$feed_id'";
3679 $cat_qpart = "cat_id IS NULL";
3682 /* Recalculate counters for child feeds */
3684 $result = db_query($link, "SELECT id FROM ttrss_feeds
3685 WHERE owner_uid = '$owner_uid' AND $cat_qpart");
3687 while ($line = db_fetch_assoc($result)) {
3688 ccache_update($link, $line["id"], $owner_uid, false, false);
3691 $result = db_query($link, "SELECT SUM(value) AS sv
3692 FROM ttrss_counters_cache, ttrss_feeds
3693 WHERE id = feed_id AND $cat_qpart AND
3694 ttrss_feeds.owner_uid = '$owner_uid'");
3696 $unread = (int) db_fetch_result($result, 0, "sv");
3699 $unread = (int) getFeedArticles($link, $feed_id, $is_cat, true, $owner_uid);
3702 db_query($link, "BEGIN");
3704 $result = db_query($link, "SELECT feed_id FROM $table
3705 WHERE owner_uid = '$owner_uid' AND feed_id = '$feed_id' LIMIT 1");
3707 if (db_num_rows($result) == 1) {
3708 db_query($link, "UPDATE $table SET
3709 value = '$unread', updated = NOW() WHERE
3710 feed_id = '$feed_id' AND owner_uid = '$owner_uid'");
3713 db_query($link, "INSERT INTO $table
3714 (feed_id, value, owner_uid, updated)
3716 ($feed_id, $unread, $owner_uid, NOW())");
3719 db_query($link, "COMMIT");
3721 if ($feed_id > 0 && $prev_unread != $unread) {
3725 /* Update parent category */
3729 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3730 WHERE owner_uid = '$owner_uid' AND id = '$feed_id'");
3732 $cat_id = (int) db_fetch_result($result, 0, "cat_id");
3734 ccache_update($link, $cat_id, $owner_uid, true);
3738 } else if ($feed_id < 0) {
3739 ccache_update_all($link, $owner_uid);
3745 /* function ccache_cleanup($link, $owner_uid) {
3747 if (DB_TYPE == "pgsql") {
3748 db_query($link, "DELETE FROM ttrss_counters_cache AS c1 WHERE
3749 (SELECT count(*) FROM ttrss_counters_cache AS c2
3750 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3751 AND owner_uid = '$owner_uid'");
3753 db_query($link, "DELETE FROM ttrss_cat_counters_cache AS c1 WHERE
3754 (SELECT count(*) FROM ttrss_cat_counters_cache AS c2
3755 WHERE c1.feed_id = c2.feed_id AND c2.owner_uid = c1.owner_uid) > 1
3756 AND owner_uid = '$owner_uid'");
3758 db_query($link, "DELETE c1 FROM
3759 ttrss_counters_cache AS c1,
3760 ttrss_counters_cache AS c2
3762 c1.owner_uid = '$owner_uid' AND
3763 c1.owner_uid = c2.owner_uid AND
3764 c1.feed_id = c2.feed_id");
3766 db_query($link, "DELETE c1 FROM
3767 ttrss_cat_counters_cache AS c1,
3768 ttrss_cat_counters_cache AS c2
3770 c1.owner_uid = '$owner_uid' AND
3771 c1.owner_uid = c2.owner_uid AND
3772 c1.feed_id = c2.feed_id");
3777 function label_find_id($link, $label, $owner_uid) {
3778 $result = db_query($link,
3779 "SELECT id FROM ttrss_labels2 WHERE caption = '$label'
3780 AND owner_uid = '$owner_uid' LIMIT 1");
3782 if (db_num_rows($result) == 1) {
3783 return db_fetch_result($result, 0, "id");
3789 function get_article_labels($link, $id) {
3792 $obj_id = md5("LABELS:$id:" . $_SESSION["uid"]);
3796 if ($memcache && $obj = $memcache->get($obj_id)) {
3800 $result = db_query($link, "SELECT label_cache FROM
3801 ttrss_user_entries WHERE ref_id = '$id' AND owner_uid = " .
3804 $label_cache = db_fetch_result($result, 0, "label_cache");
3808 $label_cache = json_decode($label_cache, true);
3810 if ($label_cache["no-labels"] == 1)
3813 return $label_cache;
3816 $result = db_query($link,
3817 "SELECT DISTINCT label_id,caption,fg_color,bg_color
3818 FROM ttrss_labels2, ttrss_user_labels2
3820 AND article_id = '$id'
3821 AND owner_uid = ".$_SESSION["uid"] . "
3824 while ($line = db_fetch_assoc($result)) {
3825 $rk = array($line["label_id"], $line["caption"], $line["fg_color"],
3827 array_push($rv, $rk);
3829 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
3832 label_update_cache($link, $id, $rv);
3834 label_update_cache($link, $id, array("no-labels" => 1));
3841 function label_find_caption($link, $label, $owner_uid) {
3842 $result = db_query($link,
3843 "SELECT caption FROM ttrss_labels2 WHERE id = '$label'
3844 AND owner_uid = '$owner_uid' LIMIT 1");
3846 if (db_num_rows($result) == 1) {
3847 return db_fetch_result($result, 0, "caption");
3853 function label_update_cache($link, $id, $labels = false, $force = false) {
3856 label_clear_cache($link, $id);
3859 $labels = get_article_labels($link, $id);
3861 $labels = db_escape_string(json_encode($labels));
3863 db_query($link, "UPDATE ttrss_user_entries SET
3864 label_cache = '$labels' WHERE ref_id = '$id'");
3868 function label_clear_cache($link, $id) {
3870 db_query($link, "UPDATE ttrss_user_entries SET
3871 label_cache = '' WHERE ref_id = '$id'");
3875 function label_remove_article($link, $id, $label, $owner_uid) {
3877 $label_id = label_find_id($link, $label, $owner_uid);
3879 if (!$label_id) return;
3881 $result = db_query($link,
3882 "DELETE FROM ttrss_user_labels2
3884 label_id = '$label_id' AND
3885 article_id = '$id'");
3887 label_clear_cache($link, $id);
3890 function label_add_article($link, $id, $label, $owner_uid) {
3895 $obj_id = md5("LABELS:$id:$owner_uid");
3896 $memcache->delete($obj_id);
3899 $label_id = label_find_id($link, $label, $owner_uid);
3901 if (!$label_id) return;
3903 $result = db_query($link,
3905 article_id FROM ttrss_labels2, ttrss_user_labels2
3908 label_id = '$label_id' AND
3909 article_id = '$id' AND owner_uid = '$owner_uid'
3912 if (db_num_rows($result) == 0) {
3913 db_query($link, "INSERT INTO ttrss_user_labels2
3914 (label_id, article_id) VALUES ('$label_id', '$id')");
3917 label_clear_cache($link, $id);
3921 function label_remove($link, $id, $owner_uid) {
3924 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3927 $obj_id = md5("LABELS:$id:$owner_uid");
3928 $memcache->delete($obj_id);
3931 db_query($link, "BEGIN");
3933 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3936 $caption = db_fetch_result($result, 0, "caption");
3938 $result = db_query($link, "DELETE FROM ttrss_labels2 WHERE id = '$id'
3939 AND owner_uid = " . $owner_uid);
3941 if (db_affected_rows($link, $result) != 0 && $caption) {
3943 /* Remove access key for the label */
3945 $ext_id = -11 - $id;
3947 db_query($link, "DELETE FROM ttrss_access_keys WHERE
3948 feed_id = '$ext_id' AND owner_uid = $owner_uid");
3950 /* Disable filters that reference label being removed */
3952 db_query($link, "UPDATE ttrss_filters SET
3953 enabled = false WHERE action_param = '$caption'
3955 AND owner_uid = " . $owner_uid);
3957 /* Remove cached data */
3959 db_query($link, "UPDATE ttrss_user_entries SET label_cache = ''
3960 WHERE label_cache LIKE '%$caption%' AND owner_uid = " . $owner_uid);
3964 db_query($link, "COMMIT");
3967 function label_create($link, $caption) {
3969 db_query($link, "BEGIN");
3973 $result = db_query($link, "SELECT id FROM ttrss_labels2
3974 WHERE caption = '$caption' AND owner_uid = ". $_SESSION["uid"]);
3976 if (db_num_rows($result) == 0) {
3977 $result = db_query($link,
3978 "INSERT INTO ttrss_labels2 (caption,owner_uid)
3979 VALUES ('$caption', '".$_SESSION["uid"]."')");
3981 $result = db_affected_rows($link, $result) != 0;
3984 db_query($link, "COMMIT");
3989 function format_tags_string($tags, $id) {
3992 $tags_nolinks_str = "";
3998 $formatted_tags = array();
4000 foreach ($tags as $tag) {
4002 $tag_escaped = str_replace("'", "\\'", $tag);
4004 if (mb_strlen($tag) > 30) {
4005 $tag = truncate_string($tag, 30);
4008 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
4010 array_push($formatted_tags, $tag_str);
4012 $tmp_tags_str = implode(", ", $formatted_tags);
4014 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
4019 $tags_str = implode(", ", $formatted_tags);
4021 if ($num_tags < count($tags)) {
4022 $tags_str .= ", …";
4025 if ($num_tags == 0) {
4026 $tags_str = __("no tags");
4033 function format_article_labels($labels, $id) {
4037 foreach ($labels as $l) {
4038 $labels_str .= sprintf("<span class='hlLabelRef'
4039 style='color : %s; background-color : %s'>%s</span>",
4040 $l[2], $l[3], $l[1]);
4047 function format_article_note($id, $note) {
4049 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
4050 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
4051 __('(edit note)')."</div>$note</div>";
4056 function toggle_collapse_cat($link, $cat_id, $mode) {
4058 $mode = bool_to_sql_bool($mode);
4060 db_query($link, "UPDATE ttrss_feed_categories SET
4061 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
4068 $pref_name = '_COLLAPSED_SPECIAL';
4071 $pref_name = '_COLLAPSED_LABELS';
4074 $pref_name = '_COLLAPSED_UNCAT';
4080 set_pref($link, $pref_name, 'true');
4082 set_pref($link, $pref_name, 'false');
4088 function remove_feed($link, $id, $owner_uid) {
4092 /* save starred articles in Archived feed */
4094 db_query($link, "BEGIN");
4096 /* prepare feed if necessary */
4098 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4101 if (db_num_rows($result) == 0) {
4102 db_query($link, "INSERT INTO ttrss_archived_feeds
4103 (id, owner_uid, title, feed_url, site_url)
4104 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4108 db_query($link, "UPDATE ttrss_user_entries SET feed_id = NULL,
4109 orig_feed_id = '$id' WHERE feed_id = '$id' AND
4110 marked = true AND owner_uid = $owner_uid");
4112 /* Remove access key for the feed */
4114 db_query($link, "DELETE FROM ttrss_access_keys WHERE
4115 feed_id = '$id' AND owner_uid = $owner_uid");
4117 /* remove the feed */
4119 db_query($link, "DELETE FROM ttrss_feeds
4120 WHERE id = '$id' AND owner_uid = $owner_uid");
4122 db_query($link, "COMMIT");
4124 if (file_exists(ICONS_DIR
. "/$id.ico")) {
4125 unlink(ICONS_DIR
. "/$id.ico");
4128 ccache_remove($link, $id, $owner_uid);
4131 label_remove($link, -11-$id, $owner_uid);
4132 ccache_remove($link, -11-$id, $owner_uid);
4136 function add_feed_category($link, $feed_cat) {
4138 if (!$feed_cat) return false;
4140 db_query($link, "BEGIN");
4142 $result = db_query($link,
4143 "SELECT id FROM ttrss_feed_categories
4144 WHERE title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
4146 if (db_num_rows($result) == 0) {
4148 $result = db_query($link,
4149 "INSERT INTO ttrss_feed_categories (owner_uid,title)
4150 VALUES ('".$_SESSION["uid"]."', '$feed_cat')");
4152 db_query($link, "COMMIT");
4160 function remove_feed_category($link, $id, $owner_uid) {
4162 db_query($link, "DELETE FROM ttrss_feed_categories
4163 WHERE id = '$id' AND owner_uid = $owner_uid");
4165 ccache_remove($link, $id, $owner_uid, true);
4168 function archive_article($link, $id, $owner_uid) {
4169 db_query($link, "BEGIN");
4171 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4172 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
4174 if (db_num_rows($result) != 0) {
4176 /* prepare the archived table */
4178 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
4181 $result = db_query($link, "SELECT id FROM ttrss_archived_feeds
4182 WHERE id = '$feed_id'");
4184 if (db_num_rows($result) == 0) {
4185 db_query($link, "INSERT INTO ttrss_archived_feeds
4186 (id, owner_uid, title, feed_url, site_url)
4187 SELECT id, owner_uid, title, feed_url, site_url from ttrss_feeds
4188 WHERE id = '$feed_id'");
4191 db_query($link, "UPDATE ttrss_user_entries
4192 SET orig_feed_id = feed_id, feed_id = NULL
4193 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4197 db_query($link, "COMMIT");
4200 function getArticleFeed($link, $id) {
4201 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
4202 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
4204 if (db_num_rows($result) != 0) {
4205 return db_fetch_result($result, 0, "feed_id");
4212 * Fixes incomplete URLs by prepending "http://".
4213 * Also replaces feed:// with http://, and
4214 * prepends a trailing slash if the url is a domain name only.
4216 * @param string $url Possibly incomplete URL
4218 * @return string Fixed URL.
4220 function fix_url($url) {
4221 if (strpos($url, '://') === false) {
4222 $url = 'http://' . $url;
4223 } else if (substr($url, 0, 5) == 'feed:') {
4224 $url = 'http:' . substr($url, 5);
4227 //prepend slash if the URL has no slash in it
4228 // "http://www.example" -> "http://www.example/"
4229 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
4233 if ($url != "http:///")
4239 function validate_feed_url($url) {
4240 $parts = parse_url($url);
4242 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
4246 function get_article_enclosures($link, $id) {
4250 $query = "SELECT * FROM ttrss_enclosures
4251 WHERE post_id = '$id' AND content_url != ''";
4253 $obj_id = md5("ENCLOSURES:$id");
4257 if ($memcache && $obj = $memcache->get($obj_id)) {
4260 $result = db_query($link, $query);
4262 if (db_num_rows($result) > 0) {
4263 while ($line = db_fetch_assoc($result)) {
4264 array_push($rv, $line);
4266 if ($memcache) $memcache->add($obj_id, $rv, 0, 3600);
4273 function api_get_feeds($link, $cat_id, $unread_only, $limit, $offset) {
4279 if ($cat_id == -4 ||
$cat_id == -2) {
4280 $counters = getLabelCounters($link, true);
4282 foreach (array_values($counters) as $cv) {
4284 $unread = $cv["counter"];
4286 if ($unread ||
!$unread_only) {
4290 "title" => $cv["description"],
4291 "unread" => $cv["counter"],
4295 array_push($feeds, $row);
4302 if ($cat_id == -4 ||
$cat_id == -1) {
4303 foreach (array(-1, -2, -3, -4, 0) as $i) {
4304 $unread = getFeedUnread($link, $i);
4306 if ($unread ||
!$unread_only) {
4307 $title = getFeedTitle($link, $i);
4312 "unread" => $unread,
4315 array_push($feeds, $row);
4324 $limit_qpart = "LIMIT $limit OFFSET $offset";
4329 if ($cat_id == -4 ||
$cat_id == -3) {
4330 $result = db_query($link, "SELECT
4331 id, feed_url, cat_id, title, ".
4332 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4333 FROM ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"] .
4334 " ORDER BY cat_id, title " . $limit_qpart);
4338 $cat_qpart = "cat_id = '$cat_id'";
4340 $cat_qpart = "cat_id IS NULL";
4342 $result = db_query($link, "SELECT
4343 id, feed_url, cat_id, title, ".
4344 SUBSTRING_FOR_DATE
."(last_updated,1,19) AS last_updated
4345 FROM ttrss_feeds WHERE
4346 $cat_qpart AND owner_uid = " . $_SESSION["uid"] .
4347 " ORDER BY cat_id, title " . $limit_qpart);
4350 while ($line = db_fetch_assoc($result)) {
4352 $unread = getFeedUnread($link, $line["id"]);
4354 $has_icon = feed_has_icon($line['id']);
4356 if ($unread ||
!$unread_only) {
4359 "feed_url" => $line["feed_url"],
4360 "title" => $line["title"],
4361 "id" => (int)$line["id"],
4362 "unread" => (int)$unread,
4363 "has_icon" => $has_icon,
4364 "cat_id" => (int)$line["cat_id"],
4365 "last_updated" => strtotime($line["last_updated"])
4368 array_push($feeds, $row);
4375 function api_get_headlines($link, $feed_id, $limit, $offset,
4376 $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order,
4377 $include_attachments, $since_id) {
4379 /* do not rely on params below */
4381 $search = db_escape_string($_REQUEST["search"]);
4382 $search_mode = db_escape_string($_REQUEST["search_mode"]);
4383 $match_on = db_escape_string($_REQUEST["match_on"]);
4385 $qfh_ret = queryFeedHeadlines($link, $feed_id, $limit,
4386 $view_mode, $is_cat, $search, $search_mode, $match_on,
4387 $order, $offset, 0, false, $since_id);
4389 $result = $qfh_ret[0];
4390 $feed_title = $qfh_ret[1];
4392 $headlines = array();
4394 while ($line = db_fetch_assoc($result)) {
4395 $is_updated = ($line["last_read"] == "" &&
4396 ($line["unread"] != "t" && $line["unread"] != "1"));
4398 $tags = explode(",", $line["tag_cache"]);
4399 $labels = json_decode($line["label_cache"], true);
4401 //if (!$tags) $tags = get_article_tags($link, $line["id"]);
4402 //if (!$labels) $labels = get_article_labels($link, $line["id"]);
4404 $headline_row = array(
4405 "id" => (int)$line["id"],
4406 "unread" => sql_bool_to_bool($line["unread"]),
4407 "marked" => sql_bool_to_bool($line["marked"]),
4408 "published" => sql_bool_to_bool($line["published"]),
4409 "updated" => strtotime($line["updated"]),
4410 "is_updated" => $is_updated,
4411 "title" => $line["title"],
4412 "link" => $line["link"],
4413 "feed_id" => $line["feed_id"],
4417 if ($include_attachments)
4418 $headline_row['attachments'] = get_article_enclosures($link,
4421 if ($show_excerpt) {
4422 $excerpt = truncate_string(strip_tags($line["content_preview"]), 100);
4423 $headline_row["excerpt"] = $excerpt;
4426 if ($show_content) {
4427 $headline_row["content"] = $line["content_preview"];
4430 // unify label output to ease parsing
4431 if ($labels["no-labels"] == 1) $labels = array();
4433 $headline_row["labels"] = $labels;
4435 array_push($headlines, $headline_row);
4441 function generate_error_feed($link, $error) {
4444 $reply['headlines']['id'] = -6;
4445 $reply['headlines']['is_cat'] = false;
4447 $reply['headlines']['toolbar'] = '';
4448 $reply['headlines']['content'] = "<div class='whiteBox'>". $error . "</div>";
4450 $reply['headlines-info'] = array("count" => 0,
4451 "vgroup_last_feed" => '',
4453 "disable_cache" => true);
4459 function generate_dashboard_feed($link) {
4462 $reply['headlines']['id'] = -5;
4463 $reply['headlines']['is_cat'] = false;
4465 $reply['headlines']['toolbar'] = '';
4466 $reply['headlines']['content'] = "<div class='whiteBox'>".__('No feed selected.');
4468 $reply['headlines']['content'] .= "<p class=\"small\"><span class=\"insensitive\">";
4470 $result = db_query($link, "SELECT ".SUBSTRING_FOR_DATE
."(MAX(last_updated), 1, 19) AS last_updated FROM ttrss_feeds
4471 WHERE owner_uid = " . $_SESSION['uid']);
4473 $last_updated = db_fetch_result($result, 0, "last_updated");
4474 $last_updated = make_local_datetime($link, $last_updated, false);
4476 $reply['headlines']['content'] .= sprintf(__("Feeds last updated at %s"), $last_updated);
4478 $result = db_query($link, "SELECT COUNT(id) AS num_errors
4479 FROM ttrss_feeds WHERE last_error != '' AND owner_uid = ".$_SESSION["uid"]);
4481 $num_errors = db_fetch_result($result, 0, "num_errors");
4483 if ($num_errors > 0) {
4484 $reply['headlines']['content'] .= "<br/>";
4485 $reply['headlines']['content'] .= "<a class=\"insensitive\" href=\"#\" onclick=\"showFeedsWithErrors()\">".
4486 __('Some feeds have update errors (click for details)')."</a>";
4488 $reply['headlines']['content'] .= "</span></p>";
4490 $reply['headlines-info'] = array("count" => 0,
4491 "vgroup_last_feed" => '',
4493 "disable_cache" => true);
4498 function save_email_address($link, $email) {
4499 // FIXME: implement persistent storage of emails
4501 if (!$_SESSION['stored_emails'])
4502 $_SESSION['stored_emails'] = array();
4504 if (!in_array($email, $_SESSION['stored_emails']))
4505 array_push($_SESSION['stored_emails'], $email);
4508 function update_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4509 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4511 $sql_is_cat = bool_to_sql_bool($is_cat);
4513 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4514 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4515 AND owner_uid = " . $owner_uid);
4517 if (db_num_rows($result) == 1) {
4518 $key = db_escape_string(sha1(uniqid(rand(), true)));
4520 db_query($link, "UPDATE ttrss_access_keys SET access_key = '$key'
4521 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4522 AND owner_uid = " . $owner_uid);
4527 return get_feed_access_key($link, $feed_id, $is_cat, $owner_uid);
4531 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
4533 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
4535 $sql_is_cat = bool_to_sql_bool($is_cat);
4537 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
4538 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
4539 AND owner_uid = " . $owner_uid);
4541 if (db_num_rows($result) == 1) {
4542 return db_fetch_result($result, 0, "access_key");
4544 $key = db_escape_string(sha1(uniqid(rand(), true)));
4546 $result = db_query($link, "INSERT INTO ttrss_access_keys
4547 (access_key, feed_id, is_cat, owner_uid)
4548 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
4556 * Extracts RSS/Atom feed URLs from the given HTML URL.
4558 * @param string $url HTML page URL
4560 * @return array Array of feeds. Key is the full URL, value the title
4562 function get_feeds_from_html($url, $login = false, $pass = false)
4564 $url = fix_url($url);
4565 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
4567 libxml_use_internal_errors(true);
4569 $content = @fetch_file_contents
($url, false, $login, $pass);
4571 $doc = new DOMDocument();
4572 $doc->loadHTML($content);
4573 $xpath = new DOMXPath($doc);
4574 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
4575 $feedUrls = array();
4576 foreach ($entries as $entry) {
4577 if ($entry->hasAttribute('href')) {
4578 $title = $entry->getAttribute('title');
4580 $title = $entry->getAttribute('type');
4582 $feedUrl = rewrite_relative_url(
4583 $baseUrl, $entry->getAttribute('href')
4585 $feedUrls[$feedUrl] = $title;
4592 * Checks if the content behind the given URL is a HTML file
4594 * @param string $url URL to check
4596 * @return boolean True if the URL contains HTML content
4598 function url_is_html($url, $login = false, $pass = false) {
4599 $content = substr(fetch_file_contents($url, false, $login, $pass), 0, 1000);
4601 if (stripos($content, '<html>') === false
4602 && stripos($content, '<html ') === false
4610 function print_label_select($link, $name, $value, $attributes = "") {
4612 $result = db_query($link, "SELECT caption FROM ttrss_labels2
4613 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
4615 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
4616 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
4618 while ($line = db_fetch_assoc($result)) {
4620 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
4622 print "<option value=\"".htmlspecialchars($line["caption"])."\"
4623 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
4627 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
4634 function format_article_enclosures($link, $id, $always_display_enclosures,
4637 $result = get_article_enclosures($link, $id);
4640 if (count($result) > 0) {
4642 $entries_html = array();
4645 foreach ($result as $line) {
4647 $url = $line["content_url"];
4648 $ctype = $line["content_type"];
4650 if (!$ctype) $ctype = __("unknown type");
4652 # $filename = substr($url, strrpos($url, "/")+1);
4654 $entry = format_inline_player($link, $url, $ctype);
4656 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
4657 # $filename . " (" . $ctype . ")" . "</a>";
4659 array_push($entries_html, $entry);
4663 $entry["type"] = $ctype;
4664 $entry["filename"] = $filename;
4665 $entry["url"] = $url;
4667 array_push($entries, $entry);
4670 $rv .= "<div class=\"postEnclosures\">";
4672 if (!get_pref($link, "STRIP_IMAGES")) {
4673 if ($always_display_enclosures ||
4674 !preg_match("/<img/i", $article_content)) {
4676 foreach ($entries as $entry) {
4678 if (preg_match("/image/", $entry["type"]) ||
4679 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
4682 alt=\"".htmlspecialchars($entry["filename"])."\"
4683 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
4689 if (count($entries) == 1) {
4690 $rv .= __("Attachment:") . " ";
4692 $rv .= __("Attachments:") . " ";
4695 $rv .= join(", ", $entries_html);
4703 function getLastArticleId($link) {
4704 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
4705 WHERE owner_uid = " . $_SESSION["uid"]);
4707 if (db_num_rows($result) == 1) {
4708 return db_fetch_result($result, 0, "id");
4714 function build_url($parts) {
4715 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
4719 * Converts a (possibly) relative URL to a absolute one.
4721 * @param string $url Base URL (i.e. from where the document is)
4722 * @param string $rel_url Possibly relative URL in the document
4724 * @return string Absolute URL
4726 function rewrite_relative_url($url, $rel_url) {
4727 if (strpos($rel_url, "://") !== false) {
4729 } else if (strpos($rel_url, "/") === 0)
4731 $parts = parse_url($url);
4732 $parts['path'] = $rel_url;
4734 return build_url($parts);
4737 $parts = parse_url($url);
4738 if (!isset($parts['path'])) {
4739 $parts['path'] = '/';
4741 $dir = $parts['path'];
4742 if (substr($dir, -1) !== '/') {
4743 $dir = dirname($parts['path']);
4744 $dir !== '/' && $dir .= '/';
4746 $parts['path'] = $dir . $rel_url;
4748 return build_url($parts);
4752 function sphinx_search($query, $offset = 0, $limit = 30) {
4753 require_once 'lib/sphinxapi.php';
4755 $sphinxClient = new SphinxClient();
4757 $sphinxClient->SetServer('localhost', 9312);
4758 $sphinxClient->SetConnectTimeout(1);
4760 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
4761 'feed_title' => 20));
4763 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
4764 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
4765 $sphinxClient->SetLimits($offset, $limit, 1000);
4766 $sphinxClient->SetArrayResult(false);
4767 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
4769 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
4773 if (is_array($result['matches'])) {
4774 foreach (array_keys($result['matches']) as $int_id) {
4775 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
4776 array_push($ids, $ref_id);
4783 function cleanup_tags($link, $days = 14, $limit = 1000) {
4785 if (DB_TYPE
== "pgsql") {
4786 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
4787 } else if (DB_TYPE
== "mysql") {
4788 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
4793 while ($limit > 0) {
4796 $query = "SELECT ttrss_tags.id AS id
4797 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
4798 WHERE post_int_id = int_id AND $interval_query AND
4799 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
4801 $result = db_query($link, $query);
4805 while ($line = db_fetch_assoc($result)) {
4806 array_push($ids, $line['id']);
4809 if (count($ids) > 0) {
4810 $ids = join(",", $ids);
4813 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
4814 $tags_deleted +
= db_affected_rows($link, $tmp_result);
4819 $limit -= $limit_part;
4824 return $tags_deleted;
4827 function print_user_stylesheet($link) {
4828 $value = get_pref($link, 'USER_STYLESHEET');
4831 print "<style type=\"text/css\">";
4832 print str_replace("<br/>", "\n", $value);
4838 function rewrite_urls($line) {
4843 $result = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
4844 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $line);
4849 function filter_to_sql($filter) {
4852 if (DB_TYPE
== "pgsql")
4855 $reg_qpart = "REGEXP";
4857 switch ($filter["type"]) {
4859 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4860 $filter['reg_exp'] . "')";
4863 $query = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
4864 $filter['reg_exp'] . "')";
4867 $query = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
4868 $filter['reg_exp'] . "') OR LOWER(" .
4869 "ttrss_entries.content) $reg_qpart LOWER('" . $filter['reg_exp'] . "')";
4872 $query = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
4873 $filter['reg_exp'] . "')";
4876 $query = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
4877 $filter['reg_exp'] . "')";
4881 if ($filter["filter_param"] == "before")
4886 $timestamp = date("Y-m-d H:N:s", strtotime($filter["reg_exp"]));
4887 $query = "ttrss_entries.date_entered $cmp_qpart '$timestamp'";
4890 $query = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
4891 $filter['reg_exp'] . "')";
4895 if ($filter["inverse"])
4896 $query = "NOT ($query)";
4899 if (DB_TYPE
== "pgsql") {
4900 $query = " ($query) AND ttrss_entries.date_entered > NOW() - INTERVAL '14 days'";
4902 $query = " ($query) AND ttrss_entries.date_entered > DATE_SUB(NOW(), INTERVAL 14 DAY)";
4912 // -1 - never connected
4913 // 0 - no data received
4914 // 1 - data received successfully
4915 // 2 - did not receive valid data
4916 // >10 - server error, code + 10 (e.g. 16 means server error 6)
4918 function get_linked_feeds($link, $instance_id = false) {
4920 $instance_qpart = "id = '$instance_id' AND ";
4922 $instance_qpart = "";
4924 if (DB_TYPE
== "pgsql") {
4925 $date_qpart = "last_connected < NOW() - INTERVAL '6 hours'";
4927 $date_qpart = "last_connected < DATE_SUB(NOW(), INTERVAL 6 HOUR)";
4930 $result = db_query($link, "SELECT id, access_key, access_url FROM ttrss_linked_instances
4931 WHERE $instance_qpart $date_qpart ORDER BY last_connected");
4933 while ($line = db_fetch_assoc($result)) {
4936 _debug("Updating: " . $line['access_url'] . " ($id)");
4938 $fetch_url = $line['access_url'] . '/public.php?op=fbexport';
4939 $post_query = 'key=' . $line['access_key'];
4941 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
4943 // try doing it the old way
4945 $fetch_url = $line['access_url'] . '/backend.php?op=fbexport';
4946 $feeds = fetch_file_contents($fetch_url, false, false, false, $post_query);
4950 $feeds = json_decode($feeds, true);
4953 if ($feeds['error']) {
4954 $status = $feeds['error']['code'] +
10;
4958 if (count($feeds['feeds']) > 0) {
4960 db_query($link, "DELETE FROM ttrss_linked_feeds
4961 WHERE instance_id = '$id'");
4963 foreach ($feeds['feeds'] as $feed) {
4964 $feed_url = db_escape_string($feed['feed_url']);
4965 $title = db_escape_string($feed['title']);
4966 $subscribers = db_escape_string($feed['subscribers']);
4967 $site_url = db_escape_string($feed['site_url']);
4969 db_query($link, "INSERT INTO ttrss_linked_feeds
4970 (feed_url, site_url, title, subscribers, instance_id, created, updated)
4972 ('$feed_url', '$site_url', '$title', '$subscribers', '$id', NOW(), NOW())");
4975 // received 0 feeds, this might indicate that
4976 // the instance on the other hand is rebuilding feedbrowser cache
4977 // we will try again later
4979 // TODO: maybe perform expiration based on updated here?
4982 _debug("Processed " . count($feeds['feeds']) . " feeds.");
4992 _debug("Status: $status");
4994 db_query($link, "UPDATE ttrss_linked_instances SET
4995 last_status_out = '$status', last_connected = NOW() WHERE id = '$id'");
5000 function make_feed_browser($link, $search, $limit, $mode = 1) {
5002 $owner_uid = $_SESSION["uid"];
5006 $search_qpart = "AND (UPPER(feed_url) LIKE UPPER('%$search%') OR
5007 UPPER(title) LIKE UPPER('%$search%'))";
5013 /* $result = db_query($link, "SELECT feed_url, subscribers FROM
5014 ttrss_feedbrowser_cache WHERE (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5015 WHERE tf.feed_url = ttrss_feedbrowser_cache.feed_url
5016 AND owner_uid = '$owner_uid') $search_qpart
5017 ORDER BY subscribers DESC LIMIT $limit"); */
5019 $result = db_query($link, "SELECT feed_url, site_url, title, SUM(subscribers) AS subscribers FROM
5020 (SELECT feed_url, site_url, title, subscribers FROM ttrss_feedbrowser_cache UNION ALL
5021 SELECT feed_url, site_url, title, subscribers FROM ttrss_linked_feeds) AS qqq
5023 (SELECT COUNT(id) = 0 FROM ttrss_feeds AS tf
5024 WHERE tf.feed_url = qqq.feed_url
5025 AND owner_uid = '$owner_uid') $search_qpart
5026 GROUP BY feed_url, site_url, title ORDER BY subscribers DESC LIMIT $limit");
5028 } else if ($mode == 2) {
5029 $result = db_query($link, "SELECT *,
5030 (SELECT COUNT(*) FROM ttrss_user_entries WHERE
5031 orig_feed_id = ttrss_archived_feeds.id) AS articles_archived
5033 ttrss_archived_feeds
5035 (SELECT COUNT(*) FROM ttrss_feeds
5036 WHERE ttrss_feeds.feed_url = ttrss_archived_feeds.feed_url AND
5037 owner_uid = '$owner_uid') = 0 AND
5038 owner_uid = '$owner_uid' $search_qpart
5039 ORDER BY id DESC LIMIT $limit");
5044 while ($line = db_fetch_assoc($result)) {
5048 $feed_url = htmlspecialchars($line["feed_url"]);
5049 $site_url = htmlspecialchars($line["site_url"]);
5050 $subscribers = $line["subscribers"];
5052 $check_box = "<input onclick='toggleSelectListRow2(this)'
5053 dojoType=\"dijit.form.CheckBox\"
5054 type=\"checkbox\" \">";
5056 $class = ($feedctr %
2) ?
"even" : "odd";
5058 $site_url = "<a target=\"_blank\"
5060 <span class=\"fb_feedTitle\">".
5061 htmlspecialchars($line["title"])."</span></a>";
5063 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5064 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5065 style='vertical-align : middle'></a>";
5067 $rv .= "<li>$check_box $feed_url $site_url".
5068 " <span class='subscribers'>($subscribers)</span></li>";
5070 } else if ($mode == 2) {
5071 $feed_url = htmlspecialchars($line["feed_url"]);
5072 $site_url = htmlspecialchars($line["site_url"]);
5073 $title = htmlspecialchars($line["title"]);
5075 $check_box = "<input onclick='toggleSelectListRow2(this)' dojoType=\"dijit.form.CheckBox\"
5076 type=\"checkbox\">";
5078 $class = ($feedctr %
2) ?
"even" : "odd";
5080 if ($line['articles_archived'] > 0) {
5081 $archived = sprintf(__("%d archived articles"), $line['articles_archived']);
5082 $archived = " <span class='subscribers'>($archived)</span>";
5087 $site_url = "<a target=\"_blank\"
5089 <span class=\"fb_feedTitle\">".
5090 htmlspecialchars($line["title"])."</span></a>";
5092 $feed_url = "<a target=\"_blank\" class=\"fb_feedUrl\"
5093 href=\"$feed_url\"><img src='images/feed-icon-12x12.png'
5094 style='vertical-align : middle'></a>";
5097 $rv .= "<li id=\"FBROW-".$line["id"]."\">".
5098 "$check_box $feed_url $site_url $archived</li>";
5104 if ($feedctr == 0) {
5105 $rv .= "<li style=\"text-align : center\"><p>".__('No feeds found.')."</p></li>";