lib_rss.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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 (str_starts_with($class, 'FreshRSS')) {
  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 (str_starts_with($class, 'Minz')) {
  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 : (int)floor(log($bytes) / log($base));
  214. $pow = min(max(0, $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<mixed> $curl_params
  269. * @return array<mixed>
  270. */
  271. function sanitizeCurlParams(array $curl_params): array {
  272. $safe_params = [
  273. CURLOPT_COOKIE,
  274. CURLOPT_COOKIEFILE,
  275. CURLOPT_FOLLOWLOCATION,
  276. CURLOPT_HTTPHEADER,
  277. CURLOPT_MAXREDIRS,
  278. CURLOPT_POST,
  279. CURLOPT_POSTFIELDS,
  280. CURLOPT_PROXY,
  281. CURLOPT_PROXYTYPE,
  282. CURLOPT_USERAGENT,
  283. ];
  284. foreach ($curl_params as $k => $_) {
  285. if (!in_array($k, $safe_params, true)) {
  286. unset($curl_params[$k]);
  287. continue;
  288. }
  289. // Allow only an empty value just to enable the libcurl cookie engine
  290. if ($k === CURLOPT_COOKIEFILE) {
  291. $curl_params[$k] = '';
  292. }
  293. }
  294. return $curl_params;
  295. }
  296. /**
  297. * @param array<string,mixed> $attributes
  298. * @param array<int,mixed> $curl_options
  299. * @throws FreshRSS_Context_Exception
  300. */
  301. function customSimplePie(array $attributes = [], array $curl_options = []): \SimplePie\SimplePie {
  302. $limits = FreshRSS_Context::systemConf()->limits;
  303. $simplePie = new \SimplePie\SimplePie();
  304. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  305. $simplePie->get_registry()->register(\SimplePie\File::class, FreshRSS_SimplePieResponse::class);
  306. }
  307. $simplePie->set_useragent(FRESHRSS_USERAGENT);
  308. $simplePie->set_cache_name_function('sha1');
  309. $simplePie->set_cache_location(CACHE_PATH);
  310. $simplePie->set_cache_duration($limits['cache_duration'], $limits['cache_duration_min'], $limits['cache_duration_max']);
  311. $simplePie->enable_order_by_date(false);
  312. $feed_timeout = empty($attributes['timeout']) || !is_numeric($attributes['timeout']) ? 0 : (int)$attributes['timeout'];
  313. $simplePie->set_timeout($feed_timeout > 0 ? $feed_timeout : $limits['timeout']);
  314. $curl_options = array_replace(FreshRSS_Context::systemConf()->curl_options, $curl_options);
  315. if (isset($attributes['ssl_verify'])) {
  316. $curl_options[CURLOPT_SSL_VERIFYHOST] = empty($attributes['ssl_verify']) ? 0 : 2;
  317. $curl_options[CURLOPT_SSL_VERIFYPEER] = (bool)$attributes['ssl_verify'];
  318. if (empty($attributes['ssl_verify'])) {
  319. $curl_options[CURLOPT_SSL_CIPHER_LIST] = 'DEFAULT@SECLEVEL=1';
  320. }
  321. }
  322. $attributes['curl_params'] = sanitizeCurlParams(is_array($attributes['curl_params'] ?? null) ? $attributes['curl_params'] : []);
  323. if (!empty($attributes['curl_params']) && is_array($attributes['curl_params'])) {
  324. foreach ($attributes['curl_params'] as $co => $v) {
  325. if (is_int($co)) {
  326. $curl_options[$co] = $v;
  327. }
  328. }
  329. }
  330. if (!empty($curl_options[CURLOPT_PROXYTYPE]) && ($curl_options[CURLOPT_PROXYTYPE] < 0 || $curl_options[CURLOPT_PROXYTYPE] === 3)) {
  331. // 3 is legacy for NONE
  332. unset($curl_options[CURLOPT_PROXYTYPE]);
  333. if (isset($curl_options[CURLOPT_PROXY])) {
  334. unset($curl_options[CURLOPT_PROXY]);
  335. }
  336. }
  337. $simplePie->set_curl_options($curl_options);
  338. $simplePie->strip_comments(true);
  339. $simplePie->strip_htmltags([
  340. 'base', 'blink', 'body', 'doctype', 'embed',
  341. 'font', 'form', 'frame', 'frameset', 'html',
  342. 'link', 'input', 'marquee', 'meta', 'noscript',
  343. 'object', 'param', 'plaintext', 'script', 'style',
  344. 'svg', //TODO: Support SVG after sanitizing and URL rewriting of xlink:href
  345. ]);
  346. $simplePie->rename_attributes(['id', 'class']);
  347. $simplePie->strip_attributes(array_merge($simplePie->strip_attributes, [
  348. 'alink', 'autoplay', 'background', 'bgcolor', 'class', 'form', 'formaction',
  349. 'link', 'onblur', 'onchange', 'onclick', 'ondblclick', 'onfocus',
  350. 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onmousedown', 'onmousemove',
  351. 'onmouseout', 'onmouseover', 'onmouseup', 'onselect', 'onunload',
  352. 'seamless', 'sizes', 'srcdoc', 'srcset', 'text', 'vlink', 'referrerpolicy', 'ping',
  353. 'target', 'rel', 'name', 'download', 'attributionsrc',
  354. ]));
  355. $simplePie->add_attributes([
  356. 'audio' => ['controls' => 'controls', 'preload' => 'none'],
  357. 'iframe' => [
  358. 'allow' => 'accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share',
  359. 'sandbox' => 'allow-scripts allow-same-origin',
  360. ],
  361. 'video' => ['controls' => 'controls', 'preload' => 'none'],
  362. ]);
  363. $simplePie->set_url_replacements([
  364. 'a' => 'href',
  365. 'area' => 'href',
  366. 'audio' => 'src',
  367. 'blockquote' => 'cite',
  368. 'del' => 'cite',
  369. 'form' => 'action',
  370. 'iframe' => 'src',
  371. 'img' => [
  372. 'longdesc',
  373. 'src',
  374. ],
  375. 'image' => [
  376. 'longdesc',
  377. 'src',
  378. ],
  379. 'input' => 'src',
  380. 'ins' => 'cite',
  381. 'q' => 'cite',
  382. 'source' => 'src',
  383. 'track' => 'src',
  384. 'video' => [
  385. 'poster',
  386. 'src',
  387. ],
  388. ]);
  389. $https_domains = [];
  390. $force = @file(FRESHRSS_PATH . '/force-https.default.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  391. if (is_array($force)) {
  392. $https_domains = array_merge($https_domains, $force);
  393. }
  394. $force = @file(DATA_PATH . '/force-https.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  395. if (is_array($force)) {
  396. $https_domains = array_merge($https_domains, $force);
  397. }
  398. // Remove whitespace and comments starting with # / ;
  399. $https_domains = preg_replace('%\\s+|[\/#;].*$%', '', $https_domains) ?? $https_domains;
  400. $https_domains = array_filter($https_domains, fn(string $v) => $v !== '');
  401. $simplePie->set_https_domains($https_domains);
  402. return $simplePie;
  403. }
  404. function sanitizeHTML(string $data, string $base = '', ?int $maxLength = null): string {
  405. if ($data === '' || ($maxLength !== null && $maxLength <= 0)) {
  406. return '';
  407. }
  408. if ($maxLength !== null) {
  409. $data = mb_strcut($data, 0, $maxLength, 'UTF-8');
  410. }
  411. /** @var \SimplePie\SimplePie|null $simplePie */
  412. static $simplePie = null;
  413. if ($simplePie === null) {
  414. $simplePie = customSimplePie();
  415. $simplePie->enable_cache(false);
  416. $simplePie->init();
  417. }
  418. $sanitized = $simplePie->sanitize->sanitize($data, \SimplePie\SimplePie::CONSTRUCT_HTML, $base);
  419. if (!is_string($sanitized)) {
  420. return '';
  421. }
  422. $result = html_only_entity_decode($sanitized);
  423. if ($maxLength !== null && strlen($result) > $maxLength) {
  424. //Sanitizing has made the result too long so try again shorter
  425. $data = mb_strcut($result, 0, (2 * $maxLength) - strlen($result) - 2, 'UTF-8');
  426. return sanitizeHTML($data, $base, $maxLength);
  427. }
  428. return $result;
  429. }
  430. function cleanCache(int $hours = 720): void {
  431. // N.B.: GLOB_BRACE is not available on all platforms
  432. $files = glob(CACHE_PATH . '/*.*', GLOB_NOSORT) ?: [];
  433. foreach ($files as $file) {
  434. if (str_ends_with($file, 'index.html')) {
  435. continue;
  436. }
  437. $cacheMtime = @filemtime($file);
  438. if ($cacheMtime !== false && $cacheMtime < time() - (3600 * $hours)) {
  439. unlink($file);
  440. }
  441. }
  442. }
  443. /**
  444. * Remove the charset meta information of an HTML document, e.g.:
  445. * `<meta charset="..." />`
  446. * `<meta http-equiv="Content-Type" content="text/html; charset=...">`
  447. */
  448. function stripHtmlMetaCharset(string $html): string {
  449. return preg_replace('/<meta\s[^>]*charset\s*=\s*[^>]+>/i', '', $html, 1) ?? '';
  450. }
  451. /**
  452. * Set an XML preamble to enforce the HTML content type charset received by HTTP.
  453. * @param string $html the raw downloaded HTML content
  454. * @param string $contentType an HTTP Content-Type such as 'text/html; charset=utf-8'
  455. * @return string an HTML string with XML encoding information for DOMDocument::loadHTML()
  456. */
  457. function enforceHttpEncoding(string $html, string $contentType = ''): string {
  458. $httpCharset = preg_match('/\bcharset=([0-9a-z_-]{2,12})$/i', $contentType, $matches) === 1 ? $matches[1] : '';
  459. if ($httpCharset == '') {
  460. // No charset defined by HTTP
  461. if (preg_match('/<meta\s[^>]*charset\s*=[\s\'"]*UTF-?8\b/i', substr($html, 0, 2048))) {
  462. // Detect UTF-8 even if declared too deep in HTML for DOMDocument
  463. $httpCharset = 'UTF-8';
  464. } else {
  465. // Do nothing
  466. return $html;
  467. }
  468. }
  469. $httpCharsetNormalized = \SimplePie\Misc::encoding($httpCharset);
  470. if (in_array($httpCharsetNormalized, ['windows-1252', 'US-ASCII'], true)) {
  471. // Default charset for HTTP, do nothing
  472. return $html;
  473. }
  474. if (substr($html, 0, 3) === "\xEF\xBB\xBF" || // UTF-8 BOM
  475. substr($html, 0, 2) === "\xFF\xFE" || // UTF-16 Little Endian BOM
  476. substr($html, 0, 2) === "\xFE\xFF" || // UTF-16 Big Endian BOM
  477. substr($html, 0, 4) === "\xFF\xFE\x00\x00" || // UTF-32 Little Endian BOM
  478. substr($html, 0, 4) === "\x00\x00\xFE\xFF") { // UTF-32 Big Endian BOM
  479. // Existing byte order mark, do nothing
  480. return $html;
  481. }
  482. if (preg_match('/^<[?]xml[^>]+encoding\b/', substr($html, 0, 64))) {
  483. // Existing XML declaration, do nothing
  484. return $html;
  485. }
  486. if ($httpCharsetNormalized !== 'UTF-8') {
  487. // Try to change encoding to UTF-8 using mbstring or iconv or intl
  488. $utf8 = \SimplePie\Misc::change_encoding($html, $httpCharsetNormalized, 'UTF-8');
  489. if (is_string($utf8)) {
  490. $html = stripHtmlMetaCharset($utf8);
  491. $httpCharsetNormalized = 'UTF-8';
  492. }
  493. }
  494. if ($httpCharsetNormalized === 'UTF-8') {
  495. // Save encoding information as XML declaration
  496. return '<' . '?xml version="1.0" encoding="' . $httpCharsetNormalized . '" ?' . ">\n" . $html;
  497. }
  498. // Give up
  499. return $html;
  500. }
  501. /**
  502. * Set an HTML base URL to the HTML content if there is none.
  503. * @param string $html the raw downloaded HTML content
  504. * @param string $href the HTML base URL
  505. * @return string an HTML string
  506. */
  507. function enforceHtmlBase(string $html, string $href): string {
  508. $doc = new DOMDocument();
  509. $doc->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
  510. if ($doc->documentElement === null) {
  511. return '';
  512. }
  513. $xpath = new DOMXPath($doc);
  514. $bases = $xpath->evaluate('//base');
  515. if (!($bases instanceof DOMNodeList) || $bases->length === 0) {
  516. $base = $doc->createElement('base');
  517. if ($base === false) {
  518. return $html;
  519. }
  520. $base->setAttribute('href', $href);
  521. $head = null;
  522. $heads = $xpath->evaluate('//head');
  523. if ($heads instanceof DOMNodeList && $heads->length > 0) {
  524. $head = $heads->item(0);
  525. }
  526. if ($head instanceof DOMElement) {
  527. $head->insertBefore($base, $head->firstChild);
  528. } else {
  529. $doc->documentElement->insertBefore($base, $doc->documentElement->firstChild);
  530. }
  531. }
  532. return $doc->saveHTML() ?: $html;
  533. }
  534. /**
  535. * @param non-empty-string $url
  536. * @param string $type {html,ico,json,opml,xml}
  537. * @param array<string,mixed> $attributes
  538. * @param array<int,mixed> $curl_options
  539. * @return array{body:string,effective_url:string,redirect_count:int,fail:bool}
  540. */
  541. function httpGet(string $url, string $cachePath, string $type = 'html', array $attributes = [], array $curl_options = []): array {
  542. $limits = FreshRSS_Context::systemConf()->limits;
  543. $feed_timeout = empty($attributes['timeout']) || !is_numeric($attributes['timeout']) ? 0 : intval($attributes['timeout']);
  544. $cacheMtime = @filemtime($cachePath);
  545. if ($cacheMtime !== false && $cacheMtime > time() - intval($limits['cache_duration'])) {
  546. $body = @file_get_contents($cachePath);
  547. if ($body != false) {
  548. syslog(LOG_DEBUG, 'FreshRSS uses cache for ' . \SimplePie\Misc::url_remove_credentials($url));
  549. return ['body' => $body, 'effective_url' => $url, 'redirect_count' => 0, 'fail' => false];
  550. }
  551. }
  552. if (rand(0, 30) === 1) { // Remove old cache once in a while
  553. cleanCache(CLEANCACHE_HOURS);
  554. }
  555. if (($retryAfter = FreshRSS_http_Util::getRetryAfter($url)) > 0) {
  556. Minz_Log::warning('For that domain, will first retry after ' . date('c', $retryAfter) . '. ' . \SimplePie\Misc::url_remove_credentials($url));
  557. return ['body' => '', 'effective_url' => $url, 'redirect_count' => 0, 'fail' => true];
  558. }
  559. if (FreshRSS_Context::systemConf()->simplepie_syslog_enabled) {
  560. syslog(LOG_INFO, 'FreshRSS GET ' . $type . ' ' . \SimplePie\Misc::url_remove_credentials($url));
  561. }
  562. $accept = '';
  563. switch ($type) {
  564. case 'json':
  565. $accept = 'application/json,application/feed+json,application/javascript;q=0.9,text/javascript;q=0.8,*/*;q=0.7';
  566. break;
  567. case 'opml':
  568. $accept = 'text/x-opml,text/xml;q=0.9,application/xml;q=0.9,*/*;q=0.8';
  569. break;
  570. case 'xml':
  571. $accept = 'application/xml,application/xhtml+xml,text/xml;q=0.9,*/*;q=0.8';
  572. break;
  573. case 'ico':
  574. $accept = 'image/x-icon,image/vnd.microsoft.icon,image/ico,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.1';
  575. break;
  576. case 'html':
  577. default:
  578. $accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
  579. break;
  580. }
  581. // TODO: Implement HTTP 1.1 conditional GET If-Modified-Since
  582. $ch = curl_init();
  583. if ($ch === false) {
  584. return ['body' => '', 'effective_url' => '', 'redirect_count' => 0, 'fail' => true];
  585. }
  586. curl_setopt_array($ch, [
  587. CURLOPT_URL => $url,
  588. CURLOPT_HTTPHEADER => ['Accept: ' . $accept],
  589. CURLOPT_USERAGENT => FRESHRSS_USERAGENT,
  590. CURLOPT_CONNECTTIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  591. CURLOPT_TIMEOUT => $feed_timeout > 0 ? $feed_timeout : $limits['timeout'],
  592. CURLOPT_MAXREDIRS => 4,
  593. CURLOPT_RETURNTRANSFER => true,
  594. CURLOPT_FOLLOWLOCATION => true,
  595. CURLOPT_ENCODING => '', //Enable all encodings
  596. //CURLOPT_VERBOSE => 1, // To debug sent HTTP headers
  597. ]);
  598. $responseHeaders = '';
  599. curl_setopt($ch, CURLOPT_HEADERFUNCTION, function (\CurlHandle $ch, string $header) use (&$responseHeaders) {
  600. if (trim($header) !== '') { // Skip e.g. separation with trailer headers
  601. $responseHeaders .= $header;
  602. }
  603. return strlen($header);
  604. });
  605. curl_setopt_array($ch, FreshRSS_Context::systemConf()->curl_options);
  606. if (is_array($attributes['curl_params'] ?? null)) {
  607. $options = sanitizeCurlParams($attributes['curl_params']);
  608. if (is_array($options[CURLOPT_HTTPHEADER] ?? null)) {
  609. // Remove headers problematic for security
  610. $options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER],
  611. fn($header) => is_string($header) && !preg_match('/^(Remote-User|X-WebAuth-User)\\s*:/i', $header));
  612. // Add Accept header if it is not set
  613. if (preg_grep('/^Accept\\s*:/i', $options[CURLOPT_HTTPHEADER]) === false) {
  614. $options[CURLOPT_HTTPHEADER][] = 'Accept: ' . $accept;
  615. }
  616. }
  617. curl_setopt_array($ch, $options);
  618. }
  619. if (isset($attributes['ssl_verify'])) {
  620. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, empty($attributes['ssl_verify']) ? 0 : 2);
  621. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (bool)$attributes['ssl_verify']);
  622. if (empty($attributes['ssl_verify'])) {
  623. curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'DEFAULT@SECLEVEL=1');
  624. }
  625. }
  626. curl_setopt_array($ch, $curl_options);
  627. $body = curl_exec($ch);
  628. $c_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  629. $c_content_type = '' . curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  630. $c_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  631. $c_redirect_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT);
  632. $c_error = curl_error($ch);
  633. $headers = [];
  634. if ($body !== false) {
  635. assert($c_redirect_count >= 0);
  636. $responseHeaders = \SimplePie\HTTP\Parser::prepareHeaders($responseHeaders, $c_redirect_count + 1);
  637. $parser = new \SimplePie\HTTP\Parser($responseHeaders);
  638. if ($parser->parse()) {
  639. $headers = $parser->headers;
  640. }
  641. }
  642. $fail = $c_status != 200 || $c_error != '' || $body === false;
  643. if ($fail) {
  644. $body = '';
  645. Minz_Log::warning('Error fetching content: HTTP code ' . $c_status . ': ' . $c_error . ' ' . $url);
  646. if (in_array($c_status, [429, 503], true)) {
  647. $retryAfter = FreshRSS_http_Util::setRetryAfter($url, $headers['retry-after'] ?? '');
  648. if ($c_status === 429) {
  649. $errorMessage = 'HTTP 429 Too Many Requests! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  650. } elseif ($c_status === 503) {
  651. $errorMessage = 'HTTP 503 Service Unavailable! [' . \SimplePie\Misc::url_remove_credentials($url) . ']';
  652. }
  653. if ($retryAfter > 0) {
  654. $errorMessage .= ' We may retry after ' . date('c', $retryAfter);
  655. }
  656. }
  657. // TODO: Implement HTTP 410 Gone
  658. } elseif (!is_string($body) || strlen($body) === 0) {
  659. $body = '';
  660. } else {
  661. if (in_array($type, ['html', 'json', 'opml', 'xml'], true)) {
  662. $body = trim($body, " \n\r\t\v"); // Do not trim \x00 to avoid breaking a BOM
  663. }
  664. if (in_array($type, ['html', 'xml', 'opml'], true)) {
  665. $body = enforceHttpEncoding($body, $c_content_type);
  666. }
  667. if (in_array($type, ['html'], true)) {
  668. $body = enforceHtmlBase($body, $c_effective_url);
  669. }
  670. }
  671. if (file_put_contents($cachePath, $body) === false) {
  672. Minz_Log::warning("Error saving cache $cachePath for $url");
  673. }
  674. return ['body' => $body, 'effective_url' => $c_effective_url, 'redirect_count' => $c_redirect_count, 'fail' => $fail];
  675. }
  676. /**
  677. * Validate an email address, supports internationalized addresses.
  678. *
  679. * @param string $email The address to validate
  680. * @return bool true if email is valid, else false
  681. */
  682. function validateEmailAddress(string $email): bool {
  683. $mailer = new PHPMailer\PHPMailer\PHPMailer();
  684. $mailer->CharSet = 'utf-8';
  685. $punyemail = $mailer->punyencodeAddress($email);
  686. return PHPMailer\PHPMailer\PHPMailer::validateAddress($punyemail, 'html5');
  687. }
  688. /**
  689. * Add support of image lazy loading
  690. * Move content from src/poster attribute to data-original
  691. * @param string $content is the text we want to parse
  692. */
  693. function lazyimg(string $content): string {
  694. return preg_replace([
  695. '/<((?:img|image|iframe|track)[^>]+?)src="([^"]+)"([^>]*)>/i',
  696. "/<((?:img|image|iframe|track)[^>]+?)src='([^']+)'([^>]*)>/i",
  697. '/<((?:video)[^>]+?)poster="([^"]+)"([^>]*)>/i',
  698. "/<((?:video)[^>]+?)poster='([^']+)'([^>]*)>/i",
  699. ], [
  700. '<$1src="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  701. "<$1src='" . Minz_Url::display('/themes/icons/grey.gif') . "' data-original='$2'$3>",
  702. '<$1poster="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  703. "<$1poster='" . Minz_Url::display('/themes/icons/grey.gif') . "' data-original='$2'$3>",
  704. ],
  705. $content
  706. ) ?? '';
  707. }
  708. /** @return numeric-string */
  709. function uTimeString(): string {
  710. $t = gettimeofday();
  711. // @phpstan-ignore return.type
  712. return ((string)$t['sec']) . str_pad((string)$t['usec'], 6, '0', STR_PAD_LEFT);
  713. }
  714. function invalidateHttpCache(string $username = ''): bool {
  715. if (!FreshRSS_user_Controller::checkUsername($username)) {
  716. Minz_Session::_param('touch', uTimeString());
  717. $username = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  718. }
  719. return FreshRSS_UserDAO::ctouch($username);
  720. }
  721. /**
  722. * @return list<string>
  723. */
  724. function listUsers(): array {
  725. $final_list = [];
  726. $base_path = join_path(DATA_PATH, 'users');
  727. $dir_list = array_values(array_diff(
  728. scandir($base_path) ?: [],
  729. ['..', '.', Minz_User::INTERNAL_USER]
  730. ));
  731. foreach ($dir_list as $file) {
  732. if ($file[0] !== '.' && is_dir(join_path($base_path, $file)) && file_exists(join_path($base_path, $file, 'config.php'))) {
  733. $final_list[] = $file;
  734. }
  735. }
  736. return $final_list;
  737. }
  738. /**
  739. * Return if the maximum number of registrations has been reached.
  740. * Note a max_registrations of 0 means there is no limit.
  741. *
  742. * @return bool true if number of users >= max registrations, false else.
  743. */
  744. function max_registrations_reached(): bool {
  745. $limit_registrations = FreshRSS_Context::systemConf()->limits['max_registrations'];
  746. $number_accounts = count(listUsers());
  747. return $limit_registrations > 0 && $number_accounts >= $limit_registrations;
  748. }
  749. /**
  750. * Register and return the configuration for a given user.
  751. *
  752. * Note this function has been created to generate temporary configuration
  753. * objects. If you need a long-time configuration, please don't use this function.
  754. *
  755. * @param string $username the name of the user of which we want the configuration.
  756. * @return FreshRSS_UserConfiguration|null object, or null if the configuration cannot be loaded.
  757. * @throws Minz_ConfigurationNamespaceException
  758. */
  759. function get_user_configuration(string $username): ?FreshRSS_UserConfiguration {
  760. if (!FreshRSS_user_Controller::checkUsername($username)) {
  761. return null;
  762. }
  763. $namespace = 'user_' . $username;
  764. try {
  765. FreshRSS_UserConfiguration::register($namespace,
  766. USERS_PATH . '/' . $username . '/config.php',
  767. FRESHRSS_PATH . '/config-user.default.php');
  768. } catch (Minz_FileNotExistException $e) {
  769. Minz_Log::warning($e->getMessage(), ADMIN_LOG);
  770. return null;
  771. }
  772. $user_conf = FreshRSS_UserConfiguration::get($namespace);
  773. return $user_conf;
  774. }
  775. /**
  776. * Converts an IP (v4 or v6) to a binary representation using inet_pton
  777. *
  778. * @param string $ip the IP to convert
  779. * @return string a binary representation of the specified IP
  780. */
  781. function ipToBits(string $ip): string {
  782. $binaryip = '';
  783. foreach (str_split(inet_pton($ip) ?: '') as $char) {
  784. $binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
  785. }
  786. return $binaryip;
  787. }
  788. /**
  789. * Check if an ip belongs to the provided range (in CIDR format)
  790. *
  791. * @param string $ip the IP that we want to verify (ex: 192.168.16.1)
  792. * @param string $range the range to check against (ex: 192.168.16.0/24)
  793. * @return bool true if the IP is in the range, otherwise false
  794. */
  795. function checkCIDR(string $ip, string $range): bool {
  796. $binary_ip = ipToBits($ip);
  797. $split = explode('/', $range);
  798. $subnet = $split[0] ?? '';
  799. if ($subnet == '') {
  800. return false;
  801. }
  802. $binary_subnet = ipToBits($subnet);
  803. $mask_bits = $split[1] ?? '';
  804. $mask_bits = (int)$mask_bits;
  805. if ($mask_bits === 0) {
  806. $mask_bits = null;
  807. }
  808. $ip_net_bits = substr($binary_ip, 0, $mask_bits);
  809. $subnet_bits = substr($binary_subnet, 0, $mask_bits);
  810. return $ip_net_bits === $subnet_bits;
  811. }
  812. /**
  813. * 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.
  814. */
  815. function connectionRemoteAddress(): string {
  816. $remoteIp = is_string($_SERVER['CONN_REMOTE_ADDR'] ?? null) ? $_SERVER['CONN_REMOTE_ADDR'] : '';
  817. if ($remoteIp == '') {
  818. $remoteIp = is_string($_SERVER['REMOTE_ADDR'] ?? null) ? $_SERVER['REMOTE_ADDR'] : '';
  819. }
  820. if ($remoteIp == 0) {
  821. $remoteIp = '';
  822. }
  823. return $remoteIp;
  824. }
  825. /**
  826. * Check if the client (e.g. last proxy) is allowed to send unsafe headers.
  827. * This uses the `TRUSTED_PROXY` environment variable or the `trusted_sources` configuration option to get an array of the authorized ranges,
  828. * 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.
  829. * @return bool true if the sender’s IP is in one of the ranges defined in the configuration, else false
  830. */
  831. function checkTrustedIP(): bool {
  832. if (!FreshRSS_Context::hasSystemConf()) {
  833. return false;
  834. }
  835. $remoteIp = connectionRemoteAddress();
  836. if ($remoteIp === '') {
  837. return false;
  838. }
  839. $trusted = getenv('TRUSTED_PROXY');
  840. if ($trusted != 0 && is_string($trusted)) {
  841. $trusted = preg_split('/\s+/', $trusted, -1, PREG_SPLIT_NO_EMPTY);
  842. }
  843. if (!is_array($trusted) || empty($trusted)) {
  844. $trusted = FreshRSS_Context::systemConf()->trusted_sources;
  845. }
  846. foreach ($trusted as $cidr) {
  847. if (checkCIDR($remoteIp, $cidr)) {
  848. return true;
  849. }
  850. }
  851. return false;
  852. }
  853. function httpAuthUser(bool $onlyTrusted = true): string {
  854. $auths = array_unique(array_intersect_key($_SERVER, ['REMOTE_USER' => '', 'REDIRECT_REMOTE_USER' => '', 'HTTP_REMOTE_USER' => '', 'HTTP_X_WEBAUTH_USER' => '']));
  855. if (count($auths) > 1) {
  856. Minz_Log::warning('Multiple HTTP authentication headers!');
  857. return '';
  858. }
  859. if (!empty($_SERVER['REMOTE_USER']) && is_string($_SERVER['REMOTE_USER'])) {
  860. return $_SERVER['REMOTE_USER'];
  861. }
  862. if (!empty($_SERVER['REDIRECT_REMOTE_USER']) && is_string($_SERVER['REDIRECT_REMOTE_USER'])) {
  863. return $_SERVER['REDIRECT_REMOTE_USER'];
  864. }
  865. if (!$onlyTrusted || checkTrustedIP()) {
  866. if (!empty($_SERVER['HTTP_REMOTE_USER']) && is_string($_SERVER['HTTP_REMOTE_USER'])) {
  867. return $_SERVER['HTTP_REMOTE_USER'];
  868. }
  869. if (!empty($_SERVER['HTTP_X_WEBAUTH_USER']) && is_string($_SERVER['HTTP_X_WEBAUTH_USER'])) {
  870. return $_SERVER['HTTP_X_WEBAUTH_USER'];
  871. }
  872. }
  873. return '';
  874. }
  875. function cryptAvailable(): bool {
  876. $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
  877. return $hash === @crypt('password', $hash);
  878. }
  879. /**
  880. * Check PHP and its extensions are well-installed.
  881. *
  882. * @return array<string,bool> of tested values.
  883. */
  884. function check_install_php(): array {
  885. $pdo_mysql = extension_loaded('pdo_mysql');
  886. $pdo_pgsql = extension_loaded('pdo_pgsql');
  887. $pdo_sqlite = extension_loaded('pdo_sqlite');
  888. return [
  889. 'php' => version_compare(PHP_VERSION, FRESHRSS_MIN_PHP_VERSION) >= 0,
  890. 'curl' => extension_loaded('curl'),
  891. 'pdo' => $pdo_mysql || $pdo_sqlite || $pdo_pgsql,
  892. 'pcre' => extension_loaded('pcre'),
  893. 'ctype' => extension_loaded('ctype'),
  894. 'fileinfo' => extension_loaded('fileinfo'),
  895. 'dom' => class_exists('DOMDocument'),
  896. 'json' => extension_loaded('json'),
  897. 'mbstring' => extension_loaded('mbstring'),
  898. 'zip' => extension_loaded('zip'),
  899. ];
  900. }
  901. /**
  902. * Check different data files and directories exist.
  903. * @return array<string,bool> of tested values.
  904. */
  905. function check_install_files(): array {
  906. return [
  907. 'data' => is_dir(DATA_PATH) && touch(DATA_PATH . '/index.html'), // is_writable() is not reliable for a folder on NFS
  908. 'cache' => is_dir(CACHE_PATH) && touch(CACHE_PATH . '/index.html'),
  909. 'users' => is_dir(USERS_PATH) && touch(USERS_PATH . '/index.html'),
  910. 'favicons' => is_dir(DATA_PATH) && touch(DATA_PATH . '/favicons/index.html'),
  911. 'tokens' => is_dir(DATA_PATH) && touch(DATA_PATH . '/tokens/index.html'),
  912. ];
  913. }
  914. /**
  915. * Check database is well-installed.
  916. *
  917. * @return array<string,bool> of tested values.
  918. */
  919. function check_install_database(): array {
  920. $status = [
  921. 'connection' => true,
  922. 'tables' => false,
  923. 'categories' => false,
  924. 'feeds' => false,
  925. 'entries' => false,
  926. 'entrytmp' => false,
  927. 'tag' => false,
  928. 'entrytag' => false,
  929. ];
  930. try {
  931. $dbDAO = FreshRSS_Factory::createDatabaseDAO();
  932. $status['tables'] = $dbDAO->tablesAreCorrect();
  933. $status['categories'] = $dbDAO->categoryIsCorrect();
  934. $status['feeds'] = $dbDAO->feedIsCorrect();
  935. $status['entries'] = $dbDAO->entryIsCorrect();
  936. $status['entrytmp'] = $dbDAO->entrytmpIsCorrect();
  937. $status['tag'] = $dbDAO->tagIsCorrect();
  938. $status['entrytag'] = $dbDAO->entrytagIsCorrect();
  939. } catch (Minz_PDOConnectionException $e) {
  940. $status['connection'] = false;
  941. }
  942. return $status;
  943. }
  944. /**
  945. * Remove a directory recursively.
  946. * From http://php.net/rmdir#110489
  947. */
  948. function recursive_unlink(string $dir): bool {
  949. if (!is_dir($dir)) {
  950. return true;
  951. }
  952. if (is_link($dir)) {
  953. if (PHP_OS_FAMILY === "Windows") {
  954. return rmdir($dir);
  955. }
  956. return unlink($dir);
  957. }
  958. $files = array_diff(scandir($dir) ?: [], ['.', '..']);
  959. foreach ($files as $filename) {
  960. $filename = $dir . '/' . $filename;
  961. if (is_dir($filename)) {
  962. @chmod($filename, 0777);
  963. recursive_unlink($filename);
  964. } else {
  965. unlink($filename);
  966. }
  967. }
  968. return rmdir($dir);
  969. }
  970. /**
  971. * Remove queries where $get is appearing.
  972. * @param string $get the get attribute which should be removed.
  973. * @param array<int,array{get?:string,name?:string,order?:string,search?:string,state?:int,url?:string,token?:string,
  974. * shareRss?:bool,shareOpml?:bool,description?:string,imageUrl?:string}> $queries an array of queries.
  975. * @return array<int,array{get?:string,name?:string,order?:string,search?:string,state?:int,url?:string,token?:string,
  976. * shareRss?:bool,shareOpml?:bool,description?:string,imageUrl?:string}> without queries where $get is appearing.
  977. */
  978. function remove_query_by_get(string $get, array $queries): array {
  979. $final_queries = [];
  980. foreach ($queries as $query) {
  981. if (empty($query['get']) || $query['get'] !== $get) {
  982. $final_queries[] = $query;
  983. }
  984. }
  985. return $final_queries;
  986. }
  987. function _i(string $icon, int $type = FreshRSS_Themes::ICON_DEFAULT): string {
  988. return FreshRSS_Themes::icon($icon, $type);
  989. }
  990. const SHORTCUT_KEYS = [
  991. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  992. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  993. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  994. 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12',
  995. 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'Backspace', 'Delete',
  996. 'End', 'Enter', 'Escape', 'Home', 'Insert', 'PageDown', 'PageUp', 'Space', 'Tab',
  997. ];
  998. /**
  999. * @param array<string> $shortcuts
  1000. * @return list<string>
  1001. */
  1002. function getNonStandardShortcuts(array $shortcuts): array {
  1003. $standard = strtolower(implode(' ', SHORTCUT_KEYS));
  1004. $nonStandard = array_filter($shortcuts, static function (string $shortcut) use ($standard) {
  1005. $shortcut = trim($shortcut);
  1006. return $shortcut !== '' && stripos($standard, $shortcut) === false;
  1007. });
  1008. return array_values($nonStandard);
  1009. }
  1010. function errorMessageInfo(string $errorTitle, string $error = ''): string {
  1011. $errorTitle = htmlspecialchars($errorTitle, ENT_NOQUOTES, 'UTF-8');
  1012. $message = '';
  1013. $details = '';
  1014. $error = trim($error);
  1015. // Prevent empty tags by checking if error is not empty first
  1016. if ($error !== '') {
  1017. $error = htmlspecialchars($error, ENT_NOQUOTES, 'UTF-8') . "\n";
  1018. // First line is the main message, other lines are the details
  1019. list($message, $details) = explode("\n", $error, 2);
  1020. $message = "<h2>{$message}</h2>";
  1021. $details = "<pre>{$details}</pre>";
  1022. }
  1023. header("Content-Security-Policy: default-src 'self'; frame-ancestors " .
  1024. (FreshRSS_Context::systemConf()->attributeString('csp.frame-ancestors') ?? "'none'"));
  1025. header('Referrer-Policy: same-origin');
  1026. return <<<MSG
  1027. <!DOCTYPE html><html><header><title>HTTP 500: {$errorTitle}</title></header><body>
  1028. <h1>HTTP 500: {$errorTitle}</h1>
  1029. {$message}
  1030. {$details}
  1031. <hr />
  1032. <small>For help see the documentation: <a href="https://freshrss.github.io/FreshRSS/en/admins/logs_and_errors.html" target="_blank">
  1033. https://freshrss.github.io/FreshRSS/en/admins/logs_and_errors.html</a></small>
  1034. </body></html>
  1035. MSG;
  1036. }