Esempio n. 1
0
 private function getMediaModel()
 {
     $media = new \Shopware\Models\Media\Media();
     $imagePath = __DIR__ . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . 'sw_icon.png';
     $file = new \Symfony\Component\HttpFoundation\File\File($imagePath);
     $media->setFile($file);
     $media->setAlbumId(-10);
     $media->setAlbum(Shopware()->Models()->find('Shopware\\Models\\Media\\Album', -10));
     $media->setPath(str_replace(Shopware()->DocPath(), '', $imagePath));
     $media->setDescription('');
     $media->setUserId(0);
     return $media;
 }
Esempio n. 2
0
 private function getMediaModel()
 {
     $mediaService = Shopware()->Container()->get('shopware_media.media_service');
     $media = new \Shopware\Models\Media\Media();
     $sourcePath = __DIR__ . DIRECTORY_SEPARATOR . 'fixtures' . DIRECTORY_SEPARATOR . 'sw_icon.png';
     $imagePath = 'media/unknown/sw_icon.png';
     $mediaService->write($imagePath, file_get_contents($sourcePath));
     $file = new \Symfony\Component\HttpFoundation\File\File($sourcePath);
     $media->setFile($file);
     $media->setAlbumId(-10);
     $media->setAlbum(Shopware()->Models()->find('Shopware\\Models\\Media\\Album', -10));
     $media->setPath(str_replace(Shopware()->DocPath(), '', $imagePath));
     $media->setDescription('');
     $media->setUserId(0);
     return $media;
 }
Esempio n. 3
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;
    }
Esempio n. 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');
     $recreateImagesLater = array();
     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 {
             $name = pathinfo($imageData['image'], PATHINFO_FILENAME);
             $path = $this->load($imageData['image'], $name);
         } catch (\Exception $e) {
             $errors[] = sprintf("Could not load image {$imageData['image']}: %s", $e->getMessage());
             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->setName(pathinfo($imageData['image'], PATHINFO_FILENAME));
         $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[] = sprintf("Could not move image: %s", $e->getMessage());
             continue;
         }
         if (empty($imageData['main'])) {
             $imageData['main'] = 1;
         }
         //generate thumbnails
         if ($media->getType() == \Shopware\Models\Media\Media::TYPE_IMAGE) {
             /**@var $manager \Shopware\Components\Thumbnail\Manager */
             $manager = Shopware()->Container()->get('thumbnail_manager');
             $manager->createMediaThumbnail($media, array(), true);
         }
         $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()));
             }
             $recreateImagesLater[] = $article->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++;
     }
     try {
         // Clear the entity manager and rebuild images in order to get proper variant images
         Shopware()->Models()->clear();
         foreach ($recreateImagesLater as $articleId) {
             $this->recreateVariantImages($articleId);
         }
     } catch (\Exception $e) {
         $errors[] = sprintf("Error building variant images. If no other errors occurred, the images have been\n                uploaded but the image-variant mapping in the shop frontend might fail. Errormessage: %s", $e->getMessage());
     }
     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;
 }
Esempio n. 5
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;
    }
Esempio n. 6
0
 /**
  * Insert an article download
  *
  * @param unknown_type $article_download
  * @return unknown
  */
 public function sArticleDownload($article_download)
 {
     if (empty($article_download) || !is_array($article_download)) {
         return false;
     }
     $article_download['articleID'] = $this->sGetArticleID($article_download);
     if (empty($article_download['articleID'])) {
         return false;
     }
     if (empty($article_download["name"]) && empty($article_download["link"])) {
         return false;
     }
     if (empty($article_download["name"])) {
         $article_download["name"] = basename($article_download["link"]);
     }
     // In sw4 description will only be used for the media model.
     if (empty($article_download["description"])) {
         $article_download["description"] = basename($article_download["name"]);
     }
     if (!empty($article_download["link"])) {
         $article_download["new_link"] = Shopware()->DocPath('media_' . 'temp') . basename($article_download["link"]);
     } else {
         $article_download["new_link"] = Shopware()->DocPath('media_' . 'temp') . $article_download["name"];
     }
     if (strpos($article_download["link"], Shopware()->DocPath('media_' . 'temp')) !== false) {
         $this->sAPI->sSetError("Please don't copy your source files to media/temp", 10410);
         return false;
     }
     if (!empty($article_download["link"])) {
         if (file_exists($article_download["new_link"])) {
             unlink($article_download["new_link"]);
         }
         if (!copy($article_download["link"], $article_download["new_link"])) {
             return false;
         }
         if (!empty($article_download["unlink"]) && file_exists($article_download["link"])) {
             unlink($article_download["link"]);
         }
     } else {
         if (!file_exists($article_download["new_link"])) {
             return false;
         }
     }
     $article_download["size"] = filesize($article_download["new_link"]);
     $article_download["name"] = $article_download["name"];
     // Create new Media object and set the download
     $media = new \Shopware\Models\Media\Media();
     $file = new \Symfony\Component\HttpFoundation\File\File($article_download["new_link"]);
     $media->setDescription($article_download['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);
     $pathInfo = pathinfo($article_download["new_link"]);
     if ($media->getExtension() === null && $pathInfo['extension'] === null) {
         $this->sAPI->sSetError("In SW4 files must have an extension", 10409);
         return false;
     } elseif ($pathInfo['extension'] !== null) {
         $media->setExtension($pathInfo['extension']);
     }
     // Set article
     $articleRepository = $this->getArticleRepository();
     $article = $articleRepository->find((int) $article_download['articleID']);
     if ($article === null) {
         $this->sAPI->sSetError("Article '{$article_download['articleID']}' not found", 10408);
         return false;
     }
     $media->setArticles($article);
     //set media album, if no one passed set the unsorted album.
     if (isset($article_download["albumID"])) {
         $media->setAlbumId($article_download["albumID"]);
         $media->setAlbum(Shopware()->Models()->find('Shopware\\Models\\Media\\Album', $article_download["albumID"]));
     } else {
         $media->setAlbumId(-10);
         $media->setAlbum(Shopware()->Models()->find('Shopware\\Models\\Media\\Album', -10));
     }
     // Create new article download object and set values
     $articleDownload = new \Shopware\Models\Article\Download();
     // ArticleDownload does not get these infos automatically from media, so we set them manually
     $articleDownload->setArticle($article);
     $articleDownload->setSize($article_download["size"]);
     $articleDownload->setFile($media->getPath());
     $articleDownload->setName($article_download["name"]);
     $article->setDownloads($articleDownload);
     Shopware()->Models()->persist($media);
     Shopware()->Models()->persist($article);
     Shopware()->Models()->persist($articleDownload);
     Shopware()->Models()->flush();
     return (int) $articleDownload->getId();
 }