/** * @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; }
/** * @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; }
/** * Internal helper function to duplicate the image configuration from the passed article * to the new article. * @param $articleId * @param $newArticleId */ protected function duplicateArticleImages($articleId, $newArticleId) { $article = Shopware()->Models()->find('Shopware\\Models\\Article\\Article', $newArticleId); $builder = Shopware()->Models()->createQueryBuilder(); $images = $builder->select(array('images', 'media', 'attribute', 'mappings', 'rules', 'option'))->from('Shopware\\Models\\Article\\Image', 'images')->leftJoin('images.attribute', 'attribute')->leftJoin('images.mappings', 'mappings')->leftJoin('images.media', 'media')->leftJoin('mappings.rules', 'rules')->leftJoin('rules.option', 'option')->where('images.articleId = ?1')->andWhere('images.parentId IS NULL')->setParameter(1, $articleId)->getQuery()->getArrayResult(); foreach ($images as &$data) { if (!empty($data['mappings'])) { foreach ($data['mappings'] as $mappingKey => $mapping) { foreach ($mapping['rules'] as $ruleKey => $rule) { $option = Shopware()->Models()->find('\\Shopware\\Models\\Article\\Configurator\\Option', $rule['optionId']); if ($option) { $rule['option'] = $option; $data['mappings'][$mappingKey]['rules'][$ruleKey]['option'] = $option; } } } } if (!empty($data['mediaId'])) { $data['media'] = Shopware()->Models()->find('\\Shopware\\Models\\Media\\Media', $data['mediaId']); if (!$data['media']) { unset($data['media']); } } $image = new \Shopware\Models\Article\Image(); $image->fromArray($data); $image->setArticle($article); $image->setArticleDetail(null); Shopware()->Models()->persist($image); } Shopware()->Models()->flush(); }
/** * @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; }
/** * 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 */ public 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)); } else { $article_image['name'] = pathinfo($article_image['name'], PATHINFO_FILENAME); } // Copy image to local temp dir if (!empty($article_image['image'])) { $uploadFile = $uploadDir . $article_image['name']; if (!copy($article_image['image'], $uploadFile)) { $this->sAPI->sSetError("Copying image from '{$article_image['image']}' to '{$uploadFile}' did not work", 10400); return false; } // check the copied image if (getimagesize($uploadFile) === false) { unlink($uploadFile); $this->sAPI->sSetError("The file'{$uploadFile}' is not a valid image", 10402); 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(); // if ($article_image['relations'] !== '') { // $this->createImageRelationsFromArticleNumber($articleImage->getId(), $article->getId(), $article_image['relations']); // } return $articleImage->getId(); }