/** * This method controls the default routing. Don't be called when the * Enlight_Controller_Router_Route event canceled the default routing. * The default routing uses the dispatcher of the front controller to route * the request to the corresponding controller method. * * @param Enlight_Controller_Request_RequestHttp $request * @return array */ public function routeDefault(Enlight_Controller_Request_RequestHttp $request) { $path = $request->getPathInfo(); if (empty($path)) { return array(); } $dispatcher = $this->front->Dispatcher(); $query = array(); $params = array(); foreach (explode($this->separator, trim($path, $this->separator)) as $routePart) { $routePart = urldecode($routePart); if (empty($query[$request->getModuleKey()]) && $dispatcher->isValidModule($routePart)) { $query[$request->getModuleKey()] = $routePart; } elseif (empty($query[$request->getControllerKey()])) { $query[$request->getControllerKey()] = $routePart; } elseif (empty($query[$request->getActionKey()])) { $query[$request->getActionKey()] = $routePart; } else { $params[] = $routePart; } } if ($params) { $chunks = array_chunk($params, 2, false); foreach ($chunks as $chunk) { if (isset($chunk[1])) { $query[$chunk[0]] = $chunk[1]; } else { $query[$chunk[0]] = ''; } } } return $query; }
/** * @inheritdoc */ public function handleRequest(Request $request, Criteria $criteria, ShopContextInterface $context) { if ($request->has('esd')) { $criteria->addCondition(new EsdCondition()); } if ($request->get('sSort') == 'random') { $criteria->addSorting(new RandomSorting()); } $criteria->addFacet(new EsdFacet()); }
/** * Listener method for the Enlight_Controller_Front_DispatchLoopStartup event. * * @param \Enlight_Controller_EventArgs $args */ public function onDispatchLoopStartup(Enlight_Controller_EventArgs $args) { $this->request = $args->getSubject()->Request(); $this->response = $args->getSubject()->Response(); if ($this->request->getModuleName() != 'api') { return; } $this->isApiCall = true; $router = new \ShopwarePlugins\RestApi\Components\Router(); $router->assembleRoute($this->request, $this->response); }
public function testRequestQueriesGettingReplacd() { $request = new \Enlight_Controller_Request_RequestHttp(); $request->setQuery('q', 'someValue'); $request->setQuery('p', 'someOtherValue'); $request->setQuery('someParam', 'someValue'); $mapping = ['sSearch' => 'q', 'sPage' => 'p']; $mapper = new QueryAliasMapper($mapping); $mapper->replaceShortRequestQueries($request); $expected = ['someParam' => 'someValue', 'sSearch' => 'someValue', 'sPage' => 'someOtherValue']; $this->assertEquals($expected, $request->getParams()); }
public function handleRequest(Request $request, Criteria $criteria, ShopContextInterface $context) { $minSales = $request->getParam('minSales', null); $maxSales = $request->getParam('maxSales', null); if ($minSales || $maxSales) { $criteria->addCondition(new SalesCondition($minSales, $maxSales)); } $criteria->addFacet(new SalesFacet()); if ($request->getParams('sSort') == 'sales') { $criteria->resetSorting(); $criteria->addSorting(new SalesSorting()); } }
/** * @inheritdoc */ public function handleRequest(Request $request, Criteria $criteria, ShopContextInterface $context) { /* * Checks if the filter is active */ if ($request->has('productAttributesForm')) { $params = $request->getParams(); $searchParams = explode('|', $params['productAttributesForm']); $criteria->addCondition(new ProductAttributeCondition('attr1', ProductAttributeCondition::OPERATOR_IN, $searchParams)); } /** * adds the attributes facet */ $criteria->addFacet(new ProductAttributeFacet('attr1', ProductAttributeFacet::MODE_VALUE_LIST_RESULT, 'productAttributesForm', 'attributes')); }
/** * {@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; }
public function sGetImageLink($hash, $imageSize = null) { if (!empty($hash)) { $sql = "SELECT articleID FROM s_articles_img WHERE img =?"; $articleId = Shopware()->Db()->fetchOne($sql, array($hash)); $imageSize = intval($imageSize); $image = $this->getArticleRepository()->getArticleCoverImageQuery($articleId)->getOneOrNullResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY); if (empty($image)) { return ""; } //first we get all thumbnail sizes of the article album $sizes = $this->articleMediaAlbum->getSettings()->getThumbnailSize(); //now we get the configured image and thumbnail dir. $imageDir = 'http://' . $this->shop->getHost() . $this->request->getBasePath() . '/media/image/'; $thumbDir = $imageDir . 'thumbnail/'; foreach ($sizes as $key => $size) { if (strpos($size, 'x') === 0) { $size = $size . 'x' . $size; } $imageData[$key] = $thumbDir . $image['path'] . '_' . $size . '.' . $image['extension']; } if (!empty($imageData)) { return $imageData[$imageSize]; } } return ""; }
/** * @param Request $request * @param Criteria $criteria */ private function addPropertyCondition(Request $request, Criteria $criteria) { $filters = $request->getParam('sFilterProperties', []); if (empty($filters)) { return; } $filters = explode('|', $filters); $filters = $this->getGroupedFilters($filters); if (empty($filters)) { return; } foreach ($filters as $filter) { $condition = new PropertyCondition($filter); $criteria->addCondition($condition); } }
/** * * @param $exception \Exception * * @throws \Exception * @return void */ private function handleException($exception) { $request = new \Enlight_Controller_Request_RequestHttp(); $response = new \Enlight_Controller_Response_ResponseHttp(); if ($this->isModelException($exception)) { $generator = $this->container->get('models')->createModelGenerator(); $result = $generator->generateAttributeModels(); if ($result['success'] === true) { $response->setRedirect($request->getRequestUri()); setcookie(self::redirectCookieString, true, time() + 5); $response->sendResponse(); exit; } else { die(sprintf("Failed to create the attribute models, please check the permissions of the '%s' directory", $generator->getPath())); } } }
/** * @param Request $request * @param Criteria $criteria * @param ShopContextInterface $context */ public function handleRequest(Request $request, Criteria $criteria, ShopContextInterface $context) { $requestedCategoryId = $request->getParam('sCategory', $request->getParam('categoryId', false)); if (!$requestedCategoryId) { return; } $closestIdWithRules = $this->databaseAdapter->fetchClosestCategoryIdWithRule($requestedCategoryId); if (!$closestIdWithRules) { return; } $this->enabled = true; if ($request->sSort && $request->sSort != self::REQUEST_VALUE) { return; } $request->setParam('sSort', self::REQUEST_VALUE); $rules = $this->ruleHydrator->createRuleVos($this->databaseAdapter->fetchRawData($closestIdWithRules)); $criteria->resetSorting(); $criteria->addSorting(new DefaultSorting($rules)); }
/** * Secure cron actions according to system settings * * @param Enlight_Controller_Request_RequestHttp $request * @return bool If cron action is authorized */ public function authorizeCronAction($request) { // If called using CLI, always execute the cron tasks if (php_sapi_name() == 'cli') { return true; } // At least one of the security policies is enabled. // If at least one of them validates, cron tasks will be executed $cronSecureAllowedKey = Shopware()->Config()->get('cronSecureAllowedKey'); $cronSecureAllowedIp = Shopware()->Config()->get('cronSecureAllowedIp'); $cronSecureByAccount = Shopware()->Config()->get('cronSecureByAccount'); // No security policy specified, accept all requests if (empty($cronSecureAllowedKey) && empty($cronSecureAllowedIp) && !$cronSecureByAccount) { return true; } // Validate key if (!empty($cronSecureAllowedKey)) { $urlKey = $request->getParam('key'); if (strcmp($cronSecureAllowedKey, $urlKey) == 0) { return true; } } // Validate ip if (!empty($cronSecureAllowedIp)) { $requestIp = $request->getServer('REMOTE_ADDR'); if (in_array($requestIp, explode(';', $cronSecureAllowedIp))) { return true; } } // Validate user auth if ($cronSecureByAccount) { if (Shopware()->Auth()->hasIdentity() === true) { return true; } } return false; }
/** * Initiate shopware auth resource * database adapter by default * * @param Enlight_Event_EventArgs $args * @throws Exception * @return null|\Zend_Auth */ public function onInitResourceBackendSession(Enlight_Event_EventArgs $args) { $options = $this->Application()->getOption('backendSession', array()); if (!isset($options['cookie_path']) && $this->request !== null) { $options['cookie_path'] = rtrim($this->request->getBaseUrl(), '/') . '/backend/'; } if (empty($options['gc_maxlifetime'])) { $backendTimeout = $this->Config()->get('backendTimeout', 60 * 90); $options['gc_maxlifetime'] = $backendTimeout; } $refererCheck = false; $clientCheck = false; if(is_bool($options['referer_check'])) { $refererCheck = $options['referer_check']; unset($options['referer_check']); } if(!empty($options['client_check'])) { $clientCheck = true; } unset($options['client_check']); Enlight_Components_Session::start($options); $referer = $this->request->getHeader('referer'); if($refererCheck && $referer !== null && strpos($referer, 'http') === 0) { $referer = substr($referer, 0, strpos($referer, '/backend/')); $referer .= '/backend/'; if(!isset($_SESSION['__SW_REFERER'])) { $_SESSION['__SW_REFERER'] = $referer; } elseif (strpos($referer, $_SESSION['__SW_REFERER']) !== 0) { Enlight_Components_Session::destroy(); throw new Exception('Referer check for backend session failed'); } } $client = $this->request->getHeader('userAgent'); if($clientCheck && $client !== null) { if(!isset($_SESSION['__SW_CLIENT'])) { $_SESSION['__SW_CLIENT'] = $client; } elseif ($client !== $_SESSION['__SW_CLIENT']) { Enlight_Components_Session::destroy(); throw new Exception('Client check for backend session failed'); } } return new Enlight_Components_Session_Namespace('ShopwareBackend'); }
/** * Initiate shopware auth resource * database adapter by default * * @param Enlight_Event_EventArgs $args * @throws Exception * @return null|\Zend_Auth */ public function onInitResourceBackendSession(Enlight_Event_EventArgs $args) { $options = $this->Application()->getOption('backendSession', array()); if (!isset($options['cookie_path']) && $this->request !== null) { $options['cookie_path'] = rtrim($this->request->getBaseUrl(), '/') . '/backend/'; } if (empty($options['gc_maxlifetime'])) { $backendTimeout = $this->Config()->get('backendTimeout', 60 * 90); $options['gc_maxlifetime'] = $backendTimeout; } $refererCheck = false; $clientCheck = false; if (is_bool($options['referer_check'])) { $refererCheck = $options['referer_check']; unset($options['referer_check']); } if (!empty($options['client_check'])) { $clientCheck = true; } unset($options['client_check']); if (!isset($options['save_handler']) || $options['save_handler'] == 'db') { // SW-4819 Add database backend support $config_save_handler = array('name' => 's_core_sessions_backend', 'primary' => 'id', 'modifiedColumn' => 'modified', 'dataColumn' => 'data', 'lifetimeColumn' => 'expiry'); Enlight_Components_Session::setSaveHandler(new Enlight_Components_Session_SaveHandler_DbTable($config_save_handler)); } Enlight_Components_Session::start($options); if ($refererCheck && ($referer = $this->request->getHeader('referer')) !== null && strpos($referer, 'http') === 0) { $referer = substr($referer, 0, strpos($referer, '/backend/')); $referer .= '/backend/'; if (!isset($_SESSION['__SW_REFERER'])) { $_SESSION['__SW_REFERER'] = $referer; } elseif (strpos($referer, $_SESSION['__SW_REFERER']) !== 0) { Enlight_Components_Session::destroy(); throw new Exception('Referer check for backend session failed'); } } if ($clientCheck && ($client = $this->request->getHeader('userAgent')) !== null) { if (!isset($_SESSION['__SW_CLIENT'])) { $_SESSION['__SW_CLIENT'] = $client; } elseif ($client !== $_SESSION['__SW_CLIENT']) { Enlight_Components_Session::destroy(); throw new Exception('Client check for backend session failed'); } } return new Enlight_Components_Session_Namespace('ShopwareBackend'); }
/** * * @param $exception Exception * * @throws Exception * @return void */ public function handleException($exception) { $this->request = new Enlight_Controller_Request_RequestHttp(); $this->response = new Enlight_Controller_Response_ResponseHttp(); if ($this->isModelException($exception)) { $path = Shopware()->Models()->getConfiguration()->getAttributeDir(); $result = $this->generateModels($path); if ($result['success'] === true) { $this->response->setRedirect($this->request->getRequestUri()); setcookie(self::redirectCookieString, true, time() + 5); $this->response->sendResponse(); exit; } else { die(sprintf("Failed to create the attribute models, please check the permissions of the '%s' directory", $path)); } } }
/** * Invalidates a given $cacheId * * This sends a http-ban-request to the proxyUrl containing * the $cacheId in the x-shopware-invalidates http-header * * @param string $cacheId * @return bool */ protected function invalidateCacheId($cacheId) { if (!$this->Config()->get('proxyPrune')) { return false; } $proxyUrl = $this->getProxyUrl($this->request); if ($proxyUrl === null) { return false; } if (!$this->request || $this->request->getHeader('Surrogate-Capability') === false) { return false; } try { $client = new Zend_Http_Client($proxyUrl, array('useragent' => 'Shopware/' . Shopware()->Config()->get('version'), 'timeout' => 5)); $client->setHeaders('x-shopware-invalidates', $cacheId)->request('BAN'); } catch (\Exception $e) { return false; } return true; }
/** * Refresh partner log * * @param \Enlight_Controller_Request_RequestHttp $request * @param \Enlight_Controller_Response_ResponseHttp $response */ public function refreshPartner($request, $response) { $partner = $request->getParam('partner', $request->getParam('sPartner')); if ($partner !== null) { if (strpos($partner, 'sCampaign') === 0) { $campaignID = (int) str_replace('sCampaign', '', $partner); if (!empty($campaignID)) { Shopware()->Session()->sPartner = 'sCampaign' . $campaignID; $sql = ' UPDATE s_campaigns_mailings SET clicked = clicked + 1 WHERE id = ? '; Shopware()->Db()->query($sql, array($campaignID)); } } else { $sql = 'SELECT * FROM s_emarketing_partner WHERE active=1 AND idcode=?'; $row = Shopware()->Db()->fetchRow($sql, array($partner)); if (!empty($row)) { if ($row['cookielifetime']) { $valid = time() + $row['cookielifetime']; } else { $valid = 0; } $response->setCookie('partner', $row['idcode'], $valid, '/'); } Shopware()->Session()->sPartner = $partner; } } elseif ($request->getCookie('partner') !== null) { $sql = 'SELECT idcode FROM s_emarketing_partner WHERE active=1 AND idcode=?'; $partner = Shopware()->Db()->fetchOne($sql, array($request->getCookie('partner'))); if (empty($partner)) { unset(Shopware()->Session()->sPartner); } else { Shopware()->Session()->sPartner = $partner; } } }
/** * @param EnlightRequest $request */ public function updateFromEnlightRequest(EnlightRequest $request) { $this->setHost($request->getHttpHost()); $this->setBaseUrl($request->getBaseUrl()); $this->setSecure($request->isSecure()); $this->setGlobalParams(self::getGlobalParamsFromRequest($request)); $this->setParams($request->getQuery()); }
/** * This function controls the buyer protection item in the basket. * * @param \Enlight_Controller_Action $controller * @param \Enlight_Controller_Request_RequestHttp $request * @param $basketAmount * @return void */ private function controlBasketTsArticle($controller, $request, $basketAmount) { //get total basket amount $amount = $this->getAmount($controller->getShippingCosts(), $basketAmount); $basketArticle = $this->isTsArticleInBasket(); //Always use the brutto-value if ($controller->View()->sAmountWithTax) { $amount = $controller->View()->sAmountWithTax; } if (empty($basketArticle)) { return; } $sql = "SELECT COUNT(id)\n\t\t\t\tFROM s_order_basket\n\t\t\t\tWHERE sessionID = ?\n\t\t\t\t\tAND modus = 0"; $articleAmount = $this->db->fetchOne($sql, array($this->sessionId)); if ($articleAmount > 1) { if ($amount > 0) { //get trusted shop article data $toAddArticle = $this->getTsArticleByAmount($amount); if ($toAddArticle['tsProductID'] == $basketArticle['ordernumber']) { return; } } } $sql = "DELETE FROM s_order_basket\n\t\t\t\tWHERE id = ?\n\t\t\t\t\tAND sessionID = ?"; $this->db->query($sql, array($basketArticle['id'], $this->sessionId)); $controller->View()->sTsArticleRemoved = true; $controller->forward($request->getActionName()); }
/** * Returns an array with all current values in _POST * * @return array */ public function toArray() { return $this->request->getPost(); }
/** * @param $categoryId * @param Enlight_Controller_Request_RequestHttp $request * @return string */ private function buildCategoryLink($categoryId, Enlight_Controller_Request_RequestHttp $request) { $params = $this->queryAliasMapper->replaceLongParams($request->getParams()); unset($params['ordernumber']); unset($params['categoryId']); unset($params['module']); unset($params['controller']); unset($params['action']); $params = array_merge($params, ['sViewport' => 'cat', 'sCategory' => $categoryId]); $queryPrams = http_build_query($params, null, '&'); $listingLink = $this->config->get('sBASEFILE') . "?" . $queryPrams; return $listingLink; }
/** * @param Request $request * @param Criteria $criteria */ private function addLimit(Request $request, Criteria $criteria) { $limit = $request->getParam('sPerPage', (int) $this->config->get('articlesPerPage')); $criteria->limit($limit); }
/** * @param Enlight_Controller_Request_RequestHttp $request */ protected function fixRequest($request) { $aliases = array('sViewport' => 'controller', 'sAction' => 'action'); foreach ($aliases as $key => $alias) { if (($value = $request->getParam($key)) !== null) { $request->setParam($alias, $value); $request->setAlias($key, $alias); } } $request->setQuery($request->getUserParams() + $request->getQuery()); }
/** * Returns an array with all current values in _COOKIE * * @return array */ public function toArray() { return $this->request->getCookie(); }
private function getSearchLinks(Request $request, Criteria $criteria) { $filters = array('sSort', 'sPerPage', 'sFilter_supplier', 'sFilter_category', 'sFilter_price', 'sFilter_propertygroup'); $activeFilters = array(); foreach ($filters as $filter) { if (!$request->has($filter) || !$request->getParam($filter)) { continue; } $activeFilters[$filter] = $request->getParam($filter); } $activeFilters['sSearch'] = $criteria->getCondition('search')->getTerm(); /**@var $searchTerm SearchTermCondition*/ $searchTerm = $criteria->getCondition('search'); $baseLink = $this->container->get('config')->get('baseFile') . '?sViewport=search&sSearch=' . urlencode($searchTerm->getTerm()); $withoutSort = $activeFilters; $withoutPerPage = $activeFilters; $withoutCategory = $activeFilters; $withoutSupplier = $activeFilters; $withoutPrice = $activeFilters; $withoutProperty = $activeFilters; unset($withoutSort['sSort']); unset($withoutPerPage['sPerPage']); unset($withoutCategory['sFilter_category']); unset($withoutSupplier['sFilter_supplier']); unset($withoutPrice['sFilter_price']); unset($withoutProperty['sFilter_propertygroup']); $links = array('sLink' => $baseLink, 'sSearch' => $this->container->get('router')->assemble(array('sViewport' => 'search')), 'sPage' => $baseLink . '&' . http_build_query($activeFilters, "", "&"), 'sSort' => $baseLink . '&' . http_build_query($withoutSort, "", "&"), 'sPerPage' => $baseLink . '&' . http_build_query($withoutPerPage, "", "&"), 'sFilter' => array('category' => $baseLink . '&' . http_build_query($withoutCategory, "", "&"), 'supplier' => $baseLink . '&' . http_build_query($withoutSupplier, "", "&"), 'price' => $baseLink . '&' . http_build_query($withoutPrice, "", "&"), 'property' => $baseLink . '&' . http_build_query($withoutProperty, "", "&"))); return $links; }
/** * @param \Enlight_Controller_Request_RequestHttp $request * @return \Shopware\Models\Shop\Shop */ public function getActiveByRequest($request) { /** @var $shop \Shopware\Models\Shop\Shop */ $shop = null; $host = $request->getHttpHost(); if (empty($host)) { return $shop; } $requestPath = $request->getRequestUri(); $builder = $this->getActiveQueryBuilder(); $builder->andWhere("shop.host=:host OR (shop.host IS NULL AND main.host=:host)"); if ($request->isSecure()) { $builder->orWhere("shop.secureHost=:host OR (shop.secureHost IS NULL AND main.secureHost=:host)"); } $builder->setParameter('host', $host); /** @var $shops \Shopware\Models\Shop\Shop[] */ $shops = $builder->getQuery()->getResult(); foreach ($shops as $currentShop) { $this->fixActive($currentShop); } //returns the right shop depending on the url $shop = $this->getShopByRequest($shops, $requestPath); if ($shop !== null) { return $shop; } $builder = $this->getActiveQueryBuilder(); $builder->andWhere('shop.hosts LIKE :host1 OR shop.hosts LIKE :host2 OR shop.hosts LIKE :host3')->setParameter('host1', "%\n" . $host . "\n%")->setParameter('host2', $host . "\n%")->setParameter('host3', "%\n" . $host); $shop = $builder->getQuery()->getOneOrNullResult(); if ($shop !== null) { $this->fixActive($shop); } return $shop; }
/** * @param \Enlight_Controller_Request_RequestHttp $request * @return \Shopware\Models\Shop\Shop */ public function getActiveByRequest($request) { /** @var $shop \Shopware\Models\Shop\Shop */ $shop = null; $host = $request->getHttpHost(); $requestPath = $request->getRequestUri(); $builder = $this->getActiveQueryBuilder(); $builder->andWhere("shop.host=:host OR (shop.host IS NULL AND main.host=:host)"); if($request->isSecure()) { $builder->orWhere("shop.secureHost=:host OR (shop.secureHost IS NULL AND main.secureHost=:host)"); } $builder->setParameter('host', $host); /** @var $shops \Shopware\Models\Shop\Shop[] */ $shops = $builder->getQuery()->getResult(); foreach ($shops as $currentShop) { $this->getEntityManager()->detach($currentShop); if ($currentShop->getBasePath() === null) { $shop = $currentShop; } elseif (strpos($requestPath, $currentShop->getBasePath()) === 0) { $shop = $currentShop; break; } } if ($shop === null) { $builder = $this->getActiveQueryBuilder(); $builder->andWhere('shop.hosts LIKE :host') ->setParameter('host', '%' . $host . '%'); $shop = $builder->getQuery()->getOneOrNullResult(); } if ($shop !== null) { $this->fixActive($shop); } return $shop; }
/** * @param Request $request * @return bool */ public function acceptsRequest(Request $request) { $firePhpVersion = $request->getHeader('X-FirePHP-Version'); $userAgent = preg_match('{\\bFirePHP/\\d+\\.\\d+\\b}', $request->getHeader('User-Agent')); return $firePhpVersion || $userAgent; }
/** * @param Enlight_Controller_Request_RequestHttp $request * @return bool */ public function isRequestAllowed(\Enlight_Controller_Request_RequestHttp $request) { $clientIp = $request->getClientIp(); $allowedIp = $this->Config()->get('AllowIP'); if (empty($allowedIp)) { return true; } if (empty($clientIp)) { return false; } return strpos($allowedIp, $clientIp) !== false; }
/** * Returns the symfony request context. * * @param Enlight_Controller_Request_RequestHttp $request * @return Symfony\Component\Routing\RequestContext */ protected function getRequestContext($request) { return new RequestContext('', $request->getMethod(), $request->getHttpHost(), $request->getScheme()); }