storage.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. /**
  41. * Read-modify-write a JSON file with an exclusive lock held across the whole
  42. * cycle, so concurrent writers cannot lose each other's changes.
  43. *
  44. * json_write() replaces the file by rename(), so the target inode changes on
  45. * every write and cannot itself carry the lock — a sidecar "<file>.lock" does.
  46. * $mutate receives the current contents and returns the array to store, or
  47. * null to leave the file untouched. Returns the current (or stored) array.
  48. */
  49. function json_update(string $file, callable $mutate, array $default = []): array
  50. {
  51. $dir = dirname($file);
  52. if (!is_dir($dir)) {
  53. mkdir($dir, 0755, true);
  54. }
  55. // Cannot lock (read-only dir, exotic host): still perform the update rather
  56. // than dropping it — degrades to the previous last-writer-wins behaviour.
  57. $lock = fopen($file . '.lock', 'c');
  58. if ($lock !== false) {
  59. flock($lock, LOCK_EX);
  60. }
  61. try {
  62. $current = json_read($file, $default);
  63. $data = $mutate($current);
  64. if ($data === null) {
  65. return $current;
  66. }
  67. json_write($file, $data);
  68. return $data;
  69. } finally {
  70. if ($lock !== false) {
  71. flock($lock, LOCK_UN);
  72. fclose($lock);
  73. }
  74. }
  75. }
  76. /** URL-safe random token. */
  77. function random_token(int $chars = 8): string
  78. {
  79. $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  80. $out = '';
  81. for ($i = 0; $i < $chars; $i++) {
  82. $out .= $alphabet[random_int(0, strlen($alphabet) - 1)];
  83. }
  84. return $out;
  85. }
  86. /**
  87. * Transliterate German (and, best effort, other accented) characters to ASCII
  88. * so they survive in slugs, filenames and S3 keys instead of being dropped:
  89. * ä→ae, ö→oe, ü→ue, ß→ss, é→e, … Case is preserved.
  90. */
  91. function ascii_transliterate(string $s): string
  92. {
  93. $map = [
  94. 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue',
  95. 'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ß' => 'ss',
  96. ];
  97. $s = strtr($s, $map);
  98. if (function_exists('iconv')) {
  99. $converted = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
  100. if ($converted !== false) {
  101. $s = $converted;
  102. }
  103. }
  104. return $s;
  105. }
  106. /** Turn a title into a URL slug fragment ("Wedding Müller" → "wedding-mueller"). */
  107. function slugify(string $title): string
  108. {
  109. $s = strtolower(ascii_transliterate($title));
  110. $s = preg_replace('/[^a-z0-9]+/', '-', $s) ?? '';
  111. $s = trim($s, '-');
  112. return $s !== '' ? $s : 'gallery';
  113. }
  114. /**
  115. * Sanitize an upload filename to a safe ASCII basename, keeping the extension.
  116. * German characters are transliterated rather than replaced by dashes, so
  117. * "Straße.jpg" becomes "Strasse.jpg" instead of "Stra-e.jpg".
  118. */
  119. function safe_filename(string $name, string $fallback = 'file'): string
  120. {
  121. $name = basename($name);
  122. $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  123. $base = ascii_transliterate(pathinfo($name, PATHINFO_FILENAME));
  124. $base = preg_replace('/[^A-Za-z0-9._-]+/', '-', $base) ?? '';
  125. $base = trim($base, '-.');
  126. if ($base === '') {
  127. $base = $fallback;
  128. }
  129. $ext = preg_replace('/[^A-Za-z0-9]+/', '', $ext) ?? '';
  130. return $ext !== '' ? $base . '.' . $ext : $base;
  131. }
  132. // ---------------------------------------------------------------------------
  133. // Local media (hero + showreel images in media/)
  134. // ---------------------------------------------------------------------------
  135. const MEDIA_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif'];
  136. /**
  137. * Store one uploaded image in media/, full resolution, unmodified.
  138. * Returns the stored filename, or null if the upload is invalid.
  139. */
  140. function media_store_upload(array $file): ?string
  141. {
  142. if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
  143. return null;
  144. }
  145. $ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
  146. if (!in_array($ext, MEDIA_EXTENSIONS, true)) {
  147. return null;
  148. }
  149. // Cheap content sanity check without touching the image data.
  150. if (function_exists('getimagesize') && @getimagesize($file['tmp_name']) === false) {
  151. return null;
  152. }
  153. $base = ascii_transliterate(pathinfo($file['name'], PATHINFO_FILENAME));
  154. $base = trim(preg_replace('/[^A-Za-z0-9._-]+/', '-', $base) ?? '', '-.') ?: 'image';
  155. $name = substr($base, 0, 60) . '-' . random_token(6) . '.' . $ext;
  156. if (!move_uploaded_file($file['tmp_name'], MEDIA_DIR . '/' . $name)) {
  157. return null;
  158. }
  159. return $name;
  160. }
  161. /** Delete a local media file (filename only, no paths). */
  162. function media_delete(string $name): void
  163. {
  164. if ($name !== '' && basename($name) === $name) {
  165. @unlink(MEDIA_DIR . '/' . $name);
  166. }
  167. }
  168. // ---------------------------------------------------------------------------
  169. // Site content (landing page + showreel)
  170. // ---------------------------------------------------------------------------
  171. function site_get(): array
  172. {
  173. return json_read(DATA_DIR . '/site.json', [
  174. 'intro_title' => 'Jane Doe',
  175. 'intro_text' => "Photographer based in Berlin.\nAvailable for portraits, weddings and events.",
  176. 'hero_image' => null,
  177. 'showreel' => [],
  178. 'contact_title' => 'Get in touch',
  179. 'contact_text' => "For bookings and enquiries, drop me a line.",
  180. 'contact_email' => '',
  181. 'contact_phone' => '',
  182. 'contact_instagram' => '',
  183. 'impressum' => '',
  184. 'datenschutz' => '',
  185. ]);
  186. }
  187. function site_save(array $site): void
  188. {
  189. json_write(DATA_DIR . '/site.json', $site);
  190. }
  191. // ---------------------------------------------------------------------------
  192. // Galleries — one JSON file per gallery in data/galleries/
  193. // ---------------------------------------------------------------------------
  194. function gallery_file(string $slug): string
  195. {
  196. // Slugs are generated by us, but never trust a request parameter in a path.
  197. if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/', $slug) || strlen($slug) > 120) {
  198. throw new InvalidArgumentException('Invalid gallery slug');
  199. }
  200. return DATA_DIR . '/galleries/' . $slug . '.json';
  201. }
  202. function gallery_load(string $slug): ?array
  203. {
  204. try {
  205. $file = gallery_file($slug);
  206. } catch (InvalidArgumentException) {
  207. return null;
  208. }
  209. $g = json_read($file);
  210. return $g === [] ? null : $g;
  211. }
  212. function gallery_save(array $gallery): void
  213. {
  214. json_write(gallery_file($gallery['slug']), $gallery);
  215. }
  216. function gallery_delete(string $slug): void
  217. {
  218. $file = gallery_file($slug);
  219. if (is_file($file)) {
  220. unlink($file);
  221. }
  222. @unlink($file . '.lock');
  223. }
  224. /**
  225. * Append one image to a gallery under an exclusive lock, so parallel uploads
  226. * into the same gallery cannot overwrite each other's entries.
  227. *
  228. * Returns the new image count, or null if the gallery no longer exists — an
  229. * absent gallery must not be resurrected as a stub by a late upload.
  230. */
  231. function gallery_append_image(string $slug, array $image): ?int
  232. {
  233. $missing = false;
  234. $gallery = json_update(gallery_file($slug), function (array $g) use ($image, &$missing) {
  235. if ($g === []) {
  236. $missing = true;
  237. return null; // deleted mid-upload — do not write a stub file back
  238. }
  239. $g['images'][] = $image;
  240. return $g;
  241. });
  242. return $missing ? null : count($gallery['images'] ?? []);
  243. }
  244. /** All galleries, newest first. */
  245. function galleries_all(): array
  246. {
  247. $out = [];
  248. foreach (glob(DATA_DIR . '/galleries/*.json') ?: [] as $file) {
  249. $g = json_read($file);
  250. if ($g !== []) {
  251. $out[] = $g;
  252. }
  253. }
  254. usort($out, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
  255. return $out;
  256. }
  257. /** A gallery past its expiry date is treated as nonexistent for visitors. */
  258. function gallery_is_expired(array $gallery): bool
  259. {
  260. $expires = $gallery['expires_at'] ?? null;
  261. if ($expires === null || $expires === '') {
  262. return false;
  263. }
  264. // The gallery stays visible through the whole expiry day.
  265. return date('Y-m-d') > $expires;
  266. }
  267. // ---------------------------------------------------------------------------
  268. // Upload resolution cap (per gallery)
  269. // ---------------------------------------------------------------------------
  270. /**
  271. * Named sizes offered in the gallery forms, largest first. Only the pixel value
  272. * is ever stored, so renaming a preset here cannot orphan existing galleries —
  273. * a gallery capped at 2560 simply starts reading as whatever that number is
  274. * called now, and a value matching no preset renders as bare pixels.
  275. */
  276. const RESOLUTION_PRESETS = [
  277. 'Ultra' => 4096,
  278. 'High' => 2560,
  279. 'Mid' => 1920,
  280. 'Low' => 1280,
  281. ];
  282. const RESOLUTION_MIN = 320;
  283. const RESOLUTION_MAX = 12000;
  284. /**
  285. * Read a max_resolution choice from a submitted form: a preset's pixel value, a
  286. * custom number, or null for "Original" (no resize). Out-of-range custom values
  287. * are clamped rather than rejected — a typo becomes the nearest sane cap
  288. * instead of silently turning the resize off.
  289. */
  290. function parse_max_resolution(array $post): ?int
  291. {
  292. $choice = trim((string)($post['max_resolution'] ?? ''));
  293. $value = $choice === 'custom'
  294. ? trim((string)($post['max_resolution_custom'] ?? ''))
  295. : $choice;
  296. if ($value === '' || !ctype_digit($value)) {
  297. return null;
  298. }
  299. return max(RESOLUTION_MIN, min(RESOLUTION_MAX, (int)$value));
  300. }
  301. /** Human label for a cap: "High (2560 px)", "800 px", or "Original". */
  302. function resolution_label(?int $px): string
  303. {
  304. if ($px === null) {
  305. return 'Original';
  306. }
  307. $name = array_search($px, RESOLUTION_PRESETS, true);
  308. return $name === false ? "$px px" : "$name ($px px)";
  309. }