lib_rss.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. declare(strict_types=1);
  3. if (!function_exists('mb_strcut')) {
  4. function mb_strcut(string $str, int $start, ?int $length = null, string $encoding = 'UTF-8'): string {
  5. return substr($str, $start, $length) ?: '';
  6. }
  7. }
  8. if (!function_exists('syslog')) {
  9. if (COPY_SYSLOG_TO_STDERR && !defined('STDERR')) {
  10. define('STDERR', fopen('php://stderr', 'w'));
  11. }
  12. function syslog(int $priority, string $message): bool {
  13. if (COPY_SYSLOG_TO_STDERR && defined('STDERR') && is_resource(STDERR)) {
  14. return fwrite(STDERR, $message . "\n") != false;
  15. }
  16. return false;
  17. }
  18. }
  19. if (function_exists('openlog')) {
  20. if (COPY_SYSLOG_TO_STDERR) {
  21. openlog('FreshRSS', LOG_CONS | LOG_ODELAY | LOG_PID | LOG_PERROR, LOG_USER);
  22. } else {
  23. openlog('FreshRSS', LOG_CONS | LOG_ODELAY | LOG_PID, LOG_USER);
  24. }
  25. }
  26. /**
  27. * Build a directory path by concatenating a list of directory names.
  28. *
  29. * @param string ...$path_parts a list of directory names
  30. * @return string corresponding to the final pathname
  31. */
  32. function join_path(...$path_parts): string {
  33. return join(DIRECTORY_SEPARATOR, $path_parts);
  34. }
  35. //<Auto-loading>
  36. function classAutoloader(string $class): void {
  37. if (str_starts_with($class, 'FreshRSS')) {
  38. $components = explode('_', $class);
  39. switch (count($components)) {
  40. case 1:
  41. include APP_PATH . '/' . $components[0] . '.php';
  42. return;
  43. case 2:
  44. include APP_PATH . '/Models/' . $components[1] . '.php';
  45. return;
  46. case 3: //Controllers, Exceptions
  47. include APP_PATH . '/' . $components[2] . 's/' . $components[1] . $components[2] . '.php';
  48. return;
  49. }
  50. } elseif (str_starts_with($class, 'Minz')) {
  51. include LIB_PATH . '/' . str_replace('_', '/', $class) . '.php';
  52. } elseif (str_starts_with($class, 'SimplePie\\')) {
  53. $prefix = 'SimplePie\\';
  54. $base_dir = LIB_PATH . '/simplepie/simplepie/src/';
  55. $relative_class_name = substr($class, strlen($prefix));
  56. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  57. } elseif (str_starts_with($class, 'Gt\\CssXPath\\')) {
  58. $prefix = 'Gt\\CssXPath\\';
  59. $base_dir = LIB_PATH . '/phpgt/cssxpath/src/';
  60. $relative_class_name = substr($class, strlen($prefix));
  61. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  62. } elseif (str_starts_with($class, 'marienfressinaud\\LibOpml\\')) {
  63. $prefix = 'marienfressinaud\\LibOpml\\';
  64. $base_dir = LIB_PATH . '/marienfressinaud/lib_opml/src/LibOpml/';
  65. $relative_class_name = substr($class, strlen($prefix));
  66. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  67. } elseif (str_starts_with($class, 'PHPMailer\\PHPMailer\\')) {
  68. $prefix = 'PHPMailer\\PHPMailer\\';
  69. $base_dir = LIB_PATH . '/phpmailer/phpmailer/src/';
  70. $relative_class_name = substr($class, strlen($prefix));
  71. include $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
  72. }
  73. }
  74. spl_autoload_register('classAutoloader');
  75. //</Auto-loading>
  76. /**
  77. * @param array<mixed,mixed> $array
  78. * @phpstan-assert-if-true array<string,mixed> $array
  79. */
  80. function is_array_keys_string(array $array): bool {
  81. foreach ($array as $key => $value) {
  82. if (!is_string($key)) {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. /**
  89. * @param array<mixed,mixed> $array
  90. * @phpstan-assert-if-true array<mixed,string> $array
  91. */
  92. function is_array_values_string(array $array): bool {
  93. foreach ($array as $value) {
  94. if (!is_string($value)) {
  95. return false;
  96. }
  97. }
  98. return true;
  99. }
  100. /**
  101. * Memory efficient replacement of `echo json_encode(...)`
  102. * @param array<mixed>|mixed $json
  103. * @param int $optimisationDepth Number of levels for which to perform memory optimisation
  104. * before calling the faster native JSON serialisation.
  105. * Set to negative value for infinite depth.
  106. */
  107. function echoJson($json, int $optimisationDepth = -1): void {
  108. if ($optimisationDepth === 0 || !is_array($json)) {
  109. echo json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  110. return;
  111. }
  112. $first = true;
  113. if (array_is_list($json)) {
  114. echo '[';
  115. foreach ($json as $item) {
  116. if ($first) {
  117. $first = false;
  118. } else {
  119. echo ',';
  120. }
  121. echoJson($item, $optimisationDepth - 1);
  122. }
  123. echo ']';
  124. } else {
  125. echo '{';
  126. foreach ($json as $key => $value) {
  127. if ($first) {
  128. $first = false;
  129. } else {
  130. echo ',';
  131. }
  132. echo json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ':';
  133. echoJson($value, $optimisationDepth - 1);
  134. }
  135. echo '}';
  136. }
  137. }
  138. function safe_ascii(?string $text): string {
  139. return $text === null ? '' : (filter_var($text, FILTER_DEFAULT, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH) ?: '');
  140. }
  141. if (function_exists('mb_convert_encoding')) {
  142. function safe_utf8(?string $text): string {
  143. return $text === null ? '' : (mb_convert_encoding($text, 'UTF-8', 'UTF-8') ?: '');
  144. }
  145. } elseif (function_exists('iconv')) {
  146. function safe_utf8(?string $text): string {
  147. return $text === null ? '' : (iconv('UTF-8', 'UTF-8//IGNORE', $text) ?: '');
  148. }
  149. } else {
  150. function safe_utf8(?string $text): string {
  151. return $text ?? '';
  152. }
  153. }
  154. function escapeToUnicodeAlternative(string $text, bool $extended = true): string {
  155. $text = htmlspecialchars_decode($text, ENT_QUOTES);
  156. //Problematic characters
  157. $problem = ['&', '<', '>'];
  158. //Use their fullwidth Unicode form instead:
  159. $replace = ['&', '<', '>'];
  160. // https://raw.githubusercontent.com/mihaip/google-reader-api/master/wiki/StreamId.wiki
  161. if ($extended) {
  162. $problem += ["'", '"', '^', '?', '\\', '/', ',', ';'];
  163. $replace += ["’", '"', '^', '?', '\', '/', ',', ';'];
  164. }
  165. return trim(str_replace($problem, $replace, $text));
  166. }
  167. function format_number(int|float $n, int $precision = 0): string {
  168. // number_format does not seem to be Unicode-compatible
  169. return str_replace(' ', ' ', // Thin non-breaking space
  170. number_format((float)$n, $precision, '.', ' ')
  171. );
  172. }
  173. function format_bytes(int $bytes, int $precision = 2, string $system = 'IEC'): string {
  174. if ($system === 'IEC') {
  175. $base = 1024;
  176. $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
  177. } elseif ($system === 'SI') {
  178. $base = 1000;
  179. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  180. } else {
  181. return format_number($bytes, $precision);
  182. }
  183. $bytes = max(intval($bytes), 0);
  184. $pow = $bytes === 0 ? 0 : (int)floor(log($bytes) / log($base));
  185. $pow = min(max(0, $pow), count($units) - 1);
  186. $bytes /= pow($base, $pow);
  187. return format_number($bytes, $precision) . ' ' . $units[$pow];
  188. }
  189. function timestamptodate(int $t, bool $hour = true): string {
  190. $month = _t('gen.date.' . date('M', $t));
  191. if ($hour) {
  192. $date = _t('gen.date.format_date_hour', $month);
  193. } else {
  194. $date = _t('gen.date.format_date', $month);
  195. }
  196. return @date($date, $t) ?: '';
  197. }
  198. /**
  199. * Decode HTML entities but preserve XML entities.
  200. */
  201. function html_only_entity_decode(?string $text): string {
  202. /** @var array<string,string>|null $htmlEntitiesOnly */
  203. static $htmlEntitiesOnly = null;
  204. if ($htmlEntitiesOnly === null) {
  205. $htmlEntitiesOnly = array_flip(array_diff(
  206. get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'UTF-8'), //Decode HTML entities
  207. get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES, 'UTF-8') //Preserve XML entities
  208. ));
  209. }
  210. return $text == null ? '' : strtr($text, $htmlEntitiesOnly);
  211. }
  212. /**
  213. * Remove passwords in FreshRSS logs.
  214. * See also ../cli/sensitive-log.sh for Web server logs.
  215. * @param array<string,mixed>|string $log
  216. * @return array<string,mixed>|string
  217. */
  218. function sensitive_log(array|string $log): array|string {
  219. if (is_array($log)) {
  220. foreach ($log as $k => $v) {
  221. if (in_array($k, ['api_key', 'Passwd', 'T'], true)) {
  222. $log[$k] = '██';
  223. } elseif ((is_array($v) && is_array_keys_string($v)) || is_string($v)) {
  224. $log[$k] = sensitive_log($v);
  225. } else {
  226. return '';
  227. }
  228. }
  229. } elseif (is_string($log)) {
  230. $log = preg_replace([
  231. '/\b(auth=.*?\/)[^&]+/i',
  232. '/\b(Passwd=)[^&]+/i',
  233. '/\b(Authorization)[^&]+/i',
  234. ], '$1█', $log) ?? '';
  235. }
  236. return $log;
  237. }
  238. function cleanCache(int $hours = 720): void {
  239. // N.B.: GLOB_BRACE is not available on all platforms
  240. $files = glob(CACHE_PATH . '/*.*', GLOB_NOSORT) ?: [];
  241. foreach ($files as $file) {
  242. if (str_ends_with($file, 'index.html')) {
  243. continue;
  244. }
  245. $cacheMtime = @filemtime($file);
  246. if ($cacheMtime !== false && $cacheMtime < time() - (3600 * $hours)) {
  247. unlink($file);
  248. }
  249. }
  250. }
  251. /**
  252. * Add support of image lazy loading
  253. * Move content from src/poster attribute to data-original
  254. * @param string $content is the text we want to parse
  255. */
  256. function lazyimg(string $content): string {
  257. return preg_replace([
  258. '/<((?:img|image|iframe|track)[^>]+?)src="([^"]+)"([^>]*)>/i',
  259. "/<((?:img|image|iframe|track)[^>]+?)src='([^']+)'([^>]*)>/i",
  260. '/<((?:video)[^>]+?)poster="([^"]+)"([^>]*)>/i',
  261. "/<((?:video)[^>]+?)poster='([^']+)'([^>]*)>/i",
  262. ], [
  263. '<$1src="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  264. "<$1src='" . Minz_Url::display('/themes/icons/grey.gif') . "' data-original='$2'$3>",
  265. '<$1poster="' . Minz_Url::display('/themes/icons/grey.gif') . '" data-original="$2"$3>',
  266. "<$1poster='" . Minz_Url::display('/themes/icons/grey.gif') . "' data-original='$2'$3>",
  267. ],
  268. $content
  269. ) ?? '';
  270. }
  271. /** @return numeric-string */
  272. function uTimeString(): string {
  273. $t = gettimeofday();
  274. // @phpstan-ignore return.type
  275. return ((string)$t['sec']) . str_pad((string)$t['usec'], 6, '0', STR_PAD_LEFT);
  276. }
  277. function invalidateHttpCache(string $username = ''): bool {
  278. if (!FreshRSS_user_Controller::checkUsername($username)) {
  279. Minz_Session::_param('touch', uTimeString());
  280. $username = Minz_User::name() ?? Minz_User::INTERNAL_USER;
  281. }
  282. return FreshRSS_UserDAO::ctouch($username);
  283. }
  284. #[Deprecated('Use Minz_Request::connectionRemoteAddress() instead.')]
  285. function connectionRemoteAddress(): string {
  286. return Minz_Request::connectionRemoteAddress();
  287. }
  288. #[Deprecated('Use FreshRSS_http_Util::checkTrustedIP() instead.')]
  289. function checkTrustedIP(): bool {
  290. return FreshRSS_http_Util::checkTrustedIP();
  291. }
  292. /**
  293. * Remove a directory recursively.
  294. * From http://php.net/rmdir#110489
  295. */
  296. function recursive_unlink(string $dir): bool {
  297. if (!is_dir($dir)) {
  298. return true;
  299. }
  300. if (is_link($dir)) {
  301. if (PHP_OS_FAMILY === "Windows") {
  302. return rmdir($dir);
  303. }
  304. return unlink($dir);
  305. }
  306. $files = array_diff(scandir($dir) ?: [], ['.', '..']);
  307. foreach ($files as $filename) {
  308. $filename = $dir . '/' . $filename;
  309. if (is_dir($filename)) {
  310. @chmod($filename, 0777);
  311. recursive_unlink($filename);
  312. } else {
  313. unlink($filename);
  314. }
  315. }
  316. return rmdir($dir);
  317. }
  318. function _i(string $icon, int $type = FreshRSS_Themes::ICON_DEFAULT): string {
  319. return FreshRSS_Themes::icon($icon, $type);
  320. }
  321. function errorMessageInfo(string $errorTitle, string $error = ''): string {
  322. $errorTitle = htmlspecialchars($errorTitle, ENT_NOQUOTES, 'UTF-8');
  323. $message = '';
  324. $details = '';
  325. $error = trim($error);
  326. // Prevent empty tags by checking if error is not empty first
  327. if ($error !== '') {
  328. $error = htmlspecialchars($error, ENT_NOQUOTES, 'UTF-8') . "\n";
  329. // First line is the main message, other lines are the details
  330. list($message, $details) = explode("\n", $error, 2);
  331. $message = "<h2>{$message}</h2>";
  332. $details = "<pre>{$details}</pre>";
  333. }
  334. header("Content-Security-Policy: default-src 'self'; frame-ancestors " .
  335. (FreshRSS_Context::systemConf()->attributeString('csp.frame-ancestors') ?? "'none'"));
  336. header('Referrer-Policy: same-origin');
  337. return <<<MSG
  338. <!DOCTYPE html><html><header><title>HTTP 500: {$errorTitle}</title></header><body>
  339. <h1>HTTP 500: {$errorTitle}</h1>
  340. {$message}
  341. {$details}
  342. <hr />
  343. <small>For help see the documentation: <a href="https://freshrss.github.io/FreshRSS/en/admins/logs_and_errors.html" target="_blank">
  344. https://freshrss.github.io/FreshRSS/en/admins/logs_and_errors.html</a></small>
  345. </body></html>
  346. MSG;
  347. }