public function getCollectors() { if (empty($this->collectors)) { $this->collectors = [new GeneralCollector(), new PHPCollector(), new UserCollector(), new SmartyCollector(), new EventCollector(), new DBCollector(), new ConfigCollector(), new ExceptionCollector()]; $this->collectors = $this->events->filter('Profiler_onCollectCollectors', $this->collectors); } return $this->collectors; }
/** * @param string $event * @param mixed $value * @param null $eventArgs * @return mixed * @throws Enlight_Event_Exception */ public function filter($event, $value, $eventArgs = null) { if (isset($eventArgs) && is_array($eventArgs)) { $eventArgs = new Enlight_Event_EventArgs($eventArgs); } elseif (!isset($eventArgs)) { $eventArgs = new Enlight_Event_EventArgs(); } elseif (!$eventArgs instanceof Enlight_Event_EventArgs) { throw new Enlight_Event_Exception('Parameter "eventArgs" must be an instance of "Enlight_Event_EventArgs"'); } $eventArgs->setReturn($value); $this->getPluginBootstrap()->addEvent($event, 'filter', $this->getListeners($event), $eventArgs); return $this->events->filter($event, $value, $eventArgs); }
/** * Helper for sAdmin::sSaveRegister() * Validates fields. Throws exception if any field is missing * * @param $register Registration data * @throws Enlight_Exception If validation fails */ private function validateRegistrationFields($register) { $neededFields = array("auth" => array("email", "password"), "billing" => array("salutation", "firstname", "lastname", "street", "zipcode", "city", "country"), "payment" => array("object" => array("id"))); $neededFields = $this->eventManager->filter('Shopware_Modules_Admin_SaveRegister_FilterNeededFields', $neededFields, array('subject' => $this)); // Check for needed fields foreach ($neededFields as $sectionKey => $sectionFields) { foreach ($neededFields[$sectionKey] as $fieldKey => $fieldValue) { if (is_array($fieldValue)) { $objKey = $fieldValue[0]; if (empty($register[$sectionKey][$fieldKey][$objKey])) { $errorFields[] = $sectionKey . "#1({$sectionKey})({$fieldKey})({$objKey})->" . $fieldValue; } } else { if (empty($register[$sectionKey][$fieldValue])) { $errorFields[] = $sectionKey . "#2->" . $fieldValue; } } } } $errorFields = $this->eventManager->filter('Shopware_Modules_Admin_SaveRegister_FilterErrors', $errorFields, array('subject' => $this)); // Check for errors if (count($errorFields)) { if (!$_COOKIE["SHOPWARESID"]) { $noCookies = "NO SESSION-COOKIE"; } throw new Enlight_Exception("sSaveRegister #00: Fields are missing {$noCookies} - " . $this->session->offsetGet('sessionId') . " - " . print_r($errorFields, true)); } }
/** * Returns all config elements of the passed template. * * @param \Shopware\Models\Shop\Template $template * @return ArrayCollection */ private function getElements(Shop\Template $template) { $builder = $this->entityManager->createQueryBuilder(); $builder->select('elements')->from('Shopware\\Models\\Shop\\TemplateConfig\\Element', 'elements')->where('elements.templateId = :templateId')->setParameter('templateId', $template->getId()); $elements = $builder->getQuery()->getResult(); $elements = $this->eventManager->filter('Theme_Configurator_Elements_Loaded', $elements, array('template' => $template)); return new ArrayCollection($elements); }
/** * @param string $templateDir * @param int|null $key * @return string */ public function resolveTemplateDir($templateDir, $key = null) { if ($this->eventManager !== null) { $templateDir = $this->eventManager->filter(__CLASS__ . '_ResolveTemplateDir', $templateDir, array('subject' => $this, 'key' => $key)); } $templateDir = Enlight_Loader::isReadable($templateDir); return $templateDir; }
/** * Builds the configuration for the less compiler class. * * @param \Shopware\Models\Shop\Shop $shop * @return array */ private function getCompilerConfiguration(Shop\Shop $shop) { $settings = $this->service->getSystemConfiguration(AbstractQuery::HYDRATE_OBJECT); $config = array('compress' => $settings->getCompressCss(), 'sourceMap' => $settings->getCreateSourceMap()); if ($settings->getCreateSourceMap()) { $config += array('sourceMapWriteTo' => $this->pathResolver->getSourceMapPath(), 'sourceMapURL' => $this->pathResolver->getSourceMapUrl($shop)); } $config = $this->eventManager->filter('Theme_Compiler_Configure', $config, array('shop' => $shop, 'settings' => $settings)); return $config; }
/** * Following events are deprecated and only implemented for backward compatibility to shopware 4 * Removed with shopware 5.1 * * @param array $product * @param \sArticles $module * @return array|mixed */ public function fireArticleByIdEvents(array $product, \sArticles $module) { $getArticle = $product; $context = $this->contextService->getShopContext(); if ($getArticle["pricegroupActive"]) { $getArticle["priceBeforePriceGroup"] = $getArticle["price"]; $getArticle["price"] = $this->eventManager->filter('sArticles::sGetPricegroupDiscount::replace', $getArticle["price"], array('subject' => $module, 'customergroup' => $context->getCurrentCustomerGroup()->getKey(), 'groupID' => $getArticle["pricegroupID"], 'listprice' => $getArticle["price"], 'quantity' => 1, 'doMatrix' => false)); $getArticle["price"] = $this->eventManager->filter('sArticles::sGetPricegroupDiscount::after', $getArticle["price"], array('subject' => $module, 'customergroup' => $context->getCurrentCustomerGroup()->getKey(), 'groupID' => $getArticle["pricegroupID"], 'listprice' => $getArticle["price"], 'quantity' => 1, 'doMatrix' => false)); $getArticle["sBlockPrices"] = $this->eventManager->filter('sArticles::sGetPricegroupDiscount::replace', $getArticle["sBlockPrices"], array('subject' => $module, 'customergroup' => $context->getCurrentCustomerGroup()->getKey(), 'groupID' => $getArticle["pricegroupID"], 'listprice' => $getArticle["price"], 'quantity' => 1, 'doMatrix' => true)); $getArticle["sBlockPrices"] = $this->eventManager->filter('sArticles::sGetPricegroupDiscount::after', $getArticle["sBlockPrices"], array('subject' => $module, 'customergroup' => $context->getCurrentCustomerGroup()->getKey(), 'groupID' => $getArticle["pricegroupID"], 'listprice' => $getArticle["price"], 'quantity' => 1, 'doMatrix' => true)); } else { foreach ($getArticle["sBlockPrices"] as &$blockPrice) { $blockPrice["price"] = $this->eventManager->filter('sArticles::sCalculatingPrice::replace', $blockPrice["price"], array('subject' => $module, 'price' => $blockPrice["price"], 'tax' => $getArticle["tax"], 'taxId' => $getArticle["taxID"], 'article' => $getArticle)); $blockPrice["price"] = $this->eventManager->filter('sArticles::sCalculatingPrice::after', $blockPrice["price"], array('subject' => $module, 'price' => $blockPrice["price"], 'tax' => $getArticle["tax"], 'taxId' => $getArticle["taxID"], 'article' => $getArticle)); if (!$blockPrice['pseudoprice']) { continue; } $blockPrice["pseudoprice"] = $this->eventManager->filter('sArticles::sCalculatingPrice::replace', $blockPrice["pseudoprice"], array('subject' => $module, 'price' => $blockPrice["pseudoprice"], 'tax' => $getArticle["tax"], 'taxId' => $getArticle["taxID"], 'article' => $getArticle)); $blockPrice["pseudoprice"] = $this->eventManager->filter('sArticles::sCalculatingPrice::after', $blockPrice["pseudoprice"], array('subject' => $module, 'price' => $blockPrice["pseudoprice"], 'tax' => $getArticle["tax"], 'taxId' => $getArticle["taxID"], 'article' => $getArticle)); } } $getArticle = Enlight()->Events()->filter('Shopware_Modules_Articles_GetArticleById_FilterArticle', $getArticle, array('subject' => $module, 'id' => $product['articleID'], 'customergroup' => $context->getCurrentCustomerGroup()->getKey())); if ($getArticle["unitID"]) { $getArticle["sUnit"] = $this->eventManager->filter('sArticles::sGetUnit::replace', $getArticle["sUnit"], array('subject' => $module, 'id' => $getArticle["unitID"])); $getArticle["sUnit"] = $this->eventManager->filter('sArticles::sGetUnit::after', $getArticle["sUnit"], array('subject' => $module, 'id' => $getArticle["unitID"])); } // Get cheapest price $getArticle["priceStartingFrom"] = $this->eventManager->filter('sArticles::sGetCheapestPrice::replace', $getArticle["priceStartingFrom"], array('subject' => $module, 'article' => $getArticle["articleID"], 'group' => $getArticle["pricegroup"], 'pricegroup' => $getArticle["pricegroupID"], 'usepricegroups' => $getArticle["pricegroupActive"])); // Get cheapest price $getArticle["priceStartingFrom"] = $this->eventManager->filter('sArticles::sGetCheapestPrice::after', $getArticle["priceStartingFrom"], array('subject' => $module, 'article' => $getArticle["articleID"], 'group' => $getArticle["pricegroup"], 'pricegroup' => $getArticle["pricegroupID"], 'usepricegroups' => $getArticle["pricegroupActive"])); if ($getArticle["price"]) { $getArticle["price"] = $this->eventManager->filter('sArticles::sCalculatingPrice::replace', $getArticle["price"], array('subject' => $module, 'price' => $getArticle["price"], 'tax' => $getArticle["tax"], 'taxId' => $getArticle["taxID"], 'article' => $getArticle)); $getArticle["price"] = $this->eventManager->filter('sArticles::sCalculatingPrice::after', $getArticle["price"], array('subject' => $module, 'price' => $getArticle["price"], 'tax' => $getArticle["tax"], 'taxId' => $getArticle["taxID"], 'article' => $getArticle)); } $getArticle["image"] = $this->eventManager->filter('sArticles::sGetArticlePictures::replace', $getArticle["image"], array('subject' => $module, 'sArticleID' => $getArticle["articleID"], 'onlyCover' => true, 'pictureSize' => 4, 'ordernumber' => $getArticle['ordernumber'])); $getArticle["image"] = $this->eventManager->filter('sArticles::sGetArticlePictures::after', $getArticle["image"], array('subject' => $module, 'sArticleID' => $getArticle["articleID"], 'onlyCover' => true, 'pictureSize' => 4, 'ordernumber' => $getArticle['ordernumber'])); $getArticle["images"] = $this->eventManager->filter('sArticles::sGetArticlePictures::replace', $getArticle["images"], array('subject' => $module, 'sArticleID' => $getArticle["articleID"], 'onlyCover' => false, 'pictureSize' => 0, 'ordernumber' => $getArticle['ordernumber'])); $getArticle["images"] = $this->eventManager->filter('sArticles::sGetArticlePictures::after', $getArticle["images"], array('subject' => $module, 'sArticleID' => $getArticle["articleID"], 'onlyCover' => false, 'pictureSize' => 0, 'ordernumber' => $getArticle['ordernumber'])); $getArticle["sVoteAverange"] = $this->eventManager->filter('sArticles::sGetArticlesAverangeVote::replace', $getArticle["sVoteAverange"], array('subject' => $module, 'article' => $getArticle["articleID"])); $getArticle["sVoteAverange"] = $this->eventManager->filter('sArticles::sGetArticlesAverangeVote::after', $getArticle["sVoteAverange"], array('subject' => $module, 'article' => $getArticle["articleID"])); $getArticle["sVoteComments"] = $this->eventManager->filter('sArticles::sGetArticlesVotes::replace', $getArticle["sVoteComments"], array('subject' => $module, 'article' => $getArticle["articleID"])); $getArticle["sVoteComments"] = $this->eventManager->filter('sArticles::sGetArticlesVotes::after', $getArticle["sVoteComments"], array('subject' => $module, 'article' => $getArticle["articleID"])); if (!empty($getArticle["filtergroupID"]) && $this->displayFiltersOnArticleDetailPage()) { $getArticle["sProperties"] = $this->eventManager->filter('sArticles::sGetArticleProperties::replace', $getArticle["sProperties"], array('subject' => $module, 'articleId' => $getArticle["articleID"], 'filterGroupId' => $getArticle["filtergroupID"])); $getArticle["sProperties"] = $this->eventManager->filter('sArticles::sGetArticleProperties::after', $getArticle["sProperties"], array('subject' => $module, 'articleId' => $getArticle["articleID"], 'filterGroupId' => $getArticle["filtergroupID"])); } $getArticle = Enlight()->Events()->filter('Shopware_Modules_Articles_GetArticleById_FilterResult', $getArticle, array('subject' => $module, 'id' => $getArticle["articleID"], 'isBlog' => false, 'customergroup' => $context->getCurrentCustomerGroup()->getKey())); return $getArticle; }
/** * Get article data for sAddArticle * * @param int $id Article ordernumber * @return array|false Article data, or false if none found */ private function getArticleForAddArticle($id) { $sql = "\n SELECT s_articles.id AS articleID, name AS articleName, taxID,\n additionaltext, s_articles_details.shippingfree, laststock, instock,\n s_articles_details.id as articledetailsID, ordernumber\n FROM s_articles, s_articles_details\n WHERE s_articles_details.ordernumber = ?\n AND s_articles_details.articleID = s_articles.id\n AND s_articles.active = 1\n AND (\n SELECT articleID\n FROM s_articles_avoid_customergroups\n WHERE articleID = s_articles.id AND customergroupID = ?\n ) IS NULL\n "; $article = $this->db->fetchRow($sql, array($id, $this->sSYSTEM->sUSERGROUPDATA["id"])); $article = $this->eventManager->filter('Shopware_Modules_Basket_getArticleForAddArticle_FilterArticle', $article, array("id" => $id, 'subject' => $this, "partner" => $this->sSYSTEM->_SESSION["sPartner"])); if (!$article) { return false; } $name = $this->moduleManager->Articles()->sGetArticleNameByOrderNumber($article["ordernumber"], true); if (!empty($name)) { $article["articleName"] = $name["articleName"]; $article["additionaltext"] = $name["additionaltext"]; } return $article; }
/** * Generates the Theme.php file for the theme. * * @param array $data * @param Template $parent */ private function generateThemePhp(array $data, Template $parent = null) { $source = str_replace('$TEMPLATE$', $data['template'], $this->phpSource); if ($parent instanceof Template) { $source = str_replace('$PARENT$', $parent->getTemplate(), $source); } else { $source = str_replace('$PARENT$', 'null', $source); } $source = $this->replacePlaceholder('name', $data['name'], $source); $source = $this->replacePlaceholder('author', $data['author'], $source); $source = $this->replacePlaceholder('license', $data['license'], $source); $source = $this->replacePlaceholder('description', $data['description'], $source); $output = new \SplFileObject($this->getThemeDirectory($data['template']) . DIRECTORY_SEPARATOR . 'Theme.php', "w+"); $source = $this->eventManager->filter('Theme_Generator_Theme_Source_Generated', $source, array('data' => $data, 'parent' => $parent)); $output->fwrite($source); }
/** * Get article data for sAddArticle * * @param int $id Article ordernumber * @return array|false Article data, or false if none found */ private function getArticleForAddArticle($id) { $sql = "\n SELECT s_articles.id AS articleID, s_articles.main_detail_id, name AS articleName, taxID,\n additionaltext, s_articles_details.shippingfree, laststock, instock,\n s_articles_details.id as articledetailsID, ordernumber,\n s_articles.configurator_set_id\n FROM s_articles, s_articles_details\n WHERE s_articles_details.ordernumber = ?\n AND s_articles_details.articleID = s_articles.id\n AND s_articles.active = 1\n AND (\n SELECT articleID\n FROM s_articles_avoid_customergroups\n WHERE articleID = s_articles.id AND customergroupID = ?\n ) IS NULL\n "; $article = $this->db->fetchRow($sql, array($id, $this->sSYSTEM->sUSERGROUPDATA["id"])); $article = $this->eventManager->filter('Shopware_Modules_Basket_getArticleForAddArticle_FilterArticle', $article, array("id" => $id, 'subject' => $this, "partner" => $this->sSYSTEM->_SESSION["sPartner"])); if (!$article) { return false; } $article = $this->moduleManager->Articles()->sGetTranslation($article, $article['articleID'], "article"); $article = $this->moduleManager->Articles()->sGetTranslation($article, $article['articledetailsID'], "variant"); if ($article['configurator_set_id'] > 0) { $context = $this->contextService->getProductContext(); $product = Shopware()->Container()->get('shopware_storefront.list_product_service')->get($article['ordernumber'], $context); $product = $this->additionalTextService->buildAdditionalText($product, $context); $article['additionaltext'] = $product->getAdditional(); } return $article; }
/** * Method to generate a single thumbnail. * * First it loads an image from the media path, * then resizes it and saves it to the default thumbnail directory * * @param Media $media * @param array $thumbnailSizes - array of all sizes which needs to be generated * @param bool $keepProportions - Whether or not keeping the proportions of the original image, the size can be affected when true * @throws \Exception * @return bool */ public function createMediaThumbnail(Media $media, $thumbnailSizes = array(), $keepProportions = false) { if ($media->getType() !== $media::TYPE_IMAGE) { throw new \Exception("File is not an image."); } if (empty($thumbnailSizes)) { $thumbnailSizes = $this->getThumbnailSizesFromMedia($media); $thumbnailSizes = array_merge($thumbnailSizes, $media->getDefaultThumbnails()); } $albumSettings = $this->getAlbumSettingsFromMedia($media); if ($albumSettings) { $highDpi = $albumSettings->isThumbnailHighDpi(); $standardQuality = $albumSettings->getThumbnailQuality(); $highDpiQuality = $albumSettings->getThumbnailHighDpiQuality(); } else { $highDpi = false; $standardQuality = 90; $highDpiQuality = 90; } $thumbnailSizes = $this->uniformThumbnailSizes($thumbnailSizes); $imagePath = $media->getPath(); $parameters = array('path' => $imagePath, 'sizes' => $thumbnailSizes, 'keepProportions' => $keepProportions); if ($this->eventManager) { $parameters = $this->eventManager->filter('Shopware_Components_Thumbnail_Manager_CreateThumbnail', $parameters, array('subject' => $this, 'media' => $media)); } foreach ($parameters['sizes'] as $size) { $suffix = $size['width'] . 'x' . $size['height']; $destinations = $this->getDestination($media, $suffix); foreach ($destinations as $destination) { $this->generator->createThumbnail($parameters['path'], $destination, $size['width'], $size['height'], $parameters['keepProportions'], $standardQuality); } } if (!$highDpi) { return; } foreach ($parameters['sizes'] as $size) { $suffix = $size['width'] . 'x' . $size['height'] . '@2x'; $destinations = $this->getDestination($media, $suffix); foreach ($destinations as $destination) { $this->generator->createThumbnail($parameters['path'], $destination, $size['width'] * 2, $size['height'] * 2, $parameters['keepProportions'], $highDpiQuality); } } }
/** * @param StoreFrontBundle\Struct\Media $media * @return array */ public function convertMediaStruct(StoreFrontBundle\Struct\Media $media) { if (!$media instanceof StoreFrontBundle\Struct\Media) { return []; } $thumbnails = []; foreach ($media->getThumbnails() as $thumbnail) { $retina = null; $thumbnails[] = ['source' => $thumbnail->getSource(), 'retinaSource' => $retina, 'sourceSet' => $this->getSourceSet($thumbnail), 'maxWidth' => $thumbnail->getMaxWidth(), 'maxHeight' => $thumbnail->getMaxHeight()]; } $data = array('id' => $media->getId(), 'position' => 1, 'source' => $media->getFile(), 'description' => $media->getName(), 'extension' => $media->getExtension(), 'main' => $media->isPreview(), 'parentId' => null, 'width' => $media->getWidth(), 'height' => $media->getHeight(), 'thumbnails' => $thumbnails); $attributes = $media->getAttributes(); if ($attributes && isset($attributes['image'])) { $data['attribute'] = $attributes['image']->toArray(); unset($data['attribute']['id']); unset($data['attribute']['imageID']); } else { $data['attribute'] = []; } return $this->eventManager->filter('Legacy_Struct_Converter_Convert_Media', $data, ['media' => $media]); }
/** * Method to generate a single thumbnail. * First it loads an image from the media path, * then resizes it and saves it to the default thumbnail directory * * @param Media $media * @param array $thumbnailSizes - array of all sizes which needs to be generated * @param bool $keepProportions - Whether or not keeping the proportions of the original image, the size can be affected when true * @throws \Exception * @return bool */ public function createMediaThumbnail(Media $media, $thumbnailSizes = array(), $keepProportions = false) { if ($media->getType() !== $media::TYPE_IMAGE) { throw new \Exception("File is not an image."); } if (!is_writable($this->getThumbnailDir($media))) { throw new \Exception("Thumbnail directory is not writable"); } if (empty($thumbnailSizes)) { $album = $media->getAlbum(); if (!$album) { throw new \Exception("No album configured for the passed media object and no size passed!"); } $settings = $album->getSettings(); if (!$settings) { throw new \Exception("No settings configured in the album of the given media object!"); } $settingSizes = $settings->getThumbnailSize(); //when no sizes are defined in the album if (empty($settingSizes) || empty($settingSizes[0])) { $settingSizes = array(); } $thumbnailSizes = array_merge($thumbnailSizes, $settingSizes); } $thumbnailSizes = array_merge($thumbnailSizes, $media->getDefaultThumbnails()); $thumbnailSizes = $this->uniformThumbnailSizes($thumbnailSizes); $imagePath = $this->rootDir . DIRECTORY_SEPARATOR . $media->getPath(); $parameters = array('path' => $imagePath, 'sizes' => $thumbnailSizes, 'keepProportions' => $keepProportions); if ($this->eventManager) { $parameters = $this->eventManager->filter('Shopware_Components_Thumbnail_Manager_CreateThumbnail', $parameters, array('subject' => $this, 'media' => $media)); } foreach ($parameters['sizes'] as $size) { $suffix = $size['width'] . 'x' . $size['height']; $destinations = $this->getDestination($media, $suffix); foreach ($destinations as $destination) { $this->generator->createThumbnail($parameters['path'], $destination, $size['width'], $size['height'], $parameters['keepProportions']); } } }
/** * Returns a result which displays the total order amount per customer gorup. * @param \DateTime $from * @param \DateTime $to * @param array $shopIds * @return Result */ public function getCustomerGroupAmount(\DateTime $from = null, \DateTime $to = null, array $shopIds = array()) { $builder = $this->createCustomerGroupAmountBuilder($from, $to, $shopIds); $builder = $this->eventManager->filter('Shopware_Analytics_CustomerGroupAmount', $builder, array('subject' => $this)); return new Result($builder); }
/** * @param array $records * @throws \Enlight_Event_Exception * @throws \Exception * @throws \Zend_Db_Adapter_Exception */ public function write($records) { $customerCount = 0; if (empty($records)) { $message = SnippetsHelper::getNamespace()->get('adapters/customer/no_records', 'No customer records were found.'); throw new \Exception($message); } $records = $this->eventManager->filter('Shopware_Components_SwagImportExport_DbAdapters_CustomerDbAdapter_Write', $records, ['subject' => $this]); $defaultValues = $this->getDefaultValues(); foreach ($records['default'] as $record) { try { $customerCount++; $record = $this->validator->filterEmptyString($record); $customer = $this->findExistingEntries($record); $createNewCustomer = false; if (!$customer instanceof Customer) { $createNewCustomer = true; $record = $this->dataManager->setDefaultFieldsForCreate($record, $defaultValues); $this->validator->checkRequiredFieldsForCreate($record); $customer = new Customer(); } $this->preparePassword($record); $this->validator->checkRequiredFields($record); $this->validator->validate($record, CustomerDataType::$mapper); $customerData = $this->prepareCustomer($record); $customerData['billing'] = $this->prepareBilling($record); $customerData['shipping'] = $this->prepareShipping($record, $createNewCustomer, $customerData['billing']); $customer->fromArray($customerData); if (isset($customerData['subshopID'])) { $shop = $this->manager->getRepository(Shop::class)->find($customerData['subshopID']); if (!$shop) { $message = SnippetsHelper::getNamespace()->get('adapters/shop_not_found', 'Shop with id %s was not found'); throw new AdapterException(sprintf($message, $customerData['subshopID'])); } $customer->setShop($shop); } if (isset($customerData['languageId'])) { $languageSubShop = $this->manager->getRepository(Shop::class)->find($customerData['languageId']); if (!$languageSubShop) { $message = SnippetsHelper::getNamespace()->get('adapters/language_shop_not_found', 'Language-Shop with id %s was not found'); throw new AdapterException(sprintf($message, $customerData['languageId'])); } $customer->setLanguageSubShop($languageSubShop); } $billing = $customer->getDefaultBillingAddress(); if (!$billing instanceof Address) { $billing = new Address(); $billing->setCustomer($customer); } if (isset($customerData['billing']['countryId'])) { $customerData['billing']['country'] = $this->manager->find(Country::class, $customerData['billing']['countryId']); } if (isset($customerData['billing']['stateId'])) { $customerData['billing']['state'] = $this->manager->find(State::class, $customerData['billing']['stateId']); } $billing->fromArray($customerData['billing']); $shipping = $customer->getDefaultShippingAddress(); if (!$shipping instanceof Address) { $shipping = new Address(); $shipping->setCustomer($customer); } if (isset($customerData['shipping']['countryId'])) { $customerData['shipping']['country'] = $this->manager->find(Country::class, $customerData['shipping']['countryId']); } if (isset($customerData['shipping']['stateId'])) { $customerData['shipping']['state'] = $this->manager->find(State::class, $customerData['shipping']['stateId']); } $shipping->fromArray($customerData['shipping']); $customer->setFirstname($billing->getFirstname()); $customer->setLastname($billing->getLastname()); $customer->setSalutation($billing->getSalutation()); $customer->setTitle($billing->getTitle()); $violations = $this->manager->validate($customer); if ($violations->count() > 0) { $message = SnippetsHelper::getNamespace()->get('adapters/customer/no_valid_customer_entity', 'No valid user entity for email %s'); $message = sprintf($message, $customer->getEmail()); foreach ($violations as $violation) { $message .= "\n" . $violation->getPropertyPath() . ': ' . $violation->getMessage(); } throw new AdapterException($message); } $this->manager->persist($customer); if ($createNewCustomer) { $this->manager->flush(); } $customer->setDefaultBillingAddress($billing); $this->manager->persist($billing); $customer->setDefaultShippingAddress($shipping); $this->manager->persist($shipping); $this->insertCustomerAttributes($customerData, $customer->getId(), $createNewCustomer); if ($customerCount % 20 === 0) { $this->manager->flush(); } } catch (AdapterException $e) { $message = $e->getMessage(); $this->saveMessage($message); } } $this->manager->flush(); }
/** * Create status mail * * @param int $orderId * @param int $statusId * @param string $templateName * @return Enlight_Components_Mail */ public function createStatusMail($orderId, $statusId, $templateName = null) { $statusId = (int) $statusId; $orderId = (int) $orderId; if (empty($templateName)) { $templateName = 'sORDERSTATEMAIL' . $statusId; } if (empty($orderId) || !is_numeric($statusId)) { return; } $order = $this->getOrderForStatusMail($orderId); $orderDetails = $this->getOrderDetailsForStatusMail($orderId); if (!empty($order['dispatchID'])) { $dispatch = $this->db->fetchRow(' SELECT name, description FROM s_premium_dispatch WHERE id=? ', array($order['dispatchID'])); } $user = $this->getCustomerInformationByOrderId($orderId); if (empty($order) || empty($orderDetails) || empty($user)) { return; } $repository = Shopware()->Models()->getRepository('Shopware\\Models\\Shop\\Shop'); $shopId = is_numeric($order['language']) ? $order['language'] : $order['subshopID']; $shop = $repository->getActiveById($shopId); $shop->registerResources(Shopware()->Bootstrap()); $order['status_description'] = Shopware()->Snippets()->getNamespace('backend/static/order_status')->get($order['status_name'], $order['status_description']); $order['cleared_description'] = Shopware()->Snippets()->getNamespace('backend/static/payment_status')->get($order['cleared_name'], $order['cleared_description']); /* @var $mailModel \Shopware\Models\Mail\Mail */ $mailModel = Shopware()->Models()->getRepository('Shopware\\Models\\Mail\\Mail')->findOneBy(array('name' => $templateName)); if (!$mailModel) { return; } $context = array('sOrder' => $order, 'sOrderDetails' => $orderDetails, 'sUser' => $user); if (!empty($dispatch)) { $context['sDispatch'] = $dispatch; } $result = $this->eventManager->notify('Shopware_Controllers_Backend_OrderState_Notify', array('subject' => Shopware()->Front(), 'id' => $orderId, 'status' => $statusId, 'mailname' => $templateName)); if (!empty($result)) { $context['EventResult'] = $result->getValues(); } $mail = Shopware()->TemplateMail()->createMail($templateName, $context, $shop); $return = array('content' => $mail->getPlainBodyText(), 'subject' => $mail->getPlainSubject(), 'email' => trim($user['email']), 'frommail' => $mail->getFrom(), 'fromname' => $mail->getFromName()); $return = $this->eventManager->filter('Shopware_Controllers_Backend_OrderState_Filter', $return, array('subject' => Shopware()->Front(), 'id' => $orderId, 'status' => $statusId, 'mailname' => $templateName, 'mail' => $mail, 'engine' => Shopware()->Template())); $mail->clearSubject(); $mail->setSubject($return['subject']); $mail->setBodyText($return['content']); $mail->clearFrom(); $mail->setFrom($return['frommail'], $return['fromname']); $mail->addTo($return['email']); return $mail; }
/** * Returns all smarty directories for the inheritance * structure of the passed shop template. * The returned directory array will be registered * as smarty plugin directory. * This allows the developers to implement own smarty plugins. * * @param \Shopware\Models\Shop\Template $template * @return array */ public function getSmartyDirectories(Shop\Template $template) { $directories = $this->getSmartyDirectoriesRecursive($template); $directories = $this->eventManager->filter('Theme_Inheritance_Smarty_Directories_Collected', $directories, array('template' => $template)); return $directories; }
/** * @param $records * @throws AdapterException * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException * @throws \Enlight_Event_Exception * @throws \Exception */ public function write($records) { if (empty($records['default'])) { $message = SnippetsHelper::getNamespace()->get('adapters/articlesTranslations/no_records', 'No article translation records were found.'); throw new \Exception($message); } $records = $this->eventManager->filter('Shopware_Components_SwagImportExport_DbAdapters_ArticlesTranslationsDbAdapter_Write', $records, ['subject' => $this]); $whiteList = ['name', 'description', 'descriptionLong', 'metaTitle', 'keywords']; $variantWhiteList = ['additionalText', 'packUnit']; $whiteList = array_merge($whiteList, $variantWhiteList); if (!SwagVersionHelper::isDeprecated('5.3.0')) { $elementBuilder = $this->getElementBuilder(); $legacyAttributes = $elementBuilder->getQuery()->getArrayResult(); if ($legacyAttributes) { foreach ($legacyAttributes as $attr) { $whiteList[] = $attr['name']; $variantWhiteList[] = $attr['name']; } } } $attributes = $this->getAttributes(); if ($attributes) { foreach ($attributes as $attribute) { $whiteList[] = $attribute['columnName']; $variantWhiteList[] = $attribute['columnName']; } } $articleDetailRepository = $this->manager->getRepository(Detail::class); $shopRepository = $this->manager->getRepository(Shop::class); foreach ($records['default'] as $index => $record) { try { $record = $this->validator->filterEmptyString($record); $this->validator->checkRequiredFields($record); $this->validator->validate($record, ArticleTranslationValidator::$mapper); $shop = false; if (isset($record['languageId'])) { $shop = $shopRepository->find($record['languageId']); } if (!$shop) { $message = SnippetsHelper::getNamespace()->get('adapters/articlesTranslations/lang_id_not_found', 'Language with id %s does not exists for article %s'); throw new AdapterException(sprintf($message, $record['languageId'], $record['articleNumber'])); } $articleDetail = $articleDetailRepository->findOneBy(['number' => $record['articleNumber']]); if (!$articleDetail) { $message = SnippetsHelper::getNamespace()->get('adapters/article_number_not_found', 'Article with order number %s doen not exists'); throw new AdapterException(sprintf($message, $record['articleNumber'])); } $articleId = $articleDetail->getArticle()->getId(); if ($articleDetail->getKind() === 1) { $data = array_intersect_key($record, array_flip($whiteList)); $type = 'article'; $objectKey = $articleId; } else { $data = array_intersect_key($record, array_flip($variantWhiteList)); $type = 'variant'; $objectKey = $articleDetail->getId(); } if (!empty($data)) { $data = $this->prepareAttributePrefix($data, $attributes); $this->translationComponent->write($shop->getId(), $type, $objectKey, $data); } } catch (AdapterException $e) { $message = $e->getMessage(); $this->saveMessage($message); } } }
/** * 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); } } }