storage.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. /**
  51. * Transliterate German (and, best effort, other accented) characters to ASCII
  52. * so they survive in slugs, filenames and S3 keys instead of being dropped:
  53. * ä→ae, ö→oe, ü→ue, ß→ss, é→e, … Case is preserved.
  54. */
  55. function ascii_transliterate(string $s): string
  56. {
  57. $map = [
  58. 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue',
  59. 'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ß' => 'ss',
  60. ];
  61. $s = strtr($s, $map);
  62. if (function_exists('iconv')) {
  63. $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
  64. if ($converted !== false) {
  65. $s = $converted;
  66. }
  67. }
  68. return $s;
  69. }
  70. /** Turn a title into a URL slug fragment ("Wedding Müller" → "wedding-mueller"). */
  71. function slugify(string $title): string
  72. {
  73. $s = strtolower(ascii_transliterate($title));
  74. $s = preg_replace('/[^a-z0-9]+/', '-', $s) ?? '';
  75. $s = trim($s, '-');
  76. return $s !== '' ? $s : 'gallery';
  77. }
  78. /**
  79. * Sanitize an upload filename to a safe ASCII basename, keeping the extension.
  80. * German characters are transliterated rather than replaced by dashes, so
  81. * "Straße.jpg" becomes "Strasse.jpg" instead of "Stra-e.jpg".
  82. */
  83. function safe_filename(string $name, string $fallback = 'file'): string
  84. {
  85. $name = basename($name);
  86. $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  87. $base = ascii_transliterate(pathinfo($name, PATHINFO_FILENAME));
  88. $base = preg_replace('/[^A-Za-z0-9._-]+/', '-', $base) ?? '';
  89. $base = trim($base, '-.');
  90. if ($base === '') {
  91. $base = $fallback;
  92. }
  93. $ext = preg_replace('/[^A-Za-z0-9]+/', '', $ext) ?? '';
  94. return $ext !== '' ? $base . '.' . $ext : $base;
  95. }
  96. // ---------------------------------------------------------------------------
  97. // Local media (hero + showreel images in media/)
  98. // ---------------------------------------------------------------------------
  99. const MEDIA_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif'];
  100. /**
  101. * Store one uploaded image in media/, full resolution, unmodified.
  102. * Returns the stored filename, or null if the upload is invalid.
  103. */
  104. function media_store_upload(array $file): ?string
  105. {
  106. if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
  107. return null;
  108. }
  109. $ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
  110. if (!in_array($ext, MEDIA_EXTENSIONS, true)) {
  111. return null;
  112. }
  113. // Cheap content sanity check without touching the image data.
  114. if (function_exists('getimagesize') && @getimagesize($file['tmp_name']) === false) {
  115. return null;
  116. }
  117. $base = ascii_transliterate(pathinfo($file['name'], PATHINFO_FILENAME));
  118. $base = trim(preg_replace('/[^A-Za-z0-9._-]+/', '-', $base) ?? '', '-.') ?: 'image';
  119. $name = substr($base, 0, 60) . '-' . random_token(6) . '.' . $ext;
  120. if (!move_uploaded_file($file['tmp_name'], MEDIA_DIR . '/' . $name)) {
  121. return null;
  122. }
  123. return $name;
  124. }
  125. /** Delete a local media file (filename only, no paths). */
  126. function media_delete(string $name): void
  127. {
  128. if ($name !== '' && basename($name) === $name) {
  129. @unlink(MEDIA_DIR . '/' . $name);
  130. }
  131. }
  132. // ---------------------------------------------------------------------------
  133. // Site content (landing page + showreel)
  134. // ---------------------------------------------------------------------------
  135. function site_get(): array
  136. {
  137. return json_read(DATA_DIR . '/site.json', [
  138. 'intro_title' => 'Jane Doe',
  139. 'intro_text' => "Photographer based in Berlin.\nAvailable for portraits, weddings and events.",
  140. 'hero_image' => null,
  141. 'showreel' => [],
  142. ]);
  143. }
  144. function site_save(array $site): void
  145. {
  146. json_write(DATA_DIR . '/site.json', $site);
  147. }
  148. // ---------------------------------------------------------------------------
  149. // Galleries — one JSON file per gallery in data/galleries/
  150. // ---------------------------------------------------------------------------
  151. function gallery_file(string $slug): string
  152. {
  153. // Slugs are generated by us, but never trust a request parameter in a path.
  154. if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/', $slug) || strlen($slug) > 120) {
  155. throw new InvalidArgumentException('Invalid gallery slug');
  156. }
  157. return DATA_DIR . '/galleries/' . $slug . '.json';
  158. }
  159. function gallery_load(string $slug): ?array
  160. {
  161. try {
  162. $file = gallery_file($slug);
  163. } catch (InvalidArgumentException) {
  164. return null;
  165. }
  166. $g = json_read($file);
  167. return $g === [] ? null : $g;
  168. }
  169. function gallery_save(array $gallery): void
  170. {
  171. json_write(gallery_file($gallery['slug']), $gallery);
  172. }
  173. function gallery_delete(string $slug): void
  174. {
  175. $file = gallery_file($slug);
  176. if (is_file($file)) {
  177. unlink($file);
  178. }
  179. }
  180. /** All galleries, newest first. */
  181. function galleries_all(): array
  182. {
  183. $out = [];
  184. foreach (glob(DATA_DIR . '/galleries/*.json') ?: [] as $file) {
  185. $g = json_read($file);
  186. if ($g !== []) {
  187. $out[] = $g;
  188. }
  189. }
  190. usort($out, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
  191. return $out;
  192. }
  193. /** A gallery past its expiry date is treated as nonexistent for visitors. */
  194. function gallery_is_expired(array $gallery): bool
  195. {
  196. $expires = $gallery['expires_at'] ?? null;
  197. if ($expires === null || $expires === '') {
  198. return false;
  199. }
  200. // The gallery stays visible through the whole expiry day.
  201. return date('Y-m-d') > $expires;
  202. }