Example #1
0
 /**
  * Deletes all thumbnails from the given media object
  *
  * @param Media $media
  */
 public function removeMediaThumbnails(Media $media)
 {
     $thumbnails = $media->getThumbnailFilePaths();
     foreach ($thumbnails as $thumbnail) {
         $thumbnailPath = $this->rootDir . DIRECTORY_SEPARATOR . $thumbnail;
         if (file_exists($thumbnailPath)) {
             unlink($thumbnailPath);
         }
     }
 }
 /**
  * @param Media $media
  * @return bool
  */
 private function imageExists(Media $media)
 {
     $mediaService = Shopware()->Container()->get('shopware_media.media_service');
     return $mediaService->has(Shopware()->DocPath() . DIRECTORY_SEPARATOR . $media->getPath());
 }
Example #3
0
 /**
  * @param array $params
  * @return \Shopware\Models\Media\Media
  * @throws \Shopware\Components\Api\Exception\ValidationException
  * @throws \Exception
  */
 public function create(array $params)
 {
     $this->checkPrivilege('create');
     $params = $this->prepareMediaData($params);
     $media = new \Shopware\Models\Media\Media();
     $media->fromArray($params);
     $violations = $this->getManager()->validate($media);
     if ($violations->count() > 0) {
         throw new ApiException\ValidationException($violations);
     }
     $this->getManager()->persist($media);
     $this->flush();
     if ($media->getType() == MediaModel::TYPE_IMAGE) {
         /**@var $manager Manager */
         $manager = $this->getContainer()->get('thumbnail_manager');
         $manager->createMediaThumbnail($media, array(), true);
     }
     return $media;
 }
 /**
  * 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);
         }
     }
 }
Example #5
0
 /**
  * Internal helper function which is used to upload the passed image link
  * to the server and create a media object for the image.
  *
  * @param $link
  * @param $albumId
  * @throws \Shopware\Components\Api\Exception\CustomValidationException
  * @return MediaModel
  */
 public function internalCreateMediaByFileLink($link, $albumId = -1)
 {
     $name = pathinfo($link, PATHINFO_FILENAME);
     $path = $this->load($link, $name);
     $name = pathinfo($path, PATHINFO_FILENAME);
     $file = new File($path);
     $media = new MediaModel();
     $media->setAlbumId($albumId);
     $media->setFile($file);
     $media->setName($name);
     $media->setDescription('');
     $media->setCreated(new \DateTime());
     $media->setUserId(0);
     /**@var $album Album*/
     $album = $this->getManager()->find('Shopware\\Models\\Media\\Album', $albumId);
     if (!$album) {
         throw new ApiException\CustomValidationException(sprintf("Album by id %s not found", $albumId));
     }
     $media->setAlbum($album);
     try {
         //persist the model into the model manager this uploads and resizes the image
         $this->getManager()->persist($media);
     } catch (\Doctrine\ORM\ORMException $e) {
         throw new ApiException\CustomValidationException(sprintf("Some error occurred while loading your image"));
     }
     if ($media->getType() === MediaModel::TYPE_IMAGE) {
         /**@var $manager Manager */
         $manager = Shopware()->Container()->get('thumbnail_manager');
         $manager->createMediaThumbnail($media, array(), true);
     }
     return $media;
 }
Example #6
0
    /**
     * The uploadAction function is responsible for the uploading of media.
     * If no album id passed, the uploaded media is assigned to the unsorted album.
     *
     * @return bool
     */
    public function uploadAction()
    {
        $params = $this->Request()->getParams();

        //try to get the transferred file
        try {
			$file = $_FILES['fileId'];

			if($file['size'] < 1 && $file['error'] === 1 || empty($_FILES)){
				throw new Exception("The file exceeds the max file size.");
			}

			$fileInfo = pathinfo($file['name']);
			$fileExtension = strtolower($fileInfo['extension']);
			$file['name'] = $fileInfo['filename'].".".$fileExtension;
			$_FILES['fileId']['name'] = $file['name'];

            $fileBag = new \Symfony\Component\HttpFoundation\FileBag($_FILES);

            /**@var $file UploadedFile*/
            $file = $fileBag->get('fileId');

        }
        catch (Exception $e) {
            die(json_encode(array('success' => false, 'message' => $e->getMessage())));
        }
        if ($file === null) {
            die(json_encode(array('success' => false)));
        }

        $fileInfo = pathinfo($file->getClientOriginalName());
        $extension = $fileInfo['extension'];
        if (in_array(strtolower($extension), $this->blackList)) {
            unlink($file->getPathname());
            unlink($file);
            die(json_encode(array('success' => false, 'blacklist' => true, 'extension' => $extension)));
        }

        //create a new model and set the properties
        $media = new Media();
        $params['attribute'] = $params['attribute'][0];

        //set media album, if no one passed set the unsorted album.
        if (isset($params['albumID'])) {
            $media->setAlbumId($params['albumID']);
            $media->setAlbum(Shopware()->Models()->find('Shopware\Models\Media\Album', $params['albumID']));
        } else {
            $media->setAlbumId(-10);
            $media->setAlbum(Shopware()->Models()->find('Shopware\Models\Media\Album', -10));
        }

        $media->setDescription('');
        $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);

        try { //persist the model into the model manager
            Shopware()->Models()->persist($media);
            Shopware()->Models()->flush();
            $data = $this->getMedia($media->getId())->getQuery()->getArrayResult();
            $this->Response()->setHeader('Content-Type', 'text/plain');

            die(json_encode(array('success' => true, 'data' => $data[0])));
        }
        catch (\Doctrine\ORM\ORMException $e) {
            die(json_encode(array('success' => false, 'message' => $e->getMessage())));
        }

    }
 /**
  * {@inheritDoc}
  */
 public function setManyToOne($data, $model, $property)
 {
     $this->__initializer__ && $this->__initializer__->__invoke($this, 'setManyToOne', array($data, $model, $property));
     return parent::setManyToOne($data, $model, $property);
 }
Example #8
0
 /**
  * @param Media $media
  * @return Settings|null
  */
 private function getAlbumSettingsFromMedia(Media $media)
 {
     $album = $media->getAlbum();
     if (!$album) {
         return null;
     }
     $settings = $album->getSettings();
     if (!$settings) {
         return null;
     }
     return $settings;
 }
Example #9
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();
 }