public function run($requestParams) { self::$is_at_root = true; $this->pushCurrent(); $controller = new ModelAsController(); $controller->setUrlParams(array('URLSegment' => self::get_homepage_urlsegment(), 'Action' => '')); $result = $controller->run($requestParams); $this->popCurrent(); return $result; }
public static function get_navbar_html($page = null) { // remove the protocol from the URL, otherwise we run into https/http issues $url = self::remove_protocol_from_url(self::get_toolbar_hostname()); $static = true; if (!$page instanceof SiteTree) { $page = Director::get_current_page(); $static = false; } // In some cases, controllers are bound to "mock" pages, like Security. In that case, // throw the "default section" as the current controller. if (!$page instanceof SiteTree || !$page->isInDB()) { $controller = ModelAsController::controller_for($page = SiteTree::get_by_link(Config::inst()->get('GlobalNav', 'default_section'))); } else { // Use controller_for to negotiate sub controllers, e.g. /showcase/listing/slug // (Controller::curr() would return the nested RequestHandler) $controller = ModelAsController::controller_for($page); } // Ensure staging links are not exported to the nav $origStage = Versioned::current_stage(); Versioned::reading_stage('Live'); $html = ViewableData::create()->customise(array('ToolbarHostname' => $url, 'Scope' => $controller, 'ActivePage' => $page, 'ActiveParent' => $page instanceof SiteTree && $page->Parent()->exists() ? $page->Parent() : $page, 'StaticRender' => $static, 'GoogleCustomSearchId' => Config::inst()->get('GlobalNav', 'google_search_id')))->renderWith('GlobalNavbar'); Versioned::reading_stage($origStage); return $html; }
public function handleRequest(SS_HTTPRequest $request, DataModel $model) { $this->pushCurrent(); $this->urlParams = $request->allParams(); $this->request = $request; $this->response = new SS_HTTPResponse(); $this->setDataModel($model); $urlsegment = $request->param('URLSegment'); $this->extend('onBeforeInit'); $this->init(); $this->extend('onAfterInit'); // First check products against URL segment if ($product = Product::get()->filter(array('URLSegment' => $urlsegment, 'Disabled' => 0))->first()) { $controller = Catalogue_Controller::create($product); } elseif ($category = ProductCategory::get()->filter('URLSegment', $urlsegment)->first()) { $controller = Catalogue_Controller::create($category); } else { // If CMS is installed if (class_exists('ModelAsController')) { $controller = ModelAsController::create(); } } $result = $controller->handleRequest($request, $model); $this->popCurrent(); return $result; }
public function handleRequest($request) { self::$is_at_root = true; $this->pushCurrent(); $this->init(); $controller = new ModelAsController(); $request = new HTTPRequest("GET", self::get_homepage_urlsegment().'/', $request->getVars(), $request->postVars()); $request->match('$URLSegment//$Action', true); $result = $controller->handleRequest($request); $this->popCurrent(); return $result; }
/** * @uses ModelAsController::getNestedController() * @param SS_HTTPRequest $request * @param DataModel $model * @return SS_HTTPResponse */ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { // Check Translatable dependency if (!class_exists('Translatable') || !SiteTree::has_extension('Translatable') && !SiteTree::has_extension('LanguagePrefixTranslatable')) { throw new Exception('Dependency error: the LanguagePrefix module expects the Translatable module.'); } $disablePrefixForDefaultLang = Config::inst()->get('prefixconfig', 'disable_prefix_for_default_lang'); $firstSegment = $request->param('URLSegment'); if ($firstSegment) { $prefixUsed = $this->setLocale($firstSegment); $defaultLocale = Translatable::default_locale(); $isDefaultLocale = $this->locale == $defaultLocale; if ($prefixUsed) { if ($isDefaultLocale && $disablePrefixForDefaultLang) { $url = substr($request->getURL(true), strlen($firstSegment)); return $this->redirect($url, 301); } else { $request->shiftAllParams(); $request->shift(1); } } else { /* * if no prefix is used but $disablePrefixForDefaultLang * is set, we go on like nothing happened. Otherwise a * 404 is generated. @todo: maybe we should redirect * pages that do actually exist, because this is a bit * harsh? */ //if (!$isDefaultLocale || !$disablePrefixForDefaultLang) { // return $this->showPageNotFound(); //} } } return parent::handleRequest($request, $model); }
public function testFindOldPage() { $page = new Page(); $page->Title = 'Test Page'; $page->URLSegment = 'test-page'; $page->write(); $page->publish('Stage', 'Live'); $page->URLSegment = 'test'; $page->write(); $page->publish('Stage', 'Live'); $router = new ModelAsController(); $request = new HTTPRequest('GET', 'test-page/action/id/otherid'); $request->match('$URLSegment/$Action/$ID/$OtherID'); $response = $router->handleRequest($request); $this->assertEquals($response->getHeader('Location'), Controller::join_links(Director::baseURL() . 'test/action/id/otherid')); }
public function GetRootPages() { $controllers = new ArrayList(); $pageModels = Page::get()->filter(array("ParentId" => 0, "ID:not" => AllInOneHelper::excludedPageIds())); foreach ($pageModels as $model) { $controllers->push(ModelAsController::controller_for($model)); } return $controllers; }
public function handleRequest($request) { self::$is_at_root = true; $this->pushCurrent(); $this->init(); // If the basic database hasn't been created, then build it. if (!DB::isActive() || !ClassInfo::hasTable('SiteTree')) { $this->response = new HTTPResponse(); $this->redirect("dev/build?returnURL="); return $this->response; } $controller = new ModelAsController(); $request = new HTTPRequest("GET", self::get_homepage_urlsegment() . '/', $request->getVars(), $request->postVars()); $request->match('$URLSegment//$Action', true); $result = $controller->handleRequest($request); $this->popCurrent(); return $result; }
/** * Retrieve the correct error page for the current multisite instance. * @param integer * @param SS_HTTPRequest * @throws SS_HTTPResponse_Exception */ public function onBeforeHTTPError($code, $request) { $errorPage = ErrorPage::get()->filter(array('ErrorCode' => $code, 'SiteID' => Multisites::inst()->getCurrentSiteId()))->first(); if ($errorPage) { Requirements::clear(); Requirements::clear_combined_files(); $response = ModelAsController::controller_for($errorPage)->handleRequest($request, DataModel::inst()); throw new SS_HTTPResponse_Exception($response, $code); } }
/** * Runs the permissiion checks, and setup of the controller view. */ public function index() { if (!Director::isDev() && !Permission::check('ADMIN')) { return Security::permissionFailure(); } $page = Page::get()->first(); $controller = ModelAsController::controller_for($page); $controller->init(); return $controller->customise($this->getStyleGuideData())->renderWith(array('SimpleStyleguideController', 'Page')); }
/** * @param string $action * @return string */ public function Link($action = null) { $page = TrainingDirectoryPage::get()->first(); if (is_null($page)) { return ''; } $controller = ModelAsController::controller_for($page); if (is_null($controller)) { return ''; } return $controller->Link($action); }
/** * Site search form */ public function SearchForm() { // Retrieve the search form input, excluding any filters. $form = ($page = $this->owner->getSearchPage()) && $page->SearchEngine ? ModelAsController::controller_for($page)->getForm(false) : null; // Update the search input to account for usability. if ($form) { $search = $form->Fields()->dataFieldByName('Search'); $search->setAttribute('placeholder', $search->Title()); $search->setTitle(''); } return $form; }
/** * Prepare the controller for handling the response to this request * * @param string $title Title to use * @return Controller */ protected function getResponseController($title) { if (!class_exists('SiteTree')) { return $this; } // Use sitetree pages to render the opauth pages $tmpPage = new Page(); $tmpPage->ID = -1; $tmpPage->Title = $title; $controller = ModelAsController::controller_for($tmpPage); $controller->init(); return $controller; }
/** * @param string $action * @return string */ public function Link($action = null) { $class = $this->getDirectoryPageClass(); $page = $class::get()->first(); if (is_null($page)) { return ''; } $controller = ModelAsController::controller_for($page); if (is_null($controller)) { return ''; } return $controller->Link($action); }
/** * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an {@link ErrorPage} for that code is present. * * @param int $statusCode * @return SS_HTTPResponse */ public static function response_for($statusCode) { // first attempt to dynamically generate the error page if ($errorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = {$statusCode}")) { return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst()); } // then fall back on a cached version $cachedPath = self::get_filepath_for_errorcode($statusCode, class_exists('Translatable') ? Translatable::get_current_locale() : null); if (file_exists($cachedPath)) { $response = new SS_HTTPResponse(); $response->setStatusCode($statusCode); $response->setBody(file_get_contents($cachedPath)); return $response; } }
public function testValidation() { $validator = new OrderActionsForm_Validator('PaymentMethod'); $form = new OrderActionsForm(ModelAsController::controller_for($this->checkoutPage), 'ActionsForm', $this->order); $validator->setForm($form); Form::set_current_action('dopayment'); $validator->php(array('OrderID' => $this->order->ID, 'PaymentMethod' => 'Dummy', 'type' => 'visa', 'name' => 'Tester Mc. Testerson', 'number' => '4242424242424242')); $requiredCount = 0; foreach ($validator->getErrors() as $error) { if ($error['messageType'] == 'required') { $requiredCount++; } } // 3 required fields missing $this->assertEquals(3, $requiredCount); }
/** * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an * {@link ErrorPage} for that code is present. First tries to serve it * through the standard SilverStripe request method. Falls back to a static * file generated when the user hit's save and publish in the CMS * * @param int $statusCode * * @return SS_HTTPResponse */ public static function response_for($statusCode) { // first attempt to dynamically generate the error page $errorPage = ErrorPage::get()->filter(array("ErrorCode" => $statusCode))->first(); if ($errorPage) { Requirements::clear(); Requirements::clear_combined_files(); return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst()); } // then fall back on a cached version $cachedPath = self::get_filepath_for_errorcode($statusCode, class_exists('Translatable') ? Translatable::get_current_locale() : null); if (file_exists($cachedPath)) { $response = new SS_HTTPResponse(); $response->setStatusCode($statusCode); $response->setBody(file_get_contents($cachedPath)); return $response; } }
/** * * @return ContentController */ public function getControllerForSearchForm() { $controllerName = Config::inst()->get('CustomSearch', 'search_controller'); if ($controllerName == 'this') { return $this->owner; } if (class_exists($controllerName)) { $obj = Object::create($controllerName); if ($obj instanceof SiteTree && ($page = $controllerName::get()->first())) { return ModelAsController::controller_for($page); } if ($obj instanceof Controller) { return $obj; } } //fallback: //@todo: throw notice return $this->owner; }
public function getNestedController() { $url = $this->request->getUrl(); $getVars = $this->request->getVars(); if(isset($getVars['url'])) unset($getVars['url']); if($getVars) $url .= '?' . http_build_query($getVars); if($url) { $SQL_URLSegment = Convert::raw2sql($url); $page = DataObject::get_one( 'Page', "`SiteTree`.LegacyURL = '{$SQL_URLSegment}'" ); if($page) { $response = new HTTPResponse(); $newUrl = Director::baseURL() . $page->URLSegment; $response->redirect($newUrl, 301); return $response; } } return parent::getNestedController(); }
/** * @return SS_HTTPResponse */ public function onBeforeInit() { $config = SiteConfig::current_site_config(); // If Maintenance Mode is Off, skip processing if (!$config->MaintenanceMode) { return; } // Check if the visitor is Admin OR if they have an allowed IP. if (Permission::check('VIEW_SITE_MAINTENANCE_MODE') || Permission::check('ADMIN') || $this->hasAllowedIP()) { return; } // Are we already on the UtilityPage? If so, skip processing. if ($this->owner instanceof UtilityPage_Controller) { return; } // Fetch our utility page instance now. /** * @var Page $utilityPage */ $utilityPage = UtilityPage::get()->first(); if (!$utilityPage) { return; } // We need a utility page before we can do anything. // Are we configured to prevent redirection to the UtilityPage URL? if ($utilityPage->config()->DisableRedirect) { // Process the request internally to ensure that the URL is maintained // (instead of redirecting to the maintenance page's URL) and skip any further processing. $controller = ModelAsController::controller_for($utilityPage); $response = $controller->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst()); HTTP::add_cache_headers($response); $response->output(); die; } // Default: Skip any further processing and immediately respond with a redirect to the UtilityPage. $response = new SS_HTTPResponse(); $response->redirect($utilityPage->AbsoluteLink(), 302); HTTP::add_cache_headers($response); $response->output(); die; }
/** * Returns the Layout template based on the current ClassName * @return {mixed} template to be rendered * */ public function GetLayoutTemplate() { $res = ""; try { if (class_exists($this->owner->ClassName)) { $controller = ModelAsController::controller_for($this->owner); $controller->setSession(Controller::curr()->getSession()); $controller->init(); $viewer = $controller->getViewer("index"); $templates = $viewer->templates(); if (isset($templates["Layout"])) { $layoutViewer = Injector::inst()->create("SSViewer", $templates["Layout"]); $layoutViewer->setPartialCacheStore($viewer->getPartialCacheStore()); $viewer = $layoutViewer; } $res = $viewer->process($controller); } } catch (Exception $exc) { // echo $exc->getTraceAsString(); } return $res; }
public function _getAnnouncement($render = true) { if (ClassInfo::hasTable('MediaHolder')) { $media = MediaHolder::get()->filter(array('MediaType.Title' => 'News')); $possible = $media->first(); // what about an announcement title'd page $page = $media->filter(array('Title' => 'Announcements'))->first(); if (!$page) { $page = $possible; } if ($page) { $announcement = MediaPage::get()->filter('ParentID', $page->ID)->sort('Date DESC')->first(); if ($announcement) { if (!$render) { return $announcement; } else { return ModelAsController::controller_for($announcement)->index(); } } } } }
/** * Display an error page on invalid request. * * @parameter <{ERROR_CODE}> integer * @parameter <{ERROR_MESSAGE}> string */ public function httpError($code, $message = null) { // Determine the error page for the given status code. $errorPages = ClassInfo::exists('SiteTree') ? ErrorPage::get()->filter('ErrorCode', $code) : null; // Allow extension customisation. $this->extend('updateErrorPages', $errorPages); // Retrieve the error page response. if ($errorPages && ($errorPage = $errorPages->first())) { Requirements::clear(); Requirements::clear_combined_files(); $response = ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst()); throw new SS_HTTPResponse_Exception($response, $code); } else { if ($errorPages && file_exists($cachedPage = ErrorPage::get_filepath_for_errorcode($code, class_exists('Translatable') ? Translatable::get_current_locale() : null))) { $response = new SS_HTTPResponse(); $response->setStatusCode($code); $response->setBody(file_get_contents($cachedPage)); throw new SS_HTTPResponse_Exception($response, $code); } else { return parent::httpError($code, $message); } } }
public function handleRequest(SS_HTTPRequest $request, DataModel $model) { $action = $request->param('Action'); $result = parent::handleRequest($request, $model); if (!$action && AllInOneHelper::shouldProcess($request, $result->getStatusCode())) { $realController = $this->getNestedController(); $parentId = intval($realController->ParentID); $currentPageId = intval($realController->ID); if ($parentId === 0 && !AllInOneHelper::isPageIdExluded($currentPageId)) { $jsMin = Director::isDev() ? "" : ".min"; Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery' . $jsMin . '.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui' . $jsMin . '.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript('silverstripe-all-in-one-page/javascript/dist/AllInOnePage' . $jsMin . '.js'); $tmpContoller = Injector::inst()->create("AllInOnePage_Controller", $realController->data()); if ($this->session) { $tmpContoller->setSession($this->session); } $result = $tmpContoller->handleRequest($this->request, $model); } } return $result; }
/** * @throws SS_HTTPResponse_Exception * @return SS_HTTPResponse */ public function onBeforeInit() { if (Permission::check("ADMIN")) { return; } $config = SiteConfig::current_site_config(); if (!$config->MaintenanceMode) { return; } // Fetch our utility page instance now. /** @var Page $utilityPage */ $utilityPage = UtilityPage::get()->first(); if (!$utilityPage) { return; } // We need a utility page before we can do anything. // See if we're still configured to redirect... if (!$utilityPage->config()->DisableRedirect) { //If this is not the utility page, do a temporary (302) redirect to it if ($this->owner->dataRecord->ClassName != "UtilityPage") { return $this->owner->redirect($utilityPage->AbsoluteLink(), 302); } } // No need to execute more than once. if ($this->owner instanceof UtilityPage_Controller) { return; } // Additional failsafe, just in case (for some reason) the current controller isn't descended from UtilityPage_Controller. if (static::$runOnce) { return; } static::$runOnce = true; // Process the request internally to ensure the URL is maintained (instead of redirecting to our maintenance page's URL). $controller = ModelAsController::controller_for($utilityPage); $response = $controller->handleRequest(new SS_HTTPRequest("GET", "/"), new DataModel()); throw new SS_HTTPResponse_Exception($response, $response->getStatusCode()); }
/** * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function handleRequest(SS_HTTPRequest $request, DataModel $model = null) { self::$is_at_root = true; $this->setDataModel($model); $this->pushCurrent(); $this->init(); if (!DB::isActive() || !ClassInfo::hasTable('SiteTree')) { $this->response = new SS_HTTPResponse(); $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null)); return $this->response; } $request = new SS_HTTPRequest($request->httpMethod(), self::get_homepage_link() . '/', $request->getVars(), $request->postVars()); $request->match('$URLSegment//$Action', true); $controller = new ModelAsController(); $result = $controller->handleRequest($request, $model); $this->popCurrent(); return $result; }
/** * Instantiate the search form, primarily outside the search page. * * @parameter <{REQUEST}> ss http request * @parameter <{DISPLAY_SORTING}> boolean * @return search form */ public function getSearchForm($request = null, $sorting = false) { // Instantiate the search form, primarily excluding the sorting selection. return ($page = $this->owner->getSearchPage()) ? ModelAsController::controller_for($page)->getSearchForm($request, $sorting) : null; }
/** * Check catalogue URL's before we get to the CMS (if it exists) * * @param SS_HTTPRequest $request * @param DataModel|null $model * @return SS_HTTPResponse */ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { $this->request = $request; $this->setDataModel($model); $this->pushCurrent(); // Create a response just in case init() decides to redirect $this->response = new SS_HTTPResponse(); $this->init(); // If we had a redirection or something, halt processing. if ($this->response->isFinished()) { $this->popCurrent(); return $this->response; } // If DB is not present, build if (!DB::isActive() || !ClassInfo::hasTable('CatalogueProduct') || !ClassInfo::hasTable('CatalogueCategory')) { return $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null)); } $urlsegment = $request->param('URLSegment'); $this->extend('onBeforeInit'); $this->init(); $this->extend('onAfterInit'); // Find link, regardless of current locale settings if (class_exists('Translatable')) { Translatable::disable_locale_filter(); } $filter = array('URLSegment' => $urlsegment, 'Disabled' => 0); if ($object = CatalogueProduct::get()->filter($filter)->first()) { $controller = $this->controller_for($object); } elseif ($object = CatalogueCategory::get()->filter($filter)->first()) { $controller = $this->controller_for($object); } elseif (class_exists('ModelAsController')) { // If CMS installed $controller = ModelAsController::create(); } else { $controller = Controller::create(); } if (class_exists('Translatable')) { Translatable::enable_locale_filter(); } $result = $controller->handleRequest($request, $model); $this->popCurrent(); return $result; }
/** * Returns TRUE if this object has a URLSegment value that does not conflict with any other objects. This methods * checks for: * - A page with the same URLSegment that has a conflict. * - Conflicts with actions on the parent page. * - A conflict caused by a root page having the same URLSegment as a class name. * * @return bool */ public function validURLSegment() { if (self::nested_urls() && ($parent = $this->Parent())) { if ($controller = ModelAsController::controller_for($parent)) { if ($controller instanceof Controller && $controller->hasAction($this->URLSegment)) { return false; } } } if (!self::nested_urls() || !$this->ParentID) { if (class_exists($this->URLSegment) && is_subclass_of($this->URLSegment, 'RequestHandler')) { return false; } } $IDFilter = $this->ID ? "AND \"SiteTree\".\"ID\" <> {$this->ID}" : null; $parentFilter = null; if (self::nested_urls()) { if ($this->ParentID) { $parentFilter = " AND \"SiteTree\".\"ParentID\" = {$this->ParentID}"; } else { $parentFilter = ' AND "SiteTree"."ParentID" = 0'; } } $existingPage = DataObject::get_one('SiteTree', "\"URLSegment\" = '{$this->URLSegment}' {$IDFilter} {$parentFilter}"); if ($existingPage) { return false; } $values = $this->extend('augmentValidURLSegment'); if (count($values) && !min($values)) { return false; } return true; }
/** * This acts the same as {@link Controller::handleRequest()}, but if an action cannot be found this will attempt to * fall over to a child controller in order to provide functionality for nested URLs. * * @return SS_HTTPResponse */ public function handleRequest(SS_HTTPRequest $request) { $child = null; $action = $request->param('Action'); // If nested URLs are enabled, and there is no action handler for the current request then attempt to pass // control to a child controller. This allows for the creation of chains of controllers which correspond to a // nested URL. if ($action && SiteTree::nested_urls() && !$this->hasAction($action)) { // See ModelAdController->getNestedController() for similar logic Translatable::disable_locale_filter(); // look for a page with this URLSegment $child = DataObject::get_one('SiteTree', sprintf("\"ParentID\" = %s AND \"URLSegment\" = '%s'", $this->ID, Convert::raw2sql($action))); Translatable::enable_locale_filter(); // if we can't find a page with this URLSegment try to find one that used to have // that URLSegment but changed. See ModelAsController->getNestedController() for similiar logic. if (!$child) { $child = ModelAsController::find_old_page($action, $this->ID); if ($child) { $response = new SS_HTTPResponse(); $params = $request->getVars(); if (isset($params['url'])) { unset($params['url']); } $response->redirect(Controller::join_links($child->Link(Controller::join_links($request->param('ID'), $request->param('OtherID'))), $params ? '?' . http_build_query($params) : null), 301); return $response; } } } // we found a page with this URLSegment. if ($child) { $request->shiftAllParams(); $request->shift(); $response = ModelAsController::controller_for($child)->handleRequest($request); } else { // If a specific locale is requested, and it doesn't match the page found by URLSegment, // look for a translation and redirect (see #5001). Only happens on the last child in // a potentially nested URL chain. if ($request->getVar('locale') && $this->dataRecord && $this->dataRecord->Locale != $request->getVar('locale')) { $translation = $this->dataRecord->getTranslation($request->getVar('locale')); if ($translation) { $response = new SS_HTTPResponse(); $response->redirect($translation->Link(), 301); throw new SS_HTTPResponse_Exception($response); } } Director::set_current_page($this->data()); $response = parent::handleRequest($request); Director::set_current_page(null); } return $response; }