bootstrap.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. <?php
  2. /**
  3. * Application bootstrap. Every public entry script includes this first.
  4. */
  5. declare(strict_types=1);
  6. define('APP_ROOT', dirname(__DIR__));
  7. define('DATA_DIR', APP_ROOT . '/data');
  8. define('MEDIA_DIR', APP_ROOT . '/media');
  9. define('CONFIG_DIR', APP_ROOT . '/config');
  10. if (!is_file(CONFIG_DIR . '/config.php')) {
  11. http_response_code(500);
  12. exit('Missing config/config.php — copy config/config.sample.php and adjust it.');
  13. }
  14. $GLOBALS['config'] = require CONFIG_DIR . '/config.php';
  15. // APP_VERSION. Its own file because the release build script rewrites it and
  16. // the manage client reads it back — see app/version.php.
  17. require APP_ROOT . '/app/version.php';
  18. date_default_timezone_set(config('site.timezone', 'UTC'));
  19. require APP_ROOT . '/app/storage.php';
  20. require APP_ROOT . '/app/csrf.php';
  21. require APP_ROOT . '/app/auth.php';
  22. require APP_ROOT . '/app/exif.php';
  23. require APP_ROOT . '/app/s3.php';
  24. require APP_ROOT . '/app/zip.php';
  25. require APP_ROOT . '/app/archive.php';
  26. require APP_ROOT . '/app/migrate.php';
  27. require APP_ROOT . '/app/markdown.php';
  28. require APP_ROOT . '/app/partials.php';
  29. require APP_ROOT . '/app/manage.php';
  30. /**
  31. * Read a config value by dot path, e.g. config('s3.bucket').
  32. */
  33. function config(string $path, mixed $default = null): mixed
  34. {
  35. $value = $GLOBALS['config'];
  36. foreach (explode('.', $path) as $part) {
  37. if (!is_array($value) || !array_key_exists($part, $value)) {
  38. return $default;
  39. }
  40. $value = $value[$part];
  41. }
  42. return $value;
  43. }
  44. /**
  45. * Prefix a link or asset path with the way back to the site root, so the shared
  46. * public partials work from any depth. Pages in the document root need no
  47. * prefix; pages in a subfolder (gallery/) define SITE_BASE as '../' before
  48. * including this file. Relative rather than absolute, because the app may be
  49. * installed in a subdirectory of the domain.
  50. */
  51. function base(string $path = ''): string
  52. {
  53. return (defined('SITE_BASE') ? SITE_BASE : '') . $path;
  54. }
  55. /** HTML-escape for output. */
  56. function e(?string $s): string
  57. {
  58. return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
  59. }
  60. /**
  61. * Byte count as something a client can judge at a glance. Gallery archives run
  62. * to gigabytes, so the size belongs on the download button itself.
  63. */
  64. function human_bytes(int $bytes): string
  65. {
  66. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  67. $i = 0;
  68. $value = (float)$bytes;
  69. while ($value >= 1024 && $i < count($units) - 1) {
  70. $value /= 1024;
  71. $i++;
  72. }
  73. return ($value >= 10 || $i === 0 ? round($value) : round($value, 1)) . ' ' . $units[$i];
  74. }
  75. /** Start the session with hardened cookie settings (idempotent). */
  76. function session_boot(): void
  77. {
  78. if (session_status() === PHP_SESSION_ACTIVE) {
  79. return;
  80. }
  81. session_set_cookie_params([
  82. 'lifetime' => 0,
  83. 'path' => '/',
  84. 'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
  85. 'httponly' => true,
  86. 'samesite' => 'Lax',
  87. ]);
  88. session_name('fpsid');
  89. session_start();
  90. }
  91. /**
  92. * URL of a script in this installation, for the server to call itself.
  93. *
  94. * site.base_url is preferred when it has been filled in, because it does not
  95. * depend on the request's Host header. Otherwise the URL is derived from the
  96. * current request, mapping APP_ROOT against DOCUMENT_ROOT so an app installed
  97. * in a subdirectory still resolves. Null means the URL cannot be determined —
  98. * the caller then has to do the work inline instead of dispatching it.
  99. */
  100. function self_url(string $pathAndQuery): ?string
  101. {
  102. $configured = rtrim((string)config('site.base_url', ''), '/');
  103. if ($configured !== '' && !str_contains($configured, 'example.com')) {
  104. return $configured . $pathAndQuery;
  105. }
  106. $host = (string)($_SERVER['HTTP_HOST'] ?? '');
  107. $root = rtrim(str_replace('\\', '/', (string)($_SERVER['DOCUMENT_ROOT'] ?? '')), '/');
  108. $app = str_replace('\\', '/', APP_ROOT);
  109. if ($host === '' || $root === '' || !str_starts_with($app, $root)) {
  110. return null;
  111. }
  112. $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  113. return $scheme . '://' . $host . rtrim(substr($app, strlen($root)), '/') . $pathAndQuery;
  114. }
  115. /**
  116. * Fire a request at one of this installation's own background scripts and hang
  117. * up without waiting for it. Those scripts set ignore_user_abort(), so they run
  118. * on regardless.
  119. *
  120. * A timeout is the expected, successful outcome: it means the request was
  121. * delivered and the script is busy with it. A *completed* response only counts
  122. * as success if it is the script's own 204 — anything else (a 404 from a wrong
  123. * key or a misconfigured base URL) means nothing is running, and saying so lets
  124. * the caller fall back to doing the work inline instead of silently stalling.
  125. */
  126. function self_dispatch(?string $url, int $timeoutMs = 1000): bool
  127. {
  128. if ($url === null || !function_exists('curl_init')) {
  129. return false;
  130. }
  131. $ch = curl_init($url);
  132. curl_setopt_array($ch, [
  133. CURLOPT_RETURNTRANSFER => true,
  134. CURLOPT_NOSIGNAL => true,
  135. CURLOPT_CONNECTTIMEOUT_MS => $timeoutMs,
  136. CURLOPT_TIMEOUT_MS => $timeoutMs,
  137. ]);
  138. curl_exec($ch);
  139. $errno = curl_errno($ch);
  140. $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  141. return $errno === CURLE_OPERATION_TIMEOUTED || ($errno === 0 && $status === 204);
  142. }
  143. /** Redirect and stop. */
  144. function redirect(string $url): never
  145. {
  146. header('Location: ' . $url);
  147. exit;
  148. }
  149. /** Send a JSON response and stop (used by admin/api.php). */
  150. function json_response(array $payload, int $status = 200): never
  151. {
  152. http_response_code($status);
  153. header('Content-Type: application/json; charset=utf-8');
  154. echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  155. exit;
  156. }