v1.0.0.1
StocketBase
- <?php
-
- declare(strict_types=1);
-
- if (count(get_included_files()) === 1) {
- http_response_code(403);
- exit;
- }
-
- $db = Database::site();
- $canManageAny = Auth::hasRoleAtLeast(Auth::ROLE_STORE_OWNER);
-
- $loadTrashed = static function (int $id) use ($db): ?array {
- $statement = $db->prepare('SELECT * FROM products WHERE id = :id AND deleted_at IS NOT NULL LIMIT 1');
- $statement->execute(['id' => $id]);
-
- return $statement->fetch() ?: null;
- };
-
- $canTouch = static fn (array $product): bool => $canManageAny || (int) $product['created_by'] === (int) $currentUser['id'];
-
- require_once __DIR__ . '/../includes/digital-files.php';
-
- $deleteFiles = ($_POST['file_action'] ?? 'keep') === 'delete';
-
- $purge = static function (int $id, string $title) use ($db, $deleteFiles): void {
- if ($deleteFiles) {
- DigitalFiles::deleteForProduct($id);
- } else {
- DigitalFiles::detachForProduct($id, $title);
- }
- $db->prepare('DELETE FROM product_versions WHERE product_id = :id')->execute(['id' => $id]);
- $db->prepare('DELETE FROM product_tags WHERE product_id = :id')->execute(['id' => $id]);
- $db->prepare('DELETE FROM products WHERE id = :id')->execute(['id' => $id]);
- };
-
- $productId = (int) ($_POST['product_id'] ?? 0);
-
- if ($action === 'restore_product') {
- $product = $productId > 0 ? $loadTrashed($productId) : null;
- if ($product === null || !$canTouch($product)) {
- return 0;
- }
-
- $restoredStatus = in_array($product['trashed_status'], ['published', 'pending_review', 'rejected'], true) ? $product['trashed_status'] : 'draft';
-
- $db->prepare('UPDATE products SET status = :status, deleted_at = NULL, trashed_status = NULL WHERE id = :id')
- ->execute(['status' => $restoredStatus, 'id' => $productId]);
- ActivityLog::record('product.restore', 'product', $productId, (string) $product['title']);
-
- return $productId;
- }
-
- if ($action === 'purge_product') {
- $product = $productId > 0 ? $loadTrashed($productId) : null;
- if ($product === null || !$canTouch($product)) {
- return 0;
- }
-
- $purge($productId, (string) $product['title']);
- ActivityLog::record('product.purge', 'product', $productId, (string) $product['title'] . ($deleteFiles ? ' [files deleted]' : ' [files kept]'));
-
- return 0;
- }
-
- if ($action === 'empty_trash') {
- $statement = $canManageAny
- ? $db->query('SELECT id, title FROM products WHERE deleted_at IS NOT NULL')
- : $db->prepare('SELECT id, title FROM products WHERE deleted_at IS NOT NULL AND created_by = :author');
-
- if (!$canManageAny) {
- $statement->execute(['author' => $currentUser['id']]);
- }
-
- $trashedRows = $statement->fetchAll();
- foreach ($trashedRows as $trashedRow) {
- $purge((int) $trashedRow['id'], (string) $trashedRow['title']);
- }
- ActivityLog::record('product.empty_trash', 'product', null, count($trashedRows) . ' products' . ($deleteFiles ? ' [files deleted]' : ' [files kept]'));
-
- return 0;
- }
-
- return 0;
-