4
0

lib_rss.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. <?php
  2. declare(strict_types=1);
  3. if (!function_exists('mb_strcut')) {
  4. function mb_strcut(string $str, int $start, ?int $length = null, string $encoding = 'UTF-8'): string {
  5. return substr($str, $start, $length) ?: '';
  6. }
  7. }
  8. if (!function_exists('syslog')) {
  9. if (COPY_SYSLOG_TO_STDERR && !defined('STDERR')) {
  10. define('STDERR', fopen('php://stderr', 'w'));
  11. }
  12. function syslog(int $priority, string $message): bool {
  13. if (COPY_SYSLOG_TO_STDERR && defined('STDERR') && is_resource(STDERR)) {
  14. return fwrite(STDERR, $message . "\n") != false;
  15. }
  16. return false;
  17. }
  18. }
  19. if (function_exists('openlog')) {
  20. if (COPY_SYSLOG_TO_STDERR) {
  21. openlog('FreshRSS', LOG_CONS | LOG_ODELAY | LOG_PID | LOG_PERROR, LOG_USER);
  22. } else {
  23. openlog('FreshRSS', LOG_CONS | LOG_ODELAY | LOG_PID, LOG_USER);
  24. }
  25. }
  26. /**
  27. * Build a directory path by concatenating a list of directory names.
  28. *
  29. * @param string ...$path_parts a list of directory names
  30. * @return string corresponding to the final pathname
  31. */
  32. function join_path(...$path_parts): string {
  33. return join(DIRECTORY_SEPARATOR, $path_parts);
  34. }
  35. //<Auto-loading>
  36. function classAutoloader(string $class): void {
  37. if (strpos($class, 'FreshRSS') === 0) {
  38. $components = explode('_', $class);
  39. switch (count($components)) {
  40. case 1:
  41. include(APP_PATH . '/' . $components[0] . '.php');
  42. return;
  43. case 2:
  44. include(APP_PATH . '/Models/' . $components[1] . '.php');
  45. return;
  46. case 3: //Controllers, Exceptions
  47. include(APP_PATH . '/' . $components[2] . 's/' . $components[1] . $components[2] . '.php');
  48. return;
  49. }
  50. } elseif (strpos($class, 'Minz') === 0) {
  51. include(LIB_PATH . '/' . str_replace('_', '/', $class) . '.php');
  52. } elseif (str_starts_with($class, 'SimplePie\\')) {
  53. $prefix = 'SimplePie\\';
  54. $base_dir = LIB_PATH . '/simplepie/simplepie/src/';
  55. $relative_class_name = substr($class, strlen($prefix));
  56. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  57. } elseif (str_starts_with($class, 'Gt\\CssXPath\\')) {
  58. $prefix = 'Gt\\CssXPath\\';
  59. $base_dir = LIB_PATH . '/phpgt/cssxpath/src/';
  60. $relative_class_name = substr($class, strlen($prefix));
  61. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  62. } elseif (str_starts_with($class, 'marienfressinaud\\LibOpml\\')) {
  63. $prefix = 'marienfressinaud\\LibOpml\\';
  64. $base_dir = LIB_PATH . '/marienfressinaud/lib_opml/src/LibOpml/';
  65. $relative_class_name = substr($class, strlen($prefix));
  66. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  67. } elseif (str_starts_with($class, 'PHPMailer\\PHPMailer\\')) {
  68. $prefix = 'PHPMailer\\PHPMailer\\';
  69. $base_dir = LIB_PATH . '/phpmailer/phpmailer/src/';
  70. $relative_class_name = substr($class, strlen($prefix));
  71. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  72. }
  73. }
  74. spl_autoload_register('classAutoloader');
  75. //</Auto-loading>
  76. /**
  77. * @param array<mixed,mixed> $array
  78. * @phpstan-assert-if-true array<string,mixed> $array
  79. */
  80. function is_array_keys_string(array $array): bool {
  81. foreach ($array as $key => $value) {
  82. if (!is_string($key)) {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. /**
  89. * @param array<mixed,mixed> $array
  90. * @phpstan-assert-if-true array<mixed,string> $array
  91. */
  92. function is_array_values_string(array $array): bool {
  93. foreach ($array as $value) {
  94. if (!is_string($value)) {
  95. return false;
  96. }
  97. }
  98. return true;
  99. }
  100. /**
  101. * Memory efficient replacement of `echo json_encode(...)`
  102. * @param array<mixed>|mixed $json
  103. * @param int $optimisationDepth Number of levels for which to perform memory optimisation
  104. * before calling the faster native JSON serialisation.
  105. * Set to negative value for infinite depth.
  106. */
  107. function echoJson($json, int $optimisationDepth = -1): void {
  108. if ($optimisationDepth === 0 || !is_array($json)) {
  109. echo json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  110. return;
  111. }
  112. $first = true;
  113. if (array_is_list($json)) {
  114. echo '[';
  115. foreach ($json as $item) {
  116. if ($first) {
  117. $first = false;
  118. } else {
  119. echo ',';
  120. }
  121. echoJson($item, $optimisationDepth - 1);
  122. }
  123. echo ']';
  124. } else {
  125. echo '{';
  126. foreach ($json as $key => $value) {
  127. if ($first) {
  128. $first = false;
  129. } else {
  130. echo ',';
  131. }
  132. echo json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ':';
  133. echoJson($value, $optimisationDepth - 1);
  134. }
  135. echo '}';
  136. }
  137. }
  138. function idn_to_puny(string $url): string {
  139. if (function_exists('idn_to_ascii')) {
  140. $idn = parse_url($url, PHP_URL_HOST);
  141. if (is_string($idn) && $idn != '') {
  142. $puny = idn_to_ascii($idn);
  143. $pos = strpos($url, $idn);
  144. if ($puny != false && $pos !== false) {
  145. $url = substr_replace($url, $puny, $pos, strlen($idn));
  146. }
  147. }
  148. }
  149. return $url;
  150. }
  151. function checkUrl(string $url, bool $fixScheme = true): string|false {
  152. $url = trim($url);
  153. if ($url == '') {
  154. return '';
  155. }
  156. if ($fixScheme && preg_match('#^https?://#i', $url) !== 1) {
  157. $url = 'https://' . ltrim($url, '/');
  158. }
  159. $url = idn_to_puny($url); // https://bugs.php.net/bug.php?id=53474
  160. $urlRelaxed = str_replace('_', 'z', $url); //PHP discussion #64948 Underscore
  161. if (is_string(filter_var($urlRelaxed, FILTER_VALIDATE_URL))) {
  162. return $url;
  163. } else {
  164. return false;
  165. }
  166. }
  167. function safe_ascii(?string $text): string {
  168. return $text === null ? '' : (filter_var($text, FILTER_DEFAULT, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH) ?: '');
  169. }
  170. if (function_exists('mb_convert_encoding')) {
  171. function safe_utf8(string $text): string {
  172. return mb_convert_encoding($text, 'UTF-8', 'UTF-8') ?: '';
  173. }
  174. } elseif (function_exists('iconv')) {
  175. function safe_utf8(string $text): string {
  176. return iconv('UTF-8', 'UTF-8//IGNORE', $text) ?: '';
  177. }
  178. } else {
  179. function safe_utf8(string $text): string {
  180. return $text;
  181. }
  182. }
  183. function escapeToUnicodeAlternative(string $text, bool $extended = true): string {
  184. $text = htmlspecialchars_decode($text, ENT_QUOTES);
  185. //Problematic characters
  186. $problem = ['&', '<', '>'];
  187. //Use their fullwidth Unicode form instead:
  188. $replace = ['&', '<', '>'];
  189. // https://raw.githubusercontent.com/mihaip/google-reader-api/master/wiki/StreamId.wiki
  190. if ($extended) {
  191. $problem += ["'", '"', '^', '?', '\\', '/', ',', ';'];
  192. $replace += ["’", '"', '^', '?', '\', '/', ',', ';'];
  193. }
  194. return trim(str_replace($problem, $replace, $text));
  195. }
  196. function format_number(int|float $n, int $precision = 0): string {
  197. // number_format does not seem to be Unicode-compatible
  198. return str_replace(' ', ' ', // Thin non-breaking space
  199. number_format((float)$n, $precision, '.', ' ')
  200. );
  201. }
  202. function format_bytes(int $bytes, int $precision = 2, string $system = 'IEC'): string {
  203. if ($system === 'IEC') {
  204. $base = 1024;
  205. $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
  206. } elseif ($system === 'SI') {
  207. $base = 1000;
  208. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  209. } else {
  210. return format_number($bytes, $precision);
  211. }
  212. $bytes = max(intval($bytes), 0);
  213. $pow = $bytes === 0 ? 0 : floor(log($bytes) / log($base));
  214. $pow = min($pow, count($units) - 1);
  215. $bytes /= pow($base, $pow);
  216. return format_number($bytes, $precision) . ' ' . $units[$pow];
  217. }
  218. function timestamptodate(int $t, bool $hour = true): string {
  219. $month = _t('gen.date.' . date('M', $t));
  220. if ($hour) {
  221. $date = _t('gen.date.format_date_hour', $month);
  222. } else {
  223. $date = _t('gen.date.format_date', $month);
  224. }
  225. return @date($date, $t) ?: '';
  226. }
  227. /**
  228. * Decode HTML entities but preserve XML entities.
  229. */
  230. function html_only_entity_decode(?string $text): string {
  231. /** @var array<string,string>|null $htmlEntitiesOnly */
  232. static $htmlEntitiesOnly = null;
  233. if ($htmlEntitiesOnly === null) {
  234. $htmlEntitiesOnly = array_flip(array_diff(
  235. get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'UTF-8'), //Decode HTML entities
  236. get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES, 'UTF-8') //Preserve XML entities
  237. ));
  238. }
  239. return $text == null ? '' : strtr($text, $htmlEntitiesOnly);
  240. }
  241. /**
  242. * Remove passwords in FreshRSS logs.
  243. * See also ../cli/sensitive-log.sh for Web server logs.
  244. * @param array<string,mixed>|string $log
  245. * @return array<string,mixed>|string
  246. */
  247. function sensitive_log(array|string $log): array|string {
  248. if (is_array($log)) {
  249. foreach ($log as $k => $v) {
  250. if (in_array($k, ['api_key', 'Passwd', 'T'], true)) {
  251. $log[$k] = '██';
  252. } elseif ((is_array($v) && is_array_keys_string($v)) || is_string($v)) {
  253. $log[$k] = sensitive_log($v);
  254. } else {
  255. return '';
  256. }
  257. }
  258. } elseif (is_string($log)) {
  259. $log = preg_replace([
  260. '/\b(auth=.*?\/)[^&]+/i',
  261. '/\b(Passwd=)[^&]+/i',
  262. '/\b(Authorization)[^&]+/i',
  263. ], '$1█', $log) ?? '';
  264. }
  265. return $log;
  266. }
  267. /**
  268. * @param array<string,mixed> $attributes
  269. * @param array<int,mixed> $curl_options
  270. * @throws FreshRSS_Context_Exception
  271. */
  272. function customSimplePie(array $attributes = [], array $curl_options = []): \SimplePie\SimplePie {
  273. $limits = FreshRSS_Context::systemConf()->limits;
  274. $simplePie = new \SimplePie\SimplePie();
  275. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  276. $simplePie->get_registry()->register(\SimplePie\File::class, FreshRSS_SimplePieResponse::class);
  277. }
  278. $simplePie->set_useragent(FRESHRSS_USERAGENT);
  279. $simplePie->set_cache_name_function('sha1');
  280. $simplePie->set_cache_location(CACHE_PATH);
  281. $simplePie->set_cache_duration($limits['cache_duration'], $limits['cache_duration_min'], $limits['cache_duration_max']);
  282. $simplePie->enable_order_by_date(false);
  283. $feed_timeout = empty($attributes['timeout']) || !is_numeric($attributes['timeout']) ? 0 : (int)$attributes['timeout'];
  284. $simplePie->set_timeout($feed_timeout > 0 ? $feed_timeout : $limits['timeout']);
  285. $curl_options = array_replace(FreshRSS_Context::systemConf()->curl_options, $curl_options);
  286. if (isset($attributes['ssl_verify'])) {
  287. $curl_options[CURLOPT_SSL_VERIFYHOST] = empty($attributes['ssl_verify']) ? 0 : 2;
  288. $curl_options[CURLOPT_SSL_VERIFYPEER] = (bool)$attributes['ssl_verify'];
  289. if (empty($attributes['ssl_verify'])) {
  290. $curl_options[CURLOPT_SSL_CIPHER_LIST] = 'DEFAULT@SECLEVEL=1';
  291. }
  292. }
  293. if (!empty($attributes['curl_params']) && is_array($attributes['curl_params'])) {
  294. foreach ($attributes['curl_params'] as $co => $v) {
  295. if (is_int($co)) {
  296. $curl_options[$co] = $v;
  297. }
  298. }
  299. }
  300. if (!empty($curl_options[CURLOPT_PROXYTYPE]) && ($curl_options[CURLOPT_PROXYTYPE] < 0 || $curl_options[CURLOPT_PROXYTYPE] === 3)) {
  301. // 3 is legacy for NONE
  302. unset($curl_options[CURLOPT_PROXYTYPE]);
  303. if (isset($curl_options[CURLOPT_PROXY])) {
  304. unset($curl_options[CURLOPT_PROXY]);
  305. }
  306. }
  307. $simplePie->set_curl_options($curl_options);
  308. $simplePie->strip_comments(true);
  309. $simplePie->strip_htmltags([
  310. 'base', 'blink', 'body', 'doctype', 'embed',
  311. 'font', 'form', 'frame', 'frameset', 'html',
  312. 'link', 'input', 'marquee', 'meta', 'noscript',
  313. 'object', 'param', 'plaintext', 'script', 'style',
  314. 'svg', //TODO: Support SVG after sanitizing and URL rewriting of xlink:href
  315. ]);
  316. $simplePie->rename_attributes(['id', 'class']);
  317. $simplePie->strip_attributes(array_merge($simplePie->strip_attributes, [
  318. 'alink', 'autoplay', 'background', 'bgcolor', 'class', 'form', 'formaction',
  319. 'link', 'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus',
  320. 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmousemove',
  321. 'onmouseout', 'onmouseover', 'onmouseup', 'onselect', 'onunload',
  322. 'seamless', 'sizes', 'srcdoc', 'srcset', 'text', 'vlink', 'referrerpolicy', 'ping',
  323. 'target', 'rel', 'name', 'download', 'attributionsrc',
  324. ]));
  325. $simplePie->add_attributes([
  326. 'audio' => ['controls' => 'controls', 'preload' => 'none'],
  327. 'iframe' => [
  328. 'allow' => 'accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share',
  329. 'sandbox' => 'allow-scripts allow-same-origin',
  330. ],
  331. 'video' => ['controls' => 'controls', 'preload' => 'none'],
  332. ]);
  333. $simplePie->set_url_replacements([
  334. 'a' => 'href',
  335. 'area' => 'href',
  336. 'audio' => 'src',
  337. 'blockquote' => 'cite',
  338. 'del' => 'cite',
  339. 'form' => 'action',
  340. 'iframe' => 'src',
  341. 'img' => [
  342. 'longdesc',
  343. 'src',
  344. ],
  345. 'image' => [
  346. 'longdesc',
  347. 'src',
  348. ],
  349. 'input' => 'src',
  350. 'ins' => 'cite',
  351. 'q' => 'cite',
  352. 'source' => 'src',
  353. 'track' => 'src',
  354. 'video' => [
  355. 'poster',
  356. 'src',
  357. ],
  358. ]);
  359. $https_domains = [];
  360. $force = @file(FRESHRSS_PATH . '/force-https.default.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  361. if (is_array($force)) {
  362. $https_domains = array_merge($https_domains, $force);
  363. }
  364. $force = @file(DATA_PATH . '/force-https.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  365. if (is_array($force)) {
  366. $https_domains = array_merge($https_domains, $force);
  367. }
  368. // Remove whitespace and comments starting with # / ;
  369. $https_domains = preg_replace('%\\s+|[\/#;].*$%', '', $https_domains) ?? $https_domains;
  370. $https_domains = array_filter($https_domains, fn(string $v) => $v !== '');
  371. $simplePie->set_https_domains($https_domains);
  372. return $simplePie;
  373. }
  374. function sanitizeHTML(string $data, string $base = '', ?int $maxLength = null): string {
  375. if ($data === '' || ($maxLength !== null && $maxLength <= 0)) {
  376. return '';
  377. }
  378. if ($maxLength !== null) {
  379. $data = mb_strcut($data, 0, $maxLength, 'UTF-8');
  380. }
  381. /** @var \SimplePie\SimplePie|null $simplePie */
  382. static $simplePie = null;
  383. if ($simplePie === null) {
  384. $simplePie = customSimplePie();
  385. $simplePie->enable_cache(false);
  386. $simplePie->init();
  387. }
  388. $sanitized = $simplePie->sanitize->sanitize($data, \SimplePie\SimplePie::CONSTRUCT_HTML, $base);
  389. if (!is_string($sanitized)) {
  390. return '';
  391. }
  392. $result = html_only_entity_decode($sanitized);
  393. if ($maxLength !== null && strlen($result) > $maxLength) {
  394. //Sanitizing has made the result too long so try again shorter
  395. $data = mb_strcut($result, 0, (2 * $maxLength) - strlen($result) - 2, 'UTF-8');
  396. return sanitizeHTML($data, $base, $maxLength);
  397. }
  398. return $result;
  399. }
  400. function cleanCache(int $hours = 720): void {
  401. // N.B.: GLOB_BRACE is not available on all platforms
  402. $files = glob(CACHE_PATH . '/*.*', GLOB_NOSORT) ?: [];
  403. foreach ($files as $file) {
  404. if (str_ends_with($file, 'index.html')) {
  405. continue;
  406. }
  407. $cacheMtime = @filemtime($file);
  408. if ($cacheMtime !== false && $cacheMtime < time() - (3600 * $hours)) {
  409. unlink($file);
  410. }
  411. }
  412. }
  413. /**
  414. * Remove the charset meta information of an HTML document, e.g.:
  415. * `<meta charset="..." />`
  416. * `<meta http-equiv="Content-Type" content="text/html; charset=...">`
  417. */
  418. function stripHtmlMetaCharset(string $html): string {
  419. return preg_replace('/<meta\s[^>]*charset\s*=\s*[^>]+>/i', '', $html, 1) ?? '';
  420. }
  421. /**
  422. * Set an XML preamble to enforce the HTML content type charset received by HTTP.
  423. * @param string $html the raw downloaded HTML content
  424. * @param string $contentType an HTTP Content-Type such as 'text/html; charset=utf-8'
  425. * @return string an HTML string with XML encoding information for DOMDocument::loadHTML()
  426. */
  427. function enforceHttpEncoding(string $html, string $contentType = ''): string {
  428. $httpCharset = preg_match('/\bcharset=([0-9a-z_-]{2,12})$/i', $contentType, $matches) === 1 ? $matches[1] : '';
  429. if ($httpCharset == '') {
  430. // No charset defined by HTTP
  431. if (preg_match('/<meta\s[^>]*charset\s*=[\s\'"]*UTF-?8\b/i', substr($html, 0, 2048))) {
  432. // Detect UTF-8 even if declared too deep in HTML for DOMDocument
  433. $httpCharset = 'UTF-8';
  434. } else {
  435. // Do nothing
  436. return $html;
  437. }
  438. }
  439. $httpCharsetNormalized = \SimplePie\Misc::encoding($httpCharset);
  440. if (in_array($httpCharsetNormalized, ['windows-1252', 'US-ASCII'], true)) {
  441. // Default charset for HTTP, do nothing
  442. return $html;
  443. }
  444. if (substr($html, 0, 3) === "\xEF\xBB\xBF" || // UTF-8 BOM
  445. substr($html, 0, 2) === "\xFF\xFE" || // UTF-16 Little Endian BOM
  446. substr($html, 0, 2) === "\xFE\xFF" || // UTF-16 Big Endian BOM
  447. substr($html, 0, 4) === "\xFF\xFE\x00\x00" || // UTF-32 Little Endian BOM
  448. substr($html, 0, 4) === "\x00\x00\xFE\xFF") { // UTF-32 Big Endian BOM
  449. // Existing byte order mark, do nothing
  450. return $html;
  451. }
  452. if (preg_match('/^<[?]xml[^>]+encoding\b/', substr($html, 0, 64))) {
  453. // Existing XML declaration, do nothing
  454. return $html;
  455. }
  456. if ($httpCharsetNormalized !== 'UTF-8') {
  457. // Try to change encoding to UTF-8 using mbstring or iconv or intl
  458. $utf8 = \SimplePie\Misc::change_encoding($html, $httpCharsetNormalized, 'UTF-8');
  459. if (is_string($utf8)) {
  460. $html = stripHtmlMetaCharset($utf8);
  461. $httpCharsetNormalized = 'UTF-8';
  462. }
  463. }
  464. if ($httpCharsetNormalized === 'UTF-8') {
  465. // Save encoding information as XML declaration
  466. return '<' . '?xml version="1.0" encoding="' . $httpCharsetNormalized . '" ?' . ">\n" . $html;
  467. }
  468. // Give up
  469. return $html;
  470. }
  471. /**
  472. * Set an HTML base URL to the HTML content if there is none.
  473. * @param string $html the raw downloaded HTML content
  474. * @param string $href the HTML base URL
  475. * @return string an HTML string
  476. */
  477. function enforceHtmlBase(string $html, string $href): string {
  478. $doc = new DOMDocument();
  479. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  480. if ($doc->documentElement === null) {
  481. return '';
  482. }
  483. $xpath = new DOMXPath($doc);
  484. $bases = $xpath->evaluate('//base');
  485. if (!($bases instanceof DOMNodeList) || $bases->length === 0) {
  486. $base = $doc->createElement('base');
  487. if ($base === false) {
  488. return $html;
  489. }
  490. $base->setAttribute('href', $href);
  491. $head = null;
  492. $heads = $xpath->evaluate('//head');
  493. if ($heads instanceof DOMNodeList && $heads->length > 0) {
  494. $head = $heads->item(0);
  495. }
  496. if ($head instanceof DOMElement) {
  497. $head->insertBefore($base, $head->firstChild);
  498. } else {
  499. $doc->documentElement->insertBefore($base, $doc->documentElement->firstChild);
  500. }
  501. }
  502. return $doc->saveHTML() ?: $html;
  503. }
  504. /**
  505. * @param string $type {html,ico,json,opml,xml}
  506. * @param array<string,mixed> $attributes
  507. * @param array<int,mixed> $curl_options
  508. * @return array{body:string,effective_url:string,redirect_count:int,fail:bool}
  509. */
  510. function httpGet(string $url, string $cachePath, string $type = 'html', array $attributes = [], array $curl_options = []): array {
  511. $limits = FreshRSS_Context::systemConf()->limits;
  512. $feed_timeout = empty($attributes['timeout']) || !is_numeric($attributes['timeout']) ? 0 : intval($attributes['timeout']);
  513. $cacheMtime = @filemtime($cachePath);
  514. if ($cacheMtime !== false && $cacheMtime > time() - intval($limits['cache_duration'])) {
  515. $body = @file_get_contents($cachePath);
  516. if ($body != false) {
  517. syslog(LOG_DEBUG, 'FreshRSS uses cache for ' . \SimplePie\Misc::url_remove_credentials($url));
  518. return ['body' => $body, 'effective_url' => $url, 'redirect_count' => 0, 'fail' => false];
  519. }
  520. }
  521. if (mt_rand(0, 30) === 1) { // Remove old entries once in a while
  522. cleanCache(CLEANCACHE_HOURS);
  523. }
  524. if (($retryAfter = FreshRSS_http_Util::getRetryAfter($url)) > 0) {
  525. Minz_Log::warning('For that domain, will first retry after ' . date('c', $retryAfter) . '. ' . \SimplePie\Misc::url_remove_credentials($url));
  526. return ['body' => '', 'effective_url' => $url, 'redirect_count' => 0, 'fail' => true];
  527. }
  528. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  529. syslog(LOG_INFO, 'FreshRSS GET ' . $type . ' ' . \SimplePie\Misc::url_remove_credentials($url));
  530. }
  531. $accept = '';
  532. switch ($type) {
  533. case 'json':
  534. $accept = 'application/json,application/feed+json,application/javascript;q=0.9,text/javascript;q=0.8,*/*;q=0.7';
  535. break;
  536. case 'opml':
  537. $accept = 'text/x-opml,text/xml;q=0.9,application/xml;q=0.9,*/*;q=0.8';
  538. break;
  539. case 'xml':
  540. $accept = 'application/xml,application/xhtml+xml,text/xml;q=0.9,*/*;q=0.8';
  541. break;
  542. case 'ico':
  543. $accept = 'image/x-icon,image/vnd.microsoft.icon,image/ico,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.1';
  544. break;
  545. case 'html':
  546. default:
  547. $accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
  548. break;
  549. }
  550. // TODO: Implement HTTP 1.1 conditional GET If-Modified-Since
  551. $ch = curl_init();
  552. if ($ch === false) {
  553. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true];
  554. }
  555. curl_setopt_array($ch, [
  556. CURLOPT_URL => $url,
  557. CURLOPT_HTTPHEADER => ['Accept: ' . $accept],
  558. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  559. CURLOPT_CONNECTTIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  560. CURLOPT_TIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  561. CURLOPT_MAXREDIRS => 4,
  562. CURLOPT_HEADER => true,
  563. CURLOPT_RETURNTRANSFER => true,
  564. CURLOPT_FOLLOWLOCATION => true,
  565. CURLOPT_ENCODING => '', //Enable all encodings
  566. //CURLOPT_VERBOSE => 1, // To debug sent HTTP headers
  567. ]);
  568. curl_setopt_array($ch, FreshRSS_Context::systemConf()->curl_options);
  569. if (is_array($attributes['curl_params'] ?? null)) {
  570. $options = $attributes['curl_params'];
  571. if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
  572. // Remove headers problematic for security
  573. $options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER],
  574. fn($header) => is_string($header) && !preg_match('/^(Remote-User|X-WebAuth-User)\\s*:/i', $header));
  575. // Add Accept header if it is not set
  576. if (preg_grep('/^Accept\\s*:/i', $options[CURLOPT_HTTPHEADER]) === false) {
  577. $options[CURLOPT_HTTPHEADER][] = 'Accept: ' . $accept;
  578. }
  579. $attributes['curl_params'] = $options;
  580. }
  581. curl_setopt_array($ch, $attributes['curl_params']);
  582. }
  583. if (isset($attributes['ssl_verify'])) {
  584. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, empty($attributes['ssl_verify']) ? 0 : 2);
  585. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (bool)$attributes['ssl_verify']);
  586. if (empty($attributes['ssl_verify'])) {
  587. curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'DEFAULT@SECLEVEL=1');
  588. }
  589. }
  590. curl_setopt_array($ch, $curl_options);
  591. $response = curl_exec($ch);
  592. $c_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  593. $c_content_type = '' . curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  594. $c_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  595. $c_redirect_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT);
  596. $c_error = curl_error($ch);
  597. curl_close($ch);
  598. $parser = new \SimplePie\HTTP\Parser(is_string($response) ? $response : '');
  599. if ($parser->parse()) {
  600. $headers = $parser->headers;
  601. $body = $parser->body;
  602. } else {
  603. $headers = [];
  604. $body = false;
  605. }
  606. $fail = $c_status != 200 || $c_error != '' || $body === false;
  607. if ($fail) {
  608. $body = '';
  609. Minz_Log::warning('Error fetching content: HTTP code ' . $c_status . ': ' . $c_error . ' ' . $url);
  610. if (in_array($c_status, [429, 503], true)) {
  611. $retryAfter = FreshRSS_http_Util::setRetryAfter($url, $headers['retry-after'] ?? '');
  612. if ($c_status === 429) {
  613. $errorMessage = 'HTTP 429 Too Many Requests! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  614. } elseif ($c_status === 503) {
  615. $errorMessage = 'HTTP 503 Service Unavailable! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  616. }
  617. if ($retryAfter > 0) {
  618. $errorMessage .= ' We may retry after ' . date('c', $retryAfter);
  619. }
  620. }
  621. // TODO: Implement HTTP 410 Gone
  622. } elseif (!is_string($body) || strlen($body) === 0) {
  623. $body = '';
  624. } else {
  625. if (in_array($type, ['html', 'json', 'opml', 'xml'], true)) {
  626. $body = trim($body, " \n\r\t\v"); // Do not trim \x00 to avoid breaking a BOM
  627. }
  628. if (in_array($type, ['html', 'xml', 'opml'], true)) {
  629. $body = enforceHttpEncoding($body, $c_content_type);
  630. }
  631. if (in_array($type, ['html'], true)) {
  632. $body = enforceHtmlBase($body, $c_effective_url);
  633. }
  634. }
  635. if (file_put_contents($cachePath, $body) === false) {
  636. Minz_Log::warning("Error saving cache $cachePath for $url");
  637. }
  638. return ['body' => $body, 'effective_url' => $c_effective_url, 'redirect_count' => $c_redirect_count, 'fail' => $fail];
  639. }
  640. /**
  641. * Validate an email address, supports internationalized addresses.
  642. *
  643. * @param string $email The address to validate
  644. * @return bool true if email is valid, else false
  645. */
  646. function validateEmailAddress(string $email): bool {
  647. $mailer = new PHPMailer\PHPMailer\PHPMailer();
  648. $mailer->CharSet = 'utf-8';
  649. $punyemail = $mailer->punyencodeAddress($email);
  650. return PHPMailer\PHPMailer\PHPMailer::validateAddress($punyemail, 'html5');
  651. }
  652. /**
  653. * Add support of image lazy loading
  654. * Move content from src/poster attribute to data-original
  655. * @param string $content is the text we want to parse
  656. */
  657. function lazyimg(string $content): string {
  658. return preg_replace([
  659. '/<((?:img|image|iframe)[^>]+?)src="([^"]+)"([^>]*)>/i',
  660. "/<((?:img|image|iframe)[^>]+?)src='([^']+)'([^>]*)>/i",
  661. '/<((?:video)[^>]+?)poster="([^"]+)"([^>]*)>/i',
  662. "/<((?:video)[^>]+?)poster='([^']+)'([^>]*)>/i",
  663. ], [
  664. '<$1src="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  665. "<$1src='" . Minz_Url::display('/themes/icons/grey.gif') . "' data-original='$2'$3>",
  666. '<$1poster="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  667. "<$1poster='" . Minz_Url::display('/themes/icons/grey.gif') . "' data-original='$2'$3>",
  668. ],
  669. $content
  670. ) ?? '';
  671. }
  672. /** @return numeric-string */
  673. function uTimeString(): string {
  674. $t = gettimeofday();
  675. // @phpstan-ignore return.type
  676. return ((string)$t['sec']) . str_pad((string)$t['usec'], 6, '0', STR_PAD_LEFT);
  677. }
  678. function invalidateHttpCache(string $username = ''): bool {
  679. if (!FreshRSS_user_Controller::checkUsername($username)) {
  680. Minz_Session::_param('touch', uTimeString());
  681. $username = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  682. }
  683. return FreshRSS_UserDAO::ctouch($username);
  684. }
  685. /**
  686. * @return list<string>
  687. */
  688. function listUsers(): array {
  689. $final_list = [];
  690. $base_path = join_path(DATA_PATH, 'users');
  691. $dir_list = array_values(array_diff(
  692. scandir($base_path) ?: [],
  693. ['..', '.', Minz_User::INTERNAL_USER]
  694. ));
  695. foreach ($dir_list as $file) {
  696. if ($file[0] !== '.' && is_dir(join_path($base_path, $file)) && file_exists(join_path($base_path, $file, 'config.php'))) {
  697. $final_list[] = $file;
  698. }
  699. }
  700. return $final_list;
  701. }
  702. /**
  703. * Return if the maximum number of registrations has been reached.
  704. * Note a max_registrations of 0 means there is no limit.
  705. *
  706. * @return bool true if number of users >= max registrations, false else.
  707. */
  708. function max_registrations_reached(): bool {
  709. $limit_registrations = FreshRSS_Context::systemConf()->limits['max_registrations'];
  710. $number_accounts = count(listUsers());
  711. return $limit_registrations > 0 && $number_accounts >= $limit_registrations;
  712. }
  713. /**
  714. * Register and return the configuration for a given user.
  715. *
  716. * Note this function has been created to generate temporary configuration
  717. * objects. If you need a long-time configuration, please don't use this function.
  718. *
  719. * @param string $username the name of the user of which we want the configuration.
  720. * @return FreshRSS_UserConfiguration|null object, or null if the configuration cannot be loaded.
  721. * @throws Minz_ConfigurationNamespaceException
  722. */
  723. function get_user_configuration(string $username): ?FreshRSS_UserConfiguration {
  724. if (!FreshRSS_user_Controller::checkUsername($username)) {
  725. return null;
  726. }
  727. $namespace = 'user_' . $username;
  728. try {
  729. FreshRSS_UserConfiguration::register($namespace,
  730. USERS_PATH . '/' . $username . '/config.php',
  731. FRESHRSS_PATH . '/config-user.default.php');
  732. } catch (Minz_FileNotExistException $e) {
  733. Minz_Log::warning($e->getMessage(), ADMIN_LOG);
  734. return null;
  735. }
  736. $user_conf = FreshRSS_UserConfiguration::get($namespace);
  737. return $user_conf;
  738. }
  739. /**
  740. * Converts an IP (v4 or v6) to a binary representation using inet_pton
  741. *
  742. * @param string $ip the IP to convert
  743. * @return string a binary representation of the specified IP
  744. */
  745. function ipToBits(string $ip): string {
  746. $binaryip = '';
  747. foreach (str_split(inet_pton($ip) ?: '') as $char) {
  748. $binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
  749. }
  750. return $binaryip;
  751. }
  752. /**
  753. * Check if an ip belongs to the provided range (in CIDR format)
  754. *
  755. * @param string $ip the IP that we want to verify (ex: 192.168.16.1)
  756. * @param string $range the range to check against (ex: 192.168.16.0/24)
  757. * @return bool true if the IP is in the range, otherwise false
  758. */
  759. function checkCIDR(string $ip, string $range): bool {
  760. $binary_ip = ipToBits($ip);
  761. $split = explode('/', $range);
  762. $subnet = $split[0] ?? '';
  763. if ($subnet == '') {
  764. return false;
  765. }
  766. $binary_subnet = ipToBits($subnet);
  767. $mask_bits = $split[1] ?? '';
  768. $mask_bits = (int)$mask_bits;
  769. if ($mask_bits === 0) {
  770. $mask_bits = null;
  771. }
  772. $ip_net_bits = substr($binary_ip, 0, $mask_bits);
  773. $subnet_bits = substr($binary_subnet, 0, $mask_bits);
  774. return $ip_net_bits === $subnet_bits;
  775. }
  776. /**
  777. * Use CONN_REMOTE_ADDR (if available, to be robust even when using Apache mod_remoteip) or REMOTE_ADDR environment variable to determine the connection IP.
  778. */
  779. function connectionRemoteAddress(): string {
  780. $remoteIp = is_string($_SERVER['CONN_REMOTE_ADDR'] ?? null) ? $_SERVER['CONN_REMOTE_ADDR'] : '';
  781. if ($remoteIp == '') {
  782. $remoteIp = is_string($_SERVER['REMOTE_ADDR'] ?? null) ? $_SERVER['REMOTE_ADDR'] : '';
  783. }
  784. if ($remoteIp == 0) {
  785. $remoteIp = '';
  786. }
  787. return $remoteIp;
  788. }
  789. /**
  790. * Check if the client (e.g. last proxy) is allowed to send unsafe headers.
  791. * This uses the `TRUSTED_PROXY` environment variable or the `trusted_sources` configuration option to get an array of the authorized ranges,
  792. * The connection IP is obtained from the `CONN_REMOTE_ADDR` (if available, to be robust even when using Apache mod_remoteip) or `REMOTE_ADDR` environment variables.
  793. * @return bool true if the sender’s IP is in one of the ranges defined in the configuration, else false
  794. */
  795. function checkTrustedIP(): bool {
  796. if (!FreshRSS_Context::hasSystemConf()) {
  797. return false;
  798. }
  799. $remoteIp = connectionRemoteAddress();
  800. if ($remoteIp === '') {
  801. return false;
  802. }
  803. $trusted = getenv('TRUSTED_PROXY');
  804. if ($trusted != 0 && is_string($trusted)) {
  805. $trusted = preg_split('/\s+/', $trusted, -1, PREG_SPLIT_NO_EMPTY);
  806. }
  807. if (!is_array($trusted) || empty($trusted)) {
  808. $trusted = FreshRSS_Context::systemConf()->trusted_sources;
  809. }
  810. foreach ($trusted as $cidr) {
  811. if (checkCIDR($remoteIp, $cidr)) {
  812. return true;
  813. }
  814. }
  815. return false;
  816. }
  817. function httpAuthUser(bool $onlyTrusted = true): string {
  818. $auths = array_unique(array_intersect_key($_SERVER, ['REMOTE_USER' => '', 'REDIRECT_REMOTE_USER' => '', 'HTTP_REMOTE_USER' => '', 'HTTP_X_WEBAUTH_USER' => '']));
  819. if (count($auths) > 1) {
  820. Minz_Log::warning('Multiple HTTP authentication headers!');
  821. return '';
  822. }
  823. if (!empty($_SERVER['REMOTE_USER']) && is_string($_SERVER['REMOTE_USER'])) {
  824. return $_SERVER['REMOTE_USER'];
  825. }
  826. if (!empty($_SERVER['REDIRECT_REMOTE_USER']) && is_string($_SERVER['REDIRECT_REMOTE_USER'])) {
  827. return $_SERVER['REDIRECT_REMOTE_USER'];
  828. }
  829. if (!$onlyTrusted || checkTrustedIP()) {
  830. if (!empty($_SERVER['HTTP_REMOTE_USER']) && is_string($_SERVER['HTTP_REMOTE_USER'])) {
  831. return $_SERVER['HTTP_REMOTE_USER'];
  832. }
  833. if (!empty($_SERVER['HTTP_X_WEBAUTH_USER']) && is_string($_SERVER['HTTP_X_WEBAUTH_USER'])) {
  834. return $_SERVER['HTTP_X_WEBAUTH_USER'];
  835. }
  836. }
  837. return '';
  838. }
  839. function cryptAvailable(): bool {
  840. $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
  841. return $hash === @crypt('password', $hash);
  842. }
  843. /**
  844. * Check PHP and its extensions are well-installed.
  845. *
  846. * @return array<string,bool> of tested values.
  847. */
  848. function check_install_php(): array {
  849. $pdo_mysql = extension_loaded('pdo_mysql');
  850. $pdo_pgsql = extension_loaded('pdo_pgsql');
  851. $pdo_sqlite = extension_loaded('pdo_sqlite');
  852. return [
  853. 'php' => version_compare(PHP_VERSION, FRESHRSS_MIN_PHP_VERSION) >= 0,
  854. 'curl' => extension_loaded('curl'),
  855. 'pdo' => $pdo_mysql || $pdo_sqlite || $pdo_pgsql,
  856. 'pcre' => extension_loaded('pcre'),
  857. 'ctype' => extension_loaded('ctype'),
  858. 'fileinfo' => extension_loaded('fileinfo'),
  859. 'dom' => class_exists('DOMDocument'),
  860. 'json' => extension_loaded('json'),
  861. 'mbstring' => extension_loaded('mbstring'),
  862. 'zip' => extension_loaded('zip'),
  863. ];
  864. }
  865. /**
  866. * Check different data files and directories exist.
  867. * @return array<string,bool> of tested values.
  868. */
  869. function check_install_files(): array {
  870. return [
  871. 'data' => is_dir(DATA_PATH) && touch(DATA_PATH . '/index.html'), // is_writable() is not reliable for a folder on NFS
  872. 'cache' => is_dir(CACHE_PATH) && touch(CACHE_PATH . '/index.html'),
  873. 'users' => is_dir(USERS_PATH) && touch(USERS_PATH . '/index.html'),
  874. 'favicons' => is_dir(DATA_PATH) && touch(DATA_PATH . '/favicons/index.html'),
  875. 'tokens' => is_dir(DATA_PATH) && touch(DATA_PATH . '/tokens/index.html'),
  876. ];
  877. }
  878. /**
  879. * Check database is well-installed.
  880. *
  881. * @return array<string,bool> of tested values.
  882. */
  883. function check_install_database(): array {
  884. $status = [
  885. 'connection' => true,
  886. 'tables' => false,
  887. 'categories' => false,
  888. 'feeds' => false,
  889. 'entries' => false,
  890. 'entrytmp' => false,
  891. 'tag' => false,
  892. 'entrytag' => false,
  893. ];
  894. try {
  895. $dbDAO = FreshRSS_Factory::createDatabaseDAO();
  896. $status['tables'] = $dbDAO->tablesAreCorrect();
  897. $status['categories'] = $dbDAO->categoryIsCorrect();
  898. $status['feeds'] = $dbDAO->feedIsCorrect();
  899. $status['entries'] = $dbDAO->entryIsCorrect();
  900. $status['entrytmp'] = $dbDAO->entrytmpIsCorrect();
  901. $status['tag'] = $dbDAO->tagIsCorrect();
  902. $status['entrytag'] = $dbDAO->entrytagIsCorrect();
  903. } catch (Minz_PDOConnectionException $e) {
  904. $status['connection'] = false;
  905. }
  906. return $status;
  907. }
  908. /**
  909. * Remove a directory recursively.
  910. * From http://php.net/rmdir#110489
  911. */
  912. function recursive_unlink(string $dir): bool {
  913. if (!is_dir($dir)) {
  914. return true;
  915. }
  916. if (is_link($dir)) {
  917. if (PHP_OS_FAMILY === "Windows") {
  918. return rmdir($dir);
  919. }
  920. return unlink($dir);
  921. }
  922. $files = array_diff(scandir($dir) ?: [], ['.', '..']);
  923. foreach ($files as $filename) {
  924. $filename = $dir . '/' . $filename;
  925. if (is_dir($filename)) {
  926. @chmod($filename, 0777);
  927. recursive_unlink($filename);
  928. } else {
  929. unlink($filename);
  930. }
  931. }
  932. return rmdir($dir);
  933. }
  934. /**
  935. * Remove queries where $get is appearing.
  936. * @param string $get the get attribute which should be removed.
  937. * @param array<int,array{get?:string,name?:string,order?:string,search?:string,state?:int,url?:string}> $queries an array of queries.
  938. * @return array<int,array{get?:string,name?:string,order?:string,search?:string,state?:int,url?:string}> without queries where $get is appearing.
  939. */
  940. function remove_query_by_get(string $get, array $queries): array {
  941. $final_queries = [];
  942. foreach ($queries as $query) {
  943. if (empty($query['get']) || $query['get'] !== $get) {
  944. $final_queries[] = $query;
  945. }
  946. }
  947. return $final_queries;
  948. }
  949. function _i(string $icon, int $type = FreshRSS_Themes::ICON_DEFAULT): string {
  950. return FreshRSS_Themes::icon($icon, $type);
  951. }
  952. const SHORTCUT_KEYS = [
  953. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  954. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  955. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  956. 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
  957. 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'Backspace', 'Delete',
  958. 'End', 'Enter', 'Escape', 'Home', 'Insert', 'PageDown', 'PageUp', 'Space', 'Tab',
  959. ];
  960. /**
  961. * @param array<string> $shortcuts
  962. * @return list<string>
  963. */
  964. function getNonStandardShortcuts(array $shortcuts): array {
  965. $standard = strtolower(implode(' ', SHORTCUT_KEYS));
  966. $nonStandard = array_filter($shortcuts, static function (string $shortcut) use ($standard) {
  967. $shortcut = trim($shortcut);
  968. return $shortcut !== '' && stripos($standard, $shortcut) === false;
  969. });
  970. return array_values($nonStandard);
  971. }
  972. function errorMessageInfo(string $errorTitle, string $error = ''): string {
  973. $errorTitle = htmlspecialchars($errorTitle, ENT_NOQUOTES, 'UTF-8');
  974. $message = '';
  975. $details = '';
  976. $error = trim($error);
  977. // Prevent empty tags by checking if error is not empty first
  978. if ($error !== '') {
  979. $error = htmlspecialchars($error, ENT_NOQUOTES, 'UTF-8') . "\n";
  980. // First line is the main message, other lines are the details
  981. list($message, $details) = explode("\n", $error, 2);
  982. $message = "<h2>{$message}</h2>";
  983. $details = "<pre>{$details}</pre>";
  984. }
  985. header("Content-Security-Policy: default-src 'self'; frame-ancestors 'none'");
  986. header('Referrer-Policy: same-origin');
  987. return <<<MSG
  988. <!DOCTYPE html><html><header><title>HTTP 500: {$errorTitle}</title></header><body>
  989. <h1>HTTP 500: {$errorTitle}</h1>
  990. {$message}
  991. {$details}
  992. <hr />
  993. <small>For help see the documentation: <a href="https://freshrss.github.io/FreshRSS/en/admins/logs_and_errors.html" target="_blank">
  994. https://freshrss.github.io/FreshRSS/en/admins/logs_and_errors.html</a></small>
  995. </body></html>
  996. MSG;
  997. }