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 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;
 }
 /**
  *	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'));
 }
Ejemplo n.º 5
0
 /**
  * @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);
 }
Ejemplo n.º 9
0
 /**
  * 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);
 }
Ejemplo n.º 11
0
 /**
  * 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;
 }
Ejemplo n.º 13
0
 /**
  * @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;
 }
 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();
                 }
             }
         }
     }
 }
 /**
  * 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;
 }
 /**
  *	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);
         }
     }
 }
 /**
  * @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());
 }
 /**
  *	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;
 }
Ejemplo n.º 19
0
 /**
  * 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;
 }
Ejemplo n.º 20
0
	/**
	 * 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;
		}

		$votes = $this->extend('augmentValidURLSegment');
		if($votes) {
			$votes = array_filter((array)$votes, 'is_null');
			if($votes) return min($votes);
		}
		
		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;
 }
 /**
  * Used by templates to access and iterate over archive years/months
  * @return ArrayList
  **/
 public function HolderController()
 {
     return ModelAsController::controller_for($this);
 }
 /**
  * Returns a page that acts as the root node for a navigation block.
  * 
  * @return SilvercartProductGroupPage
  * 
  * @author Sascha Koehler <*****@*****.**>
  * @since 26.05.2011
  */
 public function Navigation()
 {
     if (!$this->SilvercartProductGroupPageID) {
         return false;
     }
     $productgroupPage = SilvercartProductGroupPage::get()->byID($this->SilvercartProductGroupPageID);
     if (!$productgroupPage) {
         $productgroupPage = SilvercartProductGroupHolder::get()->byID($this->SilvercartProductGroupPageID);
     }
     if (!$productgroupPage) {
         return false;
     }
     $currentPage = Controller::curr();
     $branchSitetree = SilvercartTools::getPageHierarchy(Controller::curr());
     $productgroupPageSiteTree = ModelAsController::controller_for($productgroupPage);
     $navigation = '';
     foreach ($productgroupPageSiteTree->Children() as $childPage) {
         $navigation .= $this->renderProductGroupNavigation($childPage, $currentPage, 0, $branchSitetree);
     }
     if (empty($navigation)) {
         $hasNavigation = false;
     } else {
         $hasNavigation = true;
     }
     return new DataObject(array('RootPage' => $productgroupPageSiteTree, 'HasMenu' => $hasNavigation, 'Menu' => $navigation));
 }
 /**
  * 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.
  *
  * @param SS_HTTPRequest $request
  * @param DataModel $model
  * @return SS_HTTPResponse
  * @throws SS_HTTPResponse_Exception
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = null)
 {
     $child = null;
     $action = $request->param('Action');
     $this->setDataModel($model);
     // 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::config()->nested_urls && !$this->hasAction($action)) {
         // See ModelAdController->getNestedController() for similar logic
         if (class_exists('Translatable')) {
             Translatable::disable_locale_filter();
         }
         // look for a page with this URLSegment
         $child = $this->model->SiteTree->filter(array('ParentID' => $this->ID, 'URLSegment' => rawurlencode($action)))->first();
         if (class_exists('Translatable')) {
             Translatable::enable_locale_filter();
         }
     }
     // we found a page with this URLSegment.
     if ($child) {
         $request->shiftAllParams();
         $request->shift();
         $response = ModelAsController::controller_for($child)->handleRequest($request, $model);
     } 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 (class_exists('Translatable')) {
             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());
         try {
             $response = parent::handleRequest($request, $model);
             Director::set_current_page(null);
         } catch (SS_HTTPResponse_Exception $e) {
             $this->popCurrent();
             Director::set_current_page(null);
             throw $e;
         }
     }
     return $response;
 }
Ejemplo n.º 25
0
 /**
  * Pass unrecognized method calls on to the original controller
  *
  * @param string $method
  * @param string $args
  * @return mixed
  *
  * @throws Exception Any error other than a 'no method' error.
  */
 public function __call($method, $args)
 {
     try {
         return parent::__call($method, $args);
     } catch (Exception $e) {
         // Hack... detect exception type. We really should use exception subclasses.
         // if the exception isn't a 'no method' error, rethrow it
         if ($e->getCode() !== 2175) {
             throw $e;
         }
         $original = $this->copyContentFrom();
         $controller = ModelAsController::controller_for($original);
         // Ensure request/response data is available on virtual controller
         $controller->setRequest($this->getRequest());
         $controller->response = $this->response;
         // @todo - replace with getter/setter in 3.3
         return call_user_func_array(array($controller, $method), $args);
     }
 }
Ejemplo n.º 26
0
 /**
  * Returns an instance of SilvercartCheckoutFormStep2 to represent a valid 
  * checkout context.
  * 
  * @return SilvercartCheckoutFormStep2
  */
 public function getCheckoutContext()
 {
     $checkoutStepPage = SilvercartTools::PageByIdentifierCode('SilvercartCheckoutStep');
     $checkoutStepPageController = ModelAsController::controller_for($checkoutStepPage);
     $checkoutStepPageController->handleRequest($this->getRequest(), DataModel::inst());
     return new SilvercartCheckoutFormStep2($checkoutStepPageController);
 }
Ejemplo n.º 27
0
 /**
  * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
  * 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::config()->nested_urls && ($parent = $this->Parent())) {
         if ($controller = ModelAsController::controller_for($parent)) {
             if ($controller instanceof Controller && $controller->hasAction($this->URLSegment)) {
                 return false;
             }
         }
     }
     if (!self::config()->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::config()->nested_urls) {
         if ($this->ParentID) {
             $parentFilter = " AND \"SiteTree\".\"ParentID\" = {$this->ParentID}";
         } else {
             $parentFilter = ' AND "SiteTree"."ParentID" = 0';
         }
     }
     $votes = array_filter((array) $this->extend('augmentValidURLSegment'), function ($v) {
         return !is_null($v);
     });
     if ($votes) {
         return min($votes);
     }
     $segment = Convert::raw2sql($this->URLSegment);
     $existingPage = DataObject::get_one('SiteTree', "\"SiteTree\".\"URLSegment\" = '{$segment}' {$IDFilter} {$parentFilter}");
     return !$existingPage;
 }
 /**
  *	Handle the current URL, parsing a year/month/day/media format, and directing towards any valid controller actions that may be defined.
  *
  *	@URLparameter <{YEAR}> integer
  *	@URLparameter <{MONTH}> integer
  *	@URLparameter <{DAY}> integer
  *	@URLparameter <{MEDIA_URL_SEGMENT}> string
  *	@return ss http response
  */
 public function handleURL()
 {
     // Retrieve the formatted URL.
     $request = $this->getRequest();
     $URL = $request->param('URL');
     // Determine whether a controller action resolves.
     if ($this->hasAction($URL) && $this->checkAccessAction($URL)) {
         $output = $this->{$URL}($request);
         // The current request URL has been successfully parsed.
         while (!$request->allParsed()) {
             $request->shift();
         }
         return $output;
     } else {
         if (!is_numeric($URL)) {
             // Determine whether a media page child once existed, and redirect appropriately.
             $response = $this->resolveURL();
             if ($response) {
                 // The current request URL has been successfully parsed.
                 while (!$request->allParsed()) {
                     $request->shift();
                 }
                 return $response;
             } else {
                 // The URL doesn't resolve.
                 return $this->httpError(404);
             }
         }
     }
     // Determine the formatted URL segments.
     $segments = array($URL);
     $remaining = $request->remaining();
     if ($remaining) {
         $remaining = explode('/', $remaining);
         // Determine the media page child to display.
         $child = null;
         $action = null;
         // Iterate the formatted URL segments.
         $iteration = 1;
         foreach ($remaining as $segment) {
             if (is_null($action)) {
                 // Update the current request.
                 $request->shift();
                 if ($child) {
                     // Determine whether a controller action has been defined.
                     $action = $segment;
                     break;
                 } else {
                     if (!is_numeric($segment)) {
                         if ($iteration === 4) {
                             // The remaining URL doesn't match the month/day/media format.
                             return $this->httpError(404);
                         }
                         // Determine the media page child to display, using the URL segment and date.
                         $children = MediaPage::get()->filter(array('ParentID' => $this->data()->ID, 'URLSegment' => $segment));
                         if (!empty($segments)) {
                             // Apply a partial match against the date, since the previous URL segments may only contain the year/month.
                             $date = array();
                             foreach ($segments as $previous) {
                                 $date[] = str_pad($previous, 2, '0', STR_PAD_LEFT);
                             }
                             $children = $children->filter(array('Date:StartsWith' => implode('-', $date)));
                         }
                         $child = $children->first();
                         // Determine whether a media page child once existed, and redirect appropriately.
                         if (is_null($child)) {
                             $response = $this->resolveURL();
                             if ($response) {
                                 // The current request URL has been successfully parsed.
                                 while (!$request->allParsed()) {
                                     $request->shift();
                                 }
                                 return $response;
                             } else {
                                 // The URL doesn't match the month/day/media format.
                                 return $this->httpError(404);
                             }
                         }
                     }
                 }
             }
             $segments[] = $segment;
             $iteration++;
         }
         // Retrieve the media page child controller, and determine whether an action resolves.
         if ($child) {
             $controller = ModelAsController::controller_for($child);
             // Determine whether a controller action resolves.
             if (is_null($action)) {
                 return $controller;
             } else {
                 if ($controller->hasAction($action) && $controller->checkAccessAction($action)) {
                     $output = $controller->{$action}($request);
                     // The current request URL has been successfully parsed.
                     while (!$request->allParsed()) {
                         $request->shift();
                     }
                     return $output;
                 } else {
                     // The controller action doesn't resolve.
                     return $this->httpError(404);
                 }
             }
         }
     }
     // Retrieve the paginated children using the date filter segments.
     $request = new SS_HTTPRequest('GET', $this->Link(), array_merge($request->getVars(), array('from' => implode('-', $segments))));
     // The new request URL doesn't require parsing.
     while (!$request->allParsed()) {
         $request->shift();
     }
     // Handle the new request URL.
     return $this->handleRequest($request);
 }
 public function display()
 {
     // We don't want the dashboard to display in the dashboard. This might create problems.
     $excluded = array("SiteDashboardPage");
     // If this call is the result of some javascript, grab the pageID or pageURL.
     $pageID = $this->getRequest()->getVar('pageID');
     $pageURL = $this->getRequest()->getVar('pageURL');
     // Use this pageID, else the pageURL, else fall back to the previously set page name field.
     if (isset($pageID)) {
         $page = Page::get()->byID($pageID);
     } else {
         if (isset($pageURL)) {
             $segments = explode('?', $pageURL);
             $page = Site::get_by_link($segments[0]);
             // If a certain page is excluded, we don't want it to display in the viewing dashlet.
         } else {
             // If a certain page is excluded, we don't want it to display in the viewing dashlet.
             $page = Page::get()->filter(array('Title' => $this->PageName))->first();
         }
     }
     foreach ($excluded as $exclude) {
         if ($page instanceof $exclude) {
             $page = null;
             break;
         }
     }
     // Display the matching page object and render it using the template, falling back on a basic custom template.
     if ($page) {
         // We need to create a controller for the given model.
         $controller = ModelAsController::controller_for($page);
         // Make sure any query parameters carry across.
         if (isset($segments) && isset($segments[1])) {
             $URL = $segments[0];
             $parameters = null;
             parse_str($segments[1], $parameters);
             foreach ($parameters as $parameter => $value) {
                 $URL = HTTP::setGetVar($parameter, $value, $URL);
             }
             $controller->setRequest(new SS_HTTPRequest('GET', $URL, $parameters));
         }
         // If the page is not the launch page, we want to track the interaction.
         if ($page->URLSegment != 'home') {
             $this->interactions->trackInteraction('page-view', $controller->data());
         }
         // Make sure the correct template is used for a media type.
         if ($page->MediaType) {
             $templates[] = "Layout/{$page->ClassName}_{$page->MediaType}";
         }
         $templates[] = "Layout/{$page->ClassName}";
         $templates[] = 'Layout/Page';
         // We want to remove the page wrapper, so we only use the layout directory.
         return $controller->renderWith($templates);
     } else {
         // If we are clicking an invalid page link from our viewing dashlet, we don't want to refresh the dashlet.
         if (isset($pageURL)) {
             return "invalid_page";
         } else {
             return "Please select a valid page.";
         }
     }
 }
Ejemplo n.º 30
0
 /**
  * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
  * 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::config()->nested_urls && ($parent = $this->Parent())) {
         if ($controller = ModelAsController::controller_for($parent)) {
             if ($controller instanceof Controller && $controller->hasAction($this->URLSegment)) {
                 return false;
             }
         }
     }
     if (!self::config()->nested_urls || !$this->ParentID) {
         if (class_exists($this->URLSegment) && is_subclass_of($this->URLSegment, 'RequestHandler')) {
             return false;
         }
     }
     // Filters by url, id, and parent
     $filter = array('"SiteTree"."URLSegment"' => $this->URLSegment);
     if ($this->ID) {
         $filter['"SiteTree"."ID" <> ?'] = $this->ID;
     }
     if (self::config()->nested_urls) {
         $filter['"SiteTree"."ParentID"'] = $this->ParentID ? $this->ParentID : 0;
     }
     $votes = array_filter((array) $this->extend('augmentValidURLSegment'), function ($v) {
         return !is_null($v);
     });
     if ($votes) {
         return min($votes);
     }
     // Check existence
     $existingPage = DataObject::get_one('SiteTree', $filter);
     if ($existingPage) {
         return false;
     }
     return !$existingPage;
 }