2 define('EXPECTED_CONFIG_VERSION', 26);
3 define('SCHEMA_VERSION', 103);
4 define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION
. ' (http://tt-rss.org/)');
6 $fetch_last_error = false;
9 function __autoload($class) {
10 $class_file = str_replace("_", "/", strtolower(basename($class)));
12 $file = dirname(__FILE__
)."/../classes/$class_file.php";
14 if (file_exists($file)) {
20 mb_internal_encoding("UTF-8");
21 date_default_timezone_set('UTC');
22 if (defined('E_DEPRECATED')) {
23 error_reporting(E_ALL
& ~E_NOTICE
& ~E_DEPRECATED
);
25 error_reporting(E_ALL
& ~E_NOTICE
);
28 require_once 'config.php';
30 if (DB_TYPE
== "pgsql") {
31 define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
33 define('SUBSTRING_FOR_DATE', 'SUBSTRING');
36 define('THEME_VERSION_REQUIRED', 1.1);
39 * Return available translations names.
42 * @return array A array of available translations.
44 function get_translations() {
46 "auto" => "Detect automatically",
51 "fr_FR" => "Français",
52 "hu_HU" => "Magyar (Hungarian)",
53 "it_IT" => "Italiano",
54 "ja_JP" => "日本語 (Japanese)",
55 "nb_NO" => "Norwegian bokmål",
58 "pt_BR" => "Portuguese/Brazil",
59 "zh_CN" => "Simplified Chinese");
64 require_once "lib/accept-to-gettext.php";
65 require_once "lib/gettext/gettext.inc";
68 function startup_gettext() {
70 # Get locale from Accept-Language header
71 $lang = al2gt(array_keys(get_translations()), "text/html");
73 if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
74 $lang = _TRANSLATION_OVERRIDE_DEFAULT
;
77 /* In login action of mobile version */
78 if ($_POST["language"] && defined('MOBILE_VERSION')) {
79 $lang = $_POST["language"];
80 } else if ($_SESSION["language"] && $_SESSION["language"] != "auto") {
81 $lang = $_SESSION["language"];
85 if (defined('LC_MESSAGES')) {
86 _setlocale(LC_MESSAGES
, $lang);
87 } else if (defined('LC_ALL')) {
88 _setlocale(LC_ALL
, $lang);
91 if (defined('MOBILE_VERSION')) {
92 _bindtextdomain("messages", "../locale");
94 _bindtextdomain("messages", "locale");
97 _textdomain("messages");
98 _bind_textdomain_codeset("messages", "UTF-8");
104 require_once 'db-prefs.php';
105 require_once 'version.php';
106 require_once 'ccache.php';
107 require_once 'labels.php';
109 ini_set('user_agent', SELF_USER_AGENT
);
111 require_once 'lib/pubsubhubbub/publisher.php';
112 require_once 'lib/htmLawed.php';
115 $utc_tz = new DateTimeZone('UTC');
116 $schema_version = false;
119 * Print a timestamped debug message.
121 * @param string $msg The debug message.
124 function _debug($msg) {
125 if (defined('QUIET') && QUIET
) {
128 $ts = strftime("%H:%M:%S", time());
129 if (function_exists('posix_getpid')) {
130 $ts = "$ts/" . posix_getpid();
132 print "[$ts] $msg\n";
136 * Purge a feed old posts.
138 * @param mixed $link A database connection.
139 * @param mixed $feed_id The id of the purged feed.
140 * @param mixed $purge_interval Olderness of purged posts.
141 * @param boolean $debug Set to True to enable the debug. False by default.
145 function purge_feed($link, $feed_id, $purge_interval, $debug = false) {
147 if (!$purge_interval) $purge_interval = feed_purge_interval($link, $feed_id);
151 $result = db_query($link,
152 "SELECT owner_uid FROM ttrss_feeds WHERE id = '$feed_id'");
156 if (db_num_rows($result) == 1) {
157 $owner_uid = db_fetch_result($result, 0, "owner_uid");
160 if ($purge_interval == -1 ||
!$purge_interval) {
162 ccache_update($link, $feed_id, $owner_uid);
167 if (!$owner_uid) return;
169 if (FORCE_ARTICLE_PURGE
== 0) {
170 $purge_unread = get_pref($link, "PURGE_UNREAD_ARTICLES",
173 $purge_unread = true;
174 $purge_interval = FORCE_ARTICLE_PURGE
;
177 if (!$purge_unread) $query_limit = " unread = false AND ";
179 if (DB_TYPE
== "pgsql") {
180 $pg_version = get_pgsql_version($link);
182 if (preg_match("/^7\./", $pg_version) ||
preg_match("/^8\.0/", $pg_version)) {
184 $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
185 ttrss_entries.id = ref_id AND
187 feed_id = '$feed_id' AND
189 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
193 $result = db_query($link, "DELETE FROM ttrss_user_entries
195 WHERE ttrss_entries.id = ref_id AND
197 feed_id = '$feed_id' AND
199 ttrss_entries.date_updated < NOW() - INTERVAL '$purge_interval days'");
202 $rows = pg_affected_rows($result);
206 /* $result = db_query($link, "DELETE FROM ttrss_user_entries WHERE
207 marked = false AND feed_id = '$feed_id' AND
208 (SELECT date_updated FROM ttrss_entries WHERE
209 id = ref_id) < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)"); */
211 $result = db_query($link, "DELETE FROM ttrss_user_entries
212 USING ttrss_user_entries, ttrss_entries
213 WHERE ttrss_entries.id = ref_id AND
215 feed_id = '$feed_id' AND
217 ttrss_entries.date_updated < DATE_SUB(NOW(), INTERVAL $purge_interval DAY)");
219 $rows = mysql_affected_rows($link);
223 ccache_update($link, $feed_id, $owner_uid);
226 _debug("Purged feed $feed_id ($purge_interval): deleted $rows articles");
228 } // function purge_feed
230 function feed_purge_interval($link, $feed_id) {
232 $result = db_query($link, "SELECT purge_interval, owner_uid FROM ttrss_feeds
233 WHERE id = '$feed_id'");
235 if (db_num_rows($result) == 1) {
236 $purge_interval = db_fetch_result($result, 0, "purge_interval");
237 $owner_uid = db_fetch_result($result, 0, "owner_uid");
239 if ($purge_interval == 0) $purge_interval = get_pref($link,
240 'PURGE_OLD_DAYS', $owner_uid);
242 return $purge_interval;
249 function purge_orphans($link, $do_output = false) {
251 // purge orphaned posts in main content table
252 $result = db_query($link, "DELETE FROM ttrss_entries WHERE
253 (SELECT COUNT(int_id) FROM ttrss_user_entries WHERE ref_id = id) = 0");
256 $rows = db_affected_rows($link, $result);
257 _debug("Purged $rows orphaned posts.");
261 function get_feed_update_interval($link, $feed_id) {
262 $result = db_query($link, "SELECT owner_uid, update_interval FROM
263 ttrss_feeds WHERE id = '$feed_id'");
265 if (db_num_rows($result) == 1) {
266 $update_interval = db_fetch_result($result, 0, "update_interval");
267 $owner_uid = db_fetch_result($result, 0, "owner_uid");
269 if ($update_interval != 0) {
270 return $update_interval;
272 return get_pref($link, 'DEFAULT_UPDATE_INTERVAL', $owner_uid, false);
280 function fetch_file_contents($url, $type = false, $login = false, $pass = false, $post_query = false) {
281 $login = urlencode($login);
282 $pass = urlencode($pass);
284 global $fetch_last_error;
286 if (function_exists('curl_init') && !ini_get("open_basedir")) {
287 $ch = curl_init($url);
289 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, 15);
290 curl_setopt($ch, CURLOPT_TIMEOUT
, 45);
291 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
292 curl_setopt($ch, CURLOPT_MAXREDIRS
, 20);
293 curl_setopt($ch, CURLOPT_BINARYTRANSFER
, true);
294 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
295 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
296 curl_setopt($ch, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
297 curl_setopt($ch, CURLOPT_USERAGENT
, SELF_USER_AGENT
);
298 curl_setopt($ch, CURLOPT_ENCODING
, "gzip");
301 curl_setopt($ch, CURLOPT_POST
, true);
302 curl_setopt($ch, CURLOPT_POSTFIELDS
, $post_query);
306 curl_setopt($ch, CURLOPT_USERPWD
, "$login:$pass");
308 $contents = @curl_exec
($ch);
310 if ($contents === false) {
311 $fetch_last_error = curl_error($ch);
316 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE
);
317 $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE
);
320 if ($http_code != 200 ||
$type && strpos($content_type, "$type") === false) {
326 if ($login && $pass ){
327 $url_parts = array();
329 preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
331 if ($url_parts[1] && $url_parts[2]) {
332 $url = $url_parts[1] . "://$login:$pass@" . $url_parts[2];
336 $data = @file_get_contents
($url);
338 if (!$data && function_exists('error_get_last')) {
339 $error = error_get_last();
340 $fetch_last_error = $error["message"];
348 * Try to determine the favicon URL for a feed.
349 * adapted from wordpress favicon plugin by Jeff Minard (http://thecodepro.com/)
350 * http://dev.wp-plugins.org/file/favatars/trunk/favatars.php
352 * @param string $url A feed or page URL
354 * @return mixed The favicon URL, or false if none was found.
356 function get_favicon_url($url) {
358 $favicon_url = false;
360 if ($html = @fetch_file_contents
($url)) {
362 libxml_use_internal_errors(true);
364 $doc = new DOMDocument();
365 $doc->loadHTML($html);
366 $xpath = new DOMXPath($doc);
368 $base = $xpath->query('/html/head/base');
369 foreach ($base as $b) {
370 $url = $b->getAttribute("href");
374 $entries = $xpath->query('/html/head/link[@rel="shortcut icon" or @rel="icon"]');
375 if (count($entries) > 0) {
376 foreach ($entries as $entry) {
377 $favicon_url = rewrite_relative_url($url, $entry->getAttribute("href"));
384 $favicon_url = rewrite_relative_url($url, "/favicon.ico");
387 } // function get_favicon_url
389 function check_feed_favicon($site_url, $feed, $link) {
390 # print "FAVICON [$site_url]: $favicon_url\n";
392 $icon_file = ICONS_DIR
. "/$feed.ico";
394 if (!file_exists($icon_file)) {
395 $favicon_url = get_favicon_url($site_url);
398 // Limiting to "image" type misses those served with text/plain
399 $contents = fetch_file_contents($favicon_url); // , "image");
402 // Crude image type matching.
403 // Patterns gleaned from the file(1) source code.
404 if (preg_match('/^\x00\x00\x01\x00/', $contents)) {
405 // 0 string \000\000\001\000 MS Windows icon resource
406 //error_log("check_feed_favicon: favicon_url=$favicon_url isa MS Windows icon resource");
408 elseif (preg_match('/^GIF8/', $contents)) {
409 // 0 string GIF8 GIF image data
410 //error_log("check_feed_favicon: favicon_url=$favicon_url isa GIF image");
412 elseif (preg_match('/^\x89PNG\x0d\x0a\x1a\x0a/', $contents)) {
413 // 0 string \x89PNG\x0d\x0a\x1a\x0a PNG image data
414 //error_log("check_feed_favicon: favicon_url=$favicon_url isa PNG image");
416 elseif (preg_match('/^\xff\xd8/', $contents)) {
417 // 0 beshort 0xffd8 JPEG image data
418 //error_log("check_feed_favicon: favicon_url=$favicon_url isa JPG image");
421 //error_log("check_feed_favicon: favicon_url=$favicon_url isa UNKNOWN type");
427 $fp = @fopen
($icon_file, "w");
430 fwrite($fp, $contents);
432 chmod($icon_file, 0644);
439 function print_select($id, $default, $values, $attributes = "") {
440 print "<select name=\"$id\" id=\"$id\" $attributes>";
441 foreach ($values as $v) {
443 $sel = "selected=\"1\"";
447 print "<option value=\"$v\" $sel>$v</option>";
452 function print_select_hash($id, $default, $values, $attributes = "") {
453 print "<select name=\"$id\" id='$id' $attributes>";
454 foreach (array_keys($values) as $v) {
456 $sel = 'selected="selected"';
460 print "<option $sel value=\"$v\">".$values[$v]."</option>";
466 function getmicrotime() {
467 list($usec, $sec) = explode(" ",microtime());
468 return ((float)$usec +
(float)$sec);
471 function print_radio($id, $default, $true_is, $values, $attributes = "") {
472 foreach ($values as $v) {
479 if ($v == $true_is) {
480 $sel .= " value=\"1\"";
482 $sel .= " value=\"0\"";
485 print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
486 type=\"radio\" $sel $attributes name=\"$id\"> $v ";
491 function initialize_user_prefs($link, $uid, $profile = false) {
493 $uid = db_escape_string($uid);
497 $profile_qpart = "AND profile IS NULL";
499 $profile_qpart = "AND profile = '$profile'";
502 if (get_schema_version($link) < 63) $profile_qpart = "";
504 db_query($link, "BEGIN");
506 $result = db_query($link, "SELECT pref_name,def_value FROM ttrss_prefs");
508 $u_result = db_query($link, "SELECT pref_name
509 FROM ttrss_user_prefs WHERE owner_uid = '$uid' $profile_qpart");
511 $active_prefs = array();
513 while ($line = db_fetch_assoc($u_result)) {
514 array_push($active_prefs, $line["pref_name"]);
517 while ($line = db_fetch_assoc($result)) {
518 if (array_search($line["pref_name"], $active_prefs) === FALSE) {
519 // print "adding " . $line["pref_name"] . "<br>";
521 if (get_schema_version($link) < 63) {
522 db_query($link, "INSERT INTO ttrss_user_prefs
523 (owner_uid,pref_name,value) VALUES
524 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."')");
527 db_query($link, "INSERT INTO ttrss_user_prefs
528 (owner_uid,pref_name,value, profile) VALUES
529 ('$uid', '".$line["pref_name"]."','".$line["def_value"]."', $profile)");
535 db_query($link, "COMMIT");
539 function get_ssl_certificate_id() {
540 if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
541 return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
542 $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
543 $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
544 $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
549 function authenticate_user($link, $login, $password, $check_only = false) {
551 if (!SINGLE_USER_MODE
) {
556 foreach ($pluginhost->get_hooks($pluginhost::HOOK_AUTH_USER
) as $plugin) {
558 $user_id = (int) $plugin->authenticate($login, $password);
561 $_SESSION["auth_module"] = strtolower(get_class($plugin));
566 if ($user_id && !$check_only) {
567 $_SESSION["uid"] = $user_id;
569 $result = db_query($link, "SELECT login,access_level,pwd_hash FROM ttrss_users
570 WHERE id = '$user_id'");
572 $_SESSION["name"] = db_fetch_result($result, 0, "login");
573 $_SESSION["access_level"] = db_fetch_result($result, 0, "access_level");
574 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
576 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
579 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
580 $_SESSION["pwd_hash"] = db_fetch_result($result, 0, "pwd_hash");
582 $_SESSION["last_version_check"] = time();
584 initialize_user_prefs($link, $_SESSION["uid"]);
593 $_SESSION["uid"] = 1;
594 $_SESSION["name"] = "admin";
595 $_SESSION["access_level"] = 10;
597 $_SESSION["hide_hello"] = true;
598 $_SESSION["hide_logout"] = true;
600 $_SESSION["auth_module"] = false;
602 if (!$_SESSION["csrf_token"]) {
603 $_SESSION["csrf_token"] = sha1(uniqid(rand(), true));
606 $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
608 initialize_user_prefs($link, $_SESSION["uid"]);
614 function make_password($length = 8) {
617 $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ";
621 while ($i < $length) {
622 $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
624 if (!strstr($password, $char)) {
632 // this is called after user is created to initialize default feeds, labels
635 // user preferences are checked on every login, not here
637 function initialize_user($link, $uid) {
639 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
640 values ('$uid', 'Tiny Tiny RSS: New Releases',
641 'http://tt-rss.org/releases.rss')");
643 db_query($link, "insert into ttrss_feeds (owner_uid,title,feed_url)
644 values ('$uid', 'Tiny Tiny RSS: Forum',
645 'http://tt-rss.org/forum/rss.php')");
648 function logout_user() {
650 if (isset($_COOKIE[session_name()])) {
651 setcookie(session_name(), '', time()-42000, '/');
655 function validate_csrf($csrf_token) {
656 return $csrf_token == $_SESSION['csrf_token'];
659 function validate_session($link) {
660 if (SINGLE_USER_MODE
) return true;
662 $check_ip = $_SESSION['ip_address'];
664 switch (SESSION_CHECK_ADDRESS
) {
669 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
672 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.'));
673 $check_ip = substr($check_ip, 0, strrpos($check_ip, '.')+
1);
677 if ($check_ip && strpos($_SERVER['REMOTE_ADDR'], $check_ip) !== 0) {
678 $_SESSION["login_error_msg"] =
679 __("Session failed to validate (incorrect IP)");
683 if ($_SESSION["ref_schema_version"] != get_schema_version($link, true))
686 if ($_SESSION["uid"]) {
688 $result = db_query($link,
689 "SELECT pwd_hash FROM ttrss_users WHERE id = '".$_SESSION["uid"]."'");
691 $pwd_hash = db_fetch_result($result, 0, "pwd_hash");
693 if ($pwd_hash != $_SESSION["pwd_hash"]) {
698 /* if ($_SESSION["cookie_lifetime"] && $_SESSION["uid"]) {
700 //print_r($_SESSION);
702 if (time() > $_SESSION["cookie_lifetime"]) {
710 function load_user_plugins($link, $owner_uid) {
712 $plugins = get_pref($link, "_ENABLED_PLUGINS", $owner_uid);
715 $pluginhost->load($plugins, $pluginhost::KIND_USER
, $owner_uid);
717 if (get_schema_version($link) > 100) {
718 $pluginhost->load_data();
723 function login_sequence($link, $login_form = 0) {
724 $_SESSION["prefs_cache"] = false;
726 if (SINGLE_USER_MODE
) {
727 authenticate_user($link, "admin", null);
728 load_user_plugins($link, $_SESSION["uid"]);
730 if (!$_SESSION["uid"] ||
!validate_session($link)) {
732 if (AUTH_AUTO_LOGIN
&& authenticate_user($link, null, null)) {
733 $_SESSION["ref_schema_version"] = get_schema_version($link, true);
735 authenticate_user($link, null, null, true);
738 if (!$_SESSION["uid"]) render_login_form($link, $login_form);
741 /* bump login timestamp */
742 db_query($link, "UPDATE ttrss_users SET last_login = NOW() WHERE id = " .
746 if ($_SESSION["uid"] && $_SESSION["language"] && SESSION_COOKIE_LIFETIME
> 0) {
747 setcookie("ttrss_lang", $_SESSION["language"],
748 time() + SESSION_COOKIE_LIFETIME
);
751 if ($_SESSION["uid"]) {
752 load_user_plugins($link, $_SESSION["uid"]);
757 function truncate_string($str, $max_len, $suffix = '…') {
758 if (mb_strlen($str, "utf-8") > $max_len - 3) {
759 return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
765 // Deprecated, TODO: remove
766 function theme_image($link, $filename) {
770 function convert_timestamp($timestamp, $source_tz, $dest_tz) {
773 $source_tz = new DateTimeZone($source_tz);
774 } catch (Exception
$e) {
775 $source_tz = new DateTimeZone('UTC');
779 $dest_tz = new DateTimeZone($dest_tz);
780 } catch (Exception
$e) {
781 $dest_tz = new DateTimeZone('UTC');
784 $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
785 return $dt->format('U') +
$dest_tz->getOffset($dt);
788 function make_local_datetime($link, $timestamp, $long, $owner_uid = false,
789 $no_smart_dt = false) {
791 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
792 if (!$timestamp) $timestamp = '1970-01-01 0:00';
797 # We store date in UTC internally
798 $dt = new DateTime($timestamp, $utc_tz);
800 if ($tz_offset == -1) {
802 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $owner_uid);
805 $user_tz = new DateTimeZone($user_tz_string);
806 } catch (Exception
$e) {
810 $tz_offset = $user_tz->getOffset($dt);
813 $user_timestamp = $dt->format('U') +
$tz_offset;
816 return smart_date_time($link, $user_timestamp,
817 $tz_offset, $owner_uid);
820 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
822 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
824 return date($format, $user_timestamp);
828 function smart_date_time($link, $timestamp, $tz_offset = 0, $owner_uid = false) {
829 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
831 if (date("Y.m.d", $timestamp) == date("Y.m.d", time() +
$tz_offset)) {
832 return date("G:i", $timestamp);
833 } else if (date("Y", $timestamp) == date("Y", time() +
$tz_offset)) {
834 $format = get_pref($link, 'SHORT_DATE_FORMAT', $owner_uid);
835 return date($format, $timestamp);
837 $format = get_pref($link, 'LONG_DATE_FORMAT', $owner_uid);
838 return date($format, $timestamp);
842 function sql_bool_to_bool($s) {
843 if ($s == "t" ||
$s == "1" ||
$s == "true") {
850 function bool_to_sql_bool($s) {
858 // Session caching removed due to causing wrong redirects to upgrade
859 // script when get_schema_version() is called on an obsolete session
860 // created on a previous schema version.
861 function get_schema_version($link, $nocache = false) {
862 global $schema_version;
864 if (!$schema_version) {
865 $result = db_query($link, "SELECT schema_version FROM ttrss_version");
866 $version = db_fetch_result($result, 0, "schema_version");
867 $schema_version = $version;
870 return $schema_version;
874 function sanity_check($link) {
875 require_once 'errors.php';
878 $schema_version = get_schema_version($link, true);
880 if ($schema_version != SCHEMA_VERSION
) {
884 if (DB_TYPE
== "mysql") {
885 $result = db_query($link, "SELECT true", false);
886 if (db_num_rows($result) != 1) {
891 if (db_escape_string("testTEST") != "testTEST") {
895 return array("code" => $error_code, "message" => $ERRORS[$error_code]);
898 function file_is_locked($filename) {
899 if (function_exists('flock')) {
900 $fp = @fopen
(LOCK_DIRECTORY
. "/$filename", "r");
902 if (flock($fp, LOCK_EX | LOCK_NB
)) {
913 return true; // consider the file always locked and skip the test
916 function make_lockfile($filename) {
917 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
919 if (flock($fp, LOCK_EX | LOCK_NB
)) {
920 if (function_exists('posix_getpid')) {
921 fwrite($fp, posix_getpid() . "\n");
929 function make_stampfile($filename) {
930 $fp = fopen(LOCK_DIRECTORY
. "/$filename", "w");
932 if (flock($fp, LOCK_EX | LOCK_NB
)) {
933 fwrite($fp, time() . "\n");
942 function sql_random_function() {
943 if (DB_TYPE
== "mysql") {
950 function catchup_feed($link, $feed, $cat_view, $owner_uid = false, $max_id = false) {
952 if (!$owner_uid) $owner_uid = $_SESSION['uid'];
954 //if (preg_match("/^-?[0-9][0-9]*$/", $feed) != false) {
956 $ref_check_qpart = ($max_id &&
957 !get_pref($link, 'REVERSE_HEADLINES')) ?
"ref_id <= '$max_id'" : "true";
959 if (is_numeric($feed)) {
965 $children = getChildCategories($link, $feed, $owner_uid);
966 array_push($children, $feed);
968 $children = join(",", $children);
970 $cat_qpart = "cat_id IN ($children)";
972 $cat_qpart = "cat_id IS NULL";
975 db_query($link, "UPDATE ttrss_user_entries
976 SET unread = false,last_read = NOW()
977 WHERE feed_id IN (SELECT id FROM ttrss_feeds WHERE $cat_qpart)
979 AND owner_uid = $owner_uid");
981 } else if ($feed == -2) {
983 db_query($link, "UPDATE ttrss_user_entries
984 SET unread = false,last_read = NOW() WHERE (SELECT COUNT(*)
985 FROM ttrss_user_labels2 WHERE article_id = ref_id) > 0
987 AND unread = true AND owner_uid = $owner_uid");
990 } else if ($feed > 0) {
992 db_query($link, "UPDATE ttrss_user_entries
993 SET unread = false,last_read = NOW()
994 WHERE feed_id = '$feed'
996 AND owner_uid = $owner_uid");
998 } else if ($feed < 0 && $feed > -10) { // special, like starred
1001 db_query($link, "UPDATE ttrss_user_entries
1002 SET unread = false,last_read = NOW()
1004 AND $ref_check_qpart
1005 AND owner_uid = $owner_uid");
1009 db_query($link, "UPDATE ttrss_user_entries
1010 SET unread = false,last_read = NOW()
1011 WHERE published = true
1012 AND $ref_check_qpart
1013 AND owner_uid = $owner_uid");
1018 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE");
1020 if (DB_TYPE
== "pgsql") {
1021 $match_part = "updated > NOW() - INTERVAL '$intl hour' ";
1023 $match_part = "updated > DATE_SUB(NOW(),
1024 INTERVAL $intl HOUR) ";
1027 $result = db_query($link, "SELECT id FROM ttrss_entries,
1028 ttrss_user_entries WHERE $match_part AND
1030 ttrss_user_entries.ref_id = ttrss_entries.id AND
1031 owner_uid = $owner_uid");
1033 $affected_ids = array();
1035 while ($line = db_fetch_assoc($result)) {
1036 array_push($affected_ids, $line["id"]);
1039 catchupArticlesById($link, $affected_ids, 0);
1043 db_query($link, "UPDATE ttrss_user_entries
1044 SET unread = false,last_read = NOW()
1045 WHERE $ref_check_qpart AND owner_uid = $owner_uid");
1048 } else if ($feed < -10) { // label
1050 $label_id = -$feed - 11;
1052 db_query($link, "UPDATE ttrss_user_entries, ttrss_user_labels2
1053 SET unread = false, last_read = NOW()
1054 WHERE label_id = '$label_id' AND unread = true
1055 AND $ref_check_qpart
1056 AND owner_uid = '$owner_uid' AND ref_id = article_id");
1060 ccache_update($link, $feed, $owner_uid, $cat_view);
1063 db_query($link, "BEGIN");
1065 $tag_name = db_escape_string($feed);
1067 $result = db_query($link, "SELECT post_int_id FROM ttrss_tags
1068 WHERE tag_name = '$tag_name' AND owner_uid = $owner_uid");
1070 while ($line = db_fetch_assoc($result)) {
1071 db_query($link, "UPDATE ttrss_user_entries SET
1072 unread = false, last_read = NOW()
1073 WHERE $ref_check_qpart AND int_id = " . $line["post_int_id"]);
1075 db_query($link, "COMMIT");
1079 function getAllCounters($link) {
1080 $data = getGlobalCounters($link);
1082 $data = array_merge($data, getVirtCounters($link));
1083 $data = array_merge($data, getLabelCounters($link));
1084 $data = array_merge($data, getFeedCounters($link, $active_feed));
1085 $data = array_merge($data, getCategoryCounters($link));
1090 function getCategoryTitle($link, $cat_id) {
1092 if ($cat_id == -1) {
1093 return __("Special");
1094 } else if ($cat_id == -2) {
1095 return __("Labels");
1098 $result = db_query($link, "SELECT title FROM ttrss_feed_categories WHERE
1101 if (db_num_rows($result) == 1) {
1102 return db_fetch_result($result, 0, "title");
1104 return __("Uncategorized");
1110 function getCategoryCounters($link) {
1113 /* Labels category */
1115 $cv = array("id" => -2, "kind" => "cat",
1116 "counter" => getCategoryUnread($link, -2));
1118 array_push($ret_arr, $cv);
1120 $result = db_query($link, "SELECT id AS cat_id, value AS unread,
1121 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2
1122 WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children
1123 FROM ttrss_feed_categories, ttrss_cat_counters_cache
1124 WHERE ttrss_cat_counters_cache.feed_id = id AND
1125 ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND
1126 ttrss_feed_categories.owner_uid = " . $_SESSION["uid"]);
1128 while ($line = db_fetch_assoc($result)) {
1129 $line["cat_id"] = (int) $line["cat_id"];
1131 if ($line["num_children"] > 0) {
1132 $child_counter = getCategoryChildrenUnread($link, $line["cat_id"], $_SESSION["uid"]);
1137 $cv = array("id" => $line["cat_id"], "kind" => "cat",
1138 "counter" => $line["unread"] +
$child_counter);
1140 array_push($ret_arr, $cv);
1143 /* Special case: NULL category doesn't actually exist in the DB */
1145 $cv = array("id" => 0, "kind" => "cat",
1146 "counter" => (int) ccache_find($link, 0, $_SESSION["uid"], true));
1148 array_push($ret_arr, $cv);
1153 // only accepts real cats (>= 0)
1154 function getCategoryChildrenUnread($link, $cat, $owner_uid = false) {
1155 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1157 $result = db_query($link, "SELECT id FROM ttrss_feed_categories WHERE parent_cat = '$cat'
1158 AND owner_uid = $owner_uid");
1162 while ($line = db_fetch_assoc($result)) {
1163 $unread +
= getCategoryUnread($link, $line["id"], $owner_uid);
1164 $unread +
= getCategoryChildrenUnread($link, $line["id"], $owner_uid);
1170 function getCategoryUnread($link, $cat, $owner_uid = false) {
1172 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1177 $cat_query = "cat_id = '$cat'";
1179 $cat_query = "cat_id IS NULL";
1182 $result = db_query($link, "SELECT id FROM ttrss_feeds WHERE $cat_query
1183 AND owner_uid = " . $owner_uid);
1185 $cat_feeds = array();
1186 while ($line = db_fetch_assoc($result)) {
1187 array_push($cat_feeds, "feed_id = " . $line["id"]);
1190 if (count($cat_feeds) == 0) return 0;
1192 $match_part = implode(" OR ", $cat_feeds);
1194 $result = db_query($link, "SELECT COUNT(int_id) AS unread
1195 FROM ttrss_user_entries
1196 WHERE unread = true AND ($match_part)
1197 AND owner_uid = " . $owner_uid);
1201 # this needs to be rewritten
1202 while ($line = db_fetch_assoc($result)) {
1203 $unread +
= $line["unread"];
1207 } else if ($cat == -1) {
1208 return getFeedUnread($link, -1) +
getFeedUnread($link, -2) +
getFeedUnread($link, -3) +
getFeedUnread($link, 0);
1209 } else if ($cat == -2) {
1211 $result = db_query($link, "
1212 SELECT COUNT(unread) AS unread FROM
1213 ttrss_user_entries, ttrss_user_labels2
1214 WHERE article_id = ref_id AND unread = true
1215 AND ttrss_user_entries.owner_uid = '$owner_uid'");
1217 $unread = db_fetch_result($result, 0, "unread");
1224 function getFeedUnread($link, $feed, $is_cat = false) {
1225 return getFeedArticles($link, $feed, $is_cat, true, $_SESSION["uid"]);
1228 function getLabelUnread($link, $label_id, $owner_uid = false) {
1229 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1231 $result = db_query($link, "SELECT COUNT(ref_id) AS unread FROM ttrss_user_entries, ttrss_user_labels2
1232 WHERE owner_uid = '$owner_uid' AND unread = true AND label_id = '$label_id' AND article_id = ref_id");
1234 if (db_num_rows($result) != 0) {
1235 return db_fetch_result($result, 0, "unread");
1241 function getFeedArticles($link, $feed, $is_cat = false, $unread_only = false,
1242 $owner_uid = false) {
1244 $n_feed = (int) $feed;
1245 $need_entries = false;
1247 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
1250 $unread_qpart = "unread = true";
1252 $unread_qpart = "true";
1256 return getCategoryUnread($link, $n_feed, $owner_uid);
1257 } else if ($n_feed == -6) {
1259 } else if ($feed != "0" && $n_feed == 0) {
1261 $feed = db_escape_string($feed);
1263 $result = db_query($link, "SELECT SUM((SELECT COUNT(int_id)
1264 FROM ttrss_user_entries,ttrss_entries WHERE int_id = post_int_id
1265 AND ref_id = id AND $unread_qpart)) AS count FROM ttrss_tags
1266 WHERE owner_uid = $owner_uid AND tag_name = '$feed'");
1267 return db_fetch_result($result, 0, "count");
1269 } else if ($n_feed == -1) {
1270 $match_part = "marked = true";
1271 } else if ($n_feed == -2) {
1272 $match_part = "published = true";
1273 } else if ($n_feed == -3) {
1274 $match_part = "unread = true AND score >= 0";
1276 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
1278 if (DB_TYPE
== "pgsql") {
1279 $match_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
1281 $match_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
1284 $need_entries = true;
1286 } else if ($n_feed == -4) {
1287 $match_part = "true";
1288 } else if ($n_feed >= 0) {
1291 $match_part = "feed_id = '$n_feed'";
1293 $match_part = "feed_id IS NULL";
1296 } else if ($feed < -10) {
1298 $label_id = -$feed - 11;
1300 return getLabelUnread($link, $label_id, $owner_uid);
1306 if ($need_entries) {
1307 $from_qpart = "ttrss_user_entries,ttrss_entries";
1308 $from_where = "ttrss_entries.id = ttrss_user_entries.ref_id AND";
1310 $from_qpart = "ttrss_user_entries";
1313 $query = "SELECT count(int_id) AS unread
1314 FROM $from_qpart WHERE
1315 $unread_qpart AND $from_where ($match_part) AND ttrss_user_entries.owner_uid = $owner_uid";
1317 //echo "[$feed/$query]\n";
1319 $result = db_query($link, $query);
1323 $result = db_query($link, "SELECT COUNT(post_int_id) AS unread
1324 FROM ttrss_tags,ttrss_user_entries,ttrss_entries
1325 WHERE tag_name = '$feed' AND post_int_id = int_id AND ref_id = ttrss_entries.id
1326 AND $unread_qpart AND ttrss_tags.owner_uid = " . $owner_uid);
1329 $unread = db_fetch_result($result, 0, "unread");
1334 function getGlobalUnread($link, $user_id = false) {
1337 $user_id = $_SESSION["uid"];
1340 $result = db_query($link, "SELECT SUM(value) AS c_id FROM ttrss_counters_cache
1341 WHERE owner_uid = '$user_id' AND feed_id > 0");
1343 $c_id = db_fetch_result($result, 0, "c_id");
1348 function getGlobalCounters($link, $global_unread = -1) {
1351 if ($global_unread == -1) {
1352 $global_unread = getGlobalUnread($link);
1355 $cv = array("id" => "global-unread",
1356 "counter" => (int) $global_unread);
1358 array_push($ret_arr, $cv);
1360 $result = db_query($link, "SELECT COUNT(id) AS fn FROM
1361 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1363 $subscribed_feeds = db_fetch_result($result, 0, "fn");
1365 $cv = array("id" => "subscribed-feeds",
1366 "counter" => (int) $subscribed_feeds);
1368 array_push($ret_arr, $cv);
1373 function getVirtCounters($link) {
1377 for ($i = 0; $i >= -4; $i--) {
1379 $count = getFeedUnread($link, $i);
1381 $cv = array("id" => $i,
1382 "counter" => (int) $count);
1384 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1385 // $cv["xmsg"] = getFeedArticles($link, $i)." ".__("total");
1387 array_push($ret_arr, $cv);
1393 function getLabelCounters($link, $descriptions = false) {
1397 $owner_uid = $_SESSION["uid"];
1399 $result = db_query($link, "SELECT id, caption FROM ttrss_labels2
1400 WHERE owner_uid = '$owner_uid'");
1402 while ($line = db_fetch_assoc($result)) {
1404 $id = -$line["id"] - 11;
1406 $label_name = $line["caption"];
1407 $count = getFeedUnread($link, $id);
1409 $cv = array("id" => $id,
1410 "counter" => (int) $count);
1413 $cv["description"] = $label_name;
1415 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1416 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1418 array_push($ret_arr, $cv);
1424 function getFeedCounters($link, $active_feed = false) {
1428 $query = "SELECT ttrss_feeds.id,
1430 ".SUBSTRING_FOR_DATE
."(ttrss_feeds.last_updated,1,19) AS last_updated,
1431 last_error, value AS count
1432 FROM ttrss_feeds, ttrss_counters_cache
1433 WHERE ttrss_feeds.owner_uid = ".$_SESSION["uid"]."
1434 AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid
1435 AND ttrss_counters_cache.feed_id = id";
1437 $result = db_query($link, $query);
1438 $fctrs_modified = false;
1440 while ($line = db_fetch_assoc($result)) {
1443 $count = $line["count"];
1444 $last_error = htmlspecialchars($line["last_error"]);
1446 $last_updated = make_local_datetime($link, $line['last_updated'], false);
1448 $has_img = feed_has_icon($id);
1450 if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2)
1453 $cv = array("id" => $id,
1454 "updated" => $last_updated,
1455 "counter" => (int) $count,
1456 "has_img" => (int) $has_img);
1459 $cv["error"] = $last_error;
1461 // if (get_pref($link, 'EXTENDED_FEEDLIST'))
1462 // $cv["xmsg"] = getFeedArticles($link, $id)." ".__("total");
1464 if ($active_feed && $id == $active_feed)
1465 $cv["title"] = truncate_string($line["title"], 30);
1467 array_push($ret_arr, $cv);
1474 function get_pgsql_version($link) {
1475 $result = db_query($link, "SELECT version() AS version");
1476 $version = explode(" ", db_fetch_result($result, 0, "version"));
1481 * @return array (code => Status code, message => error message if available)
1483 * 0 - OK, Feed already exists
1484 * 1 - OK, Feed added
1486 * 3 - URL content is HTML, no feeds available
1487 * 4 - URL content is HTML which contains multiple feeds.
1488 * Here you should call extractfeedurls in rpc-backend
1489 * to get all possible feeds.
1490 * 5 - Couldn't download the URL content.
1492 function subscribe_to_feed($link, $url, $cat_id = 0,
1493 $auth_login = '', $auth_pass = '', $need_auth = false) {
1495 global $fetch_last_error;
1497 require_once "include/rssfuncs.php";
1499 $url = fix_url($url);
1501 if (!$url ||
!validate_feed_url($url)) return array("code" => 2);
1503 $contents = @fetch_file_contents
($url, false, $auth_login, $auth_pass);
1506 return array("code" => 5, "message" => $fetch_last_error);
1509 if (is_html($contents)) {
1510 $feedUrls = get_feeds_from_html($url, $contents);
1512 if (count($feedUrls) == 0) {
1513 return array("code" => 3);
1514 } else if (count($feedUrls) > 1) {
1515 return array("code" => 4, "feeds" => $feedUrls);
1517 //use feed url as new URL
1518 $url = key($feedUrls);
1521 if ($cat_id == "0" ||
!$cat_id) {
1522 $cat_qpart = "NULL";
1524 $cat_qpart = "'$cat_id'";
1527 $result = db_query($link,
1528 "SELECT id FROM ttrss_feeds
1529 WHERE feed_url = '$url' AND owner_uid = ".$_SESSION["uid"]);
1531 if (db_num_rows($result) == 0) {
1532 $result = db_query($link,
1533 "INSERT INTO ttrss_feeds
1534 (owner_uid,feed_url,title,cat_id, auth_login,auth_pass,update_method)
1535 VALUES ('".$_SESSION["uid"]."', '$url',
1536 '[Unknown]', $cat_qpart, '$auth_login', '$auth_pass', 0)");
1538 $result = db_query($link,
1539 "SELECT id FROM ttrss_feeds WHERE feed_url = '$url'
1540 AND owner_uid = " . $_SESSION["uid"]);
1542 $feed_id = db_fetch_result($result, 0, "id");
1545 update_rss_feed($link, $feed_id, true);
1548 return array("code" => 1);
1550 return array("code" => 0);
1554 function print_feed_select($link, $id, $default_id = "",
1555 $attributes = "", $include_all_feeds = true,
1556 $root_id = false, $nest_level = 0) {
1559 print "<select id=\"$id\" name=\"$id\" $attributes>";
1560 if ($include_all_feeds) {
1561 $is_selected = ("0" == $default_id) ?
"selected=\"1\"" : "";
1562 print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
1566 if (get_pref($link, 'ENABLE_FEED_CATS')) {
1569 $parent_qpart = "parent_cat = '$root_id'";
1571 $parent_qpart = "parent_cat IS NULL";
1573 $result = db_query($link, "SELECT id,title,
1574 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1575 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1576 FROM ttrss_feed_categories
1577 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1579 while ($line = db_fetch_assoc($result)) {
1581 for ($i = 0; $i < $nest_level; $i++
)
1582 $line["title"] = " - " . $line["title"];
1584 $is_selected = ("CAT:".$line["id"] == $default_id) ?
"selected=\"1\"" : "";
1586 printf("<option $is_selected value='CAT:%d'>%s</option>",
1587 $line["id"], htmlspecialchars($line["title"]));
1589 if ($line["num_children"] > 0)
1590 print_feed_select($link, $id, $default_id, $attributes,
1591 $include_all_feeds, $line["id"], $nest_level+
1);
1593 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1594 WHERE cat_id = '".$line["id"]."' AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1596 while ($fline = db_fetch_assoc($feed_result)) {
1597 $is_selected = ($fline["id"] == $default_id) ?
"selected=\"1\"" : "";
1599 $fline["title"] = " + " . $fline["title"];
1601 for ($i = 0; $i < $nest_level; $i++
)
1602 $fline["title"] = " - " . $fline["title"];
1604 printf("<option $is_selected value='%d'>%s</option>",
1605 $fline["id"], htmlspecialchars($fline["title"]));
1610 $is_selected = ($default_id == "CAT:0") ?
"selected=\"1\"" : "";
1612 printf("<option $is_selected value='CAT:0'>%s</option>",
1613 __("Uncategorized"));
1615 $feed_result = db_query($link, "SELECT id,title FROM ttrss_feeds
1616 WHERE cat_id IS NULL AND owner_uid = ".$_SESSION["uid"] . " ORDER BY title");
1618 while ($fline = db_fetch_assoc($feed_result)) {
1619 $is_selected = ($fline["id"] == $default_id && !$default_is_cat) ?
"selected=\"1\"" : "";
1621 $fline["title"] = " + " . $fline["title"];
1623 for ($i = 0; $i < $nest_level; $i++
)
1624 $fline["title"] = " - " . $fline["title"];
1626 printf("<option $is_selected value='%d'>%s</option>",
1627 $fline["id"], htmlspecialchars($fline["title"]));
1632 $result = db_query($link, "SELECT id,title FROM ttrss_feeds
1633 WHERE owner_uid = ".$_SESSION["uid"]." ORDER BY title");
1635 while ($line = db_fetch_assoc($result)) {
1637 $is_selected = ($line["id"] == $default_id) ?
"selected=\"1\"" : "";
1639 printf("<option $is_selected value='%d'>%s</option>",
1640 $line["id"], htmlspecialchars($line["title"]));
1649 function print_feed_cat_select($link, $id, $default_id,
1650 $attributes, $include_all_cats = true, $root_id = false, $nest_level = 0) {
1653 print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" onchange=\"catSelectOnChange(this)\" $attributes>";
1657 $parent_qpart = "parent_cat = '$root_id'";
1659 $parent_qpart = "parent_cat IS NULL";
1661 $result = db_query($link, "SELECT id,title,
1662 (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
1663 c2.parent_cat = ttrss_feed_categories.id) AS num_children
1664 FROM ttrss_feed_categories
1665 WHERE owner_uid = ".$_SESSION["uid"]." AND $parent_qpart ORDER BY title");
1667 while ($line = db_fetch_assoc($result)) {
1668 if ($line["id"] == $default_id) {
1669 $is_selected = "selected=\"1\"";
1674 for ($i = 0; $i < $nest_level; $i++
)
1675 $line["title"] = " - " . $line["title"];
1678 printf("<option $is_selected value='%d'>%s</option>",
1679 $line["id"], htmlspecialchars($line["title"]));
1681 if ($line["num_children"] > 0)
1682 print_feed_cat_select($link, $id, $default_id, $attributes,
1683 $include_all_cats, $line["id"], $nest_level+
1);
1687 if ($include_all_cats) {
1688 if (db_num_rows($result) > 0) {
1689 print "<option disabled=\"1\">--------</option>";
1692 if ($default_id == 0) {
1693 $is_selected = "selected=\"1\"";
1698 print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
1704 function checkbox_to_sql_bool($val) {
1705 return ($val == "on") ?
"true" : "false";
1708 function getFeedCatTitle($link, $id) {
1710 return __("Special");
1711 } else if ($id < -10) {
1712 return __("Labels");
1713 } else if ($id > 0) {
1714 $result = db_query($link, "SELECT ttrss_feed_categories.title
1715 FROM ttrss_feeds, ttrss_feed_categories WHERE ttrss_feeds.id = '$id' AND
1716 cat_id = ttrss_feed_categories.id");
1717 if (db_num_rows($result) == 1) {
1718 return db_fetch_result($result, 0, "title");
1720 return __("Uncategorized");
1723 return "getFeedCatTitle($id) failed";
1728 function getFeedIcon($id) {
1731 return "images/archive.png";
1734 return "images/mark_set.svg";
1737 return "images/pub_set.svg";
1740 return "images/fresh.png";
1743 return "images/tag.png";
1746 return "images/recently_read.png";
1750 return "images/label.png";
1752 if (file_exists(ICONS_DIR
. "/$id.ico"))
1753 return ICONS_URL
. "/$id.ico";
1759 function getFeedTitle($link, $id, $cat = false) {
1761 return getCategoryTitle($link, $id);
1762 } else if ($id == -1) {
1763 return __("Starred articles");
1764 } else if ($id == -2) {
1765 return __("Published articles");
1766 } else if ($id == -3) {
1767 return __("Fresh articles");
1768 } else if ($id == -4) {
1769 return __("All articles");
1770 } else if ($id === 0 ||
$id === "0") {
1771 return __("Archived articles");
1772 } else if ($id == -6) {
1773 return __("Recently read");
1774 } else if ($id < -10) {
1775 $label_id = -$id - 11;
1776 $result = db_query($link, "SELECT caption FROM ttrss_labels2 WHERE id = '$label_id'");
1777 if (db_num_rows($result) == 1) {
1778 return db_fetch_result($result, 0, "caption");
1780 return "Unknown label ($label_id)";
1783 } else if (is_numeric($id) && $id > 0) {
1784 $result = db_query($link, "SELECT title FROM ttrss_feeds WHERE id = '$id'");
1785 if (db_num_rows($result) == 1) {
1786 return db_fetch_result($result, 0, "title");
1788 return "Unknown feed ($id)";
1795 function make_init_params($link) {
1798 $params["sign_progress"] = theme_image($link, "images/indicator_white.gif");
1799 $params["sign_progress_tiny"] = theme_image($link, "images/indicator_tiny.gif");
1800 $params["sign_excl"] = theme_image($link, "images/sign_excl.svg");
1801 $params["sign_info"] = theme_image($link, "images/sign_info.svg");
1803 foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
1804 "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
1805 "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE", "DEFAULT_ARTICLE_LIMIT",
1806 "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
1808 $params[strtolower($param)] = (int) get_pref($link, $param);
1811 $params["icons_url"] = ICONS_URL
;
1812 $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME
;
1813 $params["default_view_mode"] = get_pref($link, "_DEFAULT_VIEW_MODE");
1814 $params["default_view_limit"] = (int) get_pref($link, "_DEFAULT_VIEW_LIMIT");
1815 $params["default_view_order_by"] = get_pref($link, "_DEFAULT_VIEW_ORDER_BY");
1816 $params["bw_limit"] = (int) $_SESSION["bw_limit"];
1818 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1819 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1821 $max_feed_id = db_fetch_result($result, 0, "mid");
1822 $num_feeds = db_fetch_result($result, 0, "nf");
1824 $params["max_feed_id"] = (int) $max_feed_id;
1825 $params["num_feeds"] = (int) $num_feeds;
1827 $params["collapsed_feedlist"] = (int) get_pref($link, "_COLLAPSED_FEEDLIST");
1828 $params["hotkeys"] = get_hotkeys_map($link);
1830 $params["csrf_token"] = $_SESSION["csrf_token"];
1831 $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
1833 $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE
;
1838 function get_hotkeys_info($link) {
1840 __("Navigation") => array(
1841 "next_feed" => __("Open next feed"),
1842 "prev_feed" => __("Open previous feed"),
1843 "next_article" => __("Open next article"),
1844 "prev_article" => __("Open previous article"),
1845 "search_dialog" => __("Show search dialog")),
1846 __("Article") => array(
1847 "toggle_mark" => __("Toggle starred"),
1848 "toggle_publ" => __("Toggle published"),
1849 "toggle_unread" => __("Toggle unread"),
1850 "edit_tags" => __("Edit tags"),
1851 "dismiss_selected" => __("Dismiss selected"),
1852 "dismiss_read" => __("Dismiss read"),
1853 "open_in_new_window" => __("Open in new window"),
1854 "catchup_below" => __("Mark below as read"),
1855 "catchup_above" => __("Mark above as read"),
1856 "article_scroll_down" => __("Scroll down"),
1857 "article_scroll_up" => __("Scroll up"),
1858 "select_article_cursor" => __("Select article under cursor"),
1859 "email_article" => __("Email article"),
1860 "close_article" => __("Close article"),
1861 "toggle_widescreen" => __("Toggle widescreen mode")),
1862 __("Article selection") => array(
1863 "select_all" => __("Select all articles"),
1864 "select_unread" => __("Select unread"),
1865 "select_marked" => __("Select starred"),
1866 "select_published" => __("Select published"),
1867 "select_invert" => __("Invert selection"),
1868 "select_none" => __("Deselect everything")),
1869 __("Feed") => array(
1870 "feed_refresh" => __("Refresh current feed"),
1871 "feed_unhide_read" => __("Un/hide read feeds"),
1872 "feed_subscribe" => __("Subscribe to feed"),
1873 "feed_edit" => __("Edit feed"),
1874 "feed_catchup" => __("Mark as read"),
1875 "feed_reverse" => __("Reverse headlines"),
1876 "feed_debug_update" => __("Debug feed update"),
1877 "catchup_all" => __("Mark all feeds as read"),
1878 "cat_toggle_collapse" => __("Un/collapse current category")),
1879 __("Go to") => array(
1880 "goto_all" => __("All articles"),
1881 "goto_fresh" => __("Fresh"),
1882 "goto_marked" => __("Starred"),
1883 "goto_published" => __("Published"),
1884 "goto_tagcloud" => __("Tag cloud"),
1885 "goto_prefs" => __("Preferences")),
1886 __("Other") => array(
1887 "create_label" => __("Create label"),
1888 "create_filter" => __("Create filter"),
1889 "collapse_sidebar" => __("Un/collapse sidebar"),
1890 "help_dialog" => __("Show help dialog"))
1896 function get_hotkeys_map($link) {
1898 // "navigation" => array(
1901 "n" => "next_article",
1902 "p" => "prev_article",
1903 "(38)|up" => "prev_article",
1904 "(40)|down" => "next_article",
1905 "(191)|/" => "search_dialog",
1906 // "article" => array(
1907 "s" => "toggle_mark",
1908 "S" => "toggle_publ",
1909 "u" => "toggle_unread",
1911 "D" => "dismiss_selected",
1912 "X" => "dismiss_read",
1913 "o" => "open_in_new_window",
1914 "c p" => "catchup_below",
1915 "c n" => "catchup_above",
1916 "N" => "article_scroll_down",
1917 "P" => "article_scroll_up",
1918 "a W" => "toggle_widescreen",
1919 "e" => "email_article",
1920 "a q" => "close_article",
1921 // "article_selection" => array(
1922 "a a" => "select_all",
1923 "a u" => "select_unread",
1924 "a U" => "select_marked",
1925 "a p" => "select_published",
1926 "a i" => "select_invert",
1927 "a n" => "select_none",
1929 "f r" => "feed_refresh",
1930 "f a" => "feed_unhide_read",
1931 "f s" => "feed_subscribe",
1932 "f e" => "feed_edit",
1933 "f q" => "feed_catchup",
1934 "f x" => "feed_reverse",
1935 "f D" => "feed_debug_update",
1936 "Q" => "catchup_all",
1937 "x" => "cat_toggle_collapse",
1939 "g a" => "goto_all",
1940 "g f" => "goto_fresh",
1941 "g s" => "goto_marked",
1942 "g p" => "goto_published",
1943 "g t" => "goto_tagcloud",
1944 "g P" => "goto_prefs",
1945 // "other" => array(
1946 "(9)|Tab" => "select_article_cursor", // tab
1947 "c l" => "create_label",
1948 "c f" => "create_filter",
1949 "c s" => "collapse_sidebar",
1950 "^(191)|Ctrl+/" => "help_dialog",
1954 foreach ($pluginhost->get_hooks($pluginhost::HOOK_HOTKEY_MAP
) as $plugin) {
1955 $hotkeys = $plugin->hook_hotkey_map($hotkeys);
1958 $prefixes = array();
1960 foreach (array_keys($hotkeys) as $hotkey) {
1961 $pair = explode(" ", $hotkey, 2);
1963 if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
1964 array_push($prefixes, $pair[0]);
1968 return array($prefixes, $hotkeys);
1971 function make_runtime_info($link) {
1974 $result = db_query($link, "SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
1975 ttrss_feeds WHERE owner_uid = " . $_SESSION["uid"]);
1977 $max_feed_id = db_fetch_result($result, 0, "mid");
1978 $num_feeds = db_fetch_result($result, 0, "nf");
1980 $data["max_feed_id"] = (int) $max_feed_id;
1981 $data["num_feeds"] = (int) $num_feeds;
1983 $data['last_article_id'] = getLastArticleId($link);
1984 $data['cdm_expanded'] = get_pref($link, 'CDM_EXPANDED');
1986 if (file_exists(LOCK_DIRECTORY
. "/update_daemon.lock")) {
1988 $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
1990 if (time() - $_SESSION["daemon_stamp_check"] > 30) {
1992 $stamp = (int) @file_get_contents
(LOCK_DIRECTORY
. "/update_daemon.stamp");
1995 $stamp_delta = time() - $stamp;
1997 if ($stamp_delta > 1800) {
2001 $_SESSION["daemon_stamp_check"] = time();
2004 $data['daemon_stamp_ok'] = $stamp_check;
2006 $stamp_fmt = date("Y.m.d, G:i", $stamp);
2008 $data['daemon_stamp'] = $stamp_fmt;
2013 if ($_SESSION["last_version_check"] +
86400 +
rand(-1000, 1000) < time()) {
2014 $new_version_details = @check_for_update
($link);
2016 $data['new_version_available'] = (int) ($new_version_details != false);
2018 $_SESSION["last_version_check"] = time();
2019 $_SESSION["version_data"] = $new_version_details;
2025 function search_to_sql($link, $search, $match_on) {
2027 $search_query_part = "";
2029 $keywords = explode(" ", $search);
2030 $query_keywords = array();
2032 foreach ($keywords as $k) {
2033 if (strpos($k, "-") === 0) {
2040 $commandpair = explode(":", mb_strtolower($k), 2);
2042 if ($commandpair[0] == "note" && $commandpair[1]) {
2044 if ($commandpair[1] == "true")
2045 array_push($query_keywords, "($not (note IS NOT NULL AND note != ''))");
2047 array_push($query_keywords, "($not (note IS NULL OR note = ''))");
2049 } else if ($commandpair[0] == "star" && $commandpair[1]) {
2051 if ($commandpair[1] == "true")
2052 array_push($query_keywords, "($not (marked = true))");
2054 array_push($query_keywords, "($not (marked = false))");
2056 } else if ($commandpair[0] == "pub" && $commandpair[1]) {
2058 if ($commandpair[1] == "true")
2059 array_push($query_keywords, "($not (published = true))");
2061 array_push($query_keywords, "($not (published = false))");
2063 } else if (strpos($k, "@") === 0) {
2065 $user_tz_string = get_pref($link, 'USER_TIMEZONE', $_SESSION['uid']);
2066 $orig_ts = strtotime(substr($k, 1));
2067 $k = date("Y-m-d", convert_timestamp($orig_ts, $user_tz_string, 'UTC'));
2069 //$k = date("Y-m-d", strtotime(substr($k, 1)));
2071 array_push($query_keywords, "(".SUBSTRING_FOR_DATE
."(updated,1,LENGTH('$k')) $not = '$k')");
2072 } else if ($match_on == "both") {
2073 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%')
2074 OR UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2075 } else if ($match_on == "title") {
2076 array_push($query_keywords, "(UPPER(ttrss_entries.title) $not LIKE UPPER('%$k%'))");
2077 } else if ($match_on == "content") {
2078 array_push($query_keywords, "(UPPER(ttrss_entries.content) $not LIKE UPPER('%$k%'))");
2082 $search_query_part = implode("AND", $query_keywords);
2084 return $search_query_part;
2087 function getParentCategories($link, $cat, $owner_uid) {
2090 $result = db_query($link, "SELECT parent_cat FROM ttrss_feed_categories
2091 WHERE id = '$cat' AND parent_cat IS NOT NULL AND owner_uid = $owner_uid");
2093 while ($line = db_fetch_assoc($result)) {
2094 array_push($rv, $line["parent_cat"]);
2095 $rv = array_merge($rv, getParentCategories($link, $line["parent_cat"], $owner_uid));
2101 function getChildCategories($link, $cat, $owner_uid) {
2104 $result = db_query($link, "SELECT id FROM ttrss_feed_categories
2105 WHERE parent_cat = '$cat' AND owner_uid = $owner_uid");
2107 while ($line = db_fetch_assoc($result)) {
2108 array_push($rv, $line["id"]);
2109 $rv = array_merge($rv, getChildCategories($link, $line["id"], $owner_uid));
2115 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, $include_children = false, $ignore_vfeed_group = false) {
2117 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2119 $ext_tables_part = "";
2123 if (SPHINX_ENABLED
) {
2124 $ids = join(",", @sphinx_search
($search, 0, 500));
2127 $search_query_part = "ref_id IN ($ids) AND ";
2129 $search_query_part = "ref_id = -1 AND ";
2132 $search_query_part = search_to_sql($link, $search, $match_on);
2133 $search_query_part .= " AND ";
2137 $search_query_part = "";
2142 if (DB_TYPE
== "pgsql") {
2143 $query_strategy_part .= " AND updated > NOW() - INTERVAL '14 days' ";
2145 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL 14 DAY) ";
2148 $override_order = "updated DESC";
2150 $filter_query_part = filter_to_sql($link, $filter, $owner_uid);
2152 // Try to check if SQL regexp implementation chokes on a valid regexp
2153 $result = db_query($link, "SELECT true AS true_val FROM ttrss_entries,
2154 ttrss_user_entries, ttrss_feeds, ttrss_feed_categories
2155 WHERE $filter_query_part LIMIT 1", false);
2158 $test = db_fetch_result($result, 0, "true_val");
2161 $filter_query_part = "false AND";
2163 $filter_query_part .= " AND";
2166 $filter_query_part = "false AND";
2170 $filter_query_part = "";
2174 $since_id_part = "ttrss_entries.id > $since_id AND ";
2176 $since_id_part = "";
2179 $view_query_part = "";
2181 if ($view_mode == "adaptive" ||
$view_query_part == "noscores") {
2183 $view_query_part = " ";
2184 } else if ($feed != -1) {
2185 $unread = getFeedUnread($link, $feed, $cat_view);
2187 if ($cat_view && $feed > 0 && $include_children)
2188 $unread +
= getCategoryChildrenUnread($link, $feed);
2191 $view_query_part = " unread = true AND ";
2196 if ($view_mode == "marked") {
2197 $view_query_part = " marked = true AND ";
2200 if ($view_mode == "published") {
2201 $view_query_part = " published = true AND ";
2204 if ($view_mode == "unread") {
2205 $view_query_part = " unread = true AND ";
2208 if ($view_mode == "updated") {
2209 $view_query_part = " (last_read is null and unread = false) AND ";
2213 $limit_query_part = "LIMIT " . $limit;
2216 $allow_archived = false;
2218 $vfeed_query_part = "";
2220 // override query strategy and enable feed display when searching globally
2221 if ($search && $search_mode == "all_feeds") {
2222 $query_strategy_part = "true";
2223 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2225 } else if (!is_numeric($feed)) {
2226 $query_strategy_part = "true";
2227 $vfeed_query_part = "(SELECT title FROM ttrss_feeds WHERE
2228 id = feed_id) as feed_title,";
2229 } else if ($search && $search_mode == "this_cat") {
2230 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2233 if ($include_children) {
2234 $subcats = getChildCategories($link, $feed, $owner_uid);
2235 array_push($subcats, $feed);
2236 $cats_qpart = join(",", $subcats);
2238 $cats_qpart = $feed;
2241 $query_strategy_part = "ttrss_feeds.cat_id IN ($cats_qpart)";
2244 $query_strategy_part = "ttrss_feeds.cat_id IS NULL";
2247 } else if ($feed > 0) {
2252 if ($include_children) {
2254 $subcats = getChildCategories($link, $feed, $owner_uid);
2256 array_push($subcats, $feed);
2257 $query_strategy_part = "cat_id IN (".
2258 implode(",", $subcats).")";
2261 $query_strategy_part = "cat_id = '$feed'";
2265 $query_strategy_part = "cat_id IS NULL";
2268 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2271 $query_strategy_part = "feed_id = '$feed'";
2273 } else if ($feed == 0 && !$cat_view) { // archive virtual feed
2274 $query_strategy_part = "feed_id IS NULL";
2275 $allow_archived = true;
2276 } else if ($feed == 0 && $cat_view) { // uncategorized
2277 $query_strategy_part = "cat_id IS NULL AND feed_id IS NOT NULL";
2278 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2279 } else if ($feed == -1) { // starred virtual feed
2280 $query_strategy_part = "marked = true";
2281 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2282 $allow_archived = true;
2284 } else if ($feed == -2) { // published virtual feed OR labels category
2287 $query_strategy_part = "published = true";
2288 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2289 $allow_archived = true;
2291 if (!$override_order) $override_order = "last_read DESC, updated DESC";
2293 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2295 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2297 $query_strategy_part = "ttrss_labels2.id = ttrss_user_labels2.label_id AND
2298 ttrss_user_labels2.article_id = ref_id";
2301 } else if ($feed == -6) { // recently read
2302 $query_strategy_part = "unread = false AND last_read IS NOT NULL";
2303 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2304 $allow_archived = true;
2306 if (!$override_order) $override_order = "last_read DESC";
2307 } else if ($feed == -3) { // fresh virtual feed
2308 $query_strategy_part = "unread = true AND score >= 0";
2310 $intl = get_pref($link, "FRESH_ARTICLE_MAX_AGE", $owner_uid);
2312 if (DB_TYPE
== "pgsql") {
2313 $query_strategy_part .= " AND updated > NOW() - INTERVAL '$intl hour' ";
2315 $query_strategy_part .= " AND updated > DATE_SUB(NOW(), INTERVAL $intl HOUR) ";
2318 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2319 } else if ($feed == -4) { // all articles virtual feed
2320 $query_strategy_part = "true";
2321 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2322 } else if ($feed <= -10) { // labels
2323 $label_id = -$feed - 11;
2325 $query_strategy_part = "label_id = '$label_id' AND
2326 ttrss_labels2.id = ttrss_user_labels2.label_id AND
2327 ttrss_user_labels2.article_id = ref_id";
2329 $vfeed_query_part = "ttrss_feeds.title AS feed_title,";
2330 $ext_tables_part = ",ttrss_labels2,ttrss_user_labels2";
2331 $allow_archived = true;
2334 $query_strategy_part = "true";
2337 if (get_pref($link, "SORT_HEADLINES_BY_FEED_DATE", $owner_uid)) {
2338 $date_sort_field = "updated";
2340 $date_sort_field = "date_entered";
2343 if (get_pref($link, 'REVERSE_HEADLINES', $owner_uid)) {
2344 $order_by = "$date_sort_field";
2346 $order_by = "$date_sort_field DESC";
2349 if ($view_mode != "noscores") {
2350 $order_by = "score DESC, $order_by";
2353 if ($override_order) {
2354 $order_by = $override_order;
2360 $feed_title = T_sprintf("Search results: %s", $search);
2363 $feed_title = getCategoryTitle($link, $feed);
2365 if (is_numeric($feed) && $feed > 0) {
2366 $result = db_query($link, "SELECT title,site_url,last_error
2367 FROM ttrss_feeds WHERE id = '$feed' AND owner_uid = $owner_uid");
2369 $feed_title = db_fetch_result($result, 0, "title");
2370 $feed_site_url = db_fetch_result($result, 0, "site_url");
2371 $last_error = db_fetch_result($result, 0, "last_error");
2373 $feed_title = getFeedTitle($link, $feed);
2378 $content_query_part = "content as content_preview, cached_content, ";
2380 if (is_numeric($feed)) {
2383 $feed_kind = "Feeds";
2385 $feed_kind = "Labels";
2388 if ($limit_query_part) {
2389 $offset_query_part = "OFFSET $offset";
2392 // proper override_order applied above
2393 if ($vfeed_query_part && !$ignore_vfeed_group && get_pref($link, 'VFEED_GROUP_BY_FEED', $owner_uid)) {
2394 if (!$override_order) {
2395 $order_by = "ttrss_feeds.title, $order_by";
2397 $order_by = "ttrss_feeds.title, $override_order";
2401 if (!$allow_archived) {
2402 $from_qpart = "ttrss_entries,ttrss_user_entries,ttrss_feeds$ext_tables_part";
2403 $feed_check_qpart = "ttrss_user_entries.feed_id = ttrss_feeds.id AND";
2406 $from_qpart = "ttrss_entries$ext_tables_part,ttrss_user_entries
2407 LEFT JOIN ttrss_feeds ON (feed_id = ttrss_feeds.id)";
2410 $query = "SELECT DISTINCT
2413 ttrss_entries.id,ttrss_entries.title,
2417 always_display_enclosures,
2423 unread,feed_id,marked,published,link,last_read,orig_feed_id,
2424 ".SUBSTRING_FOR_DATE
."(last_read,1,19) as last_read_noms,
2427 ".SUBSTRING_FOR_DATE
."(updated,1,19) as updated_noms,
2433 ttrss_user_entries.ref_id = ttrss_entries.id AND
2434 ttrss_user_entries.owner_uid = '$owner_uid' AND
2439 $query_strategy_part ORDER BY $order_by
2440 $limit_query_part $offset_query_part";
2442 if ($_REQUEST["debug"]) print $query;
2444 $result = db_query($link, $query);
2449 $select_qpart = "SELECT DISTINCT " .
2453 "ttrss_entries.id as id," .
2466 SUBSTRING_FOR_DATE
. "(last_read,1,19) as last_read_noms," .
2469 $content_query_part .
2470 SUBSTRING_FOR_DATE
. "(updated,1,19) as updated_noms," .
2473 $feed_kind = "Tags";
2474 $all_tags = explode(",", $feed);
2475 if ($search_mode == 'any') {
2476 $tag_sql = "tag_name in (" . implode(", ", array_map("db_quote", $all_tags)) . ")";
2477 $from_qpart = " FROM ttrss_entries,ttrss_user_entries,ttrss_tags ";
2478 $where_qpart = " WHERE " .
2479 "ref_id = ttrss_entries.id AND " .
2480 "ttrss_user_entries.owner_uid = $owner_uid AND " .
2481 "post_int_id = int_id AND $tag_sql AND " .
2483 $search_query_part .
2484 $query_strategy_part . " ORDER BY $order_by " .
2489 $sub_selects = array();
2490 $sub_ands = array();
2491 foreach ($all_tags as $term) {
2492 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");
2499 array_push($sub_ands, "A$x.post_int_id = A$y.post_int_id");
2504 array_push($sub_ands, "A1.post_int_id = ttrss_user_entries.int_id and ttrss_user_entries.owner_uid = $owner_uid");
2505 array_push($sub_ands, "ttrss_user_entries.ref_id = ttrss_entries.id");
2506 $from_qpart = " FROM " . implode(", ", $sub_selects) . ", ttrss_user_entries, ttrss_entries";
2507 $where_qpart = " WHERE " . implode(" AND ", $sub_ands);
2509 // error_log("TAG SQL: " . $tag_sql);
2510 // $tag_sql = "tag_name = '$feed'"; DEFAULT way
2512 // error_log("[". $select_qpart . "][" . $from_qpart . "][" .$where_qpart . "]");
2513 $result = db_query($link, $select_qpart . $from_qpart . $where_qpart);
2516 return array($result, $feed_title, $feed_site_url, $last_error);
2520 function sanitize($link, $str, $force_strip_tags = false, $owner = false, $site_url = false) {
2521 if (!$owner) $owner = $_SESSION["uid"];
2523 $res = trim($str); if (!$res) return '';
2525 $config = array('safe' => 1, 'deny_attribute' => 'style, width, height, class, id', 'comment' => 1, 'cdata' => 1, 'balance' => 0);
2526 $res = htmLawed($res, $config);
2528 if (get_pref($link, "STRIP_IMAGES", $owner)) {
2529 $res = preg_replace('/<img[^>]+>/is', '', $res);
2532 if (strpos($res, "href=") === false)
2533 $res = rewrite_urls($res);
2535 $charset_hack = '<head>
2536 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2539 $res = trim($res); if (!$res) return '';
2541 libxml_use_internal_errors(true);
2543 $doc = new DOMDocument();
2544 $doc->loadHTML($charset_hack . $res);
2545 $xpath = new DOMXPath($doc);
2547 $entries = $xpath->query('(//a[@href]|//img[@src])');
2550 foreach ($entries as $entry) {
2554 if ($entry->hasAttribute('href'))
2555 $entry->setAttribute('href',
2556 rewrite_relative_url($site_url, $entry->getAttribute('href')));
2558 if ($entry->hasAttribute('src'))
2559 if (preg_match('/^image.php\?i=[a-z0-9]+$/', $entry->getAttribute('src')) == 0)
2560 $entry->setAttribute('src',
2561 rewrite_relative_url($site_url, $entry->getAttribute('src')));
2564 if (strtolower($entry->nodeName
) == "a") {
2565 $entry->setAttribute("target", "_blank");
2568 if (strtolower($entry->nodeName
) == "img" && !$br_inserted) {
2569 $br = $doc->createElement("br");
2571 if ($entry->parentNode
->nextSibling
) {
2572 $entry->parentNode
->insertBefore($br, $entry->nextSibling
);
2579 $node = $doc->getElementsByTagName('body')->item(0);
2581 // http://tt-rss.org/redmine/issues/357
2582 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
2585 function check_for_update($link) {
2586 if (CHECK_FOR_NEW_VERSION
&& $_SESSION['access_level'] >= 10) {
2587 $version_url = "http://tt-rss.org/version.php?ver=" . VERSION
;
2589 $version_data = @fetch_file_contents
($version_url);
2591 if ($version_data) {
2592 $version_data = json_decode($version_data, true);
2593 if ($version_data && $version_data['version']) {
2595 if (version_compare(VERSION
, $version_data['version']) == -1) {
2596 return $version_data;
2604 function catchupArticlesById($link, $ids, $cmode, $owner_uid = false) {
2606 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2607 if (count($ids) == 0) return;
2611 foreach ($ids as $id) {
2612 array_push($tmp_ids, "ref_id = '$id'");
2615 $ids_qpart = join(" OR ", $tmp_ids);
2618 db_query($link, "UPDATE ttrss_user_entries SET
2619 unread = false,last_read = NOW()
2620 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2621 } else if ($cmode == 1) {
2622 db_query($link, "UPDATE ttrss_user_entries SET
2624 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2626 db_query($link, "UPDATE ttrss_user_entries SET
2627 unread = NOT unread,last_read = NOW()
2628 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2633 $result = db_query($link, "SELECT DISTINCT feed_id FROM ttrss_user_entries
2634 WHERE ($ids_qpart) AND owner_uid = $owner_uid");
2636 while ($line = db_fetch_assoc($result)) {
2637 ccache_update($link, $line["feed_id"], $owner_uid);
2641 function get_article_tags($link, $id, $owner_uid = 0, $tag_cache = false) {
2643 $a_id = db_escape_string($id);
2645 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2647 $query = "SELECT DISTINCT tag_name,
2648 owner_uid as owner FROM
2649 ttrss_tags WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE
2650 ref_id = '$a_id' AND owner_uid = '$owner_uid' LIMIT 1) ORDER BY tag_name";
2652 $obj_id = md5("TAGS:$owner_uid:$id");
2655 /* check cache first */
2657 if ($tag_cache === false) {
2658 $result = db_query($link, "SELECT tag_cache FROM ttrss_user_entries
2659 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2661 $tag_cache = db_fetch_result($result, 0, "tag_cache");
2665 $tags = explode(",", $tag_cache);
2668 /* do it the hard way */
2670 $tmp_result = db_query($link, $query);
2672 while ($tmp_line = db_fetch_assoc($tmp_result)) {
2673 array_push($tags, $tmp_line["tag_name"]);
2676 /* update the cache */
2678 $tags_str = db_escape_string(join(",", $tags));
2680 db_query($link, "UPDATE ttrss_user_entries
2681 SET tag_cache = '$tags_str' WHERE ref_id = '$id'
2682 AND owner_uid = $owner_uid");
2688 function trim_array($array) {
2690 array_walk($tmp, 'trim');
2694 function tag_is_valid($tag) {
2695 if ($tag == '') return false;
2696 if (preg_match("/^[0-9]*$/", $tag)) return false;
2697 if (mb_strlen($tag) > 250) return false;
2699 if (function_exists('iconv')) {
2700 $tag = iconv("utf-8", "utf-8", $tag);
2703 if (!$tag) return false;
2708 function render_login_form($link, $form_id = 0) {
2711 require_once "login_form.php";
2714 require_once "mobile/login_form.php";
2720 // from http://developer.apple.com/internet/safari/faq.html
2721 function no_cache_incantation() {
2722 header("Expires: Mon, 22 Dec 1980 00:00:00 GMT"); // Happy birthday to me :)
2723 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
2724 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
2725 header("Cache-Control: post-check=0, pre-check=0", false);
2726 header("Pragma: no-cache"); // HTTP/1.0
2729 function format_warning($msg, $id = "") {
2731 return "<div class=\"warning\" id=\"$id\">
2732 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2735 function format_notice($msg, $id = "") {
2737 return "<div class=\"notice\" id=\"$id\">
2738 <img src=\"".theme_image($link, "images/sign_info.svg")."\">$msg</div>";
2741 function format_error($msg, $id = "") {
2743 return "<div class=\"error\" id=\"$id\">
2744 <img src=\"".theme_image($link, "images/sign_excl.svg")."\">$msg</div>";
2747 function print_notice($msg) {
2748 return print format_notice($msg);
2751 function print_warning($msg) {
2752 return print format_warning($msg);
2755 function print_error($msg) {
2756 return print format_error($msg);
2760 function T_sprintf() {
2761 $args = func_get_args();
2762 return vsprintf(__(array_shift($args)), $args);
2765 function format_inline_player($link, $url, $ctype) {
2769 if (strpos($ctype, "audio/") === 0) {
2771 if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
2772 strpos($_SERVER['HTTP_USER_AGENT'], "Chrome") !== false ||
2773 strpos($_SERVER['HTTP_USER_AGENT'], "Safari") !== false )) {
2775 $id = 'AUDIO-' . uniqid();
2777 $entry .= "<audio id=\"$id\"\" controls>
2778 <source type=\"$ctype\" src=\"$url\"></source>
2781 $entry .= "<span onclick=\"player(this)\"
2782 title=\"".__("Click to play")."\" status=\"0\"
2783 class=\"player\" audio-id=\"$id\">".__("Play")."</span>";
2787 $entry .= "<object type=\"application/x-shockwave-flash\"
2788 data=\"lib/button/musicplayer.swf?song_url=$url\"
2789 width=\"17\" height=\"17\" style='float : left; margin-right : 5px;'>
2790 <param name=\"movie\"
2791 value=\"lib/button/musicplayer.swf?song_url=$url\" />
2795 if ($entry) $entry .= " " . basename($url);
2803 /* $filename = substr($url, strrpos($url, "/")+1);
2805 $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
2806 $filename . " (" . $ctype . ")" . "</a>"; */
2810 function format_article($link, $id, $mark_as_read = true, $zoom_mode = false, $owner_uid = false) {
2811 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
2817 /* we can figure out feed_id from article id anyway, why do we
2818 * pass feed_id here? let's ignore the argument :( */
2820 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
2821 WHERE ref_id = '$id'");
2823 $feed_id = (int) db_fetch_result($result, 0, "feed_id");
2825 $rv['feed_id'] = $feed_id;
2827 //if (!$zoom_mode) { print "<article id='$id'><![CDATA["; };
2829 $result = db_query($link, "SELECT rtl_content, always_display_enclosures, cache_content FROM ttrss_feeds
2830 WHERE id = '$feed_id' AND owner_uid = $owner_uid");
2832 if (db_num_rows($result) == 1) {
2833 $rtl_content = sql_bool_to_bool(db_fetch_result($result, 0, "rtl_content"));
2834 $always_display_enclosures = sql_bool_to_bool(db_fetch_result($result, 0, "always_display_enclosures"));
2835 $cache_content = sql_bool_to_bool(db_fetch_result($result, 0, "cache_content"));
2837 $rtl_content = false;
2838 $always_display_enclosures = false;
2839 $cache_content = false;
2843 $rtl_tag = "dir=\"RTL\"";
2850 if ($mark_as_read) {
2851 $result = db_query($link, "UPDATE ttrss_user_entries
2852 SET unread = false,last_read = NOW()
2853 WHERE ref_id = '$id' AND owner_uid = $owner_uid");
2855 ccache_update($link, $feed_id, $owner_uid);
2858 $result = db_query($link, "SELECT id,title,link,content,feed_id,comments,int_id,
2859 ".SUBSTRING_FOR_DATE
."(updated,1,16) as updated,
2860 (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) as site_url,
2867 FROM ttrss_entries,ttrss_user_entries
2868 WHERE id = '$id' AND ref_id = id AND owner_uid = $owner_uid");
2872 $line = db_fetch_assoc($result);
2874 $feed_site_url = $line['site_url'];
2876 $num_comments = $line["num_comments"];
2877 $entry_comments = "";
2879 if ($num_comments > 0) {
2880 if ($line["comments"]) {
2881 $comments_url = htmlspecialchars($line["comments"]);
2883 $comments_url = htmlspecialchars($line["link"]);
2885 $entry_comments = "<a target='_blank' href=\"$comments_url\">$num_comments comments</a>";
2887 if ($line["comments"] && $line["link"] != $line["comments"]) {
2888 $entry_comments = "<a target='_blank' href=\"".htmlspecialchars($line["comments"])."\">comments</a>";
2893 header("Content-Type: text/html");
2894 $rv['content'] .= "<html><head>
2895 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
2896 <title>Tiny Tiny RSS - ".$line["title"]."</title>
2897 <link rel=\"stylesheet\" type=\"text/css\" href=\"tt-rss.css\">
2901 $title_escaped = htmlspecialchars($line['title']);
2903 $rv['content'] .= "<div id=\"PTITLE-FULL-$id\" style=\"display : none\">" .
2904 strip_tags($line['title']) . "</div>";
2906 $rv['content'] .= "<div class=\"postReply\" id=\"POST-$id\">";
2908 $rv['content'] .= "<div class=\"postHeader\" id=\"POSTHDR-$id\">";
2910 $entry_author = $line["author"];
2912 if ($entry_author) {
2913 $entry_author = __(" - ") . $entry_author;
2916 $parsed_updated = make_local_datetime($link, $line["updated"], true,
2919 $rv['content'] .= "<div class=\"postDate$rtl_class\">$parsed_updated</div>";
2921 if ($line["link"]) {
2922 $rv['content'] .= "<div class='postTitle'><a target='_blank'
2923 title=\"".htmlspecialchars($line['title'])."\"
2925 htmlspecialchars($line["link"]) . "\">" .
2927 "<span class='author'>$entry_author</span></a></div>";
2929 $rv['content'] .= "<div class='postTitle'>" . $line["title"] . "$entry_author</div>";
2932 $tag_cache = $line["tag_cache"];
2935 $tags = get_article_tags($link, $id, $owner_uid);
2937 $tags = explode(",", $tag_cache);
2939 $tags_str = format_tags_string($tags, $id);
2940 $tags_str_full = join(", ", $tags);
2942 if (!$tags_str_full) $tags_str_full = __("no tags");
2944 if (!$entry_comments) $entry_comments = " "; # placeholder
2946 $rv['content'] .= "<div class='postTags' style='float : right'>
2947 <img src='".theme_image($link, 'images/tag.png')."'
2948 class='tagsPic' alt='Tags' title='Tags'> ";
2951 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>
2952 <a title=\"".__('Edit tags for this article')."\"
2953 href=\"#\" onclick=\"editArticleTags($id, $feed_id)\">(+)</a>";
2955 $rv['content'] .= "<div dojoType=\"dijit.Tooltip\"
2956 id=\"ATSTRTIP-$id\" connectId=\"ATSTR-$id\"
2957 position=\"below\">$tags_str_full</div>";
2961 foreach ($pluginhost->get_hooks($pluginhost::HOOK_ARTICLE_BUTTON
) as $p) {
2962 $rv['content'] .= $p->hook_article_button($line);
2967 $tags_str = strip_tags($tags_str);
2968 $rv['content'] .= "<span id=\"ATSTR-$id\">$tags_str</span>";
2970 $rv['content'] .= "</div>";
2971 $rv['content'] .= "<div clear='both'>$entry_comments</div>";
2973 if ($line["orig_feed_id"]) {
2975 $tmp_result = db_query($link, "SELECT * FROM ttrss_archived_feeds
2976 WHERE id = ".$line["orig_feed_id"]);
2978 if (db_num_rows($tmp_result) != 0) {
2980 $rv['content'] .= "<div clear='both'>";
2981 $rv['content'] .= __("Originally from:");
2983 $rv['content'] .= " ";
2985 $tmp_line = db_fetch_assoc($tmp_result);
2987 $rv['content'] .= "<a target='_blank'
2988 href=' " . htmlspecialchars($tmp_line['site_url']) . "'>" .
2989 $tmp_line['title'] . "</a>";
2991 $rv['content'] .= " ";
2993 $rv['content'] .= "<a target='_blank' href='" . htmlspecialchars($tmp_line['feed_url']) . "'>";
2994 $rv['content'] .= "<img title='".__('Feed URL')."'class='tinyFeedIcon' src='images/pub_set.svg'></a>";
2996 $rv['content'] .= "</div>";
3000 $rv['content'] .= "</div>";
3002 $rv['content'] .= "<div id=\"POSTNOTE-$id\">";
3003 if ($line['note']) {
3004 $rv['content'] .= format_article_note($id, $line['note'], !$zoom_mode);
3006 $rv['content'] .= "</div>";
3008 $rv['content'] .= "<div class=\"postContent\">";
3012 if (DB_TYPE
== "pgsql" and defined('_NGRAM_TITLE_RELATED_THRESHOLD')) {
3014 $ngram_result = db_query($link, "SELECT id,title FROM
3015 ttrss_entries,ttrss_user_entries
3016 WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
3017 AND similarity(title, '$title_escaped') >= "._NGRAM_TITLE_RELATED_THRESHOLD
."
3018 AND title != '$title_escaped'
3019 AND owner_uid = $owner_uid");
3021 if (db_num_rows($ngram_result) > 0) {
3022 $rv['content'] .= "<div dojoType=\"dijit.form.DropDownButton\">".
3023 "<span>" . __('Related')."</span>";
3024 $rv['content'] .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3026 while ($nline = db_fetch_assoc($ngram_result)) {
3027 $rv['content'] .= "<div onclick=\"hlOpenInNewTab(null,".$nline['id'].")\"
3028 dojoType=\"dijit.MenuItem\">".$nline['title']."</div>";
3031 $rv['content'] .= "</div></div><br/";
3035 if ($cache_content && $line["cached_content"] != "") {
3036 $line["content"] =& $line["cached_content"];
3039 $article_content = sanitize($link, $line["content"], false, $owner_uid,
3042 $rv['content'] .= $article_content;
3044 $rv['content'] .= format_article_enclosures($link, $id,
3045 $always_display_enclosures, $article_content);
3047 $rv['content'] .= "</div>";
3049 $rv['content'] .= "</div>";
3055 <div style=\"text-align : center\">
3056 <button onclick=\"return window.close()\">".
3057 __("Close this window")."</button></div>";
3058 $rv['content'] .= "</body></html>";
3065 function print_checkpoint($n, $s) {
3066 $ts = getmicrotime();
3067 echo sprintf("<!-- CP[$n] %.4f seconds -->", $ts - $s);
3071 function sanitize_tag($tag) {
3074 $tag = mb_strtolower($tag, 'utf-8');
3076 $tag = preg_replace('/[\'\"\+\>\<]/', "", $tag);
3078 // $tag = str_replace('"', "", $tag);
3079 // $tag = str_replace("+", " ", $tag);
3080 $tag = str_replace("technorati tag: ", "", $tag);
3085 function get_self_url_prefix() {
3086 if (strrpos(SELF_URL_PATH
, "/") === strlen(SELF_URL_PATH
)-1) {
3087 return substr(SELF_URL_PATH
, 0, strlen(SELF_URL_PATH
)-1);
3089 return SELF_URL_PATH
;
3094 * Compute the Mozilla Firefox feed adding URL from server HOST and REQUEST_URI.
3096 * @return string The Mozilla Firefox feed adding URL.
3098 function add_feed_url() {
3099 //$url_path = ($_SERVER['HTTPS'] != "on" ? 'http://' : 'https://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
3101 $url_path = get_self_url_prefix() .
3102 "/public.php?op=subscribe&feed_url=%s";
3104 } // function add_feed_url
3106 function encrypt_password($pass, $salt = '', $mode2 = false) {
3107 if ($salt && $mode2) {
3108 return "MODE2:" . hash('sha256', $salt . $pass);
3110 return "SHA1X:" . sha1("$salt:$pass");
3112 return "SHA1:" . sha1($pass);
3114 } // function encrypt_password
3116 function load_filters($link, $feed_id, $owner_uid, $action_id = false) {
3119 $cat_id = (int)getFeedCategory($link, $feed_id);
3121 $result = db_query($link, "SELECT * FROM ttrss_filters2 WHERE
3122 owner_uid = $owner_uid AND enabled = true");
3124 $check_cats = join(",", array_merge(
3125 getParentCategories($link, $cat_id, $owner_uid),
3128 while ($line = db_fetch_assoc($result)) {
3129 $filter_id = $line["id"];
3131 $result2 = db_query($link, "SELECT
3132 r.reg_exp, r.feed_id, r.cat_id, r.cat_filter, t.name AS type_name
3133 FROM ttrss_filters2_rules AS r,
3134 ttrss_filter_types AS t
3136 (cat_id IS NULL OR cat_id IN ($check_cats)) AND
3137 (feed_id IS NULL OR feed_id = '$feed_id') AND
3138 filter_type = t.id AND filter_id = '$filter_id'");
3143 while ($rule_line = db_fetch_assoc($result2)) {
3144 # print_r($rule_line);
3147 $rule["reg_exp"] = $rule_line["reg_exp"];
3148 $rule["type"] = $rule_line["type_name"];
3150 array_push($rules, $rule);
3153 $result2 = db_query($link, "SELECT a.action_param,t.name AS type_name
3154 FROM ttrss_filters2_actions AS a,
3155 ttrss_filter_actions AS t
3157 action_id = t.id AND filter_id = '$filter_id'");
3159 while ($action_line = db_fetch_assoc($result2)) {
3160 # print_r($action_line);
3163 $action["type"] = $action_line["type_name"];
3164 $action["param"] = $action_line["action_param"];
3166 array_push($actions, $action);
3171 $filter["match_any_rule"] = sql_bool_to_bool($line["match_any_rule"]);
3172 $filter["rules"] = $rules;
3173 $filter["actions"] = $actions;
3175 if (count($rules) > 0 && count($actions) > 0) {
3176 array_push($filters, $filter);
3183 function get_score_pic($score) {
3185 return "score_high.png";
3186 } else if ($score > 0) {
3187 return "score_half_high.png";
3188 } else if ($score < -100) {
3189 return "score_low.png";
3190 } else if ($score < 0) {
3191 return "score_half_low.png";
3193 return "score_neutral.png";
3197 function feed_has_icon($id) {
3198 return is_file(ICONS_DIR
. "/$id.ico") && filesize(ICONS_DIR
. "/$id.ico") > 0;
3201 function init_connection($link) {
3204 if (DB_TYPE
== "pgsql") {
3205 pg_query($link, "set client_encoding = 'UTF-8'");
3206 pg_set_client_encoding("UNICODE");
3207 pg_query($link, "set datestyle = 'ISO, european'");
3208 pg_query($link, "set TIME ZONE 0");
3210 db_query($link, "SET time_zone = '+0:0'");
3212 if (defined('MYSQL_CHARSET') && MYSQL_CHARSET
) {
3213 db_query($link, "SET NAMES " . MYSQL_CHARSET
);
3219 $pluginhost = new PluginHost($link);
3220 $pluginhost->load(PLUGINS
, $pluginhost::KIND_ALL
);
3224 print "Unable to connect to database:" . db_last_error();
3229 function format_tags_string($tags, $id) {
3232 $tags_nolinks_str = "";
3238 $formatted_tags = array();
3240 foreach ($tags as $tag) {
3242 $tag_escaped = str_replace("'", "\\'", $tag);
3244 if (mb_strlen($tag) > 30) {
3245 $tag = truncate_string($tag, 30);
3248 $tag_str = "<a href=\"javascript:viewfeed('$tag_escaped')\">$tag</a>";
3250 array_push($formatted_tags, $tag_str);
3252 $tmp_tags_str = implode(", ", $formatted_tags);
3254 if ($num_tags == $tag_limit ||
mb_strlen($tmp_tags_str) > 150) {
3259 $tags_str = implode(", ", $formatted_tags);
3261 if ($num_tags < count($tags)) {
3262 $tags_str .= ", …";
3265 if ($num_tags == 0) {
3266 $tags_str = __("no tags");
3273 function format_article_labels($labels, $id) {
3277 foreach ($labels as $l) {
3278 $labels_str .= sprintf("<span class='hlLabelRef'
3279 style='color : %s; background-color : %s'>%s</span>",
3280 $l[2], $l[3], $l[1]);
3287 function format_article_note($id, $note, $allow_edit = true) {
3289 $str = "<div class='articleNote' onclick=\"editArticleNote($id)\">
3290 <div class='noteEdit' onclick=\"editArticleNote($id)\">".
3291 ($allow_edit ?
__('(edit note)') : "")."</div>$note</div>";
3296 function toggle_collapse_cat($link, $cat_id, $mode) {
3298 $mode = bool_to_sql_bool($mode);
3300 db_query($link, "UPDATE ttrss_feed_categories SET
3301 collapsed = $mode WHERE id = '$cat_id' AND owner_uid = " .
3308 $pref_name = '_COLLAPSED_SPECIAL';
3311 $pref_name = '_COLLAPSED_LABELS';
3314 $pref_name = '_COLLAPSED_UNCAT';
3320 set_pref($link, $pref_name, 'true');
3322 set_pref($link, $pref_name, 'false');
3329 function get_feed_category($link, $feed_cat, $parent_cat_id = false) {
3330 if ($parent_cat_id) {
3331 $parent_qpart = "parent_cat = '$parent_cat_id'";
3332 $parent_insert = "'$parent_cat_id'";
3334 $parent_qpart = "parent_cat IS NULL";
3335 $parent_insert = "NULL";
3338 $result = db_query($link,
3339 "SELECT id FROM ttrss_feed_categories
3340 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3342 if (db_num_rows($result) == 0) {
3345 return db_fetch_result($result, 0, "id");
3349 function add_feed_category($link, $feed_cat, $parent_cat_id = false) {
3351 if (!$feed_cat) return false;
3353 db_query($link, "BEGIN");
3355 if ($parent_cat_id) {
3356 $parent_qpart = "parent_cat = '$parent_cat_id'";
3357 $parent_insert = "'$parent_cat_id'";
3359 $parent_qpart = "parent_cat IS NULL";
3360 $parent_insert = "NULL";
3363 $result = db_query($link,
3364 "SELECT id FROM ttrss_feed_categories
3365 WHERE $parent_qpart AND title = '$feed_cat' AND owner_uid = ".$_SESSION["uid"]);
3367 if (db_num_rows($result) == 0) {
3369 $result = db_query($link,
3370 "INSERT INTO ttrss_feed_categories (owner_uid,title,parent_cat)
3371 VALUES ('".$_SESSION["uid"]."', '$feed_cat', $parent_insert)");
3373 db_query($link, "COMMIT");
3381 function getArticleFeed($link, $id) {
3382 $result = db_query($link, "SELECT feed_id FROM ttrss_user_entries
3383 WHERE ref_id = '$id' AND owner_uid = " . $_SESSION["uid"]);
3385 if (db_num_rows($result) != 0) {
3386 return db_fetch_result($result, 0, "feed_id");
3393 * Fixes incomplete URLs by prepending "http://".
3394 * Also replaces feed:// with http://, and
3395 * prepends a trailing slash if the url is a domain name only.
3397 * @param string $url Possibly incomplete URL
3399 * @return string Fixed URL.
3401 function fix_url($url) {
3402 if (strpos($url, '://') === false) {
3403 $url = 'http://' . $url;
3404 } else if (substr($url, 0, 5) == 'feed:') {
3405 $url = 'http:' . substr($url, 5);
3408 //prepend slash if the URL has no slash in it
3409 // "http://www.example" -> "http://www.example/"
3410 if (strpos($url, '/', strpos($url, ':') +
3) === false) {
3414 if ($url != "http:///")
3420 function validate_feed_url($url) {
3421 $parts = parse_url($url);
3423 return ($parts['scheme'] == 'http' ||
$parts['scheme'] == 'feed' ||
$parts['scheme'] == 'https');
3427 function get_article_enclosures($link, $id) {
3429 $query = "SELECT * FROM ttrss_enclosures
3430 WHERE post_id = '$id' AND content_url != ''";
3434 $result = db_query($link, $query);
3436 if (db_num_rows($result) > 0) {
3437 while ($line = db_fetch_assoc($result)) {
3438 array_push($rv, $line);
3445 function save_email_address($link, $email) {
3446 // FIXME: implement persistent storage of emails
3448 if (!$_SESSION['stored_emails'])
3449 $_SESSION['stored_emails'] = array();
3451 if (!in_array($email, $_SESSION['stored_emails']))
3452 array_push($_SESSION['stored_emails'], $email);
3456 function get_feed_access_key($link, $feed_id, $is_cat, $owner_uid = false) {
3458 if (!$owner_uid) $owner_uid = $_SESSION["uid"];
3460 $sql_is_cat = bool_to_sql_bool($is_cat);
3462 $result = db_query($link, "SELECT access_key FROM ttrss_access_keys
3463 WHERE feed_id = '$feed_id' AND is_cat = $sql_is_cat
3464 AND owner_uid = " . $owner_uid);
3466 if (db_num_rows($result) == 1) {
3467 return db_fetch_result($result, 0, "access_key");
3469 $key = db_escape_string(sha1(uniqid(rand(), true)));
3471 $result = db_query($link, "INSERT INTO ttrss_access_keys
3472 (access_key, feed_id, is_cat, owner_uid)
3473 VALUES ('$key', '$feed_id', $sql_is_cat, '$owner_uid')");
3480 function get_feeds_from_html($url, $content)
3482 $url = fix_url($url);
3483 $baseUrl = substr($url, 0, strrpos($url, '/') +
1);
3485 libxml_use_internal_errors(true);
3487 $doc = new DOMDocument();
3488 $doc->loadHTML($content);
3489 $xpath = new DOMXPath($doc);
3490 $entries = $xpath->query('/html/head/link[@rel="alternate"]');
3491 $feedUrls = array();
3492 foreach ($entries as $entry) {
3493 if ($entry->hasAttribute('href')) {
3494 $title = $entry->getAttribute('title');
3496 $title = $entry->getAttribute('type');
3498 $feedUrl = rewrite_relative_url(
3499 $baseUrl, $entry->getAttribute('href')
3501 $feedUrls[$feedUrl] = $title;
3507 function is_html($content) {
3508 return preg_match("/<html|DOCTYPE html/i", substr($content, 0, 20)) !== 0;
3511 function url_is_html($url, $login = false, $pass = false) {
3512 return is_html(fetch_file_contents($url, false, $login, $pass));
3515 function print_label_select($link, $name, $value, $attributes = "") {
3517 $result = db_query($link, "SELECT caption FROM ttrss_labels2
3518 WHERE owner_uid = '".$_SESSION["uid"]."' ORDER BY caption");
3520 print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
3521 "\" $attributes onchange=\"labelSelectOnChange(this)\" >";
3523 while ($line = db_fetch_assoc($result)) {
3525 $issel = ($line["caption"] == $value) ?
"selected=\"1\"" : "";
3527 print "<option value=\"".htmlspecialchars($line["caption"])."\"
3528 $issel>" . htmlspecialchars($line["caption"]) . "</option>";
3532 # print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
3539 function format_article_enclosures($link, $id, $always_display_enclosures,
3542 $result = get_article_enclosures($link, $id);
3545 if (count($result) > 0) {
3547 $entries_html = array();
3549 $entries_inline = array();
3551 foreach ($result as $line) {
3553 $url = $line["content_url"];
3554 $ctype = $line["content_type"];
3556 if (!$ctype) $ctype = __("unknown type");
3558 $filename = substr($url, strrpos($url, "/")+
1);
3560 $player = format_inline_player($link, $url, $ctype);
3562 if ($player) array_push($entries_inline, $player);
3564 # $entry .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\">" .
3565 # $filename . " (" . $ctype . ")" . "</a>";
3567 $entry = "<div onclick=\"window.open('".htmlspecialchars($url)."')\"
3568 dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
3570 array_push($entries_html, $entry);
3574 $entry["type"] = $ctype;
3575 $entry["filename"] = $filename;
3576 $entry["url"] = $url;
3578 array_push($entries, $entry);
3581 if (!get_pref($link, "STRIP_IMAGES")) {
3582 if ($always_display_enclosures ||
3583 !preg_match("/<img/i", $article_content)) {
3585 foreach ($entries as $entry) {
3587 if (preg_match("/image/", $entry["type"]) ||
3588 preg_match("/\.(jpg|png|gif|bmp)/i", $entry["filename"])) {
3591 alt=\"".htmlspecialchars($entry["filename"])."\"
3592 src=\"" .htmlspecialchars($entry["url"]) . "\"/></p>";
3599 if (count($entries_inline) > 0) {
3600 $rv .= "<hr clear='both'/>";
3601 foreach ($entries_inline as $entry) { $rv .= $entry; };
3602 $rv .= "<hr clear='both'/>";
3605 $rv .= "<br/><div dojoType=\"dijit.form.DropDownButton\">".
3606 "<span>" . __('Attachments')."</span>";
3607 $rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
3609 foreach ($entries_html as $entry) { $rv .= $entry; };
3611 $rv .= "</div></div>";
3617 function getLastArticleId($link) {
3618 $result = db_query($link, "SELECT MAX(ref_id) AS id FROM ttrss_user_entries
3619 WHERE owner_uid = " . $_SESSION["uid"]);
3621 if (db_num_rows($result) == 1) {
3622 return db_fetch_result($result, 0, "id");
3628 function build_url($parts) {
3629 return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
3633 * Converts a (possibly) relative URL to a absolute one.
3635 * @param string $url Base URL (i.e. from where the document is)
3636 * @param string $rel_url Possibly relative URL in the document
3638 * @return string Absolute URL
3640 function rewrite_relative_url($url, $rel_url) {
3641 if (strpos($rel_url, "magnet:") === 0) {
3643 } else if (strpos($rel_url, "://") !== false) {
3645 } else if (strpos($rel_url, "//") === 0) {
3646 # protocol-relative URL (rare but they exist)
3648 } else if (strpos($rel_url, "/") === 0)
3650 $parts = parse_url($url);
3651 $parts['path'] = $rel_url;
3653 return build_url($parts);
3656 $parts = parse_url($url);
3657 if (!isset($parts['path'])) {
3658 $parts['path'] = '/';
3660 $dir = $parts['path'];
3661 if (substr($dir, -1) !== '/') {
3662 $dir = dirname($parts['path']);
3663 $dir !== '/' && $dir .= '/';
3665 $parts['path'] = $dir . $rel_url;
3667 return build_url($parts);
3671 function sphinx_search($query, $offset = 0, $limit = 30) {
3672 require_once 'lib/sphinxapi.php';
3674 $sphinxClient = new SphinxClient();
3676 $sphinxClient->SetServer('localhost', 9312);
3677 $sphinxClient->SetConnectTimeout(1);
3679 $sphinxClient->SetFieldWeights(array('title' => 70, 'content' => 30,
3680 'feed_title' => 20));
3682 $sphinxClient->SetMatchMode(SPH_MATCH_EXTENDED2
);
3683 $sphinxClient->SetRankingMode(SPH_RANK_PROXIMITY_BM25
);
3684 $sphinxClient->SetLimits($offset, $limit, 1000);
3685 $sphinxClient->SetArrayResult(false);
3686 $sphinxClient->SetFilter('owner_uid', array($_SESSION['uid']));
3688 $result = $sphinxClient->Query($query, SPHINX_INDEX
);
3692 if (is_array($result['matches'])) {
3693 foreach (array_keys($result['matches']) as $int_id) {
3694 $ref_id = $result['matches'][$int_id]['attrs']['ref_id'];
3695 array_push($ids, $ref_id);
3702 function cleanup_tags($link, $days = 14, $limit = 1000) {
3704 if (DB_TYPE
== "pgsql") {
3705 $interval_query = "date_updated < NOW() - INTERVAL '$days days'";
3706 } else if (DB_TYPE
== "mysql") {
3707 $interval_query = "date_updated < DATE_SUB(NOW(), INTERVAL $days DAY)";
3712 while ($limit > 0) {
3715 $query = "SELECT ttrss_tags.id AS id
3716 FROM ttrss_tags, ttrss_user_entries, ttrss_entries
3717 WHERE post_int_id = int_id AND $interval_query AND
3718 ref_id = ttrss_entries.id AND tag_cache != '' LIMIT $limit_part";
3720 $result = db_query($link, $query);
3724 while ($line = db_fetch_assoc($result)) {
3725 array_push($ids, $line['id']);
3728 if (count($ids) > 0) {
3729 $ids = join(",", $ids);
3732 $tmp_result = db_query($link, "DELETE FROM ttrss_tags WHERE id IN ($ids)");
3733 $tags_deleted +
= db_affected_rows($link, $tmp_result);
3738 $limit -= $limit_part;
3743 return $tags_deleted;
3746 function print_user_stylesheet($link) {
3747 $value = get_pref($link, 'USER_STYLESHEET');
3750 print "<style type=\"text/css\">";
3751 print str_replace("<br/>", "\n", $value);
3757 function rewrite_urls($html) {
3758 libxml_use_internal_errors(true);
3760 $charset_hack = '<head>
3761 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
3764 $doc = new DOMDocument();
3765 $doc->loadHTML($charset_hack . $html);
3766 $xpath = new DOMXPath($doc);
3768 $entries = $xpath->query('//*/text()');
3770 foreach ($entries as $entry) {
3771 if (strstr($entry->wholeText
, "://") !== false) {
3772 $text = preg_replace("/((?<!=.)((http|https|ftp)+):\/\/[^ ,!]+)/i",
3773 "<a target=\"_blank\" href=\"\\1\">\\1</a>", $entry->wholeText
);
3775 if ($text != $entry->wholeText
) {
3776 $cdoc = new DOMDocument();
3777 $cdoc->loadHTML($charset_hack . $text);
3780 foreach ($cdoc->childNodes
as $cnode) {
3781 $cnode = $doc->importNode($cnode, true);
3784 $entry->parentNode
->insertBefore($cnode);
3788 $entry->parentNode
->removeChild($entry);
3794 $node = $doc->getElementsByTagName('body')->item(0);
3796 // http://tt-rss.org/forum/viewtopic.php?f=1&t=970
3798 return $doc->saveXML($node, LIBXML_NOEMPTYTAG
);
3803 function filter_to_sql($link, $filter, $owner_uid) {
3806 if (DB_TYPE
== "pgsql")
3809 $reg_qpart = "REGEXP";
3811 foreach ($filter["rules"] AS $rule) {
3812 $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
3813 $rule['reg_exp']) !== FALSE;
3815 if ($regexp_valid) {
3817 $rule['reg_exp'] = db_escape_string($rule['reg_exp']);
3819 switch ($rule["type"]) {
3821 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3822 $rule['reg_exp'] . "')";
3825 $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
3826 $rule['reg_exp'] . "')";
3829 $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
3830 $rule['reg_exp'] . "') OR LOWER(" .
3831 "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
3834 $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
3835 $rule['reg_exp'] . "')";
3838 $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
3839 $rule['reg_exp'] . "')";
3842 $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
3843 $rule['reg_exp'] . "')";
3847 if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
3848 $qpart .= " AND feed_id = " . db_escape_string($rule["feed_id"]);
3851 if (isset($rule["cat_id"])) {
3853 if ($rule["cat_id"] > 0) {
3854 $children = getChildCategories($link, $rule["cat_id"], $owner_uid);
3855 array_push($children, $rule["cat_id"]);
3857 $children = join(",", $children);
3859 $cat_qpart = "cat_id IN ($children)";
3861 $cat_qpart = "cat_id IS NULL";
3864 $qpart .= " AND $cat_qpart";
3867 array_push($query, "($qpart)");
3872 if (count($query) > 0) {
3873 return "(" . join($filter["match_any_rule"] ?
"OR" : "AND", $query) . ")";
3879 if (!function_exists('gzdecode')) {
3880 function gzdecode($string) { // no support for 2nd argument
3881 return file_get_contents('compress.zlib://data:who/cares;base64,'.
3882 base64_encode($string));
3886 function get_random_bytes($length) {
3887 if (function_exists('openssl_random_pseudo_bytes')) {
3888 return openssl_random_pseudo_bytes($length);
3892 for ($i = 0; $i < $length; $i++
)
3893 $output .= chr(mt_rand(0, 255));
3899 function read_stdin() {
3900 $fp = fopen("php://stdin", "r");
3903 $line = trim(fgets($fp));
3911 function tmpdirname($path, $prefix) {
3912 // Use PHP's tmpfile function to create a temporary
3913 // directory name. Delete the file and keep the name.
3914 $tempname = tempnam($path,$prefix);
3918 if (!unlink($tempname))
3924 function getFeedCategory($link, $feed) {
3925 $result = db_query($link, "SELECT cat_id FROM ttrss_feeds
3926 WHERE id = '$feed'");
3928 if (db_num_rows($result) > 0) {
3929 return db_fetch_result($result, 0, "cat_id");
3936 function implements_interface($class, $interface) {
3937 return in_array($interface, class_implements($class));