storage.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. <?php
  2. /**
  3. * Flat-file JSON storage with locking, plus the site/gallery data accessors.
  4. */
  5. declare(strict_types=1);
  6. /** Read a JSON file; returns $default if missing or unreadable. */
  7. function json_read(string $file, array $default = []): array
  8. {
  9. if (!is_file($file)) {
  10. return $default;
  11. }
  12. $fh = fopen($file, 'r');
  13. if ($fh === false) {
  14. return $default;
  15. }
  16. flock($fh, LOCK_SH);
  17. $raw = stream_get_contents($fh);
  18. flock($fh, LOCK_UN);
  19. fclose($fh);
  20. $data = json_decode((string)$raw, true);
  21. return is_array($data) ? $data : $default;
  22. }
  23. /** Write a JSON file atomically (tmp file + rename) under an exclusive lock. */
  24. function json_write(string $file, array $data): void
  25. {
  26. $dir = dirname($file);
  27. if (!is_dir($dir)) {
  28. mkdir($dir, 0755, true);
  29. }
  30. $tmp = $file . '.' . bin2hex(random_bytes(6)) . '.tmp';
  31. $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  32. if (file_put_contents($tmp, $json, LOCK_EX) === false) {
  33. throw new RuntimeException("Cannot write $tmp");
  34. }
  35. if (!rename($tmp, $file)) {
  36. @unlink($tmp);
  37. throw new RuntimeException("Cannot replace $file");
  38. }
  39. }
  40. /** URL-safe random token. */
  41. function random_token(int $chars = 8): string
  42. {
  43. $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  44. $out = '';
  45. for ($i = 0; $i < $chars; $i++) {
  46. $out .= $alphabet[random_int(0, strlen($alphabet) - 1)];
  47. }
  48. return $out;
  49. }
  50. /** Turn a title into a URL slug fragment ("Wedding Müller" → "wedding-mueller"). */
  51. function slugify(string $title): string
  52. {
  53. $map = ['ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'Ä' => 'ae', 'Ö' => 'oe', 'Ü' => 'ue', 'ß' => 'ss'];
  54. $s = strtr($title, $map);
  55. if (function_exists('iconv')) {
  56. $s = (string)@iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
  57. }
  58. $s = strtolower($s);
  59. $s = preg_replace('/[^a-z0-9]+/', '-', $s) ?? '';
  60. $s = trim($s, '-');
  61. return $s !== '' ? $s : 'gallery';
  62. }
  63. // ---------------------------------------------------------------------------
  64. // Site content (landing page + showreel)
  65. // ---------------------------------------------------------------------------
  66. function site_get(): array
  67. {
  68. return json_read(DATA_DIR . '/site.json', [
  69. 'intro_title' => 'Jane Doe',
  70. 'intro_text' => "Photographer based in Berlin.\nAvailable for portraits, weddings and events.",
  71. 'hero_image' => null,
  72. 'showreel' => [],
  73. ]);
  74. }
  75. function site_save(array $site): void
  76. {
  77. json_write(DATA_DIR . '/site.json', $site);
  78. }
  79. // ---------------------------------------------------------------------------
  80. // Galleries — one JSON file per gallery in data/galleries/
  81. // ---------------------------------------------------------------------------
  82. function gallery_file(string $slug): string
  83. {
  84. // Slugs are generated by us, but never trust a request parameter in a path.
  85. if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/', $slug) || strlen($slug) > 120) {
  86. throw new InvalidArgumentException('Invalid gallery slug');
  87. }
  88. return DATA_DIR . '/galleries/' . $slug . '.json';
  89. }
  90. function gallery_load(string $slug): ?array
  91. {
  92. try {
  93. $file = gallery_file($slug);
  94. } catch (InvalidArgumentException) {
  95. return null;
  96. }
  97. $g = json_read($file);
  98. return $g === [] ? null : $g;
  99. }
  100. function gallery_save(array $gallery): void
  101. {
  102. json_write(gallery_file($gallery['slug']), $gallery);
  103. }
  104. function gallery_delete(string $slug): void
  105. {
  106. $file = gallery_file($slug);
  107. if (is_file($file)) {
  108. unlink($file);
  109. }
  110. }
  111. /** All galleries, newest first. */
  112. function galleries_all(): array
  113. {
  114. $out = [];
  115. foreach (glob(DATA_DIR . '/galleries/*.json') ?: [] as $file) {
  116. $g = json_read($file);
  117. if ($g !== []) {
  118. $out[] = $g;
  119. }
  120. }
  121. usort($out, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
  122. return $out;
  123. }
  124. /** A gallery past its expiry date is treated as nonexistent for visitors. */
  125. function gallery_is_expired(array $gallery): bool
  126. {
  127. $expires = $gallery['expires_at'] ?? null;
  128. if ($expires === null || $expires === '') {
  129. return false;
  130. }
  131. // The gallery stays visible through the whole expiry day.
  132. return date('Y-m-d') > $expires;
  133. }