Skip to content

Will replace images during CSV import #21855

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 150 additions & 19 deletions app/code/Magento/CatalogImportExport/Model/Import/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -997,6 +997,7 @@ public function setParameters(array $params)
* Delete products for replacement.
*
* @return $this
* @throws \Exception
*/
public function deleteProductsForReplacement()
{
Expand Down Expand Up @@ -1088,6 +1089,11 @@ protected function _importData()
* Replace imported products.
*
* @return $this
* @throws LocalizedException
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Validation\ValidationException
* @throws \Zend_Validate_Exception
*/
protected function _replaceProducts()
{
Expand All @@ -1109,6 +1115,11 @@ protected function _replaceProducts()
* Save products data.
*
* @return $this
* @throws LocalizedException
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Validation\ValidationException
* @throws \Zend_Validate_Exception
*/
protected function _saveProductsData()
{
Expand Down Expand Up @@ -1249,6 +1260,11 @@ protected function _prepareRowForDb(array $rowData)
* Must be called after ALL products saving done.
*
* @return $this
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @throws LocalizedException
* phpcs:disable Generic.Metrics.NestingLevel
*/
protected function _saveLinks()
{
Expand Down Expand Up @@ -1280,6 +1296,7 @@ protected function _saveLinks()
*
* @param array $attributesData
* @return $this
* @throws \Exception
*/
protected function _saveProductAttributes(array $attributesData)
{
Expand Down Expand Up @@ -1350,6 +1367,7 @@ protected function _saveProductCategories(array $categoriesData)
* @param array $entityRowsUp Row for update
* @return $this
* @since 100.1.0
* @throws \Exception
*/
public function saveProductEntity(array $entityRowsIn, array $entityRowsUp)
{
Expand Down Expand Up @@ -1402,6 +1420,7 @@ private function getOldSkuFieldsForSelect()
*
* @param array $newProducts
* @return void
* @throws \Exception
*/
private function updateOldSku(array $newProducts)
{
Expand All @@ -1425,6 +1444,7 @@ private function updateOldSku(array $newProducts)
* Get new SKU fields for select
*
* @return array
* @throws \Exception
*/
private function getNewSkuFieldsForSelect()
{
Expand Down Expand Up @@ -1461,6 +1481,7 @@ protected function initMediaGalleryResources()
*
* @param array $bunch
* @return array
* @throws \Exception
*/
protected function getExistingImages($bunch)
{
Expand Down Expand Up @@ -1508,6 +1529,8 @@ public function getImagesFromRow(array $rowData)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
* @throws LocalizedException
* @throws \Zend_Validate_Exception
* phpcs:disable Generic.Metrics.NestingLevel
*/
protected function _saveProducts()
{
Expand All @@ -1524,12 +1547,17 @@ protected function _saveProducts()
$this->categoriesCache = [];
$tierPrices = [];
$mediaGallery = [];
$uploadedFiles = [];
$galleryItemsToRemove = [];
$labelsForUpdate = [];
$imagesForChangeVisibility = [];
$uploadedImages = [];
$previousType = null;
$prevAttributeSet = null;
$importDir = $this->_mediaDirectory->getAbsolutePath($this->getImportDir());

$existingImages = $this->getExistingImages($bunch);
$this->addImageHashes($existingImages);

foreach ($bunch as $rowNum => $rowData) {
// reset category processor's failed categories array
Expand Down Expand Up @@ -1618,6 +1646,7 @@ protected function _saveProducts()
if (!array_key_exists($rowSku, $this->websitesCache)) {
$this->websitesCache[$rowSku] = [];
}

// 2. Product-to-Website phase
if (!empty($rowData[self::COL_PRODUCT_WEBSITES])) {
$websiteCodes = explode($this->getMultipleValueSeparator(), $rowData[self::COL_PRODUCT_WEBSITES]);
Expand Down Expand Up @@ -1691,29 +1720,67 @@ protected function _saveProducts()
$position = 0;
foreach ($rowImages as $column => $columnImages) {
foreach ($columnImages as $columnImageKey => $columnImage) {
if (!isset($uploadedImages[$columnImage])) {
$uploadedFile = $this->uploadMediaFiles($columnImage);
$uploadedFile = $uploadedFile ?: $this->getSystemFile($columnImage);
if ($uploadedFile) {
$uploadedImages[$columnImage] = $uploadedFile;
if (filter_var($columnImage, FILTER_VALIDATE_URL) === false) {
$filename = $importDir . DIRECTORY_SEPARATOR . $columnImage;
if (file_exists($filename)) {
$hash = hash_file("sha256", $importDir . DIRECTORY_SEPARATOR . $columnImage);
} else {
unset($rowData[$column]);
$this->addRowError(
ValidatorInterface::ERROR_MEDIA_URL_NOT_ACCESSIBLE,
$rowNum,
null,
null,
ProcessingError::ERROR_LEVEL_NOT_CRITICAL
);
$hash = hash_file("sha256", $filename);
}
} else {
$uploadedFile = $uploadedImages[$columnImage];
$hash = hash_file("sha256", $columnImage);
}

// Add new images
if (!isset($existingImages[$rowSku])) {
$imageAlreadyExists = false;
} else {
$imageAlreadyExists = array_reduce(
$existingImages[$rowSku],
function ($exists, $file) use ($hash) {
if ($exists) {
return $exists;
}
if ($file['hash'] === $hash) {
return $file['value'];
}
return $exists;
},
''
);
}

if ($imageAlreadyExists) {
$uploadedFile = $imageAlreadyExists;
} else {
if (!isset($uploadedImages[$columnImage])) {
$uploadedFile = $this->uploadMediaFiles($columnImage);
$uploadedFile = $uploadedFile ?: $this->getSystemFile($columnImage);
if ($uploadedFile) {
$uploadedImages[$columnImage] = $uploadedFile;
} else {
unset($rowData[$column]);
$this->addRowError(
ValidatorInterface::ERROR_MEDIA_URL_NOT_ACCESSIBLE,
$rowNum,
null,
null,
ProcessingError::ERROR_LEVEL_NOT_CRITICAL
);
}
} else {
$uploadedFile = $uploadedImages[$columnImage];
}
}

if ($uploadedFile && $column !== self::COL_MEDIA_IMAGE) {
$rowData[$column] = $uploadedFile;
}

if ($uploadedFile) {
$uploadedFiles[] = $uploadedFile;
}

if (!$uploadedFile || isset($mediaGallery[$storeId][$rowSku][$uploadedFile])) {
continue;
}
Expand Down Expand Up @@ -1756,6 +1823,11 @@ protected function _saveProducts()
}
}

// 5.1 Items to remove phase
if (isset($existingImages[$rowSku])) {
$galleryItemsToRemove = \array_diff(\array_keys($existingImages[$rowSku]), $uploadedFiles);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your code only removes the images of the last product because the $galleryItemsToRemove variable is reassigned for each product.

I propose the use of array_merge as follows:

$galleryItemsToRemove = \array_merge($galleryItemsToRemove, \array_diff(\array_keys($existingImages[$rowSku]), $uploadedFiles));

}

// 6. Attributes phase
$rowStore = (self::SCOPE_STORE == $rowScope)
? $this->storeResolver->getStoreCodeToId($rowData[self::COL_STORE])
Expand Down Expand Up @@ -1866,6 +1938,8 @@ protected function _saveProducts()
$tierPrices
)->_saveMediaGallery(
$mediaGallery
)->_removeOldMediaGalleryItems(
$galleryItemsToRemove
)->_saveProductAttributes(
$attributes
)->updateMediaGalleryVisibility(
Expand All @@ -1883,6 +1957,23 @@ protected function _saveProducts()
return $this;
}

/**
* Generate hashes for existing images for comparison with newly uploaded images.
*
* @param array $images
*/
public function addImageHashes(&$images)
{
$productMediaPath = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath('/catalog/product');

foreach ($images as $sku => $files) {
foreach ($files as $path => $file) {
$images[$sku][$path]['hash'] = hash_file("sha256",$productMediaPath . $file['value']);
}
}
}

/**
* Prepare array with image states (visible or hidden from product page)
*
Expand Down Expand Up @@ -1984,6 +2075,7 @@ public function getStoreIdByCode($storeCode)
*
* @param array $tierPriceData
* @return $this
* @throws \Exception
*/
protected function _saveProductTierPrices(array $tierPriceData)
{
Expand Down Expand Up @@ -2018,6 +2110,24 @@ protected function _saveProductTierPrices(array $tierPriceData)
return $this;
}

/**
* Returns the import directory if specified or a default import directory (media/import).
*
* @return string
*/
protected function getImportDir()
{
$dirConfig = DirectoryList::getDefaultConfig();
$dirAddon = $dirConfig[DirectoryList::MEDIA][DirectoryList::PATH];

if (!empty($this->_parameters[Import::FIELD_NAME_IMG_FILE_DIR])) {
$tmpPath = $this->_parameters[Import::FIELD_NAME_IMG_FILE_DIR];
} else {
$tmpPath = $dirAddon . '/' . $this->_mediaDirectory->getRelativePath('import');
}
return $tmpPath;
}

/**
* Returns an object for upload a media files
*
Expand All @@ -2034,11 +2144,7 @@ protected function _getUploader()
$dirConfig = DirectoryList::getDefaultConfig();
$dirAddon = $dirConfig[DirectoryList::MEDIA][DirectoryList::PATH];

if (!empty($this->_parameters[Import::FIELD_NAME_IMG_FILE_DIR])) {
$tmpPath = $this->_parameters[Import::FIELD_NAME_IMG_FILE_DIR];
} else {
$tmpPath = $dirAddon . '/' . $this->_mediaDirectory->getRelativePath('import');
}
$tmpPath = $this->getImportDir();

if (!$this->_fileUploader->setTmpDir($tmpPath)) {
throw new LocalizedException(
Expand Down Expand Up @@ -2110,6 +2216,7 @@ private function getSystemFile($fileName)
*
* @param array $mediaGalleryData
* @return $this
* @throws \Exception
*/
protected function _saveMediaGallery(array $mediaGalleryData)
{
Expand All @@ -2121,6 +2228,22 @@ protected function _saveMediaGallery(array $mediaGalleryData)
return $this;
}

/**
* Remove old media gallery items.
*
* @param array $itemsToRemove
* @return $this
*/
protected function _removeOldMediaGalleryItems(array $itemsToRemove)
{
if (empty($itemsToRemove)) {
return $this;
}
$this->mediaProcessor->removeOldMediaItems($itemsToRemove);

return $this;
}

/**
* Save product websites.
*
Expand Down Expand Up @@ -2163,6 +2286,9 @@ protected function _saveProductWebsites(array $websiteData)
* Stock item saving.
*
* @return $this
* @throws \Magento\Framework\Exception\CouldNotSaveException
* @throws \Magento\Framework\Exception\InputException
* @throws \Magento\Framework\Validation\ValidationException
*/
protected function _saveStockItem()
{
Expand Down Expand Up @@ -2716,6 +2842,7 @@ private function _customFieldsMapping($rowData)
* Validate data rows and save bunches to DB
*
* @return $this|AbstractEntity
* @throws LocalizedException
*/
protected function _saveValidatedBunches()
{
Expand Down Expand Up @@ -2856,6 +2983,7 @@ private function isNeedToChangeUrlKey(array $rowData): bool
* Get product entity link field
*
* @return string
* @throws \Exception
*/
private function getProductEntityLinkField()
{
Expand All @@ -2871,6 +2999,7 @@ private function getProductEntityLinkField()
* Get product entity identifier field
*
* @return string
* @throws \Exception
*/
private function getProductIdentifierField()
{
Expand All @@ -2887,6 +3016,7 @@ private function getProductIdentifierField()
*
* @param array $labels
* @return void
* @throws \Exception
*/
private function updateMediaGalleryLabels(array $labels)
{
Expand All @@ -2900,6 +3030,7 @@ private function updateMediaGalleryLabels(array $labels)
*
* @param array $images
* @return $this
* @throws \Exception
*/
private function updateMediaGalleryVisibility(array $images)
{
Expand Down
Loading