lib_rss.php 28 KB

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