/**
  * @param Request $request
  * @param Criteria $criteria
  * @param ShopContextInterface $context
  */
 public function handleRequest(Request $request, Criteria $criteria, ShopContextInterface $context)
 {
     $this->addPropertyCondition($request, $criteria);
     if ($this->config->get('displayFiltersInListings')) {
         $criteria->addFacet(new PropertyFacet());
     }
 }
Esempio n. 2
0
 /**
  * @param $term
  * @return Keyword[]
  */
 public function getKeywordsOfTerm($term)
 {
     $id = md5('Shopware_Modules_Search_' . $term);
     if (($keywords = $this->cache->fetch($id)) !== false) {
         return $keywords;
     }
     $keywords = $this->keywordFinder->getKeywordsOfTerm($term);
     $this->cache->save($id, $keywords, $this->config->get('cachesearch'));
     return $keywords;
 }
Esempio n. 3
0
 /**
  * @inheritdoc
  */
 public function getProductAttribute(Struct\ListProduct $product)
 {
     $attribute = new Struct\Product\MarketingAttribute();
     $today = new \DateTime();
     $diff = $today->diff($product->getCreatedAt());
     $marker = (int) $this->config->get('markAsNew');
     $attribute->setIsNew($diff->days <= $marker || $product->getCreatedAt() > $today);
     $attribute->setComingSoon($product->getReleaseDate() && $product->getReleaseDate() > $today);
     $attribute->setIsTopSeller($product->getSales() >= $this->config->get('markAsTopSeller'));
     return $attribute;
 }
Esempio n. 4
0
 /**
  * Show also bought articles
  */
 public function boughtAction()
 {
     $articleId = (int) $this->Request()->getParam('articleId');
     $maxPages = (int) $this->config->get('alsoBoughtMaxPages', 10);
     $perPage = (int) $this->config->get('alsoBoughtPerPage', 4);
     $this->marketingModule->sBlacklist[] = $articleId;
     $articles = $this->marketingModule->sGetAlsoBoughtArticles($articleId, $maxPages * $perPage);
     $numbers = array_column($articles, 'number');
     $result = $this->getPromotions($numbers);
     $this->View()->maxPages = $maxPages;
     $this->View()->perPage = $perPage;
     $this->View()->boughtArticles = $result;
 }
Esempio n. 5
0
 /**
  * @param $article
  * @return array
  * @throws Enlight_Exception
  */
 private function getPriceForAddArticle($article)
 {
     // Read price from default price table
     $price = $this->db->fetchRow('SELECT price, s_core_tax.tax AS tax
         FROM s_articles_prices, s_core_tax
         WHERE s_articles_prices.pricegroup = ?
         AND s_articles_prices.articledetailsID = ?
         AND s_core_tax.id = ?', array($this->sSYSTEM->sUSERGROUP, $article["articledetailsID"], $article["taxID"])) ?: array();
     if (empty($price["price"])) {
         $price = $this->db->fetchRow('SELECT price, s_core_tax.tax AS tax
             FROM s_articles_prices, s_core_tax
             WHERE s_articles_prices.pricegroup = \'EK\'
             AND s_articles_prices.articledetailsID = ?
             AND s_core_tax.id = ?', array($article["articledetailsID"], $article["taxID"])) ?: array();
     }
     if (!$price["price"] && !$article["free"]) {
         // No price could acquired
         throw new Enlight_Exception("BASKET-INSERT #01 No price acquired");
     }
     // If configuration article
     if ($this->config->get('sARTICLESOUTPUTNETTO') && !$this->sSYSTEM->sUSERGROUPDATA["tax"] || !$this->sSYSTEM->sUSERGROUPDATA["tax"] && $this->sSYSTEM->sUSERGROUPDATA["id"]) {
         // If netto set both values to net-price
         $price["price"] = $this->moduleManager->Articles()->sCalculatingPriceNum($price["price"], $price["tax"], false, false, $article["taxID"], false, $article);
         $price["netprice"] = $price["price"];
     } else {
         // If brutto, save net
         $price["netprice"] = $price["price"];
         $price["price"] = $this->moduleManager->Articles()->sCalculatingPriceNum($price["price"], $price["tax"], false, false, $article["taxID"], false, $article);
     }
     return $price;
 }
Esempio n. 6
0
 /**
  * Following events are deprecated and only implemented for backward compatibility to shopware 4
  * Removed with shopware 5.1
  *
  * @param array $result
  * @param $category
  * @param \sArticles $module
  * @return array
  */
 public function firePromotionByIdEvents($result, $category, \sArticles $module)
 {
     $articleId = $result['articleID'];
     $result["sProperties"] = $this->eventManager->filter('sArticles::sGetArticleProperties::replace', isset($result["sProperties"]) ? $result["sProperties"] : [], array('subject' => $module, 'articleId' => $articleId, 'filterGroupId' => $result['filtergroupID']));
     $result["sProperties"] = $this->eventManager->filter('sArticles::sGetArticleProperties::after', $result["sProperties"], array('subject' => $module, 'articleId' => $articleId, 'filterGroupId' => $result['filtergroupID']));
     $cheapestPrice = $this->eventManager->filter('sArticles::sGetCheapestPrice::replace', $result['priceStartingFrom'], array('subject' => $module, 'article' => $articleId, 'group' => $result["pricegroup"], 'pricegroup' => $result["pricegroupID"], 'usepricegroups' => $result["pricegroupActive"]));
     $cheapestPrice = $this->eventManager->filter('sArticles::sGetCheapestPrice::after', $cheapestPrice, array('subject' => $module, 'article' => $articleId, 'group' => $result["pricegroup"], 'pricegroup' => $result["pricegroupID"], 'usepricegroups' => $result["pricegroupActive"]));
     if (!is_array($cheapestPrice)) {
         $cheapestPrice = array($cheapestPrice, 0);
     }
     $result['priceStartingFrom'] = $cheapestPrice[0];
     $result["image"] = $this->eventManager->filter('sArticles::getArticleListingCover::replace', $result["image"], array('subject' => $module, 'articleId' => $articleId, 'forceMainImage' => $this->config->get('forceArticleMainImageInListing')));
     $result["image"] = $this->eventManager->filter('sArticles::sGetArticlePictures::replace', $result["image"], array('subject' => $module, 'sArticleID' => $articleId, 'onlyCover' => true, 'pictureSize' => 0, 'ordernumber' => null, 'allImages' => null, 'realtime' => null, 'forceMainImage' => $this->config->get('forceArticleMainImageInListing')));
     $result["image"] = $this->eventManager->filter('sArticles::sGetArticlePictures::after', $result["image"], array('subject' => $module, 'sArticleID' => $articleId, 'onlyCover' => true, 'pictureSize' => 0, 'ordernumber' => null, 'allImages' => null, 'realtime' => null, 'forceMainImage' => $this->config->get('forceArticleMainImageInListing')));
     $result["image"] = $this->eventManager->filter('sArticles::getArticleListingCover::after', $result["image"], array('subject' => $module, 'articleId' => $articleId, 'forceMainImage' => $this->config->get('forceArticleMainImageInListing')));
     $result["priceStartingFrom"] = $this->eventManager->filter('sArticles::sCalculatingPrice::replace', $result["priceStartingFrom"], array('subject' => $module, 'price' => $result["priceStartingFrom"], 'tax' => $result["tax"], 'taxId' => $result["taxID"], 'article' => $result));
     $result["priceStartingFrom"] = $this->eventManager->filter('sArticles::sCalculatingPrice::after', $result["priceStartingFrom"], array('subject' => $module, 'price' => $result["priceStartingFrom"], 'tax' => $result["tax"], 'taxId' => $result["taxID"], 'article' => $result));
     $result["price"] = $this->eventManager->filter('sArticles::sCalculatingPrice::replace', $result["price"], array('subject' => $module, 'price' => $result["price"], 'tax' => $result["tax"], 'taxId' => $result["taxID"], 'article' => $result));
     $result["price"] = $this->eventManager->filter('sArticles::sCalculatingPrice::after', $result["price"], array('subject' => $module, 'price' => $result["price"], 'tax' => $result["tax"], 'taxId' => $result["taxID"], 'article' => $result));
     if ($result["pseudoprice"]) {
         $result["pseudoprice"] = $this->eventManager->filter('sArticles::sCalculatingPrice::replace', $result["pseudoprice"], array('subject' => $module, 'price' => $result["pseudoprice"], 'tax' => $result["tax"], 'taxId' => $result["taxID"], 'article' => $result));
         $result["pseudoprice"] = $this->eventManager->filter('sArticles::sCalculatingPrice::after', $result["pseudoprice"], array('subject' => $module, 'price' => $result["pseudoprice"], 'tax' => $result["tax"], 'taxId' => $result["taxID"], 'article' => $result));
     }
     $calculatedBasePriceData = $this->eventManager->filter('sArticles::calculateCheapestBasePriceData::replace', null, array('price' => $result["price"], 'articleId' => $articleId, 'priceGroup' => $result["pricegroup"], 'priceGroupId' => $result["pricegroupID"]));
     $calculatedBasePriceData = $this->eventManager->filter('sArticles::calculateCheapestBasePriceData::after', $calculatedBasePriceData, array('price' => $result["price"], 'articleId' => $articleId, 'priceGroup' => $result["pricegroup"], 'priceGroupId' => $result["pricegroupID"]));
     if (!empty($calculatedBasePriceData)) {
         $result["purchaseunit"] = empty($calculatedBasePriceData["purchaseunit"]) ? null : $calculatedBasePriceData["purchaseunit"];
         $result["referenceunit"] = empty($calculatedBasePriceData["referenceunit"]) ? null : $calculatedBasePriceData["referenceunit"];
         $result["sUnit"] = empty($calculatedBasePriceData["sUnit"]) ? null : $calculatedBasePriceData["sUnit"];
         $result['referenceprice'] = empty($calculatedBasePriceData["referenceprice"]) ? null : $calculatedBasePriceData["referenceprice"];
     }
     return Enlight()->Events()->filter('Shopware_Modules_Articles_GetPromotionById_FilterResult', $result, array('subject' => $module, 'mode' => 'fix', 'category' => $category, 'value' => $result['articleID']));
 }
 /**
  * @inheritdoc
  */
 public function getListByCategory($products, Struct\ShopContextInterface $context)
 {
     if (!$this->config->offsetExists('similarLimit') || $this->config->get('similarLimit') <= 0) {
         return [];
     }
     $ids = [];
     foreach ($products as $product) {
         $ids[] = $product->getId();
     }
     $ids = array_unique($ids);
     $categoryId = 1;
     if ($context->getShop() && $context->getShop()->getCategory()) {
         $categoryId = $context->getShop()->getCategory()->getId();
     }
     $query = $this->connection->createQueryBuilder();
     $query->select(['main.articleID', "GROUP_CONCAT(subVariant.ordernumber SEPARATOR '|') as similar"]);
     $query->from('s_articles_categories', 'main');
     $query->innerJoin('main', 's_articles_categories', 'sub', 'sub.categoryID = main.categoryID AND sub.articleID != main.articleID');
     $query->innerJoin('sub', 's_articles_details', 'subVariant', 'subVariant.articleID = sub.articleID AND subVariant.kind = 1');
     $query->innerJoin('main', 's_categories', 'category', 'category.id = sub.categoryID AND category.id = main.categoryID');
     $query->where('main.articleID IN (:ids)')->andWhere('category.path LIKE :path');
     $query->setParameter(':ids', $ids, Connection::PARAM_INT_ARRAY)->setParameter(':path', '%|' . (int) $categoryId . '|');
     $query->groupBy('main.articleID');
     $statement = $query->execute();
     $data = $statement->fetchAll(\PDO::FETCH_ASSOC);
     $limit = (int) $this->config->get('similarLimit');
     $result = [];
     foreach ($data as $row) {
         $similar = explode('|', $row['similar']);
         $result[$row['articleID']] = array_slice($similar, 0, $limit);
     }
     return $result;
 }
 /**
  * Insert articles in comparision chart
  * @param  int               $articleId s_articles.id
  * @throws Enlight_Exception
  * @return bool              true/false
  */
 public function sAddComparison($articleId)
 {
     $articleId = (int) $articleId;
     if (!$articleId) {
         return null;
     }
     // Check if this article is already noted
     $checkForArticle = $this->db->fetchRow("SELECT id FROM s_order_comparisons WHERE sessionID=? AND articleID=?", [$this->session->offsetGet('sessionId'), $articleId]);
     // Check if max. numbers of articles for one comparison-session is reached
     $checkNumberArticles = $this->db->fetchRow("SELECT COUNT(id) AS countArticles FROM s_order_comparisons WHERE sessionID=?", [$this->session->offsetGet('sessionId')]);
     if ($checkNumberArticles["countArticles"] >= $this->config->offsetGet("sMAXCOMPARISONS")) {
         return "max_reached";
     }
     if (!$checkForArticle["id"]) {
         $articleName = $this->db->fetchOne("SELECT s_articles.name AS articleName FROM s_articles WHERE id = ?", [$articleId]);
         if (!$articleName) {
             return false;
         }
         $sql = "\n            INSERT INTO s_order_comparisons (sessionID, userID, articlename, articleID, datum)\n            VALUES (?,?,?,?,now())\n            ";
         $queryNewPrice = $this->db->executeUpdate($sql, [$this->session->offsetGet('sessionId'), empty($this->session["sUserId"]) ? 0 : $this->session["sUserId"], $articleName, $articleId]);
         if (!$queryNewPrice) {
             throw new Enlight_Exception("sArticles##sAddComparison##01: Error in SQL-query");
         }
     }
     return true;
 }
Esempio n. 9
0
 /**
  * Create emotion rewrite rules
  *
  * @param null $offset
  * @param null $limit
  */
 public function sCreateRewriteTableCampaigns($offset = null, $limit = null)
 {
     $queryBuilder = $this->modelManager->getRepository('Shopware\\Models\\Emotion\\Emotion')->getListQueryBuilder();
     $queryBuilder->andWhere('emotions.isLandingPage = 1 ')->andWhere('emotions.active = 1');
     if ($limit !== null && $offset !== null) {
         $queryBuilder->setFirstResult($offset)->setMaxResults($limit);
     }
     $campaigns = $queryBuilder->getQuery()->getArrayResult();
     $routerCampaignTemplate = $this->config->get('routerCampaignTemplate');
     foreach ($campaigns as $campaign) {
         $campaign["categoryId"] = null;
         $this->data->assign('campaign', $campaign);
         $path = $this->template->fetch('string:' . $routerCampaignTemplate, $this->data);
         $path = $this->sCleanupPath($path, false);
         $org_path = 'sViewport=campaign&emotionId=' . $campaign['id'];
         $this->sInsertUrl($org_path, $path);
         foreach ($campaign['categories'] as $category) {
             $campaign["categoryId"] = $category['id'];
             $this->data->assign('campaign', $campaign);
             $path = $this->template->fetch('string:' . $routerCampaignTemplate, $this->data);
             $path = $this->sCleanupPath($path, false);
             $org_path = 'sViewport=campaign&sCategory=' . $campaign['categoryId'] . '&emotionId=' . $campaign['id'];
             $this->sInsertUrl($org_path, $path);
         }
     }
 }
Esempio n. 10
0
 /**
  * Returns category content for the given category id
  *
  * @param $id
  * @return array
  */
 public function sGetCategoryContent($id)
 {
     if ($id === null) {
         $id = $this->baseId;
     }
     $category = $this->repository->getActiveByIdQuery($id, $this->customerGroupId)->getArrayResult();
     if (empty($category[0])) {
         return null;
     }
     $category = $category[0];
     $detailUrl = $category['category']['blog'] ? $this->blogBaseUrl : $this->baseUrl;
     $detailUrl .= $category['category']['id'];
     $canonical = $detailUrl;
     if ($this->config->get('forceCanonicalHttp')) {
         $canonical = str_replace('https://', 'http://', $canonical);
     }
     $category = array_merge($category['category'], array('description' => $category['category']['name'], 'cmsheadline' => $category['category']['cmsHeadline'], 'cmstext' => $category['category']['cmsText'], 'metaKeywords' => $category['category']['metaKeywords'], 'metaDescription' => $category['category']['metaDescription'], 'noviewselect' => $category['category']['noViewSelect'], 'childrenCount' => (int) $category['childrenCount'], 'articleCount' => (int) $category['articleCount'], 'sSelf' => $detailUrl, 'sSelfCanonical' => $canonical, 'rssFeed' => $detailUrl . '&sRss=1', 'atomFeed' => $detailUrl . '&sAtom=1'));
     if (empty($category['template'])) {
         $category['template'] = $this->config->get('categoryDefaultTpl');
     }
     if (empty($category['template'])) {
         $category['template'] = 'article_listing_3col.tpl';
     }
     if (preg_match('#article_listing_([1-4]col).tpl#', $category['template'], $match)) {
         $category['layout'] = $match[1];
     }
     return $category;
 }
 /**
  * @param Criteria $criteria
  */
 private function addIsAvailableCondition(Criteria $criteria)
 {
     if (!$this->config->get('hideNoInstock')) {
         return;
     }
     $criteria->addBaseCondition(new IsAvailableCondition());
 }
 /**
  * @param Request $request
  * @param ShopContextInterface $context
  * @return Criteria
  */
 public function createAjaxSearchCriteria(Request $request, ShopContextInterface $context)
 {
     $criteria = $this->getSearchCriteria($request, $context);
     $criteria->limit($this->config->get('MaxLiveSearchResults', 6));
     $this->eventManager->notify('Shopware_SearchBundle_Create_Ajax_Search_Criteria', ['criteria' => $criteria, 'request' => $request, 'context' => $context]);
     $criteria->resetFacets();
     return $criteria;
 }
Esempio n. 13
0
 /**
  * Show also bought articles
  */
 public function boughtAction()
 {
     $articleId = (int) $this->Request()->getParam('articleId');
     $maxPages = (int) $this->config->get('alsoBoughtMaxPages', 10);
     $perPage = (int) $this->config->get('alsoBoughtPerPage', 4);
     $this->marketingModule->sBlacklist[] = $articleId;
     $articles = $this->marketingModule->sGetAlsoBoughtArticles($articleId, $maxPages * $perPage);
     foreach ($articles as $article) {
         $article = $this->articleModule->sGetPromotionById('fix', 0, (int) $article['id']);
         if (!empty($article['articleName'])) {
             $result[] = $article;
         }
     }
     $this->View()->maxPages = $maxPages;
     $this->View()->perPage = $perPage;
     $this->View()->boughtArticles = $result;
 }
Esempio n. 14
0
 /**
  * Pre selection of the cheapest prices ids.
  *
  * @param Struct\BaseProduct[] $products
  * @param Struct\Customer\Group $customerGroup
  * @return array
  */
 private function getCheapestPriceIds($products, Struct\Customer\Group $customerGroup)
 {
     $ids = [];
     foreach ($products as $product) {
         $ids[] = $product->getId();
     }
     $ids = array_unique($ids);
     $subQuery = $this->connection->createQueryBuilder();
     $subQuery->select('prices.id')->from('s_articles_prices', 'prices');
     /**
      * joins the product variants for the min purchase calculation.
      * The cheapest price is defined by prices.price * variant.minpurchase (the real basket price)
      */
     $subQuery->innerJoin('prices', 's_articles_details', 'variant', 'variant.id = prices.articledetailsID');
     /**
      * Joins the products for the closeout validation.
      * Required to select only product prices which product variant can be added to the basket and purchased
      */
     $subQuery->innerJoin('variant', 's_articles', 'product', 'product.id = variant.articleID');
     $graduation = 'prices.from = 1';
     if ($this->config->get('useLastGraduationForCheapestPrice')) {
         $graduation = "prices.to = 'beliebig'";
     }
     $subQuery->where('prices.pricegroup = :customerGroup')->andWhere($graduation)->andWhere('variant.active = 1')->andWhere('prices.articleID = outerPrices.articleID');
     /**
      * This part of the query handles the closeout products.
      *
      * The `laststock` column contains "1" if the product is a closeout product.
      * In the case that the product contains the closeout flag,
      * the stock and minpurchase are used as they defined in the database
      *
      * In the case that the product isn't a closeout product,
      * the stock and minpurchase are set to 0
      */
     $subQuery->andWhere('(product.laststock * variant.instock) >= (product.laststock * variant.minpurchase)');
     $subQuery->setMaxResults(1);
     if ($this->config->get('calculateCheapestPriceWithMinPurchase')) {
         /**
          * Sorting by the cheapest available price
          */
         $subQuery->orderBy('(prices.price * variant.minpurchase)');
     } else {
         /**
          * Sorting by the cheapest unit price
          */
         $subQuery->orderBy('prices.price');
     }
     /**
      * Creates an outer query which allows to
      * select multiple cheapest product prices.
      */
     $query = $this->connection->createQueryBuilder();
     $query->setParameter(':customerGroup', $customerGroup->getKey());
     $query->select('(' . $subQuery->getSQL() . ') as priceId')->from('s_articles_prices', 'outerPrices')->where('outerPrices.articleID IN (:products)')->setParameter(':products', $ids, Connection::PARAM_INT_ARRAY)->groupBy('outerPrices.articleID')->having('priceId IS NOT NULL');
     $statement = $query->execute();
     return $statement->fetchAll(\PDO::FETCH_COLUMN);
 }
Esempio n. 15
0
 /**
  * @return \Doctrine\DBAL\Query\QueryBuilder
  */
 private function getHasAvailableVariantQuery()
 {
     $query = $this->connection->createQueryBuilder();
     $query->select("COUNT(availableVariant.id)")->from('s_articles_details', 'availableVariant')->where('availableVariant.articleID = product.id')->andWhere('availableVariant.active = 1');
     if ($this->config->get('hideNoInstock')) {
         $query->andWhere('(product.laststock * availableVariant.instock) >= (product.laststock * availableVariant.minpurchase)');
     }
     return $query;
 }
 /**
  * @param $message
  * @throws \Exception
  */
 public function saveMessage($message)
 {
     $errorMode = $this->config->get('SwagImportExportErrorMode');
     if ($errorMode === false) {
         throw new \Exception($message);
     }
     $this->setLogMessages($message);
     $this->setLogState('true');
 }
Esempio n. 17
0
 /**
  * @param int|string $newsletterGroupId
  * @return int
  */
 private function getNewsletterGroupId($newsletterGroupId)
 {
     if (empty($newsletterGroupId)) {
         $defaultNewsletterGroup = $this->config->get('sNEWSLETTERDEFAULTGROUP');
         $newsletterGroupId = empty($defaultNewsletterGroup) ? 1 : (int) $defaultNewsletterGroup;
     } else {
         $newsletterGroupId = intval($newsletterGroupId);
     }
     return $newsletterGroupId;
 }
Esempio n. 18
0
 /**
  * Check if a keyword is on blacklist or not
  *
  * @param string $word
  * @return bool
  */
 private function filterBadWordFromString($word)
 {
     static $badWords;
     if (!isset($badWords)) {
         $badWords = preg_split("#[\\s,;]+#msi", $this->config->get('badwords'), -1, PREG_SPLIT_NO_EMPTY);
     }
     if (in_array((string) $word, $badWords)) {
         return false;
     }
     return true;
 }
Esempio n. 19
0
 /**
  * @param array $category
  * @return string
  */
 private function getCategoryCanonicalParams($category)
 {
     $request = $this->frontController->Request();
     $page = $request->getQuery('sPage');
     $emotion = $this->manager->getRepository('Shopware\\Models\\Emotion\\Emotion')->getCategoryBaseEmotionsQuery($category['id'])->getArrayResult();
     $canonicalParams = array('sViewport' => $category['blog'] ? 'blog' : 'cat', 'sCategory' => $category['id']);
     if ($this->config->get('seoIndexPaginationLinks') && (!$emotion || $page)) {
         $canonicalParams['sPage'] = $page ?: 1;
     }
     return $canonicalParams;
 }
Esempio n. 20
0
 /**
  * Generates and inserts static page urls
  *
  * @param $offset
  * @param $limit
  */
 private function insertStaticPageUrls($offset, $limit)
 {
     $shopId = Shopware()->Shop()->getId();
     $sitesData = $this->modelManager->getRepository('Shopware\\Models\\Site\\Site')->getSitesWithoutLinkQuery($shopId, $offset, $limit)->getArrayResult();
     foreach ($sitesData as $site) {
         $org_path = 'sViewport=custom&sCustom=' . $site['id'];
         $this->data->assign('site', $site);
         $path = $this->template->fetch('string:' . $this->config->get('seoCustomSiteRouteTemplate'), $this->data);
         $path = $this->sCleanupPath($path, false);
         $this->sInsertUrl($org_path, $path);
     }
 }
Esempio n. 21
0
 /**
  * @inheritdoc
  */
 public function joinAvailableVariant(QueryBuilder $query)
 {
     if ($query->hasState(self::STATE_INCLUDES_AVAILABLE_VARIANT)) {
         return;
     }
     $stockCondition = '';
     if ($this->config->get('hideNoInstock')) {
         $stockCondition = 'AND (product.laststock * availableVariant.instock) >= (product.laststock * availableVariant.minpurchase)';
     }
     $query->innerJoin('product', 's_articles_details', 'availableVariant', 'availableVariant.articleID = product.id
          AND availableVariant.active = 1 ' . $stockCondition);
     $query->addState(self::STATE_INCLUDES_AVAILABLE_VARIANT);
 }
 /**
  * Calculates the search tolerance and adds an where condition
  * to the query.
  *
  * @param QueryBuilder $query
  */
 private function addToleranceCondition(QueryBuilder $query)
 {
     $query->select("MAX(" . $this->getRelevanceSelection() . ")");
     /**@var $statement \Doctrine\DBAL\Driver\ResultStatement */
     $statement = $query->execute();
     $highestRanking = $statement->fetch(\PDO::FETCH_COLUMN);
     //calculates the tolerance limit
     $distance = $this->config->get('fuzzySearchMinDistancenTop', 20);
     if ($highestRanking && $distance) {
         $toleranceLimit = $highestRanking / 100 * $distance;
         $query->andWhere('(' . $this->getRelevanceSelection() . ') > ' . $toleranceLimit);
     }
 }
Esempio n. 23
0
 /**
  * Check if search index is valid anymore and rebuild if necessary
  */
 public function validate()
 {
     $strategy = $this->config->get('searchRefreshStrategy', 3);
     //search index refresh strategy is configured for "live refresh"?
     if ($strategy !== 3) {
         return;
     }
     $interval = (int) $this->config->get('cacheSearch');
     if (empty($interval) || $interval < 360) {
         $interval = 86400;
     }
     $sql = "\n            SELECT NOW() AS current, cf.value AS last, (SELECT 1 FROM s_search_index LIMIT 1) AS not_force\n            FROM s_core_config_elements ce, s_core_config_values cf\n            WHERE ce.name = 'fuzzysearchlastupdate'\n            AND cf.element_id = ce.id\n            AND cf.shop_id = 1\n        ";
     $result = $this->connection->fetchAll($sql);
     if (empty($result) || !isset($result[0])) {
         $this->build();
         return;
     }
     $result = $result[0];
     $last = !empty($result['last']) ? unserialize($result['last']) : null;
     if (empty($last) || empty($result['not_force']) || strtotime($last) < strtotime($result['current']) - $interval) {
         $this->build();
     }
 }
 /**
  * Returns newsletter default group name.
  *
  * @param string $email
  * @param string $groupName
  * @return string
  * @throws AdapterException
  */
 private function getGroupName($email, $groupName)
 {
     $group = $this->groupRepository->findOneBy(['name' => $groupName]);
     if ($group) {
         return $group->getName();
     }
     $groupId = $this->config->get("sNEWSLETTERDEFAULTGROUP");
     $group = $this->groupRepository->find($groupId);
     if (!$group instanceof Group) {
         $message = SnippetsHelper::getNamespace()->get('adapters/newsletter/group_required', 'Group is required for email %s');
         throw new AdapterException(sprintf($message, $email));
     }
     return $group->getName();
 }
Esempio n. 25
0
 /**
  * @inheritdoc
  */
 public function getCovers($products, Struct\ShopContextInterface $context)
 {
     if ($this->shopwareConfig->get('forceArticleMainImageInListing')) {
         return $this->productMediaGateway->getCovers($products, $context);
     }
     $covers = $this->variantMediaGateway->getCovers($products, $context);
     $fallback = [];
     foreach ($products as $product) {
         if (!array_key_exists($product->getNumber(), $covers)) {
             $fallback[] = $product;
         }
     }
     $fallback = $this->productMediaGateway->getCovers($fallback, $context);
     return $covers + $fallback;
 }
Esempio n. 26
0
 /**
  * Returns the sort mode for the passed value ids.
  * If the value ids contains more than one property set, the
  * global fallback sort mode is used.
  *
  * @param array $valueIds
  * @return int
  */
 private function getSortMode(array $valueIds)
 {
     $query = $this->connection->createQueryBuilder();
     $query->select('DISTINCT propertySet.sortmode')->from('s_filter', 'propertySet');
     $query->innerJoin('propertySet', 's_filter_relations', 'relations', 'relations.groupID = propertySet.id');
     $query->innerJoin('relations', 's_filter_values', 'propertyOption', 'relations.optionID = propertyOption.optionID');
     $query->where('propertyOption.id IN (:ids)')->setParameter(':ids', $valueIds, Connection::PARAM_INT_ARRAY);
     /**@var $statement \Doctrine\DBAL\Driver\ResultStatement */
     $statement = $query->execute();
     $rows = $statement->fetchAll(\PDO::FETCH_COLUMN);
     if (count($rows) == 1) {
         return $rows[0];
     } else {
         return $this->config->get('defaultFilterSort', self::FILTERS_SORT_POSITION);
     }
 }
Esempio n. 27
0
 private function getDescriptionKeywords($longDescription)
 {
     //sDescriptionKeywords
     $string = strip_tags(html_entity_decode($longDescription, null, 'UTF-8'));
     $string = str_replace(',', '', $string);
     $words = preg_split('/ /', $string, -1, PREG_SPLIT_NO_EMPTY);
     $badWords = explode(",", $this->config->get('badwords'));
     $words = array_diff($words, $badWords);
     $words = array_count_values($words);
     foreach (array_keys($words) as $word) {
         if (strlen($word) < 2) {
             unset($words[$word]);
         }
     }
     arsort($words);
     return htmlspecialchars(implode(", ", array_slice(array_keys($words), 0, 20)), ENT_QUOTES, 'UTF-8', false);
 }
 /**
  * @param array $record
  * @return mixed
  */
 private function getPayment($record)
 {
     if (!isset($record['subshopID'])) {
         return $this->config->get('sDEFAULTPAYMENT');
     }
     $subShopId = $record['subshopID'];
     //get defaultPaymentId for subShop
     $defaultPaymentId = $this->getSubShopDefaultPaymentId($subShopId);
     if ($defaultPaymentId) {
         return unserialize($defaultPaymentId);
     }
     //get defaultPaymentId for mainShop
     $defaultPaymentId = $this->getMainShopDefaultPaymentId($subShopId);
     if ($defaultPaymentId) {
         return unserialize($defaultPaymentId);
     }
     return $this->config->get('sDEFAULTPAYMENT');
 }
Esempio n. 29
0
 /**
  * Returns a single order number for the passed product configuration selection.
  *
  * @param int $productId
  * @param array $selection
  * @return string|false
  */
 private function getNumberBySelection($productId, array $selection)
 {
     $query = $this->connection->createQueryBuilder();
     $query->select(['variant.ordernumber'])->from('s_articles_details', 'variant')->where('variant.articleID = :productId')->andWhere('variant.active = 1')->setFirstResult(0)->setMaxResults(1)->setParameter(':productId', $productId);
     foreach ($selection as $optionId) {
         $alias = 'option_' . (int) $optionId;
         $query->innerJoin('variant', 's_article_configurator_option_relations', $alias, 'variant.id = ' . $alias . '.article_id
              AND ' . $alias . '.option_id = :' . $alias);
         $query->setParameter(':' . $alias, (int) $optionId);
     }
     if ($this->config->get('hideNoInStock')) {
         $query->innerJoin('variant', 's_articles', 'product', 'product.id = variant.articleID');
         $query->andWhere('(product.laststock * variant.instock) >= (product.laststock * variant.minpurchase)');
     }
     /**@var $statement \Doctrine\DBAL\Driver\ResultStatement */
     $statement = $query->execute();
     return $statement->fetch(\PDO::FETCH_COLUMN);
 }
Esempio n. 30
0
 /**
  * Helper method for sAdmin::sGetPremiumShippingcosts()
  * Calculates payment mean surcharge
  *
  * @param $country
  * @param $payment
  * @param $currencyFactor
  * @param $dispatch
  * @param $discount_tax
  */
 private function handlePaymentMeanSurcharge($country, $payment, $currencyFactor, $dispatch, $discount_tax)
 {
     $surcharge_name = $this->snippetManager->getNamespace('backend/static/discounts_surcharges')->get('payment_surcharge_absolute', 'Surcharge for payment');
     $surcharge_ordernumber = $this->config->get('sPAYMENTSURCHARGEABSOLUTENUMBER', 'PAYMENTSURCHARGEABSOLUTENUMBER');
     $percent_ordernumber = $this->config->get('sPAYMENTSURCHARGENUMBER', "PAYMENTSURCHARGE");
     // Country surcharge
     if (!empty($payment['country_surcharge'][$country['countryiso']])) {
         $payment['surcharge'] += $payment['country_surcharge'][$country['countryiso']];
     }
     $payment['surcharge'] = round($payment['surcharge'] * $currencyFactor, 2);
     // Fixed surcharge
     if (!empty($payment['surcharge']) && (empty($dispatch) || $dispatch['surcharge_calculation'] == 3)) {
         $surcharge = round($payment['surcharge'], 2);
         $payment['surcharge'] = 0;
         if (empty($this->sSYSTEM->sUSERGROUPDATA["tax"]) && !empty($this->sSYSTEM->sUSERGROUPDATA["id"])) {
             $surcharge_net = $surcharge;
             //$tax_rate = 0;
         } else {
             $surcharge_net = round($surcharge / (100 + $discount_tax) * 100, 2);
         }
         $tax_rate = $discount_tax;
         $this->db->insert('s_order_basket', array('sessionID' => $this->session->offsetGet('sessionId'), 'articlename' => $surcharge_name, 'articleID' => 0, 'ordernumber' => $surcharge_ordernumber, 'quantity' => 1, 'price' => $surcharge, 'netprice' => $surcharge_net, 'tax_rate' => $tax_rate, 'datum' => new Zend_Date(), 'modus' => 4, 'currencyFactor' => $currencyFactor));
     }
     // Percentage surcharge
     if (!empty($payment['debit_percent']) && (empty($dispatch) || $dispatch['surcharge_calculation'] != 2)) {
         $amount = $this->db->fetchOne('SELECT SUM(quantity*price) as amount
             FROM s_order_basket
             WHERE sessionID = ? GROUP BY sessionID', array($this->session->offsetGet('sessionId')));
         $percent = round($amount / 100 * $payment['debit_percent'], 2);
         if ($percent > 0) {
             $percent_name = $this->snippetManager->getNamespace('backend/static/discounts_surcharges')->get('payment_surcharge_add');
         } else {
             $percent_name = $this->snippetManager->getNamespace('backend/static/discounts_surcharges')->get('payment_surcharge_dev');
         }
         if (empty($this->sSYSTEM->sUSERGROUPDATA["tax"]) && !empty($this->sSYSTEM->sUSERGROUPDATA["id"])) {
             $percent_net = $percent;
         } else {
             $percent_net = round($percent / (100 + $discount_tax) * 100, 2);
         }
         $tax_rate = $discount_tax;
         $this->db->insert('s_order_basket', array('sessionID' => $this->session->offsetGet('sessionId'), 'articlename' => $percent_name, 'articleID' => 0, 'ordernumber' => $percent_ordernumber, 'quantity' => 1, 'price' => $percent, 'netprice' => $percent_net, 'tax_rate' => $tax_rate, 'datum' => new Zend_Date(), 'modus' => 4, 'currencyFactor' => $currencyFactor));
     }
     return $payment;
 }