storage.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. * Where a newly uploaded image belongs among the ones already stored.
  262. *
  263. * Uploads run several at a time, so they finish in an order set by file size
  264. * and network luck, not by the order the photographer picked them. Each job
  265. * therefore carries the batch it was selected in and its position within that
  266. * batch ($image['batch'] / $image['seq']), and lands next to its siblings
  267. * instead of wherever it happened to arrive.
  268. *
  269. * A batch occupies one contiguous run: its first arrival appends at the end,
  270. * and every later one inserts inside that run, which only shifts the runs after
  271. * it. So dropping a second selection while the first is still uploading keeps
  272. * the two apart, in the order they were dropped.
  273. *
  274. * Returns the insert position, or null to append — for an unknown batch, and
  275. * for images stored before this ordering existed (no batch at all).
  276. */
  277. function gallery_image_position(array $images, array $image): ?int
  278. {
  279. $batch = $image['batch'] ?? null;
  280. if (!is_string($batch) || $batch === '') {
  281. return null;
  282. }
  283. $seq = (int)($image['seq'] ?? 0);
  284. $pos = null;
  285. foreach ($images as $i => $existing) {
  286. if (($existing['batch'] ?? null) !== $batch) {
  287. continue;
  288. }
  289. if ((int)($existing['seq'] ?? 0) > $seq) {
  290. return $i; // first sibling that belongs after us
  291. }
  292. $pos = $i + 1;
  293. }
  294. return $pos;
  295. }
  296. /**
  297. * Insert one image into a gallery under an exclusive lock, so parallel uploads
  298. * into the same gallery cannot overwrite each other's entries.
  299. *
  300. * Position comes from gallery_image_position(), so the stored order follows the
  301. * selection order rather than the order the uploads completed in.
  302. *
  303. * $topic is the topic id the image should land in, or null for none. The
  304. * special value GALLERY_GUEST_TOPIC is created on the fly if the gallery has no
  305. * guest topic yet — inside this function's lock, so two guests uploading at the
  306. * same moment cannot each append their own copy of it.
  307. *
  308. * Returns the new image count, or null if the gallery no longer exists — an
  309. * absent gallery must not be resurrected as a stub by a late upload.
  310. */
  311. function gallery_append_image(string $slug, array $image, ?string $topic = null): ?int
  312. {
  313. $missing = false;
  314. $gallery = json_update(gallery_file($slug), function (array $g) use ($image, $topic, &$missing) {
  315. if ($g === []) {
  316. $missing = true;
  317. return null; // deleted mid-upload — do not write a stub file back
  318. }
  319. if ($topic === GALLERY_GUEST_TOPIC) {
  320. $g = gallery_with_guest_topic($g);
  321. }
  322. // Silently drop a topic that no longer exists rather than storing a
  323. // dangling reference: the gallery may have been edited mid-upload.
  324. if ($topic !== null && isset(gallery_topic_map($g)[$topic])) {
  325. $image['topic'] = $topic;
  326. }
  327. $images = $g['images'] ?? [];
  328. $at = gallery_image_position($images, $image);
  329. if ($at === null) {
  330. $images[] = $image;
  331. } else {
  332. array_splice($images, $at, 0, [$image]);
  333. }
  334. $g['images'] = $images;
  335. return $g;
  336. });
  337. if ($missing) {
  338. return null;
  339. }
  340. // The gallery's ZIP archive, if it has one, no longer matches its contents.
  341. archive_mark_dirty($slug, $gallery);
  342. return count($gallery['images'] ?? []);
  343. }
  344. // ---------------------------------------------------------------------------
  345. // Topics — optional named sections within one gallery
  346. // ---------------------------------------------------------------------------
  347. /**
  348. * Topics group a gallery's images into sections: the days of a trip, the stops
  349. * of a shoot. They are entirely optional — a gallery with no topics behaves,
  350. * renders and archives exactly as it did before they existed.
  351. *
  352. * The gallery record gains one key, and an image one optional key:
  353. *
  354. * 'topics' => [ ['id' => 't7k3f9a', 'name' => 'Day 1'], … ] // display order
  355. * 'images' => [ ['key' => …, 'topic' => 't7k3f9a'], … ] // absent = none
  356. *
  357. * The images array itself stays one flat list in upload order; the grouping is
  358. * *derived* by gallery_groups() wherever it is needed. That keeps the upload
  359. * ordering above (batch/seq) untouched, and means a gallery file written before
  360. * topics existed is already a valid one — nothing has to be backfilled for the
  361. * gallery to work. See app/migrate.php for the tidy-up pass.
  362. */
  363. /** Id of the topic guest uploads land in. Reserved; never handed out by gallery_topic_add(). */
  364. const GALLERY_GUEST_TOPIC = 'guest';
  365. const GALLERY_GUEST_TOPIC_NAME = 'Guest uploads';
  366. /** Ids are ours, but they arrive back from forms and the assign endpoint. */
  367. function gallery_topic_id_valid(string $id): bool
  368. {
  369. return (bool)preg_match('/^[A-Za-z0-9_-]{1,32}$/', $id);
  370. }
  371. /** Trim a submitted topic name to something storable; '' means "reject". */
  372. function gallery_topic_name(string $name): string
  373. {
  374. return substr(trim(preg_replace('/\s+/u', ' ', $name) ?? ''), 0, 80);
  375. }
  376. /**
  377. * A gallery's topics, normalised: well-formed entries only, duplicate ids
  378. * dropped, stored order preserved. Every reader goes through this, so a
  379. * hand-edited or half-migrated file cannot break a page.
  380. */
  381. function gallery_topics(array $gallery): array
  382. {
  383. $out = [];
  384. $seen = [];
  385. foreach ($gallery['topics'] ?? [] as $topic) {
  386. if (!is_array($topic)) {
  387. continue;
  388. }
  389. $id = (string)($topic['id'] ?? '');
  390. $name = gallery_topic_name((string)($topic['name'] ?? ''));
  391. if ($id === '' || $name === '' || isset($seen[$id]) || !gallery_topic_id_valid($id)) {
  392. continue;
  393. }
  394. $seen[$id] = true;
  395. $out[] = ['id' => $id, 'name' => $name];
  396. }
  397. return $out;
  398. }
  399. /** id => name, for membership tests and label lookups. */
  400. function gallery_topic_map(array $gallery): array
  401. {
  402. return array_column(gallery_topics($gallery), 'name', 'id');
  403. }
  404. /**
  405. * A gallery's images grouped for display, in render order: the images with no
  406. * topic first, then each topic in its stored order. Within a group the images
  407. * keep their existing order, so uploads still land where batch/seq put them.
  408. *
  409. * An image whose topic id matches no existing topic reads as untopiced — a
  410. * dangling reference must never make a photo vanish from the gallery.
  411. *
  412. * $includeEmpty keeps topics that hold no images (and the untopiced group when
  413. * the gallery has topics at all): the admin editor needs them as drop targets,
  414. * the public view does not want to show empty headings.
  415. *
  416. * Returns [ ['topic' => null|['id'=>…,'name'=>…], 'images' => [...]], … ].
  417. */
  418. function gallery_groups(array $gallery, bool $includeEmpty = false): array
  419. {
  420. $topics = gallery_topics($gallery);
  421. $map = gallery_topic_map($gallery);
  422. $buckets = ['' => []];
  423. foreach ($topics as $topic) {
  424. $buckets[$topic['id']] = [];
  425. }
  426. foreach ($gallery['images'] ?? [] as $image) {
  427. $id = (string)($image['topic'] ?? '');
  428. $buckets[isset($map[$id]) ? $id : ''][] = $image;
  429. }
  430. $groups = [];
  431. if ($buckets[''] !== [] || ($includeEmpty && $topics !== [])) {
  432. $groups[] = ['topic' => null, 'images' => $buckets['']];
  433. }
  434. foreach ($topics as $topic) {
  435. if ($buckets[$topic['id']] === [] && !$includeEmpty) {
  436. continue;
  437. }
  438. $groups[] = ['topic' => $topic, 'images' => $buckets[$topic['id']]];
  439. }
  440. return $groups;
  441. }
  442. /** Whether topics play any part in this gallery — the pre-topics fast path. */
  443. function gallery_uses_topics(array $gallery): bool
  444. {
  445. if (gallery_topics($gallery) !== []) {
  446. return true;
  447. }
  448. foreach ($gallery['images'] ?? [] as $image) {
  449. if (($image['topic'] ?? '') !== '') {
  450. return true;
  451. }
  452. }
  453. return false;
  454. }
  455. /**
  456. * The gallery with a guest topic guaranteed to exist. Called inside a lock by
  457. * gallery_append_image(); the admin may rename or reorder the topic afterwards,
  458. * but the id stays 'guest', so later guest uploads keep landing in it. Deleting
  459. * it simply means the next guest upload creates it again.
  460. */
  461. function gallery_with_guest_topic(array $gallery): array
  462. {
  463. if (isset(gallery_topic_map($gallery)[GALLERY_GUEST_TOPIC])) {
  464. return $gallery;
  465. }
  466. $topics = gallery_topics($gallery);
  467. $topics[] = ['id' => GALLERY_GUEST_TOPIC, 'name' => GALLERY_GUEST_TOPIC_NAME];
  468. $gallery['topics'] = $topics;
  469. return $gallery;
  470. }
  471. /**
  472. * Add a topic. Returns the stored entry, or null if the name was empty or the
  473. * gallery is gone. Ids are random rather than derived from the name, so
  474. * renaming a topic never has to touch the images pointing at it.
  475. */
  476. function gallery_topic_add(string $slug, string $name): ?array
  477. {
  478. $name = gallery_topic_name($name);
  479. if ($name === '') {
  480. return null;
  481. }
  482. $added = null;
  483. json_update(gallery_file($slug), function (array $g) use ($name, &$added): ?array {
  484. if ($g === []) {
  485. return null;
  486. }
  487. $topics = gallery_topics($g);
  488. do {
  489. $id = 't' . random_token(6);
  490. } while (isset(gallery_topic_map($g)[$id]));
  491. $added = ['id' => $id, 'name' => $name];
  492. $topics[] = $added;
  493. $g['topics'] = $topics;
  494. return $g;
  495. });
  496. return $added;
  497. }
  498. /** Rename a topic in place. The archive folder is named after it, hence dirty. */
  499. function gallery_topic_rename(string $slug, string $id, string $name): bool
  500. {
  501. $name = gallery_topic_name($name);
  502. if ($name === '' || !gallery_topic_id_valid($id)) {
  503. return false;
  504. }
  505. $changed = false;
  506. $gallery = json_update(gallery_file($slug), function (array $g) use ($id, $name, &$changed): ?array {
  507. $topics = gallery_topics($g);
  508. foreach ($topics as $i => $topic) {
  509. if ($topic['id'] === $id && $topic['name'] !== $name) {
  510. $topics[$i]['name'] = $name;
  511. $g['topics'] = $topics;
  512. $changed = true;
  513. return $g;
  514. }
  515. }
  516. return null;
  517. });
  518. if ($changed) {
  519. archive_mark_dirty($slug, $gallery);
  520. }
  521. return $changed;
  522. }
  523. /**
  524. * Remove a topic. Its images are not deleted — they fall back to no topic, and
  525. * so reappear at the top of the gallery.
  526. */
  527. function gallery_topic_delete(string $slug, string $id): bool
  528. {
  529. if (!gallery_topic_id_valid($id)) {
  530. return false;
  531. }
  532. $changed = false;
  533. $gallery = json_update(gallery_file($slug), function (array $g) use ($id, &$changed): ?array {
  534. $topics = gallery_topics($g);
  535. $kept = array_values(array_filter($topics, fn(array $t): bool => $t['id'] !== $id));
  536. if (count($kept) === count($topics)) {
  537. return null;
  538. }
  539. $g['topics'] = $kept;
  540. foreach ($g['images'] ?? [] as $i => $image) {
  541. if (($image['topic'] ?? '') === $id) {
  542. unset($g['images'][$i]['topic']);
  543. }
  544. }
  545. $changed = true;
  546. return $g;
  547. });
  548. if ($changed) {
  549. archive_mark_dirty($slug, $gallery);
  550. }
  551. return $changed;
  552. }
  553. /**
  554. * Move a topic one place up or down in the display order. Mirrors the showreel
  555. * reordering in admin/showreel.php: a swap with the neighbour, no-op at the end.
  556. */
  557. function gallery_topic_move(string $slug, string $id, string $dir): bool
  558. {
  559. if (!gallery_topic_id_valid($id)) {
  560. return false;
  561. }
  562. $changed = false;
  563. $gallery = json_update(gallery_file($slug), function (array $g) use ($id, $dir, &$changed): ?array {
  564. $topics = gallery_topics($g);
  565. $at = array_search($id, array_column($topics, 'id'), true);
  566. if ($at === false) {
  567. return null;
  568. }
  569. $to = $dir === 'up' ? $at - 1 : $at + 1;
  570. if ($to < 0 || $to >= count($topics)) {
  571. return null;
  572. }
  573. [$topics[$at], $topics[$to]] = [$topics[$to], $topics[$at]];
  574. $g['topics'] = $topics;
  575. $changed = true;
  576. return $g;
  577. });
  578. if ($changed) {
  579. archive_mark_dirty($slug, $gallery);
  580. }
  581. return $changed;
  582. }
  583. /**
  584. * Put one image into a topic, or back into none ($topicId null or '').
  585. *
  586. * Matched by S3 key, the image record's de-facto identity. Under the same lock
  587. * as uploads, so assigning while an upload is in flight cannot lose either one.
  588. * Returns false for an unknown image or an unknown topic; a no-op assignment
  589. * (already in that topic) counts as success and skips the write.
  590. */
  591. function gallery_assign_topic(string $slug, string $key, ?string $topicId): bool
  592. {
  593. $topicId = (string)$topicId;
  594. if ($topicId !== '' && !gallery_topic_id_valid($topicId)) {
  595. return false;
  596. }
  597. $ok = false;
  598. $changed = false;
  599. $gallery = json_update(gallery_file($slug), function (array $g) use ($key, $topicId, &$ok, &$changed): ?array {
  600. if ($topicId !== '' && !isset(gallery_topic_map($g)[$topicId])) {
  601. return null;
  602. }
  603. foreach ($g['images'] ?? [] as $i => $image) {
  604. if (($image['key'] ?? '') !== $key) {
  605. continue;
  606. }
  607. $ok = true;
  608. if ((string)($image['topic'] ?? '') === $topicId) {
  609. return null; // already there
  610. }
  611. if ($topicId === '') {
  612. unset($g['images'][$i]['topic']);
  613. } else {
  614. $g['images'][$i]['topic'] = $topicId;
  615. }
  616. $changed = true;
  617. return $g;
  618. }
  619. return null;
  620. });
  621. if ($changed) {
  622. // The image now belongs in a different folder of the ZIP.
  623. archive_mark_dirty($slug, $gallery);
  624. }
  625. return $ok;
  626. }
  627. /** Counter name => the timestamp field recording when it last moved. */
  628. const GALLERY_COUNTERS = [
  629. 'views' => 'last_viewed_at',
  630. 'downloads' => 'last_download_at',
  631. ];
  632. /**
  633. * Count one event on a gallery. Silently does nothing for an unknown slug or
  634. * counter, so a stray link cannot litter the data directory with stats for
  635. * galleries that never existed.
  636. */
  637. function gallery_record_hit(string $slug, string $counter): void
  638. {
  639. try {
  640. if (!isset(GALLERY_COUNTERS[$counter]) || !is_file(gallery_file($slug))) {
  641. return;
  642. }
  643. } catch (InvalidArgumentException) {
  644. return;
  645. }
  646. json_update(gallery_stats_file($slug), function (array $stats) use ($counter) {
  647. $stats[$counter] = (int)($stats[$counter] ?? 0) + 1;
  648. $stats[GALLERY_COUNTERS[$counter]] = date('Y-m-d H:i:s');
  649. return $stats;
  650. });
  651. }
  652. /** One gallery opened by a visitor. */
  653. function gallery_record_view(string $slug): void
  654. {
  655. gallery_record_hit($slug, 'views');
  656. }
  657. /** One ZIP archive handed out to a visitor. */
  658. function gallery_record_download(string $slug): void
  659. {
  660. gallery_record_hit($slug, 'downloads');
  661. }
  662. /**
  663. * A gallery's stats, with every counter present. Galleries that were never
  664. * opened simply read as zero, with null timestamps.
  665. */
  666. function gallery_stats(string $slug): array
  667. {
  668. try {
  669. $stored = json_read(gallery_stats_file($slug));
  670. } catch (InvalidArgumentException) {
  671. $stored = [];
  672. }
  673. $out = [];
  674. foreach (GALLERY_COUNTERS as $counter => $timestamp) {
  675. $out[$counter] = (int)($stored[$counter] ?? 0);
  676. $out[$timestamp] = $stored[$timestamp] ?? null;
  677. }
  678. return $out;
  679. }
  680. /** All galleries, newest first. */
  681. function galleries_all(): array
  682. {
  683. $out = [];
  684. foreach (glob(DATA_DIR . '/galleries/*.json') ?: [] as $file) {
  685. // Skip the sidecars (archive build state, visit counter) that live in
  686. // the same directory and match the same glob.
  687. if (str_ends_with($file, '.archive.json') || str_ends_with($file, '.stats.json')) {
  688. continue;
  689. }
  690. $g = json_read($file);
  691. if ($g !== []) {
  692. $out[] = $g;
  693. }
  694. }
  695. usort($out, fn($a, $b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));
  696. return $out;
  697. }
  698. /** A gallery past its expiry date is treated as nonexistent for visitors. */
  699. function gallery_is_expired(array $gallery): bool
  700. {
  701. $expires = $gallery['expires_at'] ?? null;
  702. if ($expires === null || $expires === '') {
  703. return false;
  704. }
  705. // The gallery stays visible through the whole expiry day.
  706. return date('Y-m-d') > $expires;
  707. }
  708. // ---------------------------------------------------------------------------
  709. // Upload resolution cap (per gallery)
  710. // ---------------------------------------------------------------------------
  711. /**
  712. * Named sizes offered in the gallery forms, largest first. Only the pixel value
  713. * is ever stored, so renaming a preset here cannot orphan existing galleries —
  714. * a gallery capped at 2560 simply starts reading as whatever that number is
  715. * called now, and a value matching no preset renders as bare pixels.
  716. */
  717. const RESOLUTION_PRESETS = [
  718. 'Ultra' => 4096,
  719. 'High' => 2560,
  720. 'Mid' => 1920,
  721. 'Low' => 1280,
  722. ];
  723. const RESOLUTION_MIN = 320;
  724. const RESOLUTION_MAX = 12000;
  725. /**
  726. * Read a max_resolution choice from a submitted form: a preset's pixel value, a
  727. * custom number, or null for "Original" (no resize). Out-of-range custom values
  728. * are clamped rather than rejected — a typo becomes the nearest sane cap
  729. * instead of silently turning the resize off.
  730. */
  731. function parse_max_resolution(array $post): ?int
  732. {
  733. $choice = trim((string)($post['max_resolution'] ?? ''));
  734. $value = $choice === 'custom'
  735. ? trim((string)($post['max_resolution_custom'] ?? ''))
  736. : $choice;
  737. if ($value === '' || !ctype_digit($value)) {
  738. return null;
  739. }
  740. return max(RESOLUTION_MIN, min(RESOLUTION_MAX, (int)$value));
  741. }
  742. /** Human label for a cap: "High (2560 px)", "800 px", or "Original". */
  743. function resolution_label(?int $px): string
  744. {
  745. if ($px === null) {
  746. return 'Original';
  747. }
  748. $name = array_search($px, RESOLUTION_PRESETS, true);
  749. return $name === false ? "$px px" : "$name ($px px)";
  750. }