lib_rss.php 28 KB

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