storage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. /**
  195. * Path of one of a gallery's data files. The single place a slug becomes a
  196. * filesystem path, so the validation below covers every one of them.
  197. */
  198. function gallery_path(string $slug, string $suffix): string
  199. {
  200. // Slugs are generated by us, but never trust a request parameter in a path.
  201. if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/', $slug) || strlen($slug) > 120) {
  202. throw new InvalidArgumentException('Invalid gallery slug');
  203. }
  204. return DATA_DIR . '/galleries/' . $slug . $suffix;
  205. }
  206. function gallery_file(string $slug): string
  207. {
  208. return gallery_path($slug, '.json');
  209. }
  210. /** Progress state of an in-flight archive build (see app/archive.php). */
  211. function gallery_archive_file(string $slug): string
  212. {
  213. return gallery_path($slug, '.archive.json');
  214. }
  215. /** The archive build's pending multipart part, waiting to reach 5 MB. */
  216. function gallery_archive_buffer(string $slug): string
  217. {
  218. return gallery_path($slug, '.archive.buf');
  219. }
  220. /**
  221. * The gallery's visit counters. Deliberately a sidecar rather than fields in
  222. * the gallery file: every visitor writes it, and the gallery file — hundreds of
  223. * image entries — would be rewritten in full on each page view, in contention
  224. * with uploads and archive builds.
  225. */
  226. function gallery_stats_file(string $slug): string
  227. {
  228. return gallery_path($slug, '.stats.json');
  229. }
  230. function gallery_load(string $slug): ?array
  231. {
  232. try {
  233. $file = gallery_file($slug);
  234. } catch (InvalidArgumentException) {
  235. return null;
  236. }
  237. $g = json_read($file);
  238. return $g === [] ? null : $g;
  239. }
  240. function gallery_save(array $gallery): void
  241. {
  242. json_write(gallery_file($gallery['slug']), $gallery);
  243. }
  244. function gallery_delete(string $slug): void
  245. {
  246. // Any half-finished archive build dies with the gallery. This has to abort
  247. // the multipart upload it was feeding, not just drop the local state file —
  248. // S3 stores and bills for the parts of an incomplete upload indefinitely.
  249. archive_abort($slug);
  250. archive_unqueue($slug);
  251. $file = gallery_file($slug);
  252. if (is_file($file)) {
  253. unlink($file);
  254. }
  255. @unlink($file . '.lock');
  256. @unlink(gallery_archive_file($slug) . '.lock');
  257. @unlink(gallery_stats_file($slug));
  258. @unlink(gallery_stats_file($slug) . '.lock');
  259. }
  260. /**
  261. * Append one image to a gallery under an exclusive lock, so parallel uploads
  262. * into the same gallery cannot overwrite each other's entries.
  263. *
  264. * Returns the new image count, or null if the gallery no longer exists — an
  265. * absent gallery must not be resurrected as a stub by a late upload.
  266. */
  267. function gallery_append_image(string $slug, array $image): ?int
  268. {
  269. $missing = false;
  270. $gallery = json_update(gallery_file($slug), function (array $g) use ($image, &$missing) {
  271. if ($g === []) {
  272. $missing = true;
  273. return null; // deleted mid-upload — do not write a stub file back
  274. }
  275. $g['images'][] = $image;
  276. return $g;
  277. });
  278. if ($missing) {
  279. return null;
  280. }
  281. // The gallery's ZIP archive, if it has one, no longer matches its contents.
  282. archive_mark_dirty($slug, $gallery);
  283. return count($gallery['images'] ?? []);
  284. }
  285. /** Counter name => the timestamp field recording when it last moved. */
  286. const GALLERY_COUNTERS = [
  287. 'views' => 'last_viewed_at',
  288. 'downloads' => 'last_download_at',
  289. ];
  290. /**
  291. * Count one event on a gallery. Silently does nothing for an unknown slug or
  292. * counter, so a stray link cannot litter the data directory with stats for
  293. * galleries that never existed.
  294. */
  295. function gallery_record_hit(string $slug, string $counter): void
  296. {
  297. try {
  298. if (!isset(GALLERY_COUNTERS[$counter]) || !is_file(gallery_file($slug))) {
  299. return;
  300. }
  301. } catch (InvalidArgumentException) {
  302. return;
  303. }
  304. json_update(gallery_stats_file($slug), function (array $stats) use ($counter) {
  305. $stats[$counter] = (int)($stats[$counter] ?? 0) + 1;
  306. $stats[GALLERY_COUNTERS[$counter]] = date('Y-m-d H:i:s');
  307. return $stats;
  308. });
  309. }
  310. /** One gallery opened by a visitor. */
  311. function gallery_record_view(string $slug): void
  312. {
  313. gallery_record_hit($slug, 'views');
  314. }
  315. /** One ZIP archive handed out to a visitor. */
  316. function gallery_record_download(string $slug): void
  317. {
  318. gallery_record_hit($slug, 'downloads');
  319. }
  320. /**
  321. * A gallery's stats, with every counter present. Galleries that were never
  322. * opened simply read as zero, with null timestamps.
  323. */
  324. function gallery_stats(string $slug): array
  325. {
  326. try {
  327. $stored = json_read(gallery_stats_file($slug));
  328. } catch (InvalidArgumentException) {
  329. $stored = [];
  330. }
  331. $out = [];
  332. foreach (GALLERY_COUNTERS as $counter => $timestamp) {
  333. $out[$counter] = (int)($stored[$counter] ?? 0);
  334. $out[$timestamp] = $stored[$timestamp] ?? null;
  335. }
  336. return $out;
  337. }
  338. /** All galleries, newest first. */
  339. function galleries_all(): array
  340. {
  341. $out = [];
  342. foreach (glob(DATA_DIR . '/galleries/*.json') ?: [] as $file) {
  343. // Skip the sidecars (archive build state, visit counter) that live in
  344. // the same directory and match the same glob.
  345. if (str_ends_with($file, '.archive.json') || str_ends_with($file, '.stats.json')) {
  346. continue;
  347. }
  348. $g = json_read($file);
  349. if ($g !== []) {
  350. $out[] = $g;
  351. }
  352. }
  353. usort($out, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
  354. return $out;
  355. }
  356. /** A gallery past its expiry date is treated as nonexistent for visitors. */
  357. function gallery_is_expired(array $gallery): bool
  358. {
  359. $expires = $gallery['expires_at'] ?? null;
  360. if ($expires === null || $expires === '') {
  361. return false;
  362. }
  363. // The gallery stays visible through the whole expiry day.
  364. return date('Y-m-d') > $expires;
  365. }
  366. // ---------------------------------------------------------------------------
  367. // Upload resolution cap (per gallery)
  368. // ---------------------------------------------------------------------------
  369. /**
  370. * Named sizes offered in the gallery forms, largest first. Only the pixel value
  371. * is ever stored, so renaming a preset here cannot orphan existing galleries —
  372. * a gallery capped at 2560 simply starts reading as whatever that number is
  373. * called now, and a value matching no preset renders as bare pixels.
  374. */
  375. const RESOLUTION_PRESETS = [
  376. 'Ultra' => 4096,
  377. 'High' => 2560,
  378. 'Mid' => 1920,
  379. 'Low' => 1280,
  380. ];
  381. const RESOLUTION_MIN = 320;
  382. const RESOLUTION_MAX = 12000;
  383. /**
  384. * Read a max_resolution choice from a submitted form: a preset's pixel value, a
  385. * custom number, or null for "Original" (no resize). Out-of-range custom values
  386. * are clamped rather than rejected — a typo becomes the nearest sane cap
  387. * instead of silently turning the resize off.
  388. */
  389. function parse_max_resolution(array $post): ?int
  390. {
  391. $choice = trim((string)($post['max_resolution'] ?? ''));
  392. $value = $choice === 'custom'
  393. ? trim((string)($post['max_resolution_custom'] ?? ''))
  394. : $choice;
  395. if ($value === '' || !ctype_digit($value)) {
  396. return null;
  397. }
  398. return max(RESOLUTION_MIN, min(RESOLUTION_MAX, (int)$value));
  399. }
  400. /** Human label for a cap: "High (2560 px)", "800 px", or "Original". */
  401. function resolution_label(?int $px): string
  402. {
  403. if ($px === null) {
  404. return 'Original';
  405. }
  406. $name = array_search($px, RESOLUTION_PRESETS, true);
  407. return $name === false ? "$px px" : "$name ($px px)";
  408. }