/** * */ public function dispatchLoopShutdown() { if (!Tool::isHtmlResponse($this->getResponse())) { return; } if (!Tool::useFrontendOutputFilters($this->getRequest()) && !$this->getRequest()->getParam("pimcore_preview")) { return; } if (isset($_COOKIE["pimcore_admin_sid"])) { try { // we should not start a session here as this can break the functionality of the site if // the website itself uses sessions, so we include the code, and check asynchronously if the user is logged in // this is done by the embedded script $body = $this->getResponse()->getBody(); $document = $this->getRequest()->getParam("document"); if ($document instanceof Model\Document && !Model\Staticroute::getCurrentRoute()) { $documentId = $document->getId(); } if (!isset($documentId) || !$documentId) { $documentId = "null"; } $code = '<script type="text/javascript" src="/admin/admin-button/script?documentId=' . $documentId . '"></script>'; // search for the end <head> tag, and insert the google analytics code before // this method is much faster than using simple_html_dom and uses less memory $bodyEndPosition = stripos($body, "</body>"); if ($bodyEndPosition !== false) { $body = substr_replace($body, $code . "\n\n</body>\n", $bodyEndPosition, 7); } $this->getResponse()->setBody($body); } catch (\Exception $e) { \Logger::error($e); } } }
/** * Loads a list of static routes for the specicifies parameters, returns an array of Staticroute elements * * @return array */ public function load() { $routesData = $this->db->fetchCol("SELECT id FROM staticroutes" . $this->getCondition() . $this->getOrder() . $this->getOffsetLimit(), $this->model->getConditionVariables()); $routes = array(); foreach ($routesData as $routeData) { $routes[] = Model\Staticroute::getById($routeData); } $this->model->setRoutes($routes); return $routes; }
/** * Loads a list of static routes for the specicifies parameters, returns an array of Staticroute elements * * @return array */ public function load() { $routesData = $this->db->fetchAll($this->model->getFilter(), $this->model->getOrder()); $routes = []; foreach ($routesData as $routeData) { $routes[] = Model\Staticroute::getById($routeData["id"]); } $this->model->setRoutes($routes); return $routes; }
/** * Checks if Controller is available in Template and use it. * * @param \Zend_Controller_Request_Abstract $request */ public function routeShutdown(\Zend_Controller_Request_Abstract $request) { $gatewayRequest = clone $request; if ($request->getModuleName() === 'Omnipay') { $frontController = \Zend_Controller_Front::getInstance(); $route = Staticroute::getCurrentRoute(); if ($route) { if ($route->getName() === "coreshop_omnipay_payment") { $gateway = ucfirst($request->getParam("gateway")); $gatewayRequest->setControllerName($gateway); if ($frontController->getDispatcher()->isDispatchable($gatewayRequest)) { $request->setControllerName($gateway); } } } } }
/** * @throws \Zend_Controller_Router_Exception */ public function init() { // this is only executed once per request (first request) if (self::$isInitial) { \Pimcore::getEventManager()->trigger("frontend.controller.preInit", $this); } parent::init(); // log exceptions if handled by error_handler $this->checkForErrors(); // general definitions if (self::$isInitial) { \Pimcore::unsetAdminMode(); Document::setHideUnpublished(true); Object\AbstractObject::setHideUnpublished(true); Object\AbstractObject::setGetInheritedValues(true); Object\Localizedfield::setGetFallbackValues(true); } // assign variables $this->view->controller = $this; // init website config $config = Config::getWebsiteConfig(); $this->config = $config; $this->view->config = $config; $document = $this->getParam("document"); if (!$document instanceof Document) { \Zend_Registry::set("pimcore_editmode", false); $this->editmode = false; $this->view->editmode = false; self::$isInitial = false; // check for a locale first, and set it if available if ($this->getParam("pimcore_parentDocument")) { // this is a special exception for renderlets in editmode (ajax request), because they depend on the locale of the parent document // otherwise there'll be notices like: Notice: 'No translation for the language 'XX' available.' if ($parentDocument = Document::getById($this->getParam("pimcore_parentDocument"))) { if ($parentDocument->getProperty("language")) { $this->setLocaleFromDocument($parentDocument->getProperty("language")); } } } // no document available, continue, ... return; } else { $this->setDocument($document); // register global locale if the document has the system property "language" if ($this->getDocument()->getProperty("language")) { $this->setLocaleFromDocument($this->getDocument()->getProperty("language")); } if (self::$isInitial) { // append meta-data to the headMeta() view helper, if it is a document-request if (!Model\Staticroute::getCurrentRoute() && $this->getDocument() instanceof Document\Page) { if (is_array($this->getDocument()->getMetaData())) { foreach ($this->getDocument()->getMetaData() as $meta) { // only name if (!empty($meta["idName"]) && !empty($meta["idValue"]) && !empty($meta["contentValue"])) { $method = "append" . ucfirst($meta["idName"]); $this->view->headMeta()->{$method}($meta["idValue"], $meta["contentValue"]); } } } } } } // this is only executed once per request (first request) if (self::$isInitial) { // contains the logged in user if necessary $user = null; // default is to set the editmode to false, is enabled later if necessary \Zend_Registry::set("pimcore_editmode", false); if (Tool::isFrontentRequestByAdmin()) { $this->disableBrowserCache(); // start admin session & get logged in user $user = Authentication::authenticateSession(); } if (\Pimcore::inDebugMode()) { $this->disableBrowserCache(); } if (!$this->document->isPublished()) { if (Tool::isFrontentRequestByAdmin()) { if (!$user) { throw new \Zend_Controller_Router_Exception("access denied for " . $this->document->getFullPath()); } } else { throw new \Zend_Controller_Router_Exception("access denied for " . $this->document->getFullPath()); } } // logged in users only if ($user) { // set the user to registry so that it is available via \Pimcore\Tool\Admin::getCurrentUser(); \Zend_Registry::set("pimcore_admin_user", $user); // document editmode if ($this->getParam("pimcore_editmode")) { \Zend_Registry::set("pimcore_editmode", true); // check if there is the document in the session $docKey = "document_" . $this->getDocument()->getId(); $docSession = Session::getReadOnly("pimcore_documents"); if ($docSession->{$docKey}) { // if there is a document in the session use it $this->setDocument($docSession->{$docKey}); } else { // set the latest available version for editmode if there is no doc in the session $latestVersion = $this->getDocument()->getLatestVersion(); if ($latestVersion) { $latestDoc = $latestVersion->loadData(); if ($latestDoc instanceof Document\PageSnippet) { $this->setDocument($latestDoc); } } } // register editmode plugin $front = \Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Pimcore\Controller\Plugin\Frontend\Editmode($this), 1000); } // document preview if ($this->getParam("pimcore_preview")) { // get document from session $docKey = "document_" . $this->getParam("document")->getId(); $docSession = Session::getReadOnly("pimcore_documents"); if ($docSession->{$docKey}) { $this->setDocument($docSession->{$docKey}); } } // object preview if ($this->getParam("pimcore_object_preview")) { $key = "object_" . $this->getParam("pimcore_object_preview"); $session = Session::getReadOnly("pimcore_objects"); if ($session->{$key}) { $object = $session->{$key}; // add the object to the registry so every call to Object::getById() will return this object instead of the real one \Zend_Registry::set("object_" . $object->getId(), $object); } } // for version preview if ($this->getParam("pimcore_version")) { // only get version data at the first call || because of embedded Snippets ... if (!\Zend_Registry::isRegistered("pimcore_version_active")) { $version = Model\Version::getById($this->getParam("pimcore_version")); $this->setDocument($version->getData()); \Zend_Registry::set("pimcore_version_active", true); } } } // for public versions if ($this->getParam("v")) { try { $version = Model\Version::getById($this->getParam("v")); if ($version->getPublic()) { $this->setDocument($version->getData()); } } catch (\Exception $e) { } } // check for persona if ($this->getDocument() instanceof Document\Page) { $this->getDocument()->setUsePersona(null); // reset because of preview and editmode (saved in session) if ($this->getParam("_ptp") && self::$isInitial) { $this->getDocument()->setUsePersona($this->getParam("_ptp")); } } // check if document is a wrapped hardlink, if this is the case send a rel=canonical header to the source document if ($this->getDocument() instanceof Document\Hardlink\Wrapper\WrapperInterface) { // get the cononical (source) document $hardlinkCanonicalSourceDocument = Document::getById($this->getDocument()->getId()); $request = $this->getRequest(); if (\Pimcore\Tool\Frontend::isDocumentInCurrentSite($hardlinkCanonicalSourceDocument)) { $this->getResponse()->setHeader("Link", '<' . $request->getScheme() . "://" . $request->getHttpHost() . $hardlinkCanonicalSourceDocument->getFullPath() . '>; rel="canonical"'); } } \Pimcore::getEventManager()->trigger("frontend.controller.postInit", $this); } // set some parameters $this->editmode = \Zend_Registry::get("pimcore_editmode"); $this->view->editmode = \Zend_Registry::get("pimcore_editmode"); self::$isInitial = false; }
public function removeStaticRoutes() { $conf = new \Zend_Config_Xml(PIMCORE_PLUGINS_PATH . '/CoreShop/install/staticroutes.xml'); foreach ($conf->routes->route as $def) { $route = Staticroute::getByName($def->name); if ($route) { $route->delete(); } } }
/** * */ public function dispatchLoopShutdown() { if (!Tool::isHtmlResponse($this->getResponse())) { return; } if ($this->enabled) { $targets = array(); $personas = array(); $dataPush = array("personas" => $this->personas, "method" => strtolower($this->getRequest()->getMethod())); if (count($this->events) > 0) { $dataPush["events"] = $this->events; } if ($this->document instanceof Document\Page && !Model\Staticroute::getCurrentRoute()) { $dataPush["document"] = $this->document->getId(); if ($this->document->getPersonas()) { if ($_GET["_ptp"]) { // if a special version is requested only return this id as target group for this page $dataPush["personas"][] = (int) $_GET["_ptp"]; } else { $docPersonas = explode(",", trim($this->document->getPersonas(), " ,")); // cast the values to int array_walk($docPersonas, function (&$value) { $value = (int) trim($value); }); $dataPush["personas"] = array_merge($dataPush["personas"], $docPersonas); } } // check for persona specific variants of this page $personaVariants = array(); foreach ($this->document->getElements() as $key => $tag) { if (preg_match("/^persona_-([0-9]+)-_/", $key, $matches)) { $id = (int) $matches[1]; if (Model\Tool\Targeting\Persona::isIdActive($id)) { $personaVariants[] = $id; } } } if (!empty($personaVariants)) { $personaVariants = array_values(array_unique($personaVariants)); $dataPush["personaPageVariants"] = $personaVariants; } } // no duplicates $dataPush["personas"] = array_unique($dataPush["personas"]); $activePersonas = array(); foreach ($dataPush["personas"] as $id) { if (Model\Tool\Targeting\Persona::isIdActive($id)) { $activePersonas[] = $id; } } $dataPush["personas"] = $activePersonas; if ($this->document) { // @TODO: cache this $list = new Model\Tool\Targeting\Rule\Listing(); $list->setCondition("active = 1"); foreach ($list->load() as $target) { $redirectUrl = $target->getActions()->getRedirectUrl(); if (is_numeric($redirectUrl)) { $doc = \Document::getById($redirectUrl); if ($doc instanceof \Document) { $target->getActions()->redirectUrl = $doc->getFullPath(); } } $targets[] = $target; } $list = new Model\Tool\Targeting\Persona\Listing(); $list->setCondition("active = 1"); foreach ($list->load() as $persona) { $personas[] = $persona; } } $code = '<script type="text/javascript" src="/pimcore/static/js/frontend/geoip.js/"></script>'; $code .= '<script type="text/javascript">'; $code .= 'var pimcore = pimcore || {};'; $code .= 'pimcore["targeting"] = {};'; $code .= 'pimcore["targeting"]["dataPush"] = ' . \Zend_Json::encode($dataPush) . ';'; $code .= 'pimcore["targeting"]["targetingRules"] = ' . \Zend_Json::encode($targets) . ';'; $code .= 'pimcore["targeting"]["personas"] = ' . \Zend_Json::encode($personas) . ';'; $code .= '</script>'; $code .= '<script type="text/javascript" src="/pimcore/static/js/frontend/targeting.js"></script>'; $code .= "\n"; // analytics $body = $this->getResponse()->getBody(); // search for the end <head> tag, and insert the google analytics code before // this method is much faster than using simple_html_dom and uses less memory $headEndPosition = stripos($body, "<head>"); if ($headEndPosition !== false) { $body = substr_replace($body, "<head>\n" . $code, $headEndPosition, 7); } $this->getResponse()->setBody($body); } }
public function staticroutesAction() { if ($this->getParam("data")) { $this->checkPermission("routes"); $data = \Zend_Json::decode($this->getParam("data")); if (is_array($data)) { foreach ($data as &$value) { if (is_string($value)) { $value = trim($value); } } } if ($this->getParam("xaction") == "destroy") { $data = \Zend_Json::decode($this->getParam("data")); if (\Pimcore\Tool\Admin::isExtJS6()) { $id = $data["id"]; } else { $id = $data; } $route = Staticroute::getById($id); $route->delete(); $this->_helper->json(array("success" => true, "data" => array())); } else { if ($this->getParam("xaction") == "update") { // save routes $route = Staticroute::getById($data["id"]); $route->setValues($data); $route->save(); $this->_helper->json(array("data" => $route, "success" => true)); } else { if ($this->getParam("xaction") == "create") { unset($data["id"]); // save route $route = new Staticroute(); $route->setValues($data); $route->save(); $this->_helper->json(array("data" => $route, "success" => true)); } } } } else { // get list of routes $list = new Staticroute\Listing(); $list->setLimit($this->getParam("limit")); $list->setOffset($this->getParam("start")); $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams()); if ($sortingSettings['orderKey']) { $list->setOrderKey($sortingSettings['orderKey']); $list->setOrder($sortingSettings['order']); } if ($this->getParam("filter")) { $list->setCondition("`name` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . " OR `pattern` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . " OR `reverse` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . " OR `controller` LIKE " . $list->quote("%" . $this->getParam("filter") . "%") . " OR `action` LIKE " . $list->quote("%" . $this->getParam("filter") . "%")); } $list->load(); $routes = array(); foreach ($list->getRoutes() as $route) { $routes[] = $route; } $this->_helper->json(array("data" => $routes, "success" => true, "total" => $list->getTotalCount())); } $this->_helper->json(false); }
/** * @param $path * @param bool $partial * @return array|bool */ public function match($path, $partial = false) { // this allows the usage of UTF8 URLs and within static routes $path = urldecode($path); $front = \Zend_Controller_Front::getInstance(); $matchFound = false; $config = Config::getSystemConfig(); $routeingDefaults = Tool::getRoutingDefaults(); $params = array_merge($_GET, $_POST); $params = array_merge($routeingDefaults, $params); // set the original path $originalPath = $path; // check for password protection (http auth) if ($config->general->http_auth) { $username = $config->general->http_auth->username; $password = $config->general->http_auth->password; if ($username && $password) { $adapter = new \Zend_Auth_Adapter_Http(array("accept_schemes" => "basic", "realm" => $_SERVER["HTTP_HOST"])); $basicResolver = new \Pimcore\Helper\Auth\Adapter\Http\ResolverStatic($username, $password); $adapter->setBasicResolver($basicResolver); $adapter->setRequest($front->getRequest()); $adapter->setResponse($front->getResponse()); $result = $adapter->authenticate(); if (!$result->isValid()) { // Bad userame/password, or canceled password prompt echo "Authentication Required"; $front->getResponse()->sendResponse(); exit; } } } // check for a registered site try { // do not initialize a site if it is a "special" admin request if (!Tool::isFrontentRequestByAdmin()) { $domain = Tool::getHostname(); $site = \Zend_Registry::isRegistered("pimcore_site") ? \Zend_Registry::get("pimcore_site") : Site::getByDomain($domain); $path = $site->getRootPath() . $path; \Zend_Registry::set("pimcore_site", $site); } } catch (\Exception $e) { } // test if there is a suitable redirect with override = all (=> priority = 99) if (!$matchFound) { $this->checkForRedirect(true); } // do not allow requests including /index.php/ => SEO // this is after the first redirect check, to allow redirects in index.php?xxx if (preg_match("@^/index.php(.*)@", $_SERVER["REQUEST_URI"], $matches) && strtolower($_SERVER["REQUEST_METHOD"]) == "get") { $redirectUrl = $matches[1]; $redirectUrl = ltrim($redirectUrl, "/"); $redirectUrl = "/" . $redirectUrl; header("Location: " . $redirectUrl, true, 301); exit; } // redirect to the main domain if specified try { $hostRedirect = null; if ($config->general->redirect_to_maindomain && $config->general->domain && $config->general->domain != Tool::getHostname() && !Site::isSiteRequest() && !Tool::isFrontentRequestByAdmin()) { $hostRedirect = $config->general->domain; } if (Site::isSiteRequest()) { $site = Site::getCurrentSite(); if ($site->getRedirectToMainDomain() && $site->getMainDomain() != Tool::getHostname()) { $hostRedirect = $site->getMainDomain(); } } if ($hostRedirect && !isset($_GET["pimcore_disable_host_redirect"])) { $url = ($front->getRequest()->isSecure() ? "https" : "http") . "://" . $hostRedirect . $_SERVER["REQUEST_URI"]; header("HTTP/1.1 301 Moved Permanently"); header("Location: " . $url, true, 301); // log all redirects to the redirect log \Pimcore\Log\Simple::log("redirect", Tool::getAnonymizedClientIp() . " \t Host-Redirect Source: " . $_SERVER["REQUEST_URI"] . " -> " . $url); exit; } } catch (\Exception $e) { } // check for direct definition of controller/action if (!empty($_REQUEST["controller"]) && !empty($_REQUEST["action"])) { $matchFound = true; //$params["document"] = $this->getNearestDocumentByPath($path); } // you can also call a page by it's ID /?pimcore_document=XXXX if (!$matchFound) { if (!empty($params["pimcore_document"]) || !empty($params["pdid"])) { $doc = Document::getById($params["pimcore_document"] ? $params["pimcore_document"] : $params["pdid"]); if ($doc instanceof Document) { $path = $doc->getFullPath(); } } } // test if there is a suitable page if (!$matchFound) { try { $document = Document::getByPath($path); // check for a pretty url inside a site if (!$document && Site::isSiteRequest()) { $documentService = new Document\Service(); $sitePrettyDocId = $documentService->getDocumentIdByPrettyUrlInSite(Site::getCurrentSite(), $originalPath); if ($sitePrettyDocId) { if ($sitePrettyDoc = Document::getById($sitePrettyDocId)) { $document = $sitePrettyDoc; // undo the modification of the path by the site detection (prefixing with site root path) // this is not necessary when using pretty-urls and will cause problems when validating the // prettyUrl later (redirecting to the prettyUrl in the case the page was called by the real path) $path = $originalPath; } } } // check for a parent hardlink with childs if (!$document instanceof Document) { $hardlinkedParentDocument = $this->getNearestDocumentByPath($path, true); if ($hardlinkedParentDocument instanceof Document\Hardlink) { if ($hardLinkedDocument = Document\Hardlink\Service::getChildByPath($hardlinkedParentDocument, $path)) { $document = $hardLinkedDocument; } } } // check for direct hardlink if ($document instanceof Document\Hardlink) { $hardlinkParentDocument = $document; $document = Document\Hardlink\Service::wrap($hardlinkParentDocument); } if ($document instanceof Document) { if (in_array($document->getType(), self::getDirectRouteDocumentTypes())) { if (Tool::isFrontentRequestByAdmin() || $document->isPublished()) { // check for a pretty url, and if the document is called by that, otherwise redirect to pretty url if ($document instanceof Document\Page && !$document instanceof Document\Hardlink\Wrapper\WrapperInterface && $document->getPrettyUrl() && !Tool::isFrontentRequestByAdmin()) { if (rtrim(strtolower($document->getPrettyUrl()), " /") != rtrim(strtolower($originalPath), "/")) { $redirectUrl = $document->getPrettyUrl(); if ($_SERVER["QUERY_STRING"]) { $redirectUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectUrl, true, 301); exit; } } $params["document"] = $document; if ($controller = $document->getController()) { $params["controller"] = $controller; $params["action"] = "index"; } if ($action = $document->getAction()) { $params["action"] = $action; } if ($module = $document->getModule()) { $params["module"] = $module; } // check for a trailing slash in path, if exists, redirect to this page without the slash // the only reason for this is: SEO, Analytics, ... there is no system specific reason, pimcore would work also with a trailing slash without problems // use $originalPath because of the sites // only do redirecting with GET requests if (strtolower($_SERVER["REQUEST_METHOD"]) == "get") { if ($config->documents->allowtrailingslash) { if ($config->documents->allowtrailingslash == "no") { if (substr($originalPath, strlen($originalPath) - 1, 1) == "/" && $originalPath != "/") { $redirectUrl = rtrim($originalPath, "/"); if ($_SERVER["QUERY_STRING"]) { $redirectUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectUrl, true, 301); exit; } } } if ($config->documents->allowcapitals) { if ($config->documents->allowcapitals == "no") { if (strtolower($originalPath) != $originalPath) { $redirectUrl = strtolower($originalPath); if ($_SERVER["QUERY_STRING"]) { $redirectUrl .= "?" . $_SERVER["QUERY_STRING"]; } header("Location: " . $redirectUrl, true, 301); exit; } } } } $matchFound = true; } } else { if ($document->getType() == "link") { // if the document is a link just redirect to the location/href of the link header("Location: " . $document->getHref(), true, 301); exit; } } } } catch (\Exception $e) { // no suitable page found $foo = "bar"; } } // test if there is a suitable static route if (!$matchFound) { try { $cacheKey = "system_route_staticroute"; if (!($routes = Cache::load($cacheKey))) { $list = new Staticroute\Listing(); $list->setOrderKey("priority"); $list->setOrder("DESC"); $routes = $list->load(); Cache::save($routes, $cacheKey, array("system", "staticroute", "route"), null, 998); } foreach ($routes as $route) { if (!$matchFound) { $routeParams = $route->match($originalPath, $params); if ($routeParams) { $params = $routeParams; // try to get nearest document to the route $document = $this->getNearestDocumentByPath($path, false, array("page", "snippet", "hardlink")); if ($document instanceof Document\Hardlink) { $document = Document\Hardlink\Service::wrap($document); } $params["document"] = $document; $matchFound = true; Staticroute::setCurrentRoute($route); // add the route object also as parameter to the request object, this is needed in // Pimcore_Controller_Action_Frontend::getRenderScript() // to determine if a call to an action was made through a staticroute or not // more on that infos see Pimcore_Controller_Action_Frontend::getRenderScript() $params["pimcore_request_source"] = "staticroute"; break; } } } } catch (\Exception $e) { // no suitable route found } } // test if there is a suitable redirect if (!$matchFound) { $this->checkForRedirect(false); } if (!$matchFound) { return false; } // remove pimcore magic parameters unset($params["pimcore_outputfilters_disabled"]); unset($params["pimcore_document"]); unset($params["nocache"]); return $params; }
/** * @param array $urlOptions * @param null $name * @param bool $reset * @param bool $encode * @return string|void * @throws \Exception */ public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true) { if (!$urlOptions) { $urlOptions = array(); } // when using $name = false we don't use the default route (happens when $name = null / ZF default behavior) // but just the query string generation using the given parameters // eg. $this->url(["foo" => "bar"], false) => /?foo=bar if ($name === null) { if (Staticroute::getCurrentRoute() instanceof Staticroute) { $name = Staticroute::getCurrentRoute()->getName(); } } $siteId = null; if (Site::isSiteRequest()) { $siteId = Site::getCurrentSite()->getId(); } // check for a site in the options, if valid remove it from the options $hostname = null; if (isset($urlOptions["site"])) { $config = Config::getSystemConfig(); $site = $urlOptions["site"]; if (!empty($site)) { try { $site = Site::getBy($site); unset($urlOptions["site"]); $hostname = $site->getMainDomain(); $siteId = $site->getId(); } catch (\Exception $e) { \Logger::warn("passed site doesn't exists"); \Logger::warn($e); } } else { if ($config->general->domain) { $hostname = $config->general->domain; } } } if ($name && ($route = Staticroute::getByName($name, $siteId))) { // assemble the route / url in Staticroute::assemble() $url = $route->assemble($urlOptions, $reset, $encode); // if there's a site, prepend the host to the generated URL if ($hostname && !preg_match("/^http/i", $url)) { $url = "//" . $hostname . $url; } if (Config::getSystemConfig()->documents->allowcapitals == 'no') { $urlParts = parse_url($url); $url = str_replace($urlParts["path"], strtolower($urlParts["path"]), $url); } return $url; } // this is to add support for arrays as values for the default \Zend_View_Helper_Url $unset = array(); foreach ($urlOptions as $optionName => $optionValues) { if (is_array($optionValues)) { foreach ($optionValues as $key => $value) { $urlOptions[$optionName . "[" . $key . "]"] = $value; } $unset[] = $optionName; } } foreach ($unset as $optionName) { unset($urlOptions[$optionName]); } try { return parent::url($urlOptions, $name, $reset, $encode); } catch (\Exception $e) { if (Tool::isFrontentRequestByAdmin()) { // routes can be site specific, so in editmode it's possible that we don't get // the right route (sites are not registered in editmode), so we cannot throw exceptions there return "ERROR_IN_YOUR_URL_CONFIGURATION:~ROUTE--" . $name . "--DOES_NOT_EXIST"; } throw new \Exception("Route '" . $name . "' for building the URL not found"); } }
/** * @param array $urlOptions * @param null $name * @param bool $reset * @param bool $encode * @return string|void * @throws \Exception */ public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true) { if (!$urlOptions) { $urlOptions = array(); } if (!$name) { if (Staticroute::getCurrentRoute() instanceof Staticroute) { $name = Staticroute::getCurrentRoute()->getName(); } } $siteId = null; if (Site::isSiteRequest()) { $siteId = Site::getCurrentSite()->getId(); } // check for a site in the options, if valid remove it from the options $hostname = null; if (isset($urlOptions["site"])) { $config = Config::getSystemConfig(); $site = $urlOptions["site"]; if (!empty($site)) { try { $site = Site::getBy($site); unset($urlOptions["site"]); $hostname = $site->getMainDomain(); $siteId = $site->getId(); } catch (\Exception $e) { \Logger::warn("passed site doesn't exists"); \Logger::warn($e); } } else { if ($config->general->domain) { $hostname = $config->general->domain; } } } if ($name && ($route = Staticroute::getByName($name, $siteId))) { // assemble the route / url in Staticroute::assemble() $url = $route->assemble($urlOptions, $reset, $encode); // if there's a site, prepend the host to the generated URL if ($hostname && !preg_match("/^http/i", $url)) { $url = "//" . $hostname . $url; } if (Config::getSystemConfig()->documents->allowcapitals == 'no') { $urlParts = parse_url($url); $url = str_replace($urlParts["path"], strtolower($urlParts["path"]), $url); } return $url; } // this is to add support for arrays as values for the default \Zend_View_Helper_Url $unset = array(); foreach ($urlOptions as $optionName => $optionValues) { if (is_array($optionValues)) { foreach ($optionValues as $key => $value) { $urlOptions[$optionName . "[" . $key . "]"] = $value; } $unset[] = $optionName; } } foreach ($unset as $optionName) { unset($urlOptions[$optionName]); } try { return parent::url($urlOptions, $name, $reset, $encode); } catch (\Exception $e) { throw new \Exception("Route '" . $name . "' for building the URL not found"); } }
public function staticroutesAction() { if ($this->getParam("data")) { $this->checkPermission("routes"); $data = \Zend_Json::decode($this->getParam("data")); if (is_array($data)) { foreach ($data as &$value) { if (is_string($value)) { $value = trim($value); } } } if ($this->getParam("xaction") == "destroy") { $data = \Zend_Json::decode($this->getParam("data")); if (\Pimcore\Tool\Admin::isExtJS6()) { $id = $data["id"]; } else { $id = $data; } $route = Staticroute::getById($id); $route->delete(); $this->_helper->json(["success" => true, "data" => []]); } elseif ($this->getParam("xaction") == "update") { // save routes $route = Staticroute::getById($data["id"]); $route->setValues($data); $route->save(); $this->_helper->json(["data" => $route, "success" => true]); } elseif ($this->getParam("xaction") == "create") { unset($data["id"]); // save route $route = new Staticroute(); $route->setValues($data); $route->save(); $this->_helper->json(["data" => $route, "success" => true]); } } else { // get list of routes $list = new Staticroute\Listing(); if ($this->getParam("filter")) { $filter = $this->getParam("filter"); $list->setFilter(function ($row) use($filter) { foreach ($row as $value) { if (strpos($value, $filter) !== false) { return true; } } return false; }); } $list->load(); $routes = []; foreach ($list->getRoutes() as $route) { $routes[] = $route; } $this->_helper->json(["data" => $routes, "success" => true, "total" => $list->getTotalCount()]); } $this->_helper->json(false); }
/** * @param array $urlOptions * @param bool $reset * @param bool $encode * @return mixed|string */ public function assemble(array $urlOptions = [], $reset = false, $encode = true) { // get request parameters $blockedRequestParams = ["controller", "action", "module", "document"]; $front = \Zend_Controller_Front::getInstance(); // allow blocked params if we use it as variables $variables = explode(",", $this->getVariables()); foreach ($variables as $name) { $pos = array_search($name, $blockedRequestParams); if ($pos !== false) { unset($blockedRequestParams[$pos]); } } if ($reset) { $requestParameters = []; } else { $requestParameters = $front->getRequest()->getParams(); // remove blocked parameters from request foreach ($blockedRequestParams as $key) { if (array_key_exists($key, $requestParameters)) { unset($requestParameters[$key]); } } } $defaultValues = $this->getDefaultsArray(); // apply values (controller,action,module, ... ) from previous match if applicable (only when ) if ($reset) { if (self::$_currentRoute && self::$_currentRoute->getName() == $this->getName()) { $defaultValues = array_merge($defaultValues, self::$_currentRoute->_values); } } // merge with defaults $urlParams = array_merge($defaultValues, $requestParameters, $urlOptions); $parametersInReversePattern = []; $parametersGet = []; $url = $this->getReverse(); $forbiddenCharacters = ["#", ":", "?"]; // check for named variables uksort($urlParams, function ($a, $b) { // order by key length, longer key have priority // (%abcd prior %ab, so that %ab doesn't replace %ab in [%ab]cd) return strlen($b) - strlen($a); }); $tmpReversePattern = $this->getReverse(); foreach ($urlParams as $key => $param) { if (strpos($tmpReversePattern, "%" . $key) !== false) { $parametersInReversePattern[$key] = $param; // we need to replace the found variable to that it cannot match again a placeholder // eg. %abcd prior %ab if %abcd matches already %ab shouldn't match again on the same placeholder $tmpReversePattern = str_replace("%" . $key, "---", $tmpReversePattern); } else { // only append the get parameters if there are defined in $urlOptions // or if they are defined in $_GET an $reset is false if (array_key_exists($key, $urlOptions) || !$reset && array_key_exists($key, $_GET)) { $parametersGet[$key] = $param; } } } $urlEncodeEscapeCharacters = "~|urlen" . md5(microtime()) . "code|~"; // replace named variables uksort($parametersInReversePattern, function ($a, $b) { // order by key length, longer key have priority // (%abcd prior %ab, so that %ab doesn't replace %ab in [%ab]cd) return strlen($b) - strlen($a); }); foreach ($parametersInReversePattern as $key => $value) { $value = str_replace($forbiddenCharacters, "", $value); if (strlen($value) > 0) { if ($encode) { $value = urlencode_ignore_slash($value); } $value = str_replace("%", $urlEncodeEscapeCharacters, $value); $url = str_replace("%" . $key, $value, $url); } } // remove optional parts $url = preg_replace("/\\{([^\\}]+)?%[^\\}]+\\}/", "", $url); $url = str_replace(["{", "}"], "", $url); // optional get parameters if (!empty($parametersGet)) { if ($encode) { $getParams = array_urlencode($parametersGet); } else { $getParams = array_toquerystring($parametersGet); } $url .= "?" . $getParams; } // convert tmp urlencode escape char back to real escape char $url = str_replace($urlEncodeEscapeCharacters, "%", $url); $results = \Pimcore::getEventManager()->trigger("frontend.path.staticroute", $this, ["frontendPath" => $url, "params" => $urlParams, "reset" => $reset, "encode" => $encode]); if ($results->count()) { $url = $results->last(); } return $url; }
private static function createStaticRoutes() { // create/update the static route for the confirmation: try { $route = Staticroute::getByName(self::STATICROUTE_CONFIRMATIONCHECK_NAME); if (!is_object($route)) { $route = new Staticroute(); } $route->setValues(array("name" => self::STATICROUTE_CONFIRMATIONCHECK_NAME, "pattern" => "@/confirm/(.*)@", "reverse" => "/confirm/%code", "variables" => 'code', "module" => self::CLASS_PARTICIPATION_NAME, "controller" => "confirmation", "action" => "check")); $route->save(); } catch (\Exception $exception) { throw new \Exception('Unable to create static route [' . Plugin::STATICROUTE_CONFIRMATIONCHECK_NAME . ']: ' . $exception->getMessage()); } }