2

Front image should only load for configs and this works fine. Simples should load front and back and all other angles. It looks for F (front) and B (back), sets those to 1 or 2, everything else is just added at the end in the order it's imported. Something broke and now nothing is being imported to simples, well actually sometimes a _F will be upload to simples but it's not importing anything else. I think the _getPosition function is the issue.

Here is the error and file naming convention:

Skipping image d65116r4_blk_1.jpg, no products matched.
Skipping image d65116r4_blk_2.jpg, no products matched.
Skipping image d65116r4_blk_3.jpg, no products matched.
Skipping image d65116r4_blk_b.jpg, no products matched.
Skipping image d65116r4_blk_f.jpg, no products matched. (This will upload for configs and most of the time simples but none of the other four above load for simples)

Please see my code below:

Model/Adapter/Product/Media.php

<?php
/**
 * Most of the following code was taken from Mage Core, and modified slightly for our needs.
 *
 * @see Mage_Catalog_Model_Product_Attribute_Backend_Media::addImage()
 */
class OnePica_FullCircle_Model_Adapter_Product_Media
    extends Mage_Catalog_Model_Convert_Adapter_Product
{
    /**
     * Add media file to products
     */
    public function saveRow(array $importData)
    {
        if (empty($importData['path'])) {
            $message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'path');
            Mage::throwException($message);
        }
        if (empty($importData['file'])) {
            $message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'file');
            Mage::throwException($message);
        }
        $path = $importData['path'];
        $file = $importData['file'];

        // If store hasn't been set, set to default
        if ($this->_store === null) {
            $this->_store = $this->getStoreById(1);
        }

        //Load list of products to add to
        $collection = $this->_getProductCollection($file);

        //Add image to the media directory
        $savedFileName = $this->_addMediaFile($path . DS . $file);

        // get image import cache setting
        $imageImportCache = Mage::getSingleton('myfoldername_fullcircle/image_import_cache')->load(1);

        //Add image to products
        foreach ($collection as $product) {
            $product->setStoreId($this->_store->getId());

            //Load Product Images
            $product->getResource()->getAttribute('media_gallery')
                ->getBackend()->afterLoad($product);

            //Check to see if we already have the image in the gallery
            $found = false;
            $curImages = $product->getMediaGallery();
            if (isset($curImages['images']) && is_array($curImages['images']) && count($curImages)) {
                foreach ($curImages['images'] as $curImage) {
                    if ($curImage['file'] == $savedFileName) {
                        //A similar image already exists..mark that the cache needs to be cleared
                        $found = true;
                        // set to clear cache
                        $imageImportCache->setIsClear(true)
                            ->setUpdatedAt(now())
                            ->save();
                    }
                }
            }

            //Add Image to Product
            if (!$found) {
                //This event gets run in the core, so let's also run it
                Mage::dispatchEvent('catalog_product_media_add_image', array('product' => $product, 'image' => $path . DS . $file));
                //Add image to product gallery
                $this->_addImageToProduct($product, $savedFileName);
            } else {
                // Even if the image is found, we still want to set the product attributes
                $this->_setProductMediaAttributes($product, $savedFileName);
                $product->save();
            }

            // Disable EU Images in US and EU images in US
            $europeanImageIds = array();
            $usImageIds = array();
            if (is_array($curImages) && isset($curImages['images']) && is_array($curImages['images'])) {
                foreach ($curImages['images'] as $img) {
                    if (stripos(basename($img['file']), '51_') === 0 && array_key_exists('value_id', $img)) {
                        $europeanImageIds[] = $img['value_id'];
                    } else if (stripos(basename($img['file']), '51_') === false && array_key_exists('value_id', $img)) {
                        $usImageIds[] = $img['value_id'];
                    }
                }

                $helper = Mage::helper('myfoldername_eudataflow');

                $usStoreIds = $helper->getStoreIdsByCompanyNumber('01');
                $euStoreIds = $helper->getStoreIdsByCompanyNumber('51');

                $adapter = Mage::getModel('myfoldername_eudataflow/convert_adapter_product');
                $adapter->disableImages($europeanImageIds, $usStoreIds);
                $adapter->disableImages($usImageIds, $euStoreIds);
            }
        }

        return true;
    }

    /**
     * Get configured store id
     *
     * @return int
     */
    protected function _getStoreId()
    {
        if (null === $this->getBatchParams('store')) {
            return 0;
        }
        return (int)$this->getBatchParams('store');
    }

    /**
     * Get collection of products matching the media file
     *
     * @param string $file
     * @return Mage_Catalog_Model_Resource_Product_Collection
     */
    protected function _getProductCollection($file)
    {
        //Initialize collection
        $collection = $this->getProductModel()->reset()
            ->getCollection()
            ->addStoreFilter($this->_getStoreId());

        //Load source for electric_color
        $colorSource = Mage::getResourceModel('catalog/product')
            ->getAttribute('color')
            ->getSource();

        //Parse filename for product details
        $parts = $this->_parseFileName($file);
        if (count(explode('_', $file)) != $parts['valid_parts']) {
            $message = Mage::helper('catalog')->__('Skipping image %s, invalid filename format.',$file);
            Mage::throwException($message);
        }
        //Filter by style
        $collection->addAttributeToFilter('style_number', $parts['sku']);

        //Filter by color
        $collection->addAttributeToFilter('color', $colorSource->getOptionId($parts['color']));
        if (strtolower($parts['angle']) == 'f' || strtolower($parts['angle']) == 'frt') {
            //Front angle...add to configurable as well
            $collection->getSelect()->orWhere('`e`.`sku` = ?', $parts['sku']);

            // Front + color - see if there's a split configurable to add it to as well
            $collection->getSelect()->orWhere('`e`.`sku` = ?', $parts['sku'] . $parts['color']);
        }

        //Set a safety guard of 100 products just to make sure
        if ($collection->getSize() > 100) {
            $message = Mage::helper('catalog')->__('Skipping image %s, too many products matched.',$file);
            Mage::throwException($message);
        }

        //Throw an exception if there aren't any products
        if (!$collection->getSize()) {
            $message = Mage::helper('catalog')->__('Skipping image %s, no products matched.',$file);
            Mage::throwException($message);
        }

        return $collection;
    }

    /**
     * Take the filename and get sku, color, angle
     * 
     * @param $file
     *
     * @return array
     */
    protected function _parseFileName($file)
    {
        $parts = explode('_', $file);
        return array(
            'sku' => $parts[0],
            'color' => $parts[1],
            'angle_extension' => $parts[2],
            'angle' => substr($parts[2], 0, 1),
            'valid_parts' => 3,
        );
    }

    /**
     * Manually add image to media directory
     *
     * @param string $file
     * @return string
     */
    protected function _addMediaFile($file)
    {
        $pathinfo       = pathinfo($file);
//         $fileName       = strtolower($pathinfo['basename']); //Force all images to lowercase
        $fileName = $pathinfo['basename'];
        $fileName       = Mage_Core_Model_File_Uploader::getCorrectFileName($fileName);
        $dispretionPath = Mage_Core_Model_File_Uploader::getDispretionPath($fileName);
        $fileName       = str_replace(DS, '/', $dispretionPath . DS . $fileName);

        //Make sure image exists in media folder, add it if it doesn't
        $mediaConfig = Mage::getSingleton('catalog/product_media_config');
        $mediaPath = $mediaConfig->getMediaPath($fileName);

        $ioAdapter = new Varien_Io_File();
        $ioAdapter->setAllowCreateFolders(true);
        $distanationDirectory = dirname($mediaPath);
        try {
            $ioAdapter->open(array('path' => $distanationDirectory));

            /** @var $storageHelper Mage_Core_Helper_File_Storage_Database */
            $storageHelper = Mage::helper('core/file_storage_database');
            $ioAdapter->mv($file, $mediaPath);
            $storageHelper->saveFile($mediaConfig->getMediaShortUrl($fileName));
            $ioAdapter->chmod($mediaPath, 0777);
        } catch (Exception $e) {
            $message = Mage::helper('catalog')->__('Skipping image %s, failed to move file.',$file);
            Mage::throwException($message);
        }

        return $fileName;
    }

    /**
     * Add image to the product
     *
     * @param Mage_Catalog_Model_Product $product
     * @param string $fileName
     * @return boolean
     */
    protected function _addImageToProduct($product, $fileName)
    {
        //Get next position value
        $mediaGalleryData = $product->getData('media_gallery');
        if (!is_array($mediaGalleryData)) {
            $mediaGalleryData = array(
                'images' => array()
            );
        }
        $position = $this->_getPosition($product, $mediaGalleryData, $fileName);

        //Add image to gallery data
        $mediaGallery = $this->getAttribute('media_gallery');
        $mediaResource = Mage::getResourceSingleton('catalog/product_attribute_backend_media');
        $valueId = $mediaResource->insertGallery(array(
            'entity_id' => $product->getId(),
            'attribute_id' => $mediaGallery->getAttributeId(),
            'value' => $fileName,
        ));
        $mediaGalleryData['images'][] = array(
            'value_id' => $valueId,
            'file'     => $fileName,
            'position' => $position,
            'label'    => '',
            'disabled' => 0,
        );

        // Set product attributes
        $this->_setProductMediaAttributes($product, $fileName);

        // Update the media gallery data
        $product->setData('media_gallery', $mediaGalleryData);

        //Save product
        Mage::helper('onepica_fullcircle')->fixUrlKey($product);
        $product->save();

        return true;
    }

    /**
     * Get the position for the media image
     *
     * @param Mage_Catalog_Model_Product $product
     * @param array $mediaGalleryData
     * @param string $fileName
     * @return int
     */
    protected function _getPosition($product, $mediaGalleryData, $fileName)
    {
        $position = 0;

        $isFrontImage = preg_match('/_f\./', strtolower($fileName)) || preg_match('/_frt\./', strtolower($fileName));
        $isBackImage  = preg_match('/_b\./', strtolower($fileName)) || preg_match('/_bck\./', strtolower($fileName));

        if ($product->getTypeId() == 'simple') {
            //Check for a front angle
            if ($isFrontImage) {
                return 1;
            }
            //Check for a back angle
            if ($isBackImage) {
                return 2;
            }
            //Make sure new position is at least 10
            $position = 9;
        }

        // Split configurables - if the image is a front angle for that color,
        // set it to default.
        if ($product->getTypeId() === Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
            $styleNumber = $product->getStyleNumber();
            $sku = $product->getSku();

            $imageContainsColor = false;
            $color = str_replace($styleNumber, '', $sku);
            if (!empty($color)) {
                $imageContainsColor = false !== stristr($fileName, $color);
            }

            if ($imageContainsColor && $isFrontImage) {
                return 1;
            }

            if ($imageContainsColor && $isBackImage) {
                return 2;
            }
        }        

        //Get position of last media image
        $lastImage = end($mediaGalleryData['images']);
        reset($mediaGalleryData);
        if ($lastImage) {
            $position = max((int)$lastImage['position'], $position);
        }
        return $position + 1;
    }

    /**
     * Set image, small_image, thumbnail for product
     * 
     * @param $product
     * @param $fileName
     */
    protected function _setProductMediaAttributes($product, $fileName)
    {
        $firstPosition = false;
        $mediaGalleryData = $product->getData('media_gallery');
        $position = $this->_getPosition($product, $mediaGalleryData, $fileName);
        if (is_array($mediaGalleryData)) {
            $firstImage = @current($mediaGalleryData['images']);
            $firstPosition = (int)@$firstImage['position']; // Could be zero
        }

        //Set Product Attributes
        // No images yet, lesser position, or is front image - set it as default
        if (false === $firstPosition || $position < $firstPosition || $position === 1) {
            foreach (array('image', 'small_image', 'thumbnail') as $mediaAttributeCode) {
                $product->setData($mediaAttributeCode, $fileName);
            }
        }
    }

    /**
     * Process after import data
     */
    public function finish()
    {
        // override parent, do not reindex
    }
}

I really look forward to some help. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.