lib_rss.php 26 KB

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