/**
     * Retrieves the images from plentymarkets and adds them to the item.
     *
     * @return number
     */
    public function image()
    {
        $plentyId2ShopwareId = array();
        $shopwareId2PlentyPosition = array();
        $Request_GetItemsImages = new PlentySoapRequest_GetItemsImages();
        $Request_GetItemsImages->Page = 0;
        $Request_GetItemsImages->SKU = $this->PLENTY_itemId;
        // Cleanup
        $this->purge();
        /**
         * @var Media $mediaResource
         */
        $mediaResource = \Shopware\Components\Api\Manager::getResource('Media');
        do {
            /**
             * @var PlentySoapResponse_GetItemsImages $Response_GetItemsImages
             */
            $Response_GetItemsImages = PlentymarketsSoapClient::getInstance()->GetItemsImages($Request_GetItemsImages);
            if ($Response_GetItemsImages->Success == false) {
                PlentymarketsLogger::getInstance()->error('Sync:Item:Image', 'The images for the plentymarkets item id »' . $this->PLENTY_itemId . '« could not be retrieved', 3200);
                continue;
            }
            /**
             * @var $Image PlentySoapResponse_ObjectItemImage
             */
            foreach ($Response_GetItemsImages->ItemsImages->item as $Image) {
                $shopwareStoreIds = array();
                /**
                 * @var $reference PlentySoapResponse_ObjectGetItemImageReference
                 */
                foreach ($Image->References->item as $reference) {
                    if ($reference->ReferenceType == 'Mandant') {
                        try {
                            if (PlentymarketsMappingController::getShopByPlentyID($reference->ReferenceValue) > 0) {
                                $shopwareStoreId = PlentymarketsMappingController::getShopByPlentyID($reference->ReferenceValue);
                            }
                        } catch (PlentymarketsMappingExceptionNotExistant $E) {
                            continue;
                        }
                        if (isset($shopwareStoreId)) {
                            $shopwareStoreIds[] = $shopwareStoreId;
                        }
                    }
                }
                // Skip the image if it should not be shown
                if (empty($shopwareStoreIds)) {
                    continue;
                } else {
                    try {
                        $media = $this->updateMedia($Image, $mediaResource);
                    } catch (PlentymarketsMappingExceptionNotExistant $e) {
                        $media = $this->createMedia($Image, $mediaResource);
                    } catch (NotFoundException $e) {
                        $media = $this->createMedia($Image, $mediaResource);
                    } catch (Exception $e) {
                        PlentymarketsLogger::getInstance()->error('Sync:Item:Image', $e->getMessage(), 3200);
                        continue;
                    }
                    $image = new Image();
                    $image->setMain(2);
                    $image->setMedia($media);
                    $image->setPath($media->getName());
                    $image->setExtension($media->getExtension());
                    // get the main language of the shop
                    //$mainLangData = array_values(PlentymarketsTranslation::getInstance()->getShopMainLanguage($shopwareStoreId));
                    //$mainLang = PlentymarketsTranslation::getInstance()->getPlentyLocaleFormat($mainLangData[0]['locale']);
                    foreach ($Image->Names->item as $imageName) {
                        if ($imageName->Lang == 'de') {
                            // set the image title in German
                            $image->setDescription($imageName->Name);
                        }
                    }
                    if (!is_null(PlentymarketsConfig::getInstance()->getItemImageAltAttributeID()) && PlentymarketsConfig::getInstance()->getItemImageAltAttributeID() > 0 && PlentymarketsConfig::getInstance()->getItemImageAltAttributeID() <= 3) {
                        // get the attribute number for alternative text from connector's settings
                        $plenty_attributeID = PlentymarketsConfig::getInstance()->getItemImageAltAttributeID();
                        // set the value for the attribute number
                        $attribute = new \Shopware\Models\Attribute\ArticleImage();
                        call_user_func(array($attribute, 'setAttribute' . $plenty_attributeID), $Image->Names->item[0]->AlternativeText);
                        $image->setAttribute($attribute);
                    }
                    $image->setPosition($Image->Position);
                    // Generate the thumbnails
                    if (version_compare(Shopware::VERSION, '4.2') != 1) {
                        PlentymarketsImportItemImageThumbnailController::getInstance()->addMediaResource($media);
                    }
                    Shopware()->Models()->persist($image);
                    Shopware()->Models()->flush();
                    $imageId = $image->getId();
                    foreach ($shopwareStoreIds as $shopwareStoreId) {
                        // import the image title translations for all active shops of the image
                        $this->importImageTitleTranslation($imageId, $Image->Names->item, $shopwareStoreId);
                    }
                    $plentyId2ShopwareId[$Image->ImageID] = $imageId;
                    $shopwareId2PlentyPosition[$Image->Position] = $imageId;
                    Shopware()->DB()->query('
											UPDATE s_articles_img
												SET articleID = ?
												WHERE id = ?
										', array($this->SHOPWARE_itemId, $imageId));
                }
            }
        } while (++$Request_GetItemsImages->Page < $Response_GetItemsImages->Pages);
        if (empty($shopwareId2PlentyPosition)) {
            return;
        }
        ksort($shopwareId2PlentyPosition);
        $mainImageId = reset($shopwareId2PlentyPosition);
        if (empty($mainImageId)) {
            return;
        }
        /**
         * @var Shopware\Models\Article\Image $mainImage
         */
        $mainImage = Shopware()->Models()->find('Shopware\\Models\\Article\\Image', $mainImageId);
        $mainImage->setMain(1);
        Shopware()->Models()->persist($mainImage);
        Shopware()->Models()->flush();
        // Get the variant images
        $Request_GetItemsVariantImages = new PlentySoapRequest_GetItemsVariantImages();
        $Request_GetItemsVariantImages->Items = array();
        $RequestObject_GetItemsVariantImages = new PlentySoapRequestObject_GetItemsVariantImages();
        $RequestObject_GetItemsVariantImages->ItemID = $this->PLENTY_itemId;
        $Request_GetItemsVariantImages->Items[] = $RequestObject_GetItemsVariantImages;
        /**
         * @var PlentySoapResponse_GetItemsVariantImages $Response_GetItemsVariantImages
         */
        $Response_GetItemsVariantImages = PlentymarketsSoapClient::getInstance()->GetItemsVariantImages($Request_GetItemsVariantImages);
        foreach ($Response_GetItemsVariantImages->Images->item as $GetItemsVariantImagesImage) {
            try {
                $shopwareOptionId = PlentymarketsMappingController::getAttributeOptionByPlentyID($GetItemsVariantImagesImage->AttributeValueID);
                /**
                 * @var \Shopware\Models\Article\Configurator\Option $shopwareOption
                 */
                $shopwareOption = Shopware()->Models()->find('Shopware\\Models\\Article\\Configurator\\Option', $shopwareOptionId);
            } catch (PlentymarketsMappingExceptionNotExistant $e) {
                continue;
            }
            if (!isset($plentyId2ShopwareId[$GetItemsVariantImagesImage->ImageID])) {
                continue;
            }
            /** @var Shopware\Models\Article\Image $shopwareImage */
            $shopwareImageId = $plentyId2ShopwareId[$GetItemsVariantImagesImage->ImageID];
            /**
             * @var Image $shopwareImage
             */
            $shopwareImage = Shopware()->Models()->find('Shopware\\Models\\Article\\Image', $shopwareImageId);
            $mapping = new Shopware\Models\Article\Image\Mapping();
            $mapping->setImage($shopwareImage);
            $rule = new Shopware\Models\Article\Image\Rule();
            $rule->setMapping($mapping);
            $rule->setOption($shopwareOption);
            $mapping->getRules()->add($rule);
            $shopwareImage->setMappings($mapping);
            Shopware()->Models()->persist($mapping);
            $details = Shopware()->Db()->fetchCol('
				SELECT
						d.id
					FROM s_articles_details d
						INNER JOIN s_article_configurator_option_relations alias16 ON alias16.option_id = ' . $shopwareOptionId . ' AND alias16.article_id = d.id
					WHERE d.articleID = ' . $this->SHOPWARE_itemId . '
			');
            foreach ($details as $detailId) {
                /**
                 * Get the detail object
                 *
                 * @var Shopware\Models\Article\Detail $detail
                 */
                $detail = Shopware()->Models()->getReference('Shopware\\Models\\Article\\Detail', $detailId);
                // Create the variant image
                $variantImage = new Shopware\Models\Article\Image();
                $variantImage->setExtension($shopwareImage->getExtension());
                $variantImage->setMain($shopwareImage->getMain());
                $variantImage->setParent($shopwareImage);
                $variantImage->setArticleDetail($detail);
                // And persist it
                Shopware()->Models()->persist($variantImage);
            }
        }
        Shopware()->Db()->update('s_articles', array('changetime' => date('c', time())), 'id=' . $this->SHOPWARE_itemId);
        Shopware()->Models()->flush();
    }
Exemplo n.º 2
0
 /**
  * Helper function which creates a variant image for the passed article image.
  * @param Image $articleImage
  * @param Detail $variant
  * @return Image
  */
 public function createVariantImage(Image $articleImage, Detail $variant)
 {
     $variantImage = new Image();
     $variantImage->setParent($articleImage);
     $variantImage->setArticleDetail($variant);
     $variantImage->setPosition($articleImage->getPosition());
     $variantImage->setMain($articleImage->getMain());
     $variantImage->setExtension($articleImage->getExtension());
     return $variantImage;
 }
 /**
  * Insert/Update data into db
  *
  * @param array $records
  * @throws \Enlight_Event_Exception
  * @throws \Exception
  * @throws \Zend_Db_Adapter_Exception
  */
 public function write($records)
 {
     if (empty($records['default'])) {
         $message = SnippetsHelper::getNamespace()->get('adapters/articlesImages/no_records', 'No new article image records were found.');
         throw new \Exception($message);
     }
     $records = $this->eventManager->filter('Shopware_Components_SwagImportExport_DbAdapters_ArticlesImagesDbAdapter_Write', $records, ['subject' => $this]);
     foreach ($records['default'] as $record) {
         try {
             $record = $this->validator->filterEmptyString($record);
             $this->validator->checkRequiredFields($record);
             /** @var \Shopware\Models\Article\Detail $articleDetailModel */
             $articleDetailModel = $this->manager->getRepository(Detail::class)->findOneBy(['number' => $record['ordernumber']]);
             if (!$articleDetailModel) {
                 $message = SnippetsHelper::getNamespace()->get('adapters/articlesImages/article_not_found', 'Article with number %s does not exists');
                 throw new AdapterException(sprintf($message, $record['ordernumber']));
             }
             $record = $this->dataManager->setDefaultFields($record, $articleDetailModel->getArticle()->getId());
             $this->validator->validate($record, ArticleImageValidator::$mapper);
             $relations = [];
             if (isset($record['relations'])) {
                 $importedRelations = explode("&", $record['relations']);
                 foreach ($importedRelations as $key => $relation) {
                     if ($relation === "") {
                         continue;
                     }
                     $variantConfig = explode('|', preg_replace('/{|}/', '', $relation));
                     foreach ($variantConfig as $config) {
                         list($group, $option) = explode(":", $config);
                         //Get configurator group
                         $cGroupModel = $this->manager->getRepository(Group::class)->findOneBy(['name' => $group]);
                         if ($cGroupModel === null) {
                             continue;
                         }
                         //Get configurator option
                         $cOptionModel = $this->manager->getRepository(Option::class)->findOneBy(['name' => $option, 'groupId' => $cGroupModel->getId()]);
                         if ($cOptionModel === null) {
                             continue;
                         }
                         $relations[$key][] = ["group" => $cGroupModel, "option" => $cOptionModel];
                     }
                 }
             }
             /** @var \Shopware\Models\Article\Article $article */
             $article = $articleDetailModel->getArticle();
             $name = pathinfo($record['image'], PATHINFO_FILENAME);
             $media = false;
             if ($this->imageImportMode === 1) {
                 $mediaRepository = $this->manager->getRepository(Media::class);
                 $media = $mediaRepository->findOneBy(['name' => $name]);
             }
             //create new media
             if ($this->imageImportMode === 2 || empty($media)) {
                 $path = $this->load($record['image'], $name);
                 $file = new File($path);
                 $media = new Media();
                 $media->setAlbumId(-1);
                 $media->setAlbum($this->manager->getRepository(Album::class)->find(-1));
                 $media->setFile($file);
                 $media->setName(pathinfo($record['image'], PATHINFO_FILENAME));
                 $media->setDescription('');
                 $media->setCreated(new \DateTime());
                 $media->setUserId(0);
                 $this->manager->persist($media);
                 $this->manager->flush();
                 //thumbnail flag
                 //TODO: validate thumbnail
                 $thumbnail = (bool) $record['thumbnail'];
                 //generate thumbnails
                 if ($media->getType() == Media::TYPE_IMAGE && $thumbnail) {
                     $this->thumbnailManager->createMediaThumbnail($media, [], true);
                 }
             }
             $image = new Image();
             $image->setArticle($article);
             $image->setPosition($record['position']);
             $image->setPath($media->getName());
             $image->setExtension($media->getExtension());
             $image->setMedia($media);
             $image->setMain($record['main']);
             $image->setDescription($record['description']);
             $this->manager->persist($image);
             $this->manager->flush();
             if ($relations && !empty($relations)) {
                 $this->setImageMappings($relations, $image->getId());
             }
             // Prevent multiple images from being a preview
             if ((int) $record['main'] === 1) {
                 $this->db->update('s_articles_img', ['main' => 2], ['articleID = ?' => $article->getId(), 'id <> ?' => $image->getId()]);
             }
         } catch (AdapterException $e) {
             $message = $e->getMessage();
             $this->saveMessage($message);
         }
     }
 }
Exemplo n.º 4
0
 /**
  * @param array $image
  * @return int
  */
 public function importArticleImage(array $image)
 {
     if (empty($image) || !is_array($image)) {
         return false;
     }
     $image = $this->prepareImageData($image);
     if (empty($image['articleID']) || empty($image['image']) && empty($image['name'])) {
         return false;
     }
     $image['main'] = $this->setMain($image['main'], $image['articleID']);
     if (!strpos($image["image"], "http://") && !strpos($image["image"], "https://")) {
         $image["image"] = "http://" . $image["image"];
     }
     $uploadFile = $this->copyImage($image['image'], $image['name']);
     if ($uploadFile === false) {
         return false;
     }
     $media = new Media();
     $file = new File($uploadFile);
     $identity = Shopware()->Auth()->getIdentity();
     $userId = $identity !== null ? $identity->id : 0;
     $media->setUserId($userId);
     $media->setDescription($image['description']);
     $media->setCreated(new \DateTime());
     $media->setFile($file);
     /* @var ArticleRepository $articleRepository */
     $articleRepository = $this->getArticleRepository();
     $article = $articleRepository->find((int) $image['articleID']);
     if (!$article instanceof Article) {
         $this->logger->error("Article '{$image['articleID']}' not found!");
         return false;
     }
     $media->setAlbumId($image['albumID']);
     /* @var \Shopware\Models\Media\Album $album */
     $album = $this->em->find('Shopware\\Models\\Media\\Album', $image['albumID']);
     $media->setAlbum($album);
     $articleImage = new Image();
     list($width, $height) = getimagesize($uploadFile);
     $articleImage->setDescription($image['description']);
     $articleImage->setMedia($media);
     $articleImage->setArticle($article);
     $articleImage->setWidth($width);
     $articleImage->setHeight($height);
     $articleImage->setPath($image['name']);
     $articleImage->setExtension($media->getExtension());
     $articleImage->setPosition($image['position']);
     $articleImage->setMain($image['main']);
     $articleImage->setRelations($image['relations']);
     $article->setImages($articleImage);
     $this->em->persist($media);
     $this->em->persist($article);
     $this->em->persist($articleImage);
     $this->em->flush();
     return $articleImage->getId();
 }