From 1934256f294ce5b717b1f4d424b860f5a72131ce Mon Sep 17 00:00:00 2001 From: GammaC0de Date: Sun, 28 Sep 2025 21:37:47 +0300 Subject: [PATCH] Support `data:` URI images for external barcode lookup plugins (#2814) * add support for data: URI images for external barcode lookup plugins * Adapt existing code style --------- Co-authored-by: Bernd Bestel --- services/StockService.php | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/services/StockService.php b/services/StockService.php index 8570b014..da27dacc 100644 --- a/services/StockService.php +++ b/services/StockService.php @@ -628,20 +628,35 @@ class StockService extends BaseService { try { - $webClient = new Client(); - $response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . $this->getApplicationService()->GetInstalledVersion()->Version . ' (https://grocy.info)']]); - $fileName = $pluginOutput['__barcode']; - $fileExtension = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); - - // Fallback to Content-Type header if file extension is missing - if (strlen($fileExtension) == 0 && $response->hasHeader('Content-Type')) + if (preg_match('/^https?:\/\//', $pluginOutput['__image_url'])) { - $fileExtension = explode('+', explode('/', $response->getHeader('Content-Type')[0])[1])[0]; + $webClient = new Client(); + $response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . $this->getApplicationService()->GetInstalledVersion()->Version . ' (https://grocy.info)']]); + $fileExtension = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); + + // Fallback to Content-Type header if file extension is missing + if (strlen($fileExtension) == 0 && $response->hasHeader('Content-Type')) + { + $fileExtension = explode('+', explode('/', $response->getHeader('Content-Type')[0])[1])[0]; + } + + $imageData = $response->getBody(); + } + elseif (preg_match('/data:image\/(\w+?);base64,([A-Za-z0-9+\/]*={0,2})$/', $pluginOutput['__image_url'], $matches)) + { + $fileExtension = $matches[1]; + if (!($imageData = base64_decode($matches[2]))) + { + unset($imageData); + } } - $filePath = $fileName . '.' . $fileExtension; - file_put_contents($this->getFilesService()->GetFilePath('productpictures', $filePath), $response->getBody()); - $productData['picture_file_name'] = $filePath; + if (!empty($fileExtension) && !empty($imageData)) + { + $fileName = $pluginOutput['__barcode'] . '.' . $fileExtension; + file_put_contents($this->getFilesService()->GetFilePath('productpictures', $fileName), $imageData); + $productData['picture_file_name'] = $fileName; + } } catch (\Exception) {