lib_rss.php 27 KB

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