functions.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. <?php
  2. define('EXPECTED_CONFIG_VERSION', 26);
  3. define('SCHEMA_VERSION', 139);
  4. define('LABEL_BASE_INDEX', -1024);
  5. define('PLUGIN_FEED_BASE_INDEX', -128);
  6. define('COOKIE_LIFETIME_LONG', 86400*365);
  7. $fetch_last_error = false;
  8. $fetch_last_error_code = false;
  9. $fetch_last_content_type = false;
  10. $fetch_last_error_content = false; // curl only for the time being
  11. $fetch_effective_url = false;
  12. $fetch_curl_used = false;
  13. libxml_disable_entity_loader(true);
  14. libxml_use_internal_errors(true);
  15. // separate test because this is included before sanity checks
  16. if (function_exists("mb_internal_encoding")) mb_internal_encoding("UTF-8");
  17. date_default_timezone_set('UTC');
  18. if (defined('E_DEPRECATED')) {
  19. error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
  20. } else {
  21. error_reporting(E_ALL & ~E_NOTICE);
  22. }
  23. require_once 'config.php';
  24. /**
  25. * Define a constant if not already defined
  26. */
  27. function define_default($name, $value) {
  28. defined($name) or define($name, $value);
  29. }
  30. /* Some tunables you can override in config.php using define(): */
  31. define_default('FEED_FETCH_TIMEOUT', 45);
  32. // How may seconds to wait for response when requesting feed from a site
  33. define_default('FEED_FETCH_NO_CACHE_TIMEOUT', 15);
  34. // How may seconds to wait for response when requesting feed from a
  35. // site when that feed wasn't cached before
  36. define_default('FILE_FETCH_TIMEOUT', 45);
  37. // Default timeout when fetching files from remote sites
  38. define_default('FILE_FETCH_CONNECT_TIMEOUT', 15);
  39. // How many seconds to wait for initial response from website when
  40. // fetching files from remote sites
  41. define_default('DAEMON_UPDATE_LOGIN_LIMIT', 30);
  42. // stop updating feeds if users haven't logged in for X days
  43. define_default('DAEMON_FEED_LIMIT', 500);
  44. // feed limit for one update batch
  45. define_default('DAEMON_SLEEP_INTERVAL', 120);
  46. // default sleep interval between feed updates (sec)
  47. define_default('MAX_CACHE_FILE_SIZE', 64*1024*1024);
  48. // do not cache files larger than that (bytes)
  49. define_default('MAX_DOWNLOAD_FILE_SIZE', 16*1024*1024);
  50. // do not download general files larger than that (bytes)
  51. define_default('CACHE_MAX_DAYS', 7);
  52. // max age in days for various automatically cached (temporary) files
  53. define_default('MAX_CONDITIONAL_INTERVAL', 3600*12);
  54. // max interval between forced unconditional updates for servers
  55. // not complying with http if-modified-since (seconds)
  56. define_default('MAX_FETCH_REQUESTS_PER_HOST', 25);
  57. // a maximum amount of allowed HTTP requests per destination host
  58. // during a single update (i.e. within PHP process lifetime)
  59. // this is used to not cause excessive load on the origin server on
  60. // e.g. feed subscription when all articles are being processes
  61. /* tunables end here */
  62. if (DB_TYPE == "pgsql") {
  63. define('SUBSTRING_FOR_DATE', 'SUBSTRING_FOR_DATE');
  64. } else {
  65. define('SUBSTRING_FOR_DATE', 'SUBSTRING');
  66. }
  67. /**
  68. * Return available translations names.
  69. *
  70. * @access public
  71. * @return array A array of available translations.
  72. */
  73. function get_translations() {
  74. $tr = array(
  75. "auto" => __("Detect automatically"),
  76. "ar_SA" => "العربيّة (Arabic)",
  77. "bg_BG" => "Bulgarian",
  78. "da_DA" => "Dansk",
  79. "ca_CA" => "Català",
  80. "cs_CZ" => "Česky",
  81. "en_US" => "English",
  82. "el_GR" => "Ελληνικά",
  83. "es_ES" => "Español (España)",
  84. "es_LA" => "Español",
  85. "de_DE" => "Deutsch",
  86. "fr_FR" => "Français",
  87. "hu_HU" => "Magyar (Hungarian)",
  88. "it_IT" => "Italiano",
  89. "ja_JP" => "日本語 (Japanese)",
  90. "lv_LV" => "Latviešu",
  91. "nb_NO" => "Norwegian bokmål",
  92. "nl_NL" => "Dutch",
  93. "pl_PL" => "Polski",
  94. "ru_RU" => "Русский",
  95. "pt_BR" => "Portuguese/Brazil",
  96. "pt_PT" => "Portuguese/Portugal",
  97. "zh_CN" => "Simplified Chinese",
  98. "zh_TW" => "Traditional Chinese",
  99. "uk_UA" => "Українська",
  100. "sv_SE" => "Svenska",
  101. "fi_FI" => "Suomi",
  102. "tr_TR" => "Türkçe");
  103. return $tr;
  104. }
  105. require_once "lib/accept-to-gettext.php";
  106. require_once "lib/gettext/gettext.inc";
  107. function startup_gettext() {
  108. # Get locale from Accept-Language header
  109. $lang = al2gt(array_keys(get_translations()), "text/html");
  110. if (defined('_TRANSLATION_OVERRIDE_DEFAULT')) {
  111. $lang = _TRANSLATION_OVERRIDE_DEFAULT;
  112. }
  113. if ($_SESSION["uid"] && get_schema_version() >= 120) {
  114. $pref_lang = get_pref("USER_LANGUAGE", $_SESSION["uid"]);
  115. if ($pref_lang && $pref_lang != 'auto') {
  116. $lang = $pref_lang;
  117. }
  118. }
  119. if ($lang) {
  120. if (defined('LC_MESSAGES')) {
  121. _setlocale(LC_MESSAGES, $lang);
  122. } else if (defined('LC_ALL')) {
  123. _setlocale(LC_ALL, $lang);
  124. }
  125. _bindtextdomain("messages", "locale");
  126. _textdomain("messages");
  127. _bind_textdomain_codeset("messages", "UTF-8");
  128. }
  129. }
  130. require_once 'db-prefs.php';
  131. require_once 'version.php';
  132. require_once 'controls.php';
  133. define('SELF_USER_AGENT', 'Tiny Tiny RSS/' . VERSION . ' (http://tt-rss.org/)');
  134. ini_set('user_agent', SELF_USER_AGENT);
  135. $schema_version = false;
  136. // TODO: compat wrapper, remove at some point
  137. function _debug($msg) {
  138. Debug::log($msg);
  139. }
  140. function reset_fetch_domain_quota() {
  141. global $fetch_domain_hits;
  142. $fetch_domain_hits = [];
  143. }
  144. // TODO: max_size currently only works for CURL transfers
  145. // TODO: multiple-argument way is deprecated, first parameter is a hash now
  146. function fetch_file_contents($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
  147. 4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false*/) {
  148. global $fetch_last_error;
  149. global $fetch_last_error_code;
  150. global $fetch_last_error_content;
  151. global $fetch_last_content_type;
  152. global $fetch_last_modified;
  153. global $fetch_effective_url;
  154. global $fetch_curl_used;
  155. global $fetch_domain_hits;
  156. $fetch_last_error = false;
  157. $fetch_last_error_code = -1;
  158. $fetch_last_error_content = "";
  159. $fetch_last_content_type = "";
  160. $fetch_curl_used = false;
  161. $fetch_last_modified = "";
  162. $fetch_effective_url = "";
  163. if (!is_array($fetch_domain_hits))
  164. $fetch_domain_hits = [];
  165. if (!is_array($options)) {
  166. // falling back on compatibility shim
  167. $option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "last_modified", "useragent" ];
  168. $tmp = [];
  169. for ($i = 0; $i < func_num_args(); $i++) {
  170. $tmp[$option_names[$i]] = func_get_arg($i);
  171. }
  172. $options = $tmp;
  173. /*$options = array(
  174. "url" => func_get_arg(0),
  175. "type" => @func_get_arg(1),
  176. "login" => @func_get_arg(2),
  177. "pass" => @func_get_arg(3),
  178. "post_query" => @func_get_arg(4),
  179. "timeout" => @func_get_arg(5),
  180. "timestamp" => @func_get_arg(6),
  181. "useragent" => @func_get_arg(7)
  182. ); */
  183. }
  184. $url = $options["url"];
  185. $type = isset($options["type"]) ? $options["type"] : false;
  186. $login = isset($options["login"]) ? $options["login"] : false;
  187. $pass = isset($options["pass"]) ? $options["pass"] : false;
  188. $post_query = isset($options["post_query"]) ? $options["post_query"] : false;
  189. $timeout = isset($options["timeout"]) ? $options["timeout"] : false;
  190. $last_modified = isset($options["last_modified"]) ? $options["last_modified"] : "";
  191. $useragent = isset($options["useragent"]) ? $options["useragent"] : false;
  192. $followlocation = isset($options["followlocation"]) ? $options["followlocation"] : true;
  193. $max_size = isset($options["max_size"]) ? $options["max_size"] : MAX_DOWNLOAD_FILE_SIZE; // in bytes
  194. $http_accept = isset($options["http_accept"]) ? $options["http_accept"] : false;
  195. $http_referrer = isset($options["http_referrer"]) ? $options["http_referrer"] : false;
  196. $url = ltrim($url, ' ');
  197. $url = str_replace(' ', '%20', $url);
  198. if (strpos($url, "//") === 0)
  199. $url = 'http:' . $url;
  200. $url_host = parse_url($url, PHP_URL_HOST);
  201. $fetch_domain_hits[$url_host] += 1;
  202. if ($fetch_domain_hits[$url_host] > MAX_FETCH_REQUESTS_PER_HOST) {
  203. user_error("Exceeded fetch request quota for $url_host: " . $fetch_domain_hits[$url_host], E_USER_WARNING);
  204. #return false;
  205. }
  206. if (!defined('NO_CURL') && function_exists('curl_init') && !ini_get("open_basedir")) {
  207. $fetch_curl_used = true;
  208. $ch = curl_init($url);
  209. $curl_http_headers = [];
  210. if ($last_modified && !$post_query)
  211. array_push($curl_http_headers, "If-Modified-Since: $last_modified");
  212. if ($http_accept)
  213. array_push($curl_http_headers, "Accept: " . $http_accept);
  214. if (count($curl_http_headers) > 0)
  215. curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_http_headers);
  216. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout ? $timeout : FILE_FETCH_CONNECT_TIMEOUT);
  217. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout ? $timeout : FILE_FETCH_TIMEOUT);
  218. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, !ini_get("open_basedir") && $followlocation);
  219. curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
  220. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  221. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  222. curl_setopt($ch, CURLOPT_HEADER, true);
  223. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  224. curl_setopt($ch, CURLOPT_USERAGENT, $useragent ? $useragent :
  225. SELF_USER_AGENT);
  226. curl_setopt($ch, CURLOPT_ENCODING, "");
  227. if ($http_referrer)
  228. curl_setopt($ch, CURLOPT_REFERER, $http_referrer);
  229. if ($max_size) {
  230. curl_setopt($ch, CURLOPT_NOPROGRESS, false);
  231. curl_setopt($ch, CURLOPT_BUFFERSIZE, 16384); // needed to get 5 arguments in progress function?
  232. // holy shit closures in php
  233. // download & upload are *expected* sizes respectively, could be zero
  234. curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($curl_handle, $download_size, $downloaded, $upload_size, $uploaded) use( &$max_size) {
  235. Debug::log("[curl progressfunction] $downloaded $max_size", Debug::$LOG_EXTENDED);
  236. return ($downloaded > $max_size) ? 1 : 0; // if max size is set, abort when exceeding it
  237. });
  238. }
  239. if (!ini_get("open_basedir")) {
  240. curl_setopt($ch, CURLOPT_COOKIEJAR, "/dev/null");
  241. }
  242. if (defined('_HTTP_PROXY')) {
  243. curl_setopt($ch, CURLOPT_PROXY, _HTTP_PROXY);
  244. }
  245. if ($post_query) {
  246. curl_setopt($ch, CURLOPT_POST, true);
  247. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);
  248. }
  249. if ($login && $pass)
  250. curl_setopt($ch, CURLOPT_USERPWD, "$login:$pass");
  251. $ret = @curl_exec($ch);
  252. $headers_length = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  253. $headers = explode("\r\n", substr($ret, 0, $headers_length));
  254. $contents = substr($ret, $headers_length);
  255. foreach ($headers as $header) {
  256. if (strstr($header, ": ") !== FALSE) {
  257. list ($key, $value) = explode(": ", $header);
  258. if (strtolower($key) == "last-modified") {
  259. $fetch_last_modified = $value;
  260. }
  261. }
  262. if (substr(strtolower($header), 0, 7) == 'http/1.') {
  263. $fetch_last_error_code = (int) substr($header, 9, 3);
  264. $fetch_last_error = $header;
  265. }
  266. }
  267. if (curl_errno($ch) === 23 || curl_errno($ch) === 61) {
  268. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  269. $contents = @curl_exec($ch);
  270. }
  271. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  272. $fetch_last_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  273. $fetch_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  274. $fetch_last_error_code = $http_code;
  275. if ($http_code != 200 || $type && strpos($fetch_last_content_type, "$type") === false) {
  276. if (curl_errno($ch) != 0) {
  277. $fetch_last_error .= "; " . curl_errno($ch) . " " . curl_error($ch);
  278. }
  279. $fetch_last_error_content = $contents;
  280. curl_close($ch);
  281. return false;
  282. }
  283. if (!$contents) {
  284. $fetch_last_error = curl_errno($ch) . " " . curl_error($ch);
  285. curl_close($ch);
  286. return false;
  287. }
  288. curl_close($ch);
  289. $is_gzipped = RSSUtils::is_gzipped($contents);
  290. if ($is_gzipped) {
  291. $tmp = @gzdecode($contents);
  292. if ($tmp) $contents = $tmp;
  293. }
  294. return $contents;
  295. } else {
  296. $fetch_curl_used = false;
  297. if ($login && $pass){
  298. $url_parts = array();
  299. preg_match("/(^[^:]*):\/\/(.*)/", $url, $url_parts);
  300. $pass = urlencode($pass);
  301. if ($url_parts[1] && $url_parts[2]) {
  302. $url = $url_parts[1] . "://$login:[email protected]" . $url_parts[2];
  303. }
  304. }
  305. // TODO: should this support POST requests or not? idk
  306. $context_options = array(
  307. 'http' => array(
  308. 'header' => array(
  309. 'Connection: close'
  310. ),
  311. 'method' => 'GET',
  312. 'ignore_errors' => true,
  313. 'timeout' => $timeout ? $timeout : FILE_FETCH_TIMEOUT,
  314. 'protocol_version'=> 1.1)
  315. );
  316. if (!$post_query && $last_modified)
  317. array_push($context_options['http']['header'], "If-Modified-Since: $last_modified");
  318. if ($http_accept)
  319. array_push($context_options['http']['header'], "Accept: $http_accept");
  320. if ($http_referrer)
  321. array_push($context_options['http']['header'], "Referer: $http_referrer");
  322. if (defined('_HTTP_PROXY')) {
  323. $context_options['http']['request_fulluri'] = true;
  324. $context_options['http']['proxy'] = _HTTP_PROXY;
  325. }
  326. $context = stream_context_create($context_options);
  327. $old_error = error_get_last();
  328. $fetch_effective_url = $url;
  329. $data = @file_get_contents($url, false, $context);
  330. if (isset($http_response_header) && is_array($http_response_header)) {
  331. foreach ($http_response_header as $header) {
  332. if (strstr($header, ": ") !== FALSE) {
  333. list ($key, $value) = explode(": ", $header);
  334. $key = strtolower($key);
  335. if ($key == 'content-type') {
  336. $fetch_last_content_type = $value;
  337. // don't abort here b/c there might be more than one
  338. // e.g. if we were being redirected -- last one is the right one
  339. } else if ($key == 'last-modified') {
  340. $fetch_last_modified = $value;
  341. } else if ($key == 'location') {
  342. $fetch_effective_url = $value;
  343. }
  344. }
  345. if (substr(strtolower($header), 0, 7) == 'http/1.') {
  346. $fetch_last_error_code = (int) substr($header, 9, 3);
  347. $fetch_last_error = $header;
  348. }
  349. }
  350. }
  351. if ($fetch_last_error_code != 200) {
  352. $error = error_get_last();
  353. if ($error['message'] != $old_error['message']) {
  354. $fetch_last_error .= "; " . $error["message"];
  355. }
  356. $fetch_last_error_content = $data;
  357. return false;
  358. }
  359. $is_gzipped = RSSUtils::is_gzipped($data);
  360. if ($is_gzipped) {
  361. $tmp = @gzdecode($data);
  362. if ($tmp) $data = $tmp;
  363. }
  364. return $data;
  365. }
  366. }
  367. function initialize_user_prefs($uid, $profile = false) {
  368. if (get_schema_version() < 63) $profile_qpart = "";
  369. $pdo = DB::pdo();
  370. $in_nested_tr = false;
  371. try {
  372. $pdo->beginTransaction();
  373. } catch (Exception $e) {
  374. $in_nested_tr = true;
  375. }
  376. $sth = $pdo->query("SELECT pref_name,def_value FROM ttrss_prefs");
  377. if (!is_numeric($profile) || !$profile || get_schema_version() < 63) $profile = null;
  378. $u_sth = $pdo->prepare("SELECT pref_name
  379. FROM ttrss_user_prefs WHERE owner_uid = :uid AND
  380. (profile = :profile OR (:profile IS NULL AND profile IS NULL))");
  381. $u_sth->execute([':uid' => $uid, ':profile' => $profile]);
  382. $active_prefs = array();
  383. while ($line = $u_sth->fetch()) {
  384. array_push($active_prefs, $line["pref_name"]);
  385. }
  386. while ($line = $sth->fetch()) {
  387. if (array_search($line["pref_name"], $active_prefs) === FALSE) {
  388. // print "adding " . $line["pref_name"] . "<br>";
  389. if (get_schema_version() < 63) {
  390. $i_sth = $pdo->prepare("INSERT INTO ttrss_user_prefs
  391. (owner_uid,pref_name,value) VALUES
  392. (?, ?, ?)");
  393. $i_sth->execute([$uid, $line["pref_name"], $line["def_value"]]);
  394. } else {
  395. $i_sth = $pdo->prepare("INSERT INTO ttrss_user_prefs
  396. (owner_uid,pref_name,value, profile) VALUES
  397. (?, ?, ?, ?)");
  398. $i_sth->execute([$uid, $line["pref_name"], $line["def_value"], $profile]);
  399. }
  400. }
  401. }
  402. if (!$in_nested_tr) $pdo->commit();
  403. }
  404. function get_ssl_certificate_id() {
  405. if ($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"]) {
  406. return sha1($_SERVER["REDIRECT_SSL_CLIENT_M_SERIAL"] .
  407. $_SERVER["REDIRECT_SSL_CLIENT_V_START"] .
  408. $_SERVER["REDIRECT_SSL_CLIENT_V_END"] .
  409. $_SERVER["REDIRECT_SSL_CLIENT_S_DN"]);
  410. }
  411. if ($_SERVER["SSL_CLIENT_M_SERIAL"]) {
  412. return sha1($_SERVER["SSL_CLIENT_M_SERIAL"] .
  413. $_SERVER["SSL_CLIENT_V_START"] .
  414. $_SERVER["SSL_CLIENT_V_END"] .
  415. $_SERVER["SSL_CLIENT_S_DN"]);
  416. }
  417. return "";
  418. }
  419. function authenticate_user($login, $password, $check_only = false, $service = false) {
  420. if (!SINGLE_USER_MODE) {
  421. $user_id = false;
  422. $auth_module = false;
  423. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_AUTH_USER) as $plugin) {
  424. $user_id = (int) $plugin->authenticate($login, $password, $service);
  425. if ($user_id) {
  426. $auth_module = strtolower(get_class($plugin));
  427. break;
  428. }
  429. }
  430. if ($user_id && !$check_only) {
  431. session_start();
  432. session_regenerate_id(true);
  433. $_SESSION["uid"] = $user_id;
  434. $_SESSION["auth_module"] = $auth_module;
  435. $pdo = DB::pdo();
  436. $sth = $pdo->prepare("SELECT login,access_level,pwd_hash FROM ttrss_users
  437. WHERE id = ?");
  438. $sth->execute([$user_id]);
  439. $row = $sth->fetch();
  440. $_SESSION["name"] = $row["login"];
  441. $_SESSION["access_level"] = $row["access_level"];
  442. $_SESSION["csrf_token"] = uniqid_short();
  443. $usth = $pdo->prepare("UPDATE ttrss_users SET last_login = NOW() WHERE id = ?");
  444. $usth->execute([$user_id]);
  445. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  446. $_SESSION["user_agent"] = sha1($_SERVER['HTTP_USER_AGENT']);
  447. $_SESSION["pwd_hash"] = $row["pwd_hash"];
  448. initialize_user_prefs($_SESSION["uid"]);
  449. return true;
  450. }
  451. return false;
  452. } else {
  453. $_SESSION["uid"] = 1;
  454. $_SESSION["name"] = "admin";
  455. $_SESSION["access_level"] = 10;
  456. $_SESSION["hide_hello"] = true;
  457. $_SESSION["hide_logout"] = true;
  458. $_SESSION["auth_module"] = false;
  459. if (!$_SESSION["csrf_token"]) {
  460. $_SESSION["csrf_token"] = uniqid_short();
  461. }
  462. $_SESSION["ip_address"] = $_SERVER["REMOTE_ADDR"];
  463. initialize_user_prefs($_SESSION["uid"]);
  464. return true;
  465. }
  466. }
  467. // this is used for user http parameters unless HTML code is actually needed
  468. function clean($param) {
  469. if (is_array($param)) {
  470. return array_map("strip_tags", $param);
  471. } else if (is_string($param)) {
  472. return strip_tags($param);
  473. } else {
  474. return $param;
  475. }
  476. }
  477. function clean_filename($filename) {
  478. return basename(preg_replace("/\.\.|[\/\\\]/", "", clean($filename)));
  479. }
  480. function make_password($length = 12) {
  481. $password = "";
  482. $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ*%+^";
  483. $i = 0;
  484. while ($i < $length) {
  485. try {
  486. $idx = function_exists("random_int") ? random_int(0, strlen($possible) - 1) : mt_rand(0, strlen($possible) - 1);
  487. } catch (Exception $e) {
  488. $idx = mt_rand(0, strlen($possible) - 1);
  489. }
  490. $char = substr($possible, $idx, 1);
  491. if (!strstr($password, $char)) {
  492. $password .= $char;
  493. $i++;
  494. }
  495. }
  496. return $password;
  497. }
  498. // this is called after user is created to initialize default feeds, labels
  499. // or whatever else
  500. // user preferences are checked on every login, not here
  501. function initialize_user($uid) {
  502. $pdo = DB::pdo();
  503. $sth = $pdo->prepare("insert into ttrss_feeds (owner_uid,title,feed_url)
  504. values (?, 'Tiny Tiny RSS: Forum',
  505. 'http://tt-rss.org/forum/rss.php')");
  506. $sth->execute([$uid]);
  507. }
  508. function logout_user() {
  509. @session_destroy();
  510. if (isset($_COOKIE[session_name()])) {
  511. setcookie(session_name(), '', time()-42000, '/');
  512. }
  513. session_commit();
  514. }
  515. function validate_csrf($csrf_token) {
  516. return $csrf_token == $_SESSION['csrf_token'];
  517. }
  518. function load_user_plugins($owner_uid, $pluginhost = false) {
  519. if (!$pluginhost) $pluginhost = PluginHost::getInstance();
  520. if ($owner_uid && SCHEMA_VERSION >= 100) {
  521. $plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
  522. $pluginhost->load($plugins, PluginHost::KIND_USER, $owner_uid);
  523. if (get_schema_version() > 100) {
  524. $pluginhost->load_data();
  525. }
  526. }
  527. }
  528. function login_sequence() {
  529. $pdo = Db::pdo();
  530. if (SINGLE_USER_MODE) {
  531. @session_start();
  532. authenticate_user("admin", null);
  533. startup_gettext();
  534. load_user_plugins($_SESSION["uid"]);
  535. } else {
  536. if (!validate_session()) $_SESSION["uid"] = false;
  537. if (!$_SESSION["uid"]) {
  538. if (AUTH_AUTO_LOGIN && authenticate_user(null, null)) {
  539. $_SESSION["ref_schema_version"] = get_schema_version(true);
  540. } else {
  541. authenticate_user(null, null, true);
  542. }
  543. if (!$_SESSION["uid"]) {
  544. logout_user();
  545. render_login_form();
  546. exit;
  547. }
  548. } else {
  549. /* bump login timestamp */
  550. $sth = $pdo->prepare("UPDATE ttrss_users SET last_login = NOW() WHERE id = ?");
  551. $sth->execute([$_SESSION['uid']]);
  552. $_SESSION["last_login_update"] = time();
  553. }
  554. if ($_SESSION["uid"]) {
  555. startup_gettext();
  556. load_user_plugins($_SESSION["uid"]);
  557. /* cleanup ccache */
  558. $sth = $pdo->prepare("DELETE FROM ttrss_counters_cache WHERE owner_uid = ?
  559. AND
  560. (SELECT COUNT(id) FROM ttrss_feeds WHERE
  561. ttrss_feeds.id = feed_id) = 0");
  562. $sth->execute([$_SESSION['uid']]);
  563. $sth = $pdo->prepare("DELETE FROM ttrss_cat_counters_cache WHERE owner_uid = ?
  564. AND
  565. (SELECT COUNT(id) FROM ttrss_feed_categories WHERE
  566. ttrss_feed_categories.id = feed_id) = 0");
  567. $sth->execute([$_SESSION['uid']]);
  568. }
  569. }
  570. }
  571. function truncate_string($str, $max_len, $suffix = '&hellip;') {
  572. if (mb_strlen($str, "utf-8") > $max_len) {
  573. return mb_substr($str, 0, $max_len, "utf-8") . $suffix;
  574. } else {
  575. return $str;
  576. }
  577. }
  578. function mb_substr_replace($original, $replacement, $position, $length) {
  579. $startString = mb_substr($original, 0, $position, "UTF-8");
  580. $endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
  581. $out = $startString . $replacement . $endString;
  582. return $out;
  583. }
  584. function truncate_middle($str, $max_len, $suffix = '&hellip;') {
  585. if (mb_strlen($str) > $max_len) {
  586. return mb_substr_replace($str, $suffix, $max_len / 2, mb_strlen($str) - $max_len);
  587. } else {
  588. return $str;
  589. }
  590. }
  591. function convert_timestamp($timestamp, $source_tz, $dest_tz) {
  592. try {
  593. $source_tz = new DateTimeZone($source_tz);
  594. } catch (Exception $e) {
  595. $source_tz = new DateTimeZone('UTC');
  596. }
  597. try {
  598. $dest_tz = new DateTimeZone($dest_tz);
  599. } catch (Exception $e) {
  600. $dest_tz = new DateTimeZone('UTC');
  601. }
  602. $dt = new DateTime(date('Y-m-d H:i:s', $timestamp), $source_tz);
  603. return $dt->format('U') + $dest_tz->getOffset($dt);
  604. }
  605. function make_local_datetime($timestamp, $long, $owner_uid = false,
  606. $no_smart_dt = false, $eta_min = false) {
  607. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  608. if (!$timestamp) $timestamp = '1970-01-01 0:00';
  609. global $utc_tz;
  610. global $user_tz;
  611. if (!$utc_tz) $utc_tz = new DateTimeZone('UTC');
  612. $timestamp = substr($timestamp, 0, 19);
  613. # We store date in UTC internally
  614. $dt = new DateTime($timestamp, $utc_tz);
  615. $user_tz_string = get_pref('USER_TIMEZONE', $owner_uid);
  616. if ($user_tz_string != 'Automatic') {
  617. try {
  618. if (!$user_tz) $user_tz = new DateTimeZone($user_tz_string);
  619. } catch (Exception $e) {
  620. $user_tz = $utc_tz;
  621. }
  622. $tz_offset = $user_tz->getOffset($dt);
  623. } else {
  624. $tz_offset = (int) -$_SESSION["clientTzOffset"];
  625. }
  626. $user_timestamp = $dt->format('U') + $tz_offset;
  627. if (!$no_smart_dt) {
  628. return smart_date_time($user_timestamp,
  629. $tz_offset, $owner_uid, $eta_min);
  630. } else {
  631. if ($long)
  632. $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
  633. else
  634. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  635. return date($format, $user_timestamp);
  636. }
  637. }
  638. function smart_date_time($timestamp, $tz_offset = 0, $owner_uid = false, $eta_min = false) {
  639. if (!$owner_uid) $owner_uid = $_SESSION['uid'];
  640. if ($eta_min && time() + $tz_offset - $timestamp < 3600) {
  641. return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
  642. } else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
  643. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  644. if (strpos((strtolower($format)), "a") === false)
  645. return date("G:i", $timestamp);
  646. else
  647. return date("g:i a", $timestamp);
  648. } else if (date("Y", $timestamp) == date("Y", time() + $tz_offset)) {
  649. $format = get_pref('SHORT_DATE_FORMAT', $owner_uid);
  650. return date($format, $timestamp);
  651. } else {
  652. $format = get_pref('LONG_DATE_FORMAT', $owner_uid);
  653. return date($format, $timestamp);
  654. }
  655. }
  656. function sql_bool_to_bool($s) {
  657. return $s && ($s !== "f" && $s !== "false"); //no-op for PDO, backwards compat for legacy layer
  658. }
  659. function bool_to_sql_bool($s) {
  660. return $s ? 1 : 0;
  661. }
  662. // Session caching removed due to causing wrong redirects to upgrade
  663. // script when get_schema_version() is called on an obsolete session
  664. // created on a previous schema version.
  665. function get_schema_version($nocache = false) {
  666. global $schema_version;
  667. $pdo = DB::pdo();
  668. if (!$schema_version && !$nocache) {
  669. $row = $pdo->query("SELECT schema_version FROM ttrss_version")->fetch();
  670. $version = $row["schema_version"];
  671. $schema_version = $version;
  672. return $version;
  673. } else {
  674. return $schema_version;
  675. }
  676. }
  677. function sanity_check() {
  678. require_once 'errors.php';
  679. global $ERRORS;
  680. $error_code = 0;
  681. $schema_version = get_schema_version(true);
  682. if ($schema_version != SCHEMA_VERSION) {
  683. $error_code = 5;
  684. }
  685. return array("code" => $error_code, "message" => $ERRORS[$error_code]);
  686. }
  687. function file_is_locked($filename) {
  688. if (file_exists(LOCK_DIRECTORY . "/$filename")) {
  689. if (function_exists('flock')) {
  690. $fp = @fopen(LOCK_DIRECTORY . "/$filename", "r");
  691. if ($fp) {
  692. if (flock($fp, LOCK_EX | LOCK_NB)) {
  693. flock($fp, LOCK_UN);
  694. fclose($fp);
  695. return false;
  696. }
  697. fclose($fp);
  698. return true;
  699. } else {
  700. return false;
  701. }
  702. }
  703. return true; // consider the file always locked and skip the test
  704. } else {
  705. return false;
  706. }
  707. }
  708. function make_lockfile($filename) {
  709. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  710. if ($fp && flock($fp, LOCK_EX | LOCK_NB)) {
  711. $stat_h = fstat($fp);
  712. $stat_f = stat(LOCK_DIRECTORY . "/$filename");
  713. if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
  714. if ($stat_h["ino"] != $stat_f["ino"] ||
  715. $stat_h["dev"] != $stat_f["dev"]) {
  716. return false;
  717. }
  718. }
  719. if (function_exists('posix_getpid')) {
  720. fwrite($fp, posix_getpid() . "\n");
  721. }
  722. return $fp;
  723. } else {
  724. return false;
  725. }
  726. }
  727. function make_stampfile($filename) {
  728. $fp = fopen(LOCK_DIRECTORY . "/$filename", "w");
  729. if (flock($fp, LOCK_EX | LOCK_NB)) {
  730. fwrite($fp, time() . "\n");
  731. flock($fp, LOCK_UN);
  732. fclose($fp);
  733. return true;
  734. } else {
  735. return false;
  736. }
  737. }
  738. function sql_random_function() {
  739. if (DB_TYPE == "mysql") {
  740. return "RAND()";
  741. } else {
  742. return "RANDOM()";
  743. }
  744. }
  745. function getFeedUnread($feed, $is_cat = false) {
  746. return Feeds::getFeedArticles($feed, $is_cat, true, $_SESSION["uid"]);
  747. }
  748. function checkbox_to_sql_bool($val) {
  749. return ($val == "on") ? 1 : 0;
  750. }
  751. function uniqid_short() {
  752. return uniqid(base_convert(rand(), 10, 36));
  753. }
  754. function make_init_params() {
  755. $params = array();
  756. foreach (array("ON_CATCHUP_SHOW_NEXT_FEED", "HIDE_READ_FEEDS",
  757. "ENABLE_FEED_CATS", "FEEDS_SORT_BY_UNREAD", "CONFIRM_FEED_CATCHUP",
  758. "CDM_AUTO_CATCHUP", "FRESH_ARTICLE_MAX_AGE",
  759. "HIDE_READ_SHOWS_SPECIAL", "COMBINED_DISPLAY_MODE") as $param) {
  760. $params[strtolower($param)] = (int) get_pref($param);
  761. }
  762. $params["check_for_updates"] = CHECK_FOR_UPDATES;
  763. $params["icons_url"] = ICONS_URL;
  764. $params["cookie_lifetime"] = SESSION_COOKIE_LIFETIME;
  765. $params["default_view_mode"] = get_pref("_DEFAULT_VIEW_MODE");
  766. $params["default_view_limit"] = (int) get_pref("_DEFAULT_VIEW_LIMIT");
  767. $params["default_view_order_by"] = get_pref("_DEFAULT_VIEW_ORDER_BY");
  768. $params["bw_limit"] = (int) $_SESSION["bw_limit"];
  769. $params["is_default_pw"] = Pref_Prefs::isdefaultpassword();
  770. $params["label_base_index"] = (int) LABEL_BASE_INDEX;
  771. $theme = get_pref( "USER_CSS_THEME", false, false);
  772. $params["theme"] = theme_exists($theme) ? $theme : "";
  773. $params["plugins"] = implode(", ", PluginHost::getInstance()->get_plugin_names());
  774. $params["php_platform"] = PHP_OS;
  775. $params["php_version"] = PHP_VERSION;
  776. $params["sanity_checksum"] = sha1(file_get_contents("include/sanity_check.php"));
  777. $pdo = Db::pdo();
  778. $sth = $pdo->prepare("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  779. ttrss_feeds WHERE owner_uid = ?");
  780. $sth->execute([$_SESSION['uid']]);
  781. $row = $sth->fetch();
  782. $max_feed_id = $row["mid"];
  783. $num_feeds = $row["nf"];
  784. $params["max_feed_id"] = (int) $max_feed_id;
  785. $params["num_feeds"] = (int) $num_feeds;
  786. $params["hotkeys"] = get_hotkeys_map();
  787. $params["csrf_token"] = $_SESSION["csrf_token"];
  788. $params["widescreen"] = (int) $_COOKIE["ttrss_widescreen"];
  789. $params['simple_update'] = defined('SIMPLE_UPDATE_MODE') && SIMPLE_UPDATE_MODE;
  790. $params["icon_indicator_white"] = base64_img("images/indicator_white.gif");
  791. $params["labels"] = Labels::get_all_labels($_SESSION["uid"]);
  792. return $params;
  793. }
  794. function get_hotkeys_info() {
  795. $hotkeys = array(
  796. __("Navigation") => array(
  797. "next_feed" => __("Open next feed"),
  798. "prev_feed" => __("Open previous feed"),
  799. "next_article_or_scroll" => __("Open next article (in combined mode, scroll down)"),
  800. "prev_article_or_scroll" => __("Open previous article (in combined mode, scroll up)"),
  801. "next_article_page" => __("Scroll article by one page down"),
  802. "prev_article_page" => __("Scroll article by one page up"),
  803. "next_article_noscroll" => __("Open next article"),
  804. "prev_article_noscroll" => __("Open previous article"),
  805. "next_article_noexpand" => __("Move to next article (don't expand or mark read)"),
  806. "prev_article_noexpand" => __("Move to previous article (don't expand or mark read)"),
  807. "search_dialog" => __("Show search dialog")),
  808. __("Article") => array(
  809. "toggle_mark" => __("Toggle starred"),
  810. "toggle_publ" => __("Toggle published"),
  811. "toggle_unread" => __("Toggle unread"),
  812. "edit_tags" => __("Edit tags"),
  813. "open_in_new_window" => __("Open in new window"),
  814. "catchup_below" => __("Mark below as read"),
  815. "catchup_above" => __("Mark above as read"),
  816. "article_scroll_down" => __("Scroll down"),
  817. "article_scroll_up" => __("Scroll up"),
  818. "article_page_down" => __("Scroll down page"),
  819. "article_page_up" => __("Scroll up page"),
  820. "select_article_cursor" => __("Select article under cursor"),
  821. "email_article" => __("Email article"),
  822. "close_article" => __("Close/collapse article"),
  823. "toggle_expand" => __("Toggle article expansion (combined mode)"),
  824. "toggle_widescreen" => __("Toggle widescreen mode"),
  825. "toggle_embed_original" => __("Toggle embed original")),
  826. __("Article selection") => array(
  827. "select_all" => __("Select all articles"),
  828. "select_unread" => __("Select unread"),
  829. "select_marked" => __("Select starred"),
  830. "select_published" => __("Select published"),
  831. "select_invert" => __("Invert selection"),
  832. "select_none" => __("Deselect everything")),
  833. __("Feed") => array(
  834. "feed_refresh" => __("Refresh current feed"),
  835. "feed_unhide_read" => __("Un/hide read feeds"),
  836. "feed_subscribe" => __("Subscribe to feed"),
  837. "feed_edit" => __("Edit feed"),
  838. "feed_catchup" => __("Mark as read"),
  839. "feed_reverse" => __("Reverse headlines"),
  840. "feed_toggle_vgroup" => __("Toggle headline grouping"),
  841. "feed_debug_update" => __("Debug feed update"),
  842. "feed_debug_viewfeed" => __("Debug viewfeed()"),
  843. "catchup_all" => __("Mark all feeds as read"),
  844. "cat_toggle_collapse" => __("Un/collapse current category"),
  845. "toggle_cdm_expanded" => __("Toggle auto expand in combined mode"),
  846. "toggle_combined_mode" => __("Toggle combined mode")),
  847. __("Go to") => array(
  848. "goto_all" => __("All articles"),
  849. "goto_fresh" => __("Fresh"),
  850. "goto_marked" => __("Starred"),
  851. "goto_published" => __("Published"),
  852. "goto_read" => __("Recently read"),
  853. "goto_tagcloud" => __("Tag cloud"),
  854. "goto_prefs" => __("Preferences")),
  855. __("Other") => array(
  856. "create_label" => __("Create label"),
  857. "create_filter" => __("Create filter"),
  858. "collapse_sidebar" => __("Un/collapse sidebar"),
  859. "help_dialog" => __("Show help dialog"))
  860. );
  861. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_INFO) as $plugin) {
  862. $hotkeys = $plugin->hook_hotkey_info($hotkeys);
  863. }
  864. return $hotkeys;
  865. }
  866. function get_hotkeys_map() {
  867. $hotkeys = array(
  868. "k" => "next_feed",
  869. "j" => "prev_feed",
  870. "n" => "next_article_noscroll",
  871. "p" => "prev_article_noscroll",
  872. //"(33)|PageUp" => "prev_article_page",
  873. //"(34)|PageDown" => "next_article_page",
  874. "*(33)|Shift+PgUp" => "article_page_up",
  875. "*(34)|Shift+PgDn" => "article_page_down",
  876. "(38)|Up" => "prev_article_or_scroll",
  877. "(40)|Down" => "next_article_or_scroll",
  878. "*(38)|Shift+Up" => "article_scroll_up",
  879. "*(40)|Shift+Down" => "article_scroll_down",
  880. "^(38)|Ctrl+Up" => "prev_article_noscroll",
  881. "^(40)|Ctrl+Down" => "next_article_noscroll",
  882. "/" => "search_dialog",
  883. "s" => "toggle_mark",
  884. "S" => "toggle_publ",
  885. "u" => "toggle_unread",
  886. "T" => "edit_tags",
  887. "o" => "open_in_new_window",
  888. "c p" => "catchup_below",
  889. "c n" => "catchup_above",
  890. "N" => "article_scroll_down",
  891. "P" => "article_scroll_up",
  892. "a W" => "toggle_widescreen",
  893. "a e" => "toggle_embed_original",
  894. "e" => "email_article",
  895. "a q" => "close_article",
  896. "a a" => "select_all",
  897. "a u" => "select_unread",
  898. "a U" => "select_marked",
  899. "a p" => "select_published",
  900. "a i" => "select_invert",
  901. "a n" => "select_none",
  902. "f r" => "feed_refresh",
  903. "f a" => "feed_unhide_read",
  904. "f s" => "feed_subscribe",
  905. "f e" => "feed_edit",
  906. "f q" => "feed_catchup",
  907. "f x" => "feed_reverse",
  908. "f g" => "feed_toggle_vgroup",
  909. "f D" => "feed_debug_update",
  910. "f G" => "feed_debug_viewfeed",
  911. "f C" => "toggle_combined_mode",
  912. "f c" => "toggle_cdm_expanded",
  913. "Q" => "catchup_all",
  914. "x" => "cat_toggle_collapse",
  915. "g a" => "goto_all",
  916. "g f" => "goto_fresh",
  917. "g s" => "goto_marked",
  918. "g p" => "goto_published",
  919. "g r" => "goto_read",
  920. "g t" => "goto_tagcloud",
  921. "g P" => "goto_prefs",
  922. "r" => "select_article_cursor",
  923. "c l" => "create_label",
  924. "c f" => "create_filter",
  925. "c s" => "collapse_sidebar",
  926. "?" => "help_dialog",
  927. );
  928. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_HOTKEY_MAP) as $plugin) {
  929. $hotkeys = $plugin->hook_hotkey_map($hotkeys);
  930. }
  931. $prefixes = array();
  932. foreach (array_keys($hotkeys) as $hotkey) {
  933. $pair = explode(" ", $hotkey, 2);
  934. if (count($pair) > 1 && !in_array($pair[0], $prefixes)) {
  935. array_push($prefixes, $pair[0]);
  936. }
  937. }
  938. return array($prefixes, $hotkeys);
  939. }
  940. function make_runtime_info() {
  941. $data = array();
  942. $pdo = Db::pdo();
  943. $sth = $pdo->prepare("SELECT MAX(id) AS mid, COUNT(*) AS nf FROM
  944. ttrss_feeds WHERE owner_uid = ?");
  945. $sth->execute([$_SESSION['uid']]);
  946. $row = $sth->fetch();
  947. $max_feed_id = $row['mid'];
  948. $num_feeds = $row['nf'];
  949. $data["max_feed_id"] = (int) $max_feed_id;
  950. $data["num_feeds"] = (int) $num_feeds;
  951. $data['cdm_expanded'] = get_pref('CDM_EXPANDED');
  952. $data["labels"] = Labels::get_all_labels($_SESSION["uid"]);
  953. if (LOG_DESTINATION == 'sql' && $_SESSION['access_level'] >= 10) {
  954. if (DB_TYPE == 'pgsql') {
  955. $log_interval = "created_at > NOW() - interval '1 hour'";
  956. } else {
  957. $log_interval = "created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)";
  958. }
  959. $sth = $pdo->prepare("SELECT COUNT(id) AS cid FROM ttrss_error_log WHERE $log_interval");
  960. $sth->execute();
  961. if ($row = $sth->fetch()) {
  962. $data['recent_log_events'] = $row['cid'];
  963. }
  964. }
  965. if (file_exists(LOCK_DIRECTORY . "/update_daemon.lock")) {
  966. $data['daemon_is_running'] = (int) file_is_locked("update_daemon.lock");
  967. if (time() - $_SESSION["daemon_stamp_check"] > 30) {
  968. $stamp = (int) @file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp");
  969. if ($stamp) {
  970. $stamp_delta = time() - $stamp;
  971. if ($stamp_delta > 1800) {
  972. $stamp_check = 0;
  973. } else {
  974. $stamp_check = 1;
  975. $_SESSION["daemon_stamp_check"] = time();
  976. }
  977. $data['daemon_stamp_ok'] = $stamp_check;
  978. $stamp_fmt = date("Y.m.d, G:i", $stamp);
  979. $data['daemon_stamp'] = $stamp_fmt;
  980. }
  981. }
  982. }
  983. return $data;
  984. }
  985. function iframe_whitelisted($entry) {
  986. @$src = parse_url($entry->getAttribute("src"), PHP_URL_HOST);
  987. if ($src) {
  988. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_IFRAME_WHITELISTED) as $plugin) {
  989. if ($plugin->hook_iframe_whitelisted($src))
  990. return true;
  991. }
  992. }
  993. return false;
  994. }
  995. function sanitize($str, $force_remove_images = false, $owner = false, $site_url = false, $highlight_words = false, $article_id = false) {
  996. if (!$owner) $owner = $_SESSION["uid"];
  997. $res = trim($str); if (!$res) return '';
  998. $doc = new DOMDocument();
  999. $doc->loadHTML('<?xml encoding="UTF-8">' . $res);
  1000. $xpath = new DOMXPath($doc);
  1001. $rewrite_base_url = $site_url ? $site_url : get_self_url_prefix();
  1002. $entries = $xpath->query('(//a[@href]|//img[@src]|//video/source[@src]|//audio/source[@src]|//picture/source[@src])');
  1003. foreach ($entries as $entry) {
  1004. if ($entry->hasAttribute('href')) {
  1005. $entry->setAttribute('href',
  1006. rewrite_relative_url($rewrite_base_url, $entry->getAttribute('href')));
  1007. $entry->setAttribute('rel', 'noopener noreferrer');
  1008. }
  1009. if ($entry->hasAttribute('src')) {
  1010. $src = rewrite_relative_url($rewrite_base_url, $entry->getAttribute('src'));
  1011. $entry->setAttribute('src', $src);
  1012. }
  1013. if ($entry->nodeName == 'img') {
  1014. $entry->setAttribute('referrerpolicy', 'no-referrer');
  1015. $entry->removeAttribute('width');
  1016. $entry->removeAttribute('height');
  1017. if ($entry->hasAttribute('src')) {
  1018. $is_https_url = parse_url($entry->getAttribute('src'), PHP_URL_SCHEME) === 'https';
  1019. if (is_prefix_https() && !$is_https_url) {
  1020. if ($entry->hasAttribute('srcset')) {
  1021. $entry->removeAttribute('srcset');
  1022. }
  1023. if ($entry->hasAttribute('sizes')) {
  1024. $entry->removeAttribute('sizes');
  1025. }
  1026. }
  1027. }
  1028. }
  1029. if ($entry->hasAttribute('src') &&
  1030. ($owner && get_pref("STRIP_IMAGES", $owner)) || $force_remove_images || $_SESSION["bw_limit"]) {
  1031. $p = $doc->createElement('p');
  1032. $a = $doc->createElement('a');
  1033. $a->setAttribute('href', $entry->getAttribute('src'));
  1034. $a->appendChild(new DOMText($entry->getAttribute('src')));
  1035. $a->setAttribute('target', '_blank');
  1036. $a->setAttribute('rel', 'noopener noreferrer');
  1037. $p->appendChild($a);
  1038. if ($entry->nodeName == 'source') {
  1039. if ($entry->parentNode && $entry->parentNode->parentNode)
  1040. $entry->parentNode->parentNode->replaceChild($p, $entry->parentNode);
  1041. } else if ($entry->nodeName == 'img') {
  1042. if ($entry->parentNode)
  1043. $entry->parentNode->replaceChild($p, $entry);
  1044. }
  1045. }
  1046. if (strtolower($entry->nodeName) == "a") {
  1047. $entry->setAttribute("target", "_blank");
  1048. $entry->setAttribute("rel", "noopener noreferrer");
  1049. }
  1050. }
  1051. $entries = $xpath->query('//iframe');
  1052. foreach ($entries as $entry) {
  1053. if (!iframe_whitelisted($entry)) {
  1054. $entry->setAttribute('sandbox', 'allow-scripts');
  1055. } else {
  1056. if (is_prefix_https()) {
  1057. $entry->setAttribute("src",
  1058. str_replace("http://", "https://",
  1059. $entry->getAttribute("src")));
  1060. }
  1061. }
  1062. }
  1063. $allowed_elements = array('a', 'abbr', 'address', 'acronym', 'audio', 'article', 'aside',
  1064. 'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
  1065. 'caption', 'cite', 'center', 'code', 'col', 'colgroup',
  1066. 'data', 'dd', 'del', 'details', 'description', 'dfn', 'div', 'dl', 'font',
  1067. 'dt', 'em', 'footer', 'figure', 'figcaption',
  1068. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'html', 'i',
  1069. 'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
  1070. 'ol', 'p', 'picture', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
  1071. 'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
  1072. 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
  1073. 'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video', 'xml:namespace' );
  1074. if ($_SESSION['hasSandbox']) $allowed_elements[] = 'iframe';
  1075. $disallowed_attributes = array('id', 'style', 'class');
  1076. foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SANITIZE) as $plugin) {
  1077. $retval = $plugin->hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes, $article_id);
  1078. if (is_array($retval)) {
  1079. $doc = $retval[0];
  1080. $allowed_elements = $retval[1];
  1081. $disallowed_attributes = $retval[2];
  1082. } else {
  1083. $doc = $retval;
  1084. }
  1085. }
  1086. $doc->removeChild($doc->firstChild); //remove doctype
  1087. $doc = strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
  1088. if ($highlight_words) {
  1089. foreach ($highlight_words as $word) {
  1090. // http://stackoverflow.com/questions/4081372/highlight-keywords-in-a-paragraph
  1091. $elements = $xpath->query("//*/text()");
  1092. foreach ($elements as $child) {
  1093. $fragment = $doc->createDocumentFragment();
  1094. $text = $child->textContent;
  1095. while (($pos = mb_stripos($text, $word)) !== false) {
  1096. $fragment->appendChild(new DomText(mb_substr($text, 0, $pos)));
  1097. $word = mb_substr($text, $pos, mb_strlen($word));
  1098. $highlight = $doc->createElement('span');
  1099. $highlight->appendChild(new DomText($word));
  1100. $highlight->setAttribute('class', 'highlight');
  1101. $fragment->appendChild($highlight);
  1102. $text = mb_substr($text, $pos + mb_strlen($word));
  1103. }
  1104. if (!empty($text)) $fragment->appendChild(new DomText($text));
  1105. $child->parentNode->replaceChild($fragment, $child);
  1106. }
  1107. }
  1108. }
  1109. $res = $doc->saveHTML();
  1110. /* strip everything outside of <body>...</body> */
  1111. $res_frag = array();
  1112. if (preg_match('/<body>(.*)<\/body>/is', $res, $res_frag)) {
  1113. return $res_frag[1];
  1114. } else {
  1115. return $res;
  1116. }
  1117. }
  1118. function strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes) {
  1119. $xpath = new DOMXPath($doc);
  1120. $entries = $xpath->query('//*');
  1121. foreach ($entries as $entry) {
  1122. if (!in_array($entry->nodeName, $allowed_elements)) {
  1123. $entry->parentNode->removeChild($entry);
  1124. }
  1125. if ($entry->hasAttributes()) {
  1126. $attrs_to_remove = array();
  1127. foreach ($entry->attributes as $attr) {
  1128. if (strpos($attr->nodeName, 'on') === 0) {
  1129. array_push($attrs_to_remove, $attr);
  1130. }
  1131. if (strpos($attr->nodeName, "data-") === 0) {
  1132. array_push($attrs_to_remove, $attr);
  1133. }
  1134. if ($attr->nodeName == 'href' && stripos($attr->value, 'javascript:') === 0) {
  1135. array_push($attrs_to_remove, $attr);
  1136. }
  1137. if (in_array($attr->nodeName, $disallowed_attributes)) {
  1138. array_push($attrs_to_remove, $attr);
  1139. }
  1140. }
  1141. foreach ($attrs_to_remove as $attr) {
  1142. $entry->removeAttributeNode($attr);
  1143. }
  1144. }
  1145. }
  1146. return $doc;
  1147. }
  1148. function trim_array($array) {
  1149. $tmp = $array;
  1150. array_walk($tmp, 'trim');
  1151. return $tmp;
  1152. }
  1153. function render_login_form() {
  1154. header('Cache-Control: public');
  1155. require_once "login_form.php";
  1156. exit;
  1157. }
  1158. function T_sprintf() {
  1159. $args = func_get_args();
  1160. return vsprintf(__(array_shift($args)), $args);
  1161. }
  1162. function print_checkpoint($n, $s) {
  1163. $ts = microtime(true);
  1164. echo sprintf("<!-- CP[$n] %.4f seconds -->\n", $ts - $s);
  1165. return $ts;
  1166. }
  1167. function is_server_https() {
  1168. return (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off')) || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
  1169. }
  1170. function is_prefix_https() {
  1171. return parse_url(SELF_URL_PATH, PHP_URL_SCHEME) == 'https';
  1172. }
  1173. // this returns SELF_URL_PATH sans ending slash
  1174. function get_self_url_prefix() {
  1175. if (strrpos(SELF_URL_PATH, "/") === strlen(SELF_URL_PATH)-1) {
  1176. return substr(SELF_URL_PATH, 0, strlen(SELF_URL_PATH)-1);
  1177. } else {
  1178. return SELF_URL_PATH;
  1179. }
  1180. }
  1181. function encrypt_password($pass, $salt = '', $mode2 = false) {
  1182. if ($salt && $mode2) {
  1183. return "MODE2:" . hash('sha256', $salt . $pass);
  1184. } else if ($salt) {
  1185. return "SHA1X:" . sha1("$salt:$pass");
  1186. } else {
  1187. return "SHA1:" . sha1($pass);
  1188. }
  1189. } // function encrypt_password
  1190. function init_plugins() {
  1191. PluginHost::getInstance()->load(PLUGINS, PluginHost::KIND_ALL);
  1192. return true;
  1193. }
  1194. function build_url($parts) {
  1195. return $parts['scheme'] . "://" . $parts['host'] . $parts['path'];
  1196. }
  1197. function cleanup_url_path($path) {
  1198. $path = str_replace("/./", "/", $path);
  1199. $path = str_replace("//", "/", $path);
  1200. return $path;
  1201. }
  1202. /**
  1203. * Converts a (possibly) relative URL to a absolute one.
  1204. *
  1205. * @param string $url Base URL (i.e. from where the document is)
  1206. * @param string $rel_url Possibly relative URL in the document
  1207. *
  1208. * @return string Absolute URL
  1209. */
  1210. function rewrite_relative_url($url, $rel_url) {
  1211. if (strpos($rel_url, "://") !== false) {
  1212. return $rel_url;
  1213. } else if (strpos($rel_url, "//") === 0) {
  1214. # protocol-relative URL (rare but they exist)
  1215. return $rel_url;
  1216. } else if (preg_match("/^[a-z]+:/i", $rel_url)) {
  1217. # magnet:, feed:, etc
  1218. return $rel_url;
  1219. } else if (strpos($rel_url, "/") === 0) {
  1220. $parts = parse_url($url);
  1221. $parts['path'] = $rel_url;
  1222. $parts['path'] = cleanup_url_path($parts['path']);
  1223. return build_url($parts);
  1224. } else {
  1225. $parts = parse_url($url);
  1226. if (!isset($parts['path'])) {
  1227. $parts['path'] = '/';
  1228. }
  1229. $dir = $parts['path'];
  1230. if (substr($dir, -1) !== '/') {
  1231. $dir = dirname($parts['path']);
  1232. $dir !== '/' && $dir .= '/';
  1233. }
  1234. $parts['path'] = $dir . $rel_url;
  1235. $parts['path'] = cleanup_url_path($parts['path']);
  1236. return build_url($parts);
  1237. }
  1238. }
  1239. function print_user_stylesheet() {
  1240. $value = get_pref('USER_STYLESHEET');
  1241. if ($value) {
  1242. print "<style type='text/css' id='user_css_style'>";
  1243. print str_replace("<br/>", "\n", $value);
  1244. print "</style>";
  1245. }
  1246. }
  1247. /* function filter_to_sql($filter, $owner_uid) {
  1248. $query = array();
  1249. $pdo = Db::pdo();
  1250. if (DB_TYPE == "pgsql")
  1251. $reg_qpart = "~";
  1252. else
  1253. $reg_qpart = "REGEXP";
  1254. foreach ($filter["rules"] AS $rule) {
  1255. $rule['reg_exp'] = str_replace('/', '\/', $rule["reg_exp"]);
  1256. $regexp_valid = preg_match('/' . $rule['reg_exp'] . '/',
  1257. $rule['reg_exp']) !== FALSE;
  1258. if ($regexp_valid) {
  1259. $rule['reg_exp'] = $pdo->quote($rule['reg_exp']);
  1260. switch ($rule["type"]) {
  1261. case "title":
  1262. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1263. $rule['reg_exp'] . "')";
  1264. break;
  1265. case "content":
  1266. $qpart = "LOWER(ttrss_entries.content) $reg_qpart LOWER('".
  1267. $rule['reg_exp'] . "')";
  1268. break;
  1269. case "both":
  1270. $qpart = "LOWER(ttrss_entries.title) $reg_qpart LOWER('".
  1271. $rule['reg_exp'] . "') OR LOWER(" .
  1272. "ttrss_entries.content) $reg_qpart LOWER('" . $rule['reg_exp'] . "')";
  1273. break;
  1274. case "tag":
  1275. $qpart = "LOWER(ttrss_user_entries.tag_cache) $reg_qpart LOWER('".
  1276. $rule['reg_exp'] . "')";
  1277. break;
  1278. case "link":
  1279. $qpart = "LOWER(ttrss_entries.link) $reg_qpart LOWER('".
  1280. $rule['reg_exp'] . "')";
  1281. break;
  1282. case "author":
  1283. $qpart = "LOWER(ttrss_entries.author) $reg_qpart LOWER('".
  1284. $rule['reg_exp'] . "')";
  1285. break;
  1286. }
  1287. if (isset($rule['inverse'])) $qpart = "NOT ($qpart)";
  1288. if (isset($rule["feed_id"]) && $rule["feed_id"] > 0) {
  1289. $qpart .= " AND feed_id = " . $pdo->quote($rule["feed_id"]);
  1290. }
  1291. if (isset($rule["cat_id"])) {
  1292. if ($rule["cat_id"] > 0) {
  1293. $children = Feeds::getChildCategories($rule["cat_id"], $owner_uid);
  1294. array_push($children, $rule["cat_id"]);
  1295. $children = array_map("intval", $children);
  1296. $children = join(",", $children);
  1297. $cat_qpart = "cat_id IN ($children)";
  1298. } else {
  1299. $cat_qpart = "cat_id IS NULL";
  1300. }
  1301. $qpart .= " AND $cat_qpart";
  1302. }
  1303. $qpart .= " AND feed_id IS NOT NULL";
  1304. array_push($query, "($qpart)");
  1305. }
  1306. }
  1307. if (count($query) > 0) {
  1308. $fullquery = "(" . join($filter["match_any_rule"] ? "OR" : "AND", $query) . ")";
  1309. } else {
  1310. $fullquery = "(false)";
  1311. }
  1312. if ($filter['inverse']) $fullquery = "(NOT $fullquery)";
  1313. return $fullquery;
  1314. } */
  1315. if (!function_exists('gzdecode')) {
  1316. function gzdecode($string) { // no support for 2nd argument
  1317. return file_get_contents('compress.zlib://data:who/cares;base64,'.
  1318. base64_encode($string));
  1319. }
  1320. }
  1321. function get_random_bytes($length) {
  1322. if (function_exists('openssl_random_pseudo_bytes')) {
  1323. return openssl_random_pseudo_bytes($length);
  1324. } else {
  1325. $output = "";
  1326. for ($i = 0; $i < $length; $i++)
  1327. $output .= chr(mt_rand(0, 255));
  1328. return $output;
  1329. }
  1330. }
  1331. function read_stdin() {
  1332. $fp = fopen("php://stdin", "r");
  1333. if ($fp) {
  1334. $line = trim(fgets($fp));
  1335. fclose($fp);
  1336. return $line;
  1337. }
  1338. return null;
  1339. }
  1340. function implements_interface($class, $interface) {
  1341. return in_array($interface, class_implements($class));
  1342. }
  1343. function T_js_decl($s1, $s2) {
  1344. if ($s1 && $s2) {
  1345. $s1 = preg_replace("/\n/", "", $s1);
  1346. $s2 = preg_replace("/\n/", "", $s2);
  1347. $s1 = preg_replace("/\"/", "\\\"", $s1);
  1348. $s2 = preg_replace("/\"/", "\\\"", $s2);
  1349. return "T_messages[\"$s1\"] = \"$s2\";\n";
  1350. }
  1351. }
  1352. function init_js_translations() {
  1353. print 'var T_messages = new Object();
  1354. function __(msg) {
  1355. if (T_messages[msg]) {
  1356. return T_messages[msg];
  1357. } else {
  1358. return msg;
  1359. }
  1360. }
  1361. function ngettext(msg1, msg2, n) {
  1362. return __((parseInt(n) > 1) ? msg2 : msg1);
  1363. }';
  1364. global $text_domains;
  1365. foreach (array_keys($text_domains) as $domain) {
  1366. $l10n = _get_reader($domain);
  1367. for ($i = 0; $i < $l10n->total; $i++) {
  1368. $orig = $l10n->get_original_string($i);
  1369. if(strpos($orig, "\000") !== FALSE) { // Plural forms
  1370. $key = explode(chr(0), $orig);
  1371. print T_js_decl($key[0], _ngettext($key[0], $key[1], 1)); // Singular
  1372. print T_js_decl($key[1], _ngettext($key[0], $key[1], 2)); // Plural
  1373. } else {
  1374. $translation = _dgettext($domain,$orig);
  1375. print T_js_decl($orig, $translation);
  1376. }
  1377. }
  1378. }
  1379. }
  1380. function get_theme_path($theme) {
  1381. if ($theme == "default.php")
  1382. return "css/default.css";
  1383. $check = "themes/$theme";
  1384. if (file_exists($check)) return $check;
  1385. $check = "themes.local/$theme";
  1386. if (file_exists($check)) return $check;
  1387. }
  1388. function theme_exists($theme) {
  1389. return file_exists("themes/$theme") || file_exists("themes.local/$theme");
  1390. }
  1391. /**
  1392. * @SuppressWarnings(unused)
  1393. */
  1394. function error_json($code) {
  1395. require_once "errors.php";
  1396. @$message = $ERRORS[$code];
  1397. return json_encode(array("error" =>
  1398. array("code" => $code, "message" => $message)));
  1399. }
  1400. /*function abs_to_rel_path($dir) {
  1401. $tmp = str_replace(dirname(__DIR__), "", $dir);
  1402. if (strlen($tmp) > 0 && substr($tmp, 0, 1) == "/") $tmp = substr($tmp, 1);
  1403. return $tmp;
  1404. }*/
  1405. function get_upload_error_message($code) {
  1406. $errors = array(
  1407. 0 => __('There is no error, the file uploaded with success'),
  1408. 1 => __('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  1409. 2 => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  1410. 3 => __('The uploaded file was only partially uploaded'),
  1411. 4 => __('No file was uploaded'),
  1412. 6 => __('Missing a temporary folder'),
  1413. 7 => __('Failed to write file to disk.'),
  1414. 8 => __('A PHP extension stopped the file upload.'),
  1415. );
  1416. return $errors[$code];
  1417. }
  1418. function base64_img($filename) {
  1419. if (file_exists($filename)) {
  1420. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  1421. return "data:image/$ext;base64," . base64_encode(file_get_contents($filename));
  1422. } else {
  1423. return "";
  1424. }
  1425. }
  1426. /* this is essentially a wrapper for readfile() which allows plugins to hook
  1427. output with httpd-specific "fast" implementation i.e. X-Sendfile or whatever else
  1428. hook function should return true if request was handled (or at least attempted to)
  1429. note that this can be called without user context so the plugin to handle this
  1430. should be loaded systemwide in config.php */
  1431. function send_local_file($filename) {
  1432. if (file_exists($filename)) {
  1433. if (is_writable($filename)) touch($filename);
  1434. $tmppluginhost = new PluginHost();
  1435. $tmppluginhost->load(PLUGINS, PluginHost::KIND_SYSTEM);
  1436. $tmppluginhost->load_data();
  1437. foreach ($tmppluginhost->get_hooks(PluginHost::HOOK_SEND_LOCAL_FILE) as $plugin) {
  1438. if ($plugin->hook_send_local_file($filename)) return true;
  1439. }
  1440. $mimetype = mime_content_type($filename);
  1441. // this is hardly ideal but 1) only media is cached in images/ and 2) seemingly only mp4
  1442. // video files are detected as octet-stream by mime_content_type()
  1443. if ($mimetype == "application/octet-stream")
  1444. $mimetype = "video/mp4";
  1445. header("Content-type: $mimetype");
  1446. $stamp = gmdate("D, d M Y H:i:s", filemtime($filename)) . " GMT";
  1447. header("Last-Modified: $stamp", true);
  1448. return readfile($filename);
  1449. } else {
  1450. return false;
  1451. }
  1452. }
  1453. function arr_qmarks($arr) {
  1454. return str_repeat('?,', count($arr) - 1) . '?';
  1455. }
  1456. function get_scripts_timestamp() {
  1457. $files = glob("js/*.js");
  1458. $ts = 0;
  1459. foreach ($files as $file) {
  1460. $file_ts = filemtime($file);
  1461. if ($file_ts > $ts) $ts = $file_ts;
  1462. }
  1463. return $ts;
  1464. }