/**
  * Clear HTTP-Cache
  */
 public function clearHttpCache()
 {
     $cacheDir = $this->container->getParameter('shopware.httpCache.cache_dir');
     $this->clearDirectory($cacheDir);
     // Fire event to let Plugin-Implementation clear cache
     $this->events->notify('Shopware_Plugins_HttpCache_ClearCache');
 }
Example #2
0
 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;
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function match($pathInfo, Context $context)
 {
     if (strpos($pathInfo, '/backend/') === 0 || strpos($pathInfo, '/api/') === 0) {
         return $pathInfo;
     }
     if ($context->getShopId() === null) {
         //only frontend
         return $pathInfo;
     }
     $request = new EnlightRequest();
     $request->setBaseUrl($context->getBaseUrl());
     $request->setPathInfo($pathInfo);
     $event = $this->eventManager->notifyUntil('Enlight_Controller_Router_Route', ['request' => $request, 'context' => $context]);
     return $event !== null ? $event->getReturn() : false;
 }
Example #4
0
 /**
  * Runs a job by handing it over to
  *
  * @param Enlight_Components_Cron_Job $job
  * @return Enlight_Event_EventArgs
  * @throw Enlight_Exception
  */
 public function runJob(Enlight_Components_Cron_Job $job)
 {
     // Fix cron action name
     $action = $job->getAction();
     if (strpos($action, 'Shopware_') !== 0) {
         $action = str_replace(' ', '', ucwords(str_replace('_', ' ', $job->getAction())));
         $job->setAction('Shopware_CronJob_' . $action);
     }
     try {
         if ($this->adapter->startJob($job)) {
             $jobArgs = new $this->eventArgsClass(array('subject' => $this, 'job' => $job));
             $jobArgs->setReturn($job->getData());
             $jobArgs = $this->eventManager->notifyUntil($job->getAction(), $jobArgs);
             if ($jobArgs !== null) {
                 $job->setData($jobArgs->getReturn());
                 $this->adapter->updateJob($job);
             }
             $this->endJob($job);
             return $jobArgs;
         }
     } catch (Exception $e) {
         $job->setData(array('error' => $e->getMessage()));
         $this->disableJob($job);
         throw $e;
     }
 }
 /**
  * @return FacetHandlerInterface[]
  */
 private function registerFacetHandlers()
 {
     $facetHandlers = new ArrayCollection();
     $facetHandlers = $this->eventManager->collect('Shopware_SearchBundleDBAL_Collect_Facet_Handlers', $facetHandlers);
     $this->assertCollectionIsInstanceOf($facetHandlers, __NAMESPACE__ . '\\FacetHandlerInterface');
     return array_merge($facetHandlers->toArray(), $this->facetHandlers);
 }
Example #6
0
 /**
  * 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));
     }
 }
Example #7
0
 /**
  * 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);
 }
Example #8
0
 /**
  * @param Container $container
  * @param \Enlight_Loader $loader
  * @param \Enlight_Event_EventManager $eventManager
  * @param \Shopware $application
  * @param array $config
  * @return \Enlight_Plugin_PluginManager
  */
 public function factory(Container $container, \Enlight_Loader $loader, \Enlight_Event_EventManager $eventManager, \Shopware $application, array $config)
 {
     $pluginManager = new \Enlight_Plugin_PluginManager($application);
     $container->load('Table');
     if (!isset($config['namespaces'])) {
         $config['namespaces'] = array('Core', 'Frontend', 'Backend');
     }
     foreach ($config['namespaces'] as $namespace) {
         $namespace = new \Shopware_Components_Plugin_Namespace($namespace);
         $pluginManager->registerNamespace($namespace);
         $eventManager->registerSubscriber($namespace->Subscriber());
     }
     foreach (array('Local', 'Community', 'Default', 'Commercial') as $dir) {
         $loader->registerNamespace('Shopware_Plugins', Shopware()->AppPath('Plugins_' . $dir));
     }
     return $pluginManager;
 }
Example #9
0
 /**
  * @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;
 }
Example #10
0
 /**
  * Returns the query builder object to select the theme configuration for the
  * current shop.
  *
  * @param \Shopware\Models\Shop\Template $template
  * @param boolean $lessCompatible
  * @return \Doctrine\ORM\QueryBuilder|\Shopware\Components\Model\QueryBuilder
  * @throws \Enlight_Event_Exception
  */
 private function getShopConfigQuery(Shop\Template $template, $lessCompatible)
 {
     $builder = $this->entityManager->createQueryBuilder();
     $builder->select(array('element.name', 'values.value', 'element.defaultValue', 'element.type'));
     $builder->from('Shopware\\Models\\Shop\\TemplateConfig\\Element', 'element')->leftJoin('element.values', 'values', 'WITH', 'values.shopId = :shopId')->where('element.templateId = :templateId');
     if ($lessCompatible) {
         $builder->andWhere('element.lessCompatible = 1');
     }
     $this->eventManager->notify('Theme_Inheritance_Shop_Query_Built', array('builder' => $builder, 'template' => $template));
     return $builder;
 }
Example #11
0
 public function testAddSubscriber()
 {
     $eventSubscriber = new EventSubsciberTest();
     $this->eventManager->addSubscriber($eventSubscriber);
     $this->assertCount(1, $this->eventManager->getListeners('eventName0'));
     $this->assertCount(1, $this->eventManager->getListeners('eventName1'));
     $this->assertCount(1, $this->eventManager->getListeners('eventName2'));
     $this->assertCount(3, $this->eventManager->getListeners('eventName3'));
     $listeners = $this->eventManager->getListeners('eventName3');
     $listener = $listeners[5];
     $this->assertEquals(5, $listener->getPosition());
 }
Example #12
0
 /**
  * Monitor execution time and memory on specified event points in application
  *
  * @return \Enlight_Event_Subscriber_Array
  */
 public function getListeners()
 {
     $events = $this->eventManager->getEvents();
     $listeners = new \Enlight_Event_Subscriber_Array();
     foreach ($events as $event) {
         if ($event == 'Enlight_Controller_Front_DispatchLoopShutdown') {
             continue;
         }
         $listeners->registerListener(new \Enlight_Event_Handler_Default($event, array($this, 'onBenchmarkEvent'), -1000));
         $listeners->registerListener(new \Enlight_Event_Handler_Default($event, array($this, 'onBenchmarkEvent'), 1000));
     }
     return $listeners;
 }
Example #13
0
 /**
  * Runs a job by handing it over to
  *
  * @param Enlight_Components_Cron_Job $job
  * @return Enlight_Event_EventArgs
  * @throw Enlight_Exception
  */
 public function run(Enlight_Components_Cron_Job $job)
 {
     try {
         if ($this->startJob($job)) {
             $jobArgs = $this->_eventManager->notifyUntil($job->getAction(), new Enlight_Components_Cron_EventArgs($job));
             $this->endJob($job);
             return $jobArgs;
         }
     } catch (Exception $e) {
         $job->setData(array('error' => $e->getMessage()));
         $this->disableJob($job);
         throw $e;
     }
 }
Example #14
0
 /**
  * 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;
 }
Example #15
0
 /**
  * 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;
 }
Example #16
0
 /**
  * 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);
 }
Example #17
0
 /**
  * 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;
 }
Example #18
0
 /**
  * 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);
         }
     }
 }
Example #19
0
 /**
  * Runs a job by handing it over to
  *
  * @param Enlight_Components_Cron_Job $job
  * @return Enlight_Event_EventArgs
  * @throw Enlight_Exception
  */
 public function runJob(Enlight_Components_Cron_Job $job)
 {
     try {
         if ($this->adapter->startJob($job)) {
             $jobArgs = new $this->eventArgsClass(array('subject' => $this, 'job' => $job));
             $jobArgs->setReturn($job->getData());
             $jobArgs = $this->eventManager->notifyUntil($job->getAction(), $jobArgs);
             if ($jobArgs !== null) {
                 $job->setData($jobArgs->getReturn());
                 $this->adapter->updateJob($job);
             }
             $this->endJob($job);
             return $jobArgs;
         }
     } catch (Exception $e) {
         $job->setData(array('error' => $e->getMessage()));
         $this->disableJob($job);
         throw $e;
     }
 }
 /**
  * @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]);
 }
Example #21
0
 /**
  * Helper function which compiles the passed less definition.
  * The shop parameter is required to build the shop url for the files.
  *
  * @param Shop\Shop $shop
  * @param LessDefinition $definition
  */
 private function compileLessDefinition(Shop\Shop $shop, LessDefinition $definition)
 {
     //set unique import directory for less @import commands
     if ($definition->getImportDirectory()) {
         $this->compiler->setImportDirectories(array($definition->getImportDirectory()));
     }
     //allows to add own configurations for the current compile step.
     if ($definition->getConfig()) {
         $this->compiler->setVariables($definition->getConfig());
     }
     $this->eventManager->notify('Theme_Compiler_Compile_Less', array('shop' => $shop, 'less' => $definition));
     //needs to iterate files, to generate source map if configured.
     foreach ($definition->getFiles() as $file) {
         if (!file_exists($file)) {
             continue;
         }
         //creates the url for the compiler, this url will be prepend to each relative path.
         //the url is additionally used for the source map generation.
         $url = $this->formatPathToUrl($file);
         $this->compiler->compile($file, $url);
     }
 }
Example #22
0
 /**
  * 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']);
         }
     }
 }
Example #23
0
 /**
  * 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);
 }
 /**
  * @return void
  */
 public function start()
 {
     $event = new \Enlight_Event_EventHandler('Enlight_Plugins_ViewRenderer_PreRender', array($this, 'onAfterRenderView'));
     $this->eventManager->registerListener($event);
 }
Example #25
0
 /**
  * Get basic article data in various modes (firmly definied by id, random, top,new)
  * @param string $mode Modus (fix, random, top, new)
  * @param int $category filter by category
  * @param int $value article id / ordernumber for firmly definied articles
  * @param bool $withImage
  * @return array
  */
 public function sGetPromotionById($mode, $category = 0, $value = 0, $withImage = false)
 {
     $notifyUntil = $this->eventManager->notifyUntil('Shopware_Modules_Articles_GetPromotionById_Start', array('subject' => $this, 'mode' => $mode, 'category' => $category, 'value' => $value));
     if ($notifyUntil) {
         return false;
     }
     $value = $this->getPromotionNumberByMode($mode, $category, $value, $withImage);
     if (!$value) {
         return false;
     }
     $result = $this->getPromotion($category, $value);
     if (!$result) {
         return false;
     }
     $result = $this->legacyEventManager->firePromotionByIdEvents($result, $category, $this);
     return $result;
 }
 /**
  * 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);
         }
     }
 }
 /**
  * @return array
  * @throws \Enlight_Event_Exception
  */
 private function registerRequestHandlers()
 {
     $requestHandlers = new ArrayCollection();
     $requestHandlers = $this->eventManager->collect('Shopware_SearchBundle_Collect_Criteria_Request_Handlers', $requestHandlers);
     return array_merge($this->requestHandlers, $requestHandlers->toArray());
 }
 /**
  * @return MediaPosition[]
  */
 private function getMediaPositions()
 {
     $mediaPositions = $this->getDefaultMediaPositions();
     $mediaPositions = $this->events->collect('Shopware_Collect_MediaPositions', $mediaPositions);
     return $mediaPositions->toArray();
 }
Example #29
0
 /**
  * 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;
 }
Example #30
-1
 /**
  * @param Container $container
  * @param EnlightEventManager $eventManager
  * @return \Shopware\Components\Routing\RouterInterface
  * @throws \Exception
  */
 public function factory(Container $container, EnlightEventManager $eventManager)
 {
     $queryAliasMapper = $container->get('query_alias_mapper');
     $matchers = [new Matchers\RewriteMatcher($container->get('dbal_connection'), $queryAliasMapper), new Matchers\EventMatcher($eventManager), new Matchers\DefaultMatcher($container->get('dispatcher'))];
     $generators = [new Generators\RewriteGenerator($container->get('dbal_connection'), $queryAliasMapper), new Generators\DefaultGenerator($container->get('dispatcher'))];
     $preFilters = [new GeneratorFilters\DefaultPreFilter(), new GeneratorFilters\FrontendPreFilter()];
     $postFilters = [new GeneratorFilters\FrontendPostFilter(), new GeneratorFilters\DefaultPostFilter()];
     $router = new \Shopware\Components\Routing\Router(Context::createEmpty(), $matchers, $generators, $preFilters, $postFilters);
     /** Still better than @see \Shopware\Models\Shop\Shop::registerResources */
     $eventManager->addListener('Enlight_Bootstrap_AfterRegisterResource_Shop', array($this, 'onAfterRegisterShop'), -100);
     $eventManager->addListener('Enlight_Controller_Front_PreDispatch', array($this, 'onPreDispatch'), -100);
     return $router;
 }