25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
2.5KB

  1. <?php
  2. declare(strict_types=1);
  3. use Core\App;
  4. use Core\Database;
  5. use Core\MigrationManager;
  6. use Core\Response;
  7. use Core\View;
  8. function app(): App
  9. {
  10. static $app = null;
  11. if ($app === null) {
  12. $app = new App();
  13. }
  14. return $app;
  15. }
  16. function view(string $view, array $data = []): Response
  17. {
  18. return View::render($view, $data);
  19. }
  20. function redirect(string $url): Response
  21. {
  22. return Response::redirect($url);
  23. }
  24. function database(): Database
  25. {
  26. static $database = null;
  27. if ($database === null) {
  28. /** @var array<string, mixed> $config */
  29. $config = require __DIR__ . '/../config/database.php';
  30. prepareSqliteDatabase($config['dsn'] ?? '');
  31. $database = new Database($config);
  32. }
  33. return $database;
  34. }
  35. function migration_manager(): MigrationManager
  36. {
  37. static $migrationManager = null;
  38. if ($migrationManager === null) {
  39. $migrationManager = new MigrationManager(database(), __DIR__ . '/../database/migrations');
  40. }
  41. return $migrationManager;
  42. }
  43. function ensureSessionStarted(): void
  44. {
  45. if (session_status() === PHP_SESSION_NONE) {
  46. session_start();
  47. }
  48. }
  49. function prepareSqliteDatabase(string $dsn): void
  50. {
  51. if (!str_starts_with($dsn, 'sqlite:')) {
  52. return;
  53. }
  54. $path = substr($dsn, 7);
  55. if ($path === false || $path === '') {
  56. return;
  57. }
  58. $directory = dirname($path);
  59. if (!is_dir($directory)) {
  60. mkdir($directory, 0777, true);
  61. }
  62. if (!is_writable($directory)) {
  63. @chmod($directory, 0777);
  64. }
  65. if (!file_exists($path)) {
  66. touch($path);
  67. }
  68. if (!is_writable($path)) {
  69. @chmod($path, 0666);
  70. }
  71. }
  72. function e(?string $value): string
  73. {
  74. return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  75. }
  76. function asset(string $path): string
  77. {
  78. return '/' . ltrim($path, '/');
  79. }
  80. function csrf_token(): string
  81. {
  82. ensureSessionStarted();
  83. if (!isset($_SESSION['_csrf_token']) || !is_string($_SESSION['_csrf_token'])) {
  84. $_SESSION['_csrf_token'] = bin2hex(random_bytes(32));
  85. }
  86. return $_SESSION['_csrf_token'];
  87. }
  88. function csrf_field(): string
  89. {
  90. return '<input type="hidden" name="_token" value="' . e(csrf_token()) . '">';
  91. }
  92. function verify_csrf_token(?string $token): bool
  93. {
  94. ensureSessionStarted();
  95. if (!is_string($token) || $token === '') {
  96. return false;
  97. }
  98. $sessionToken = $_SESSION['_csrf_token'] ?? null;
  99. return is_string($sessionToken) && hash_equals($sessionToken, $token);
  100. }

Powered by TurnKey Linux.