lib_rss.php 29 KB

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