lib_rss.php 31 KB

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