Beispiel #1
0
    /**
     * @param array $data
     * @param \Shopware\Models\Article\Article $article
     * @throws \Shopware\Components\Api\Exception\CustomValidationException
     * @return array
     */
    private function prepareImageAssociatedData($data, ArticleModel $article)
    {
        if (!isset($data['images'])) {
            return $data;
        }

        $images = $article->getImages();

        $position = 1;

        foreach ($data['images'] as &$imageData) {
            if (isset($imageData['id'])) {
                $image = $this->getManager()
                        ->getRepository('Shopware\Models\Article\Image')
                        ->find($imageData['id']);

                if (!$image instanceof \Shopware\Models\Article\Image) {
                    throw new ApiException\CustomValidationException(sprintf("Image by id %s not found", $imageData['id']));
                }
            } else {
                $image = new \Shopware\Models\Article\Image();
            }

            if (isset($imageData['link'])) {
                $path = $this->load($imageData['link']);

                $file = new \Symfony\Component\HttpFoundation\File\File($path);

                $media = new \Shopware\Models\Media\Media();
                $media->setAlbumId(-1);
                $media->setAlbum($this->getManager()->find('Shopware\Models\Media\Album', -1));

                $media->setFile($file);
                $media->setDescription('');
                $media->setCreated(new \DateTime());
                $media->setUserId(0);

                try {
                    //persist the model into the model manager
                    $this->getManager()->persist($media);
                    $this->getManager()->flush();
                } catch (\Doctrine\ORM\ORMException $e) {
                    throw new ApiException\CustomValidationException(sprintf("Some error occured while loading your image"));
                }

                $image->setMain(2);
                $image->setMedia($media);
                $image->setPosition($position);
                $image->setArticle($article);
                $position++;
                $image->setPath($media->getName());
                $image->setExtension($media->getExtension());
            }

            $image->fromArray($imageData);
            $images->add($image);
        }

        unset($data['images']);

        return $data;
    }
 /**
  * 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 \Shopware\Components\Api\Resource\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 (strtolower($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 (PlentymarketsMappingExceptionCorrupt $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 \Shopware\Models\Article\Image();
                 $image->setMain(2);
                 $image->setMedia($media);
                 $image->setPath($media->getName());
                 $image->setExtension($media->getExtension());
                 $image->setPosition($Image->Position);
                 if (!empty($Image->Names)) {
                     foreach ($Image->Names->item as $imageName) {
                         if ($imageName->Lang == 'de') {
                             // set the image title in German
                             $image->setDescription($imageName->Name);
                         }
                     }
                     if (!empty($Image->Names->item[0]->AlternativeText)) {
                         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();
                             $attribute->{setAttribute . $plenty_attributeID}($Image->Names->item[0]->AlternativeText);
                             $image->setAttribute($attribute);
                         }
                         // 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) {
                     if (!empty($Image->Names)) {
                         // 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 (!$shopwareId2PlentyPosition) {
         return;
     }
     ksort($shopwareId2PlentyPosition);
     $mainImageId = reset($shopwareId2PlentyPosition);
     /** @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);
     if (!empty($Response_GetItemsVariantImages->Images)) {
         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 \Shopware\Models\Article\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()->Models()->flush();
 }
 /**
  * Helper method which creates images for variants based on the image mappings
  * @param $articleId
  */
 protected function recreateVariantImages($articleId)
 {
     $builder = Shopware()->Models()->createQueryBuilder();
     $images = $builder->select(array('images', 'mappings', 'rules', 'option'))->from('Shopware\\Models\\Article\\Image', 'images')->innerJoin('images.mappings', 'mappings')->leftJoin('mappings.rules', 'rules')->leftJoin('rules.option', 'option')->where('images.articleId = ?1')->andWhere('images.parentId IS NULL')->setParameter(1, $articleId)->getQuery();
     $images = $images->execute();
     /** @var \Shopware\Models\Article\Image $image */
     foreach ($images as $image) {
         $query = $this->getArticleRepository()->getArticleImageDataQuery($image->getId());
         $imageData = $query->getOneOrNullResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
         $this->getArticleRepository()->getDeleteImageChildrenQuery($image->getId())->execute();
         foreach ($image->getMappings() as $mapping) {
             $options = array();
             foreach ($mapping->getRules() as $rule) {
                 $options[] = $rule->getOption();
             }
             $imageData['path'] = null;
             $imageData['parent'] = $image;
             $details = $this->getArticleRepository()->getDetailsForOptionIdsQuery($articleId, $options)->getResult();
             foreach ($details as $detail) {
                 $newImage = new \Shopware\Models\Article\Image();
                 $newImage->fromArray($imageData);
                 $newImage->setArticleDetail($detail);
                 Shopware()->Models()->persist($newImage);
                 Shopware()->Models()->flush();
             }
         }
     }
 }
Beispiel #4
0
    /**
     * @param $filePath
     */
    public function importImages($filePath)
    {
        $results = new Shopware_Components_CsvIterator($filePath, ';');

        $counter = 0;
        $total = 0;
        $errors = array();

        $articleDetailRepository = $this->getArticleDetailRepository();

        $configuratorGroupRepository = $this->getManager()->getRepository('Shopware\Models\Article\Configurator\Group');
        $configuratorOptionRepository = $this->getManager()->getRepository('Shopware\Models\Article\Configurator\Option');

        foreach ($results as $imageData) {
            if(!empty($imageData['relations'])) {
                $relations = array();
                $results = explode("&", $imageData['relations']);
                foreach($results as $result) {
                    if($result !== "") {
                        $result = preg_replace('/{|}/', '', $result);
                        list($group, $option) = explode(":", $result);

                        // Try to get given configurator group/option. Continue, if they don't exist
                        $cGroupModel = $configuratorGroupRepository->findOneBy(array('name' => $group));
                        if($cGroupModel === null) {
                            continue;
                        }
                        $cOptionModel = $configuratorOptionRepository->findOneBy(
                            array('name' => $option,
                                 'groupId'=>$cGroupModel->getId()
                            )
                        );
                        if($cOptionModel === null) {
                            continue;
                        }
                        $relations[] = array("group" => $cGroupModel, "option" => $cOptionModel);
                    }
                }
            }

            if (empty($imageData['ordernumber']) || empty($imageData['image'])) {
                continue; 
            }
            $counter++;

            /** @var \Shopware\Models\Article\Detail $articleDetailModel */
            $articleDetailModel = $articleDetailRepository->findOneBy(array('number' => $imageData['ordernumber']));
            if (!$articleDetailModel) {
                continue;
            }

            /** @var \Shopware\Models\Article\Article $article */
            $article = $articleDetailModel->getArticle();

            $image = new \Shopware\Models\Article\Image();

            try {
                $path = $this->load($imageData['image'], basename($imageData['image']));
            } catch (\Exception $e) {
                $errors[] = "Could not load image {$imageData['image']}";
                continue;
            }
            
            $file = new \Symfony\Component\HttpFoundation\File\File($path);

            $media = new \Shopware\Models\Media\Media();
            $media->setAlbumId(-1);
            $media->setAlbum($this->getManager()->find('Shopware\Models\Media\Album', -1));

            $media->setFile($file);
            $media->setDescription('');
            $media->setCreated(new \DateTime());
            $media->setUserId(0);

            try { //persist the model into the model manager
                $this->getManager()->persist($media);
                $this->getManager()->flush();
            } catch (\Doctrine\ORM\ORMException $e) {
                $errors[] = "Could not move image";
                continue;
            }

            if (empty($imageData['main'])) {
                $imageData['main'] = 1;
            }

            $image->setArticle($article);
            $image->setDescription($imageData['description']);
            $image->setPosition($imageData['position']);
            $image->setPath($media->getName());
            $image->setExtension($media->getExtension());
            $image->setMedia($media);
            $image->setMain($imageData['main']);
            $this->getManager()->persist($image);
            $this->getManager()->flush($image);

            // Set mappings
            if(!empty($relations)) {
                foreach($relations as $relation){
                    $optionModel = $relation['option'];
                    Shopware()->Db()->insert('s_article_img_mappings', array(
                        'image_id' => $image->getId()
                    ));
                    $mappingID = Shopware()->Db()->lastInsertId();
                    Shopware()->Db()->insert('s_article_img_mapping_rules', array(
                        'mapping_id' => $mappingID,
                        'option_id' => $optionModel->getId()
                    ));
                }
            }

            // Prevent multiple images from being a preview
            if((int) $imageData['main'] === 1) {
                Shopware()->Db()->update('s_articles_img',
                    array(
                        'main' => 2
                    ),
                    array(
                        'articleID = ?' => $article->getId(),
                        'id <> ?' => $image->getId()
                    )
                );
            }


            $total++;
        }

        if (!empty($errors)) {
            $errors = $this->toUtf8($errors);
            $message = implode("<br>\n", $errors);
            echo json_encode(array(
                'success' => false,
                'message' => sprintf("Errors: $message"),
            ));
            return;
        }

        echo json_encode(array(
            'success' => true,
            'message' => sprintf("Successfully uploaded %s of %s Images", $total, $counter)
        ));
        
        return;
    }
Beispiel #5
0
 /**
  * @param $options
  * @param $imageData
  * @param $parent \Shopware\Models\Article\Image
  */
 protected function createImagesForOptions($options, $imageData, $parent)
 {
     $articleId = $parent->getArticle()->getId();
     $imageData['path'] = null;
     $imageData['parent'] = $parent;
     $join = '';
     foreach ($options as $option) {
         $alias = 'alias' . $option->getId();
         $join = $join . ' INNER JOIN s_article_configurator_option_relations alias' . $option->getId() . ' ON ' . $alias . '.option_id = ' . $option->getId() . ' AND ' . $alias . '.article_id = d.id ';
     }
     $sql = "SELECT d.id\n                FROM s_articles_details d\n        " . $join . "\n        WHERE d.articleID = " . (int) $articleId;
     $details = Shopware()->Db()->fetchCol($sql);
     foreach ($details as $detailId) {
         $detail = Shopware()->Models()->getReference('Shopware\\Models\\Article\\Detail', $detailId);
         $image = new \Shopware\Models\Article\Image();
         $image->fromArray($imageData);
         $image->setArticleDetail($detail);
         Shopware()->Models()->persist($image);
     }
     Shopware()->Models()->flush();
 }
Beispiel #6
0
    /**
     * @param $options
     * @param $imageData
     * @param $parent \Shopware\Models\Article\Image
     */
    protected function createImagesForOptions($options, $imageData, $parent)
    {
        $articleId = $parent->getArticle()->getId();
        $imageData['path'] = null;
        $imageData['parent'] = $parent;

        $details = $this->getRepository()->getDetailsForOptionIdsQuery($articleId, $options)->getResult();

        foreach($details as $detail) {
            $image = new \Shopware\Models\Article\Image();
            $image->fromArray($imageData);
            $image->setArticleDetail($detail);
            Shopware()->Models()->persist($image);
        }
        Shopware()->Models()->flush();
    }
Beispiel #7
0
    /**
     * Einfügen von Artikelbildern
     * Hinweis: Falls keine anderen Bilder hinterlegt sind, wird das zuerst eingefügte Bild automatisch zum Hauptbild
     *
     * @param array $article_image Array mit Informationen �ber die Bilder die konvertiert und dem Artikel zugewiesen werden müssen
     *
     * articleID => ID des Artikels (s_articles.id)
     *
     * position => optional, Position des Bildes (fortlaufend 1 bis x)
     *
     * descripton => optional, Title/Alt-Text des Bildes
     *
     * main => Wenn 1 übergeben wird, wird das Bild zum Hauptbild (für Übersichten etc.)
     *
     * image => Http-Link oder lokaler Pfad zum Bild
     *
     * <code>
     *
     * Beispiel Laden von lokalen Bildern:
     *	foreach ($article["images"] as $image)
     *   {
     *    $image["articleID"] = $image["articleID"];
     *    $image["main"] = $image["mainpicture"];
     *    $image["image"] = $api->load("file://".$api->sPath."/engine/connectors/api/sample/images/".$image["file"]);
     *    $import->sArticleImage($image);
     *   }
     *
     * Beispiel Laden von externen Bildern:
     * foreach ($article["images"] as $image)
     *	{
     * 		$image["articleID"] = $image["articleID"];
     * 		$image["main"] = $image["mainpicture"];
     * 		$image["image"] = $api->load("ftp://*****:*****@example.org/httpdocs/dbase/images/articles/".$image["file"]);
     * 		$import->sArticleImage($image);
     *  }
     *
     * </code>
     * @access public
     * @return
     */
    function sArticleImage($article_image = array()) {
        // Some initial checks
        if (empty($article_image)||!is_array($article_image))
            return false;
        if(isset($article_image["link"]))
            $article_image["image"] = $article_image["link"];
        if(isset($article_image["albumID"]))
            $article_image["albumID"] = (int) $article_image["albumID"];
        if(isset($article_image['articleID']))
            $article_image['articleID'] = intval($article_image['articleID']);
        if(empty($article_image['articleID'])||(empty($article_image['image'])&&empty($article_image['name'])))
            return false;
        if(!empty($article_image['position']))
            $article_image['position'] = intval($article_image['position']);
        else
            $article_image['position'] = 0;
        if(empty($article_image['description']))
            $article_image['description'] = '';
        if(empty($article_image['relations']))
            $article_image['relations'] = '';

        // Checks for main flag
        if(!empty($article_image['main'])&&$article_image['main']==1)
            $article_image['main'] = 1;
        elseif(!empty($article_image['main']))
            $article_image['main'] = 2;
        // If main is not set and no other article image is main, set this to be main
        if(empty($article_image['main']))
        {
            $sql = "SELECT id FROM s_articles_img WHERE articleID={$article_image['articleID']} AND main=1";
            $row = $this->sDB->GetRow($sql);
            if(empty($row['id']))
                $article_image['main'] = 1;
            else
                $article_image['main'] = 2;
        // if this article image is set to be main, set all other images to be not-main
        } elseif($article_image['main']==1) {
            $sql = "UPDATE s_articles_img SET main=2 WHERE articleID={$article_image['articleID']}";
            $this->sDB->Execute($sql);
        }

        // First copy the image to temp dir
        $uploadDir = Shopware()->DocPath('media_' . 'temp');
        // If no name is set, choose a random one
        if(empty($article_image['name']))
        {
            $article_image['name'] =  md5(uniqid(mt_rand(), true));
        }

        // Copy image to local temp dir
        if(!empty($article_image['image']))
        {
            $uploadFile = $uploadDir.$article_image['name'].'.tmp';
            if(!copy($article_image['image'], $uploadFile))
            {
                $this->sAPI->sSetError("Copy image from '{$article_image['image']}' to '$uploadFile' not work", 10400);
                return false;
            }
        }
        else
        {
            foreach (array('png', 'gif', 'jpg') as $test)
            {
                if (file_exists($uploadDir.$article_image['name'].'.'.$test))
                {
                    $extension = $test;
                    $uploadFile = $uploadDir.$article_image['name'].'.'.$test;
                    break;
                }
            }
            if(empty($uploadFile))
            {
                $this->sAPI->sSetError("Image source '$uploadFile' not found", 10401);
                return false;
            }
        }

        // Create new Media object and set the image
        $media = new \Shopware\Models\Media\Media();
        $file = new \Symfony\Component\HttpFoundation\File\File($uploadFile);

        $media->setDescription($article_image['description']);
        $media->setCreated(new DateTime());

        $identity = Shopware()->Auth()->getIdentity();
        if ($identity !== null)
        {
            $media->setUserId($identity->id);
        } else {
            $media->setUserId(0);
        }

        //set the upload file into the model. The model saves the file to the directory
        $media->setFile($file);

        // Set article
        $articleRepository = $this->getArticleRepository();
        $article = $articleRepository->find((int) $article_image['articleID']);
        if($article === null) {
            $this->sAPI->sSetError("Article '{$article_image['articleID']}' not found", 10404);
            return false;
        }
        $media->setArticles($article);
        //set media album, if no one passed set the unsorted album.
        if (isset($article_image["albumID"])) {
            $media->setAlbumId($article_image["albumID"]);
            $media->setAlbum(Shopware()->Models()->find('Shopware\Models\Media\Album', $article_image["albumID"]));
        } else {
            $media->setAlbumId(-1);
            $media->setAlbum(Shopware()->Models()->find('Shopware\Models\Media\Album', -1));
        }

        // Create new article image object and set values
        $articleImage = new \Shopware\Models\Article\Image();
        // Get image infos for the article image
        list($width, $height, $type, $attr) = getimagesize($uploadFile);
        // ArticleImage does not get these infos automatically from media, so we set them manually
        $articleImage->setDescription($article_image['description']);
        $articleImage->setMedia($media);
        $articleImage->setArticle($article);
        $articleImage->setWidth($width);
        $articleImage->setHeight($height);
        $articleImage->setHeight($height);
        $articleImage->setPath($article_image['name']);
        $articleImage->setExtension($media->getExtension());
        $articleImage->setPosition($article_image['position']);
        $articleImage->setMain($article_image['main']);
        $articleImage->setRelations($article_image['relations']);

        $article->setImages($articleImage);

        Shopware()->Models()->persist($media);
        Shopware()->Models()->persist($article);
        Shopware()->Models()->persist($articleImage);
        Shopware()->Models()->flush();

        return $articleImage->getId();

    }