'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', ]; /** * Store uploaded attachments and optionally expose every path created by * this call to the surrounding transaction coordinator. * * The database transaction cannot roll back filesystem writes. Callers * that wrap this method in a transaction must pass a reference and call * discardPaths() if that transaction later rolls back or its commit fails. */ public static function store( $request, int $ticketId, int $messageId, int $userId, ?array &$createdPaths = null ): array { if ($createdPaths !== null) { $createdPaths = []; } $files = self::files($request); if (count($files) > self::MAX_FILES) { throw new \InvalidArgumentException('最多上传 5 张图片'); } if (!$files) { return []; } $total = 0; $stored = []; $paths = []; try { foreach ($files as $file) { $meta = self::validate($file); $total += $meta['bytes']; if ($total > self::MAX_TOTAL_BYTES) { throw new \InvalidArgumentException('图片总大小不能超过 15 MB'); } $key = bin2hex(random_bytes(24)) . '.' . $meta['extension']; $directory = self::directory(); $path = $directory . DIRECTORY_SEPARATOR . $key; // Register before writing so a short stream/write failure is // also removed by the common cleanup path. $paths[] = $path; if ($createdPaths !== null) { $createdPaths[] = $path; } if (!self::move($file, $path)) { throw new \RuntimeException('图片保存失败'); } $attachment = new TicketAttachment(); $attachment->ticket_id = $ticketId; $attachment->message_id = $messageId; $attachment->user_id = $userId; $attachment->storage_key = $key; $attachment->original_name = $meta['name']; $attachment->mime_type = $meta['mime']; $attachment->bytes = $meta['bytes']; $sha256 = hash_file('sha256', $path); if (!is_string($sha256) || preg_match('/^[a-f0-9]{64}$/', $sha256) !== 1) { throw new \RuntimeException('图片校验失败'); } $attachment->sha256 = $sha256; $attachment->created_at = time(); if (!$attachment->save()) { @unlink($path); throw new \RuntimeException('图片记录保存失败'); } $stored[] = $attachment; } } catch (\Throwable $exception) { self::discardPaths($paths); foreach ($stored as $attachment) { // The row may be inside the caller's transaction. Remove it // here for callers that use store() without a transaction; // the surrounding rollback remains authoritative otherwise. try { $attachment->delete(); } catch (\Throwable $cleanupException) { error_log('Ticket attachment row cleanup failed: ' . $cleanupException->getMessage()); } } throw $exception; } return $stored; } /** * Remove only files created by the current request. This deliberately does * not touch attachment rows: the database transaction owns those rows. */ public static function discardPaths(array $paths): void { // Do not call directory() here: cleanup must not mask the original // transaction error by trying to create storage during rollback. $directory = rtrim(BASE_PATH . '/storage/ticket-attachments', DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; foreach (array_unique($paths) as $path) { if (!is_string($path) || $path === '' || !str_starts_with($path, $directory) || basename($path) !== substr($path, strlen($directory))) { error_log('Ticket attachment cleanup skipped unsafe path'); continue; } if (is_file($path) && !@unlink($path)) { error_log('Ticket attachment file cleanup failed: ' . $path); } } } public static function path(TicketAttachment $attachment): string { return self::directory() . DIRECTORY_SEPARATOR . basename((string) $attachment->storage_key); } public static function remove(TicketAttachment $attachment): void { $path = self::path($attachment); if (is_file($path)) { @unlink($path); } try { $attachment->delete(); } catch (\Throwable $exception) { error_log('Ticket attachment cleanup failed: ' . $exception->getMessage()); } } public static function publicRow(TicketAttachment $attachment, string $prefix): array { return [ 'id' => (int) $attachment->id, 'name' => (string) $attachment->original_name, 'mime' => (string) $attachment->mime_type, 'bytes' => (int) $attachment->bytes, 'url' => $prefix . (int) $attachment->id, ]; } private static function directory(): string { $directory = BASE_PATH . '/storage/ticket-attachments'; if (!is_dir($directory) && !mkdir($directory, 0700, true) && !is_dir($directory)) { throw new \RuntimeException('无法创建工单附件目录'); } @chmod($directory, 0700); return $directory; } private static function files($request): array { $files = []; if (is_object($request) && method_exists($request, 'getUploadedFiles')) { $uploaded = $request->getUploadedFiles(); $candidate = $uploaded['attachments'] ?? []; $candidate = is_array($candidate) ? $candidate : [$candidate]; foreach ($candidate as $file) { if ($file !== null) { $files[] = $file; } } } if (!$files && isset($_FILES['attachments'])) { $raw = $_FILES['attachments']; $names = is_array($raw['name'] ?? null) ? $raw['name'] : [$raw['name'] ?? '']; foreach ($names as $index => $name) { $files[] = [ 'name' => $name, 'type' => is_array($raw['type'] ?? null) ? ($raw['type'][$index] ?? '') : ($raw['type'] ?? ''), 'tmp_name' => is_array($raw['tmp_name'] ?? null) ? ($raw['tmp_name'][$index] ?? '') : ($raw['tmp_name'] ?? ''), 'error' => is_array($raw['error'] ?? null) ? ($raw['error'][$index] ?? UPLOAD_ERR_NO_FILE) : ($raw['error'] ?? UPLOAD_ERR_NO_FILE), 'size' => is_array($raw['size'] ?? null) ? ($raw['size'][$index] ?? 0) : ($raw['size'] ?? 0), ]; } } return array_values(array_filter($files, static function ($file): bool { if (is_array($file)) { return (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE; } return method_exists($file, 'getError') && (int) $file->getError() !== UPLOAD_ERR_NO_FILE; })); } private static function validate($file): array { $error = is_array($file) ? (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) : (int) $file->getError(); if ($error !== UPLOAD_ERR_OK) { throw new \InvalidArgumentException('图片上传失败,请重新选择'); } $name = is_array($file) ? (string) ($file['name'] ?? '') : (string) $file->getClientFilename(); $tmp = is_array($file) ? (string) ($file['tmp_name'] ?? '') : (string) $file->getStream()->getMetadata('uri'); $size = is_array($file) ? (int) ($file['size'] ?? 0) : (int) $file->getSize(); if ($size <= 0 || $size > self::MAX_BYTES || $tmp === '' || !is_file($tmp)) { throw new \InvalidArgumentException('每张图片不能超过 5 MB'); } $mime = (new \finfo(FILEINFO_MIME_TYPE))->file($tmp); if (!isset(self::MIME_EXTENSIONS[$mime]) || @getimagesize($tmp) === false) { throw new \InvalidArgumentException('仅支持 JPG、PNG、GIF 或 WebP 图片'); } $safeName = trim(preg_replace('/[\x00-\x1F\x7F\\\/]+/u', '', $name) ?: 'image'); if ($safeName === '') { $safeName = 'image'; } return ['name' => mb_substr($safeName, 0, 180), 'mime' => $mime, 'extension' => self::MIME_EXTENSIONS[$mime], 'bytes' => $size]; } private static function move($file, string $path): bool { if (is_array($file)) { return move_uploaded_file((string) $file['tmp_name'], $path) || rename((string) $file['tmp_name'], $path); } $stream = $file->getStream(); $target = fopen($path, 'wb'); if ($target === false) { return false; } try { while (!$stream->eof()) { $chunk = $stream->read(1048576); if ($chunk === '' && !$stream->eof()) { return false; } if (fwrite($target, $chunk) !== strlen($chunk)) { return false; } } return true; } finally { fclose($target); } } }