bootstrap.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. date_default_timezone_set(config('site.timezone', 'UTC'));
  16. require APP_ROOT . '/app/storage.php';
  17. require APP_ROOT . '/app/csrf.php';
  18. require APP_ROOT . '/app/auth.php';
  19. require APP_ROOT . '/app/s3.php';
  20. require APP_ROOT . '/app/markdown.php';
  21. require APP_ROOT . '/app/partials.php';
  22. /**
  23. * Read a config value by dot path, e.g. config('s3.bucket').
  24. */
  25. function config(string $path, mixed $default = null): mixed
  26. {
  27. $value = $GLOBALS['config'];
  28. foreach (explode('.', $path) as $part) {
  29. if (!is_array($value) || !array_key_exists($part, $value)) {
  30. return $default;
  31. }
  32. $value = $value[$part];
  33. }
  34. return $value;
  35. }
  36. /** HTML-escape for output. */
  37. function e(?string $s): string
  38. {
  39. return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
  40. }
  41. /** Start the session with hardened cookie settings (idempotent). */
  42. function session_boot(): void
  43. {
  44. if (session_status() === PHP_SESSION_ACTIVE) {
  45. return;
  46. }
  47. session_set_cookie_params([
  48. 'lifetime' => 0,
  49. 'path' => '/',
  50. 'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
  51. 'httponly' => true,
  52. 'samesite' => 'Lax',
  53. ]);
  54. session_name('fpsid');
  55. session_start();
  56. }
  57. /** Redirect and stop. */
  58. function redirect(string $url): never
  59. {
  60. header('Location: ' . $url);
  61. exit;
  62. }
  63. /** Send a JSON response and stop (used by admin/api.php). */
  64. function json_response(array $payload, int $status = 200): never
  65. {
  66. http_response_code($status);
  67. header('Content-Type: application/json; charset=utf-8');
  68. echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  69. exit;
  70. }