diff --git a/services/StockService.php b/services/StockService.php index aba6ef2b..db61459a 100644 --- a/services/StockService.php +++ b/services/StockService.php @@ -630,7 +630,36 @@ class StockService extends BaseService { $webClient = new Client(); $response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . $this->getApplicationService()->GetInstalledVersion()->Version . ' (https://grocy.info)']]); - $fileName = $pluginOutput['__barcode'] . '.' . pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); + + $fileType = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); + + // Some API's don't use the filetype in the URL. In this case, use the content type in the headers. + if ($fileType == '') { + + // If the Content-Type does not exist, do not save the image. + if (!$response->hasHeader('Content-Type')) { + throw new \Exception('Image lookup response for product "' . $pluginOutput['name'] . '" does not have a Content-Type.'); + } + + $contentType = $response->getHeader('Content-Type')[0]; // e.g. image/jpeg + $contentTypeSplit = explode('/', $contentType); + + // If the Content-Type is not an image, do not save the image. + if ($contentTypeSplit[0] != 'image') { + throw new \Exception('Image lookup response for product "' . $pluginOutput['name'] . '" does not have a Content-Type image/xxxx.'); + } + + if ($contentType == 'image/svg+xml') { + // SVG needs special handling + $fileType = 'svg'; + } else { + // Use the content type as file extension + $fileType = $contentTypeSplit[1]; // e.g. jpeg + } + + } + + $fileName = $pluginOutput['__barcode'] . '.' . $fileType; file_put_contents($this->getFilesService()->GetFilePath('productpictures', $fileName), $response->getBody()); $productData['picture_file_name'] = $fileName; } @@ -1794,4 +1823,4 @@ class StockService extends BaseService $shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch(); return $shoppingListRow !== null; } -} +} \ No newline at end of file