storage.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. // Local media (hero + showreel images in public/media/)
  65. // ---------------------------------------------------------------------------
  66. const MEDIA_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif'];
  67. /**
  68. * Store one uploaded image in public/media/, full resolution, unmodified.
  69. * Returns the stored filename, or null if the upload is invalid.
  70. */
  71. function media_store_upload(array $file): ?string
  72. {
  73. if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
  74. return null;
  75. }
  76. $ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
  77. if (!in_array($ext, MEDIA_EXTENSIONS, true)) {
  78. return null;
  79. }
  80. // Cheap content sanity check without touching the image data.
  81. if (function_exists('getimagesize') && @getimagesize($file['tmp_name']) === false) {
  82. return null;
  83. }
  84. $base = pathinfo($file['name'], PATHINFO_FILENAME);
  85. $base = preg_replace('/[^A-Za-z0-9._-]+/', '-', $base) ?: 'image';
  86. $name = substr($base, 0, 60) . '-' . random_token(6) . '.' . $ext;
  87. if (!move_uploaded_file($file['tmp_name'], MEDIA_DIR . '/' . $name)) {
  88. return null;
  89. }
  90. return $name;
  91. }
  92. /** Delete a local media file (filename only, no paths). */
  93. function media_delete(string $name): void
  94. {
  95. if ($name !== '' && basename($name) === $name) {
  96. @unlink(MEDIA_DIR . '/' . $name);
  97. }
  98. }
  99. // ---------------------------------------------------------------------------
  100. // Site content (landing page + showreel)
  101. // ---------------------------------------------------------------------------
  102. function site_get(): array
  103. {
  104. return json_read(DATA_DIR . '/site.json', [
  105. 'intro_title' => 'Jane Doe',
  106. 'intro_text' => "Photographer based in Berlin.\nAvailable for portraits, weddings and events.",
  107. 'hero_image' => null,
  108. 'showreel' => [],
  109. ]);
  110. }
  111. function site_save(array $site): void
  112. {
  113. json_write(DATA_DIR . '/site.json', $site);
  114. }
  115. // ---------------------------------------------------------------------------
  116. // Galleries — one JSON file per gallery in data/galleries/
  117. // ---------------------------------------------------------------------------
  118. function gallery_file(string $slug): string
  119. {
  120. // Slugs are generated by us, but never trust a request parameter in a path.
  121. if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/', $slug) || strlen($slug) > 120) {
  122. throw new InvalidArgumentException('Invalid gallery slug');
  123. }
  124. return DATA_DIR . '/galleries/' . $slug . '.json';
  125. }
  126. function gallery_load(string $slug): ?array
  127. {
  128. try {
  129. $file = gallery_file($slug);
  130. } catch (InvalidArgumentException) {
  131. return null;
  132. }
  133. $g = json_read($file);
  134. return $g === [] ? null : $g;
  135. }
  136. function gallery_save(array $gallery): void
  137. {
  138. json_write(gallery_file($gallery['slug']), $gallery);
  139. }
  140. function gallery_delete(string $slug): void
  141. {
  142. $file = gallery_file($slug);
  143. if (is_file($file)) {
  144. unlink($file);
  145. }
  146. }
  147. /** All galleries, newest first. */
  148. function galleries_all(): array
  149. {
  150. $out = [];
  151. foreach (glob(DATA_DIR . '/galleries/*.json') ?: [] as $file) {
  152. $g = json_read($file);
  153. if ($g !== []) {
  154. $out[] = $g;
  155. }
  156. }
  157. usort($out, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
  158. return $out;
  159. }
  160. /** A gallery past its expiry date is treated as nonexistent for visitors. */
  161. function gallery_is_expired(array $gallery): bool
  162. {
  163. $expires = $gallery['expires_at'] ?? null;
  164. if ($expires === null || $expires === '') {
  165. return false;
  166. }
  167. // The gallery stays visible through the whole expiry day.
  168. return date('Y-m-d') > $expires;
  169. }