lib_rss.php 25 KB

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