コード例 #1
0
 /**
  * Test that nested pages, basic actions, and nested/non-nested URL switching works properly
  */
 public function testNestedPages()
 {
     RootURLController::reset();
     SiteTree::enable_nested_urls();
     $this->assertEquals('Home Page', $this->get('/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/index/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/second-index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/home/second-level/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/home/second-level/index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/home/second-level/second-index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/home/second-level/third-level/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/home/second-level/third-level/index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/home/second-level/third-level/second-index/')->getBody());
     RootURLController::reset();
     SiteTree::disable_nested_urls();
     $this->assertEquals('Home Page', $this->get('/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/second-index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/second-level/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/second-level/index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/second-level/second-index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/third-level/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/third-level/index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/third-level/second-index/')->getBody());
 }
コード例 #2
0
 public function init()
 {
     parent::init();
     // If we've accessed the homepage as /home/, then we should redirect to /.
     if ($this->dataRecord && $this->dataRecord instanceof SiteTree && RootURLController::should_be_on_root($this->dataRecord) && (!isset($this->urlParams['Action']) || !$this->urlParams['Action']) && !$_POST && !$_FILES && !$this->redirectedTo()) {
         $getVars = $_GET;
         unset($getVars['url']);
         if ($getVars) {
             $url = "?" . http_build_query($getVars);
         } else {
             $url = "";
         }
         $this->redirect($url, 301);
         return;
     }
     if ($this->dataRecord) {
         $this->dataRecord->extend('contentcontrollerInit', $this);
     } else {
         singleton('SiteTree')->extend('contentcontrollerInit', $this);
     }
     if ($this->redirectedTo()) {
         return;
     }
     // Check page permissions
     if ($this->dataRecord && $this->URLSegment != 'Security' && !$this->dataRecord->canView()) {
         return Security::permissionFailure($this);
     }
     // Use theme from the site config
     if (($config = SiteConfig::current_site_config()) && $config->Theme) {
         Config::inst()->update('SSViewer', 'theme', $config->Theme);
     }
 }
コード例 #3
0
 /**
  * @return Form
  */
 public function getEditForm($id = null, $fields = null)
 {
     $siteConfig = SiteConfig::current_site_config();
     $fields = $siteConfig->getCMSFields();
     // Tell the CMS what URL the preview should show
     $fields->push(new HiddenField('PreviewURL', 'Preview URL', RootURLController::get_homepage_link()));
     // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load
     $fields->push($navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()));
     $navField->setAllowHTML(true);
     $actions = $siteConfig->getCMSActions();
     $form = CMSForm::create($this, 'EditForm', $fields, $actions)->setHTMLID('Form_EditForm');
     $form->setResponseNegotiator($this->getResponseNegotiator());
     $form->addExtraClass('cms-content center cms-edit-form');
     // don't add data-pjax-fragment=CurrentForm, its added in the content template instead
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->setHTMLID('Form_EditForm');
     $form->loadDataFrom($siteConfig);
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     // Use <button> to allow full jQuery UI styling
     $actions = $actions->dataFields();
     if ($actions) {
         foreach ($actions as $action) {
             $action->setUseButtonTag(true);
         }
     }
     $this->extend('updateEditForm', $form);
     return $form;
 }
コード例 #4
0
 /**
  * Test that nested pages, basic actions, and nested/non-nested URL switching works properly
  */
 public function testNestedPages()
 {
     RootURLController::reset();
     Config::inst()->update('SiteTree', 'nested_urls', true);
     $this->assertEquals('Home Page', $this->get('/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/index/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/second-index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/home/second-level/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/home/second-level/index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/home/second-level/second-index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/home/second-level/third-level/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/home/second-level/third-level/index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/home/second-level/third-level/second-index/')->getBody());
     RootURLController::reset();
     SiteTree::config()->nested_urls = false;
     $this->assertEquals('Home Page', $this->get('/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/')->getBody());
     $this->assertEquals('Home Page', $this->get('/home/second-index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/second-level/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/second-level/index/')->getBody());
     $this->assertEquals('Second Level Page', $this->get('/second-level/second-index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/third-level/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/third-level/index/')->getBody());
     $this->assertEquals('Third Level Page', $this->get('/third-level/second-index/')->getBody());
 }
コード例 #5
0
	public function testGetHomepageLink() {
		$default = $this->objFromFixture('Page', 'home');
		
		SiteTree::disable_nested_urls();
		$this->assertEquals('home', RootURLController::get_homepage_link());
		SiteTree::enable_nested_urls();
		$this->assertEquals('home', RootURLController::get_homepage_link());
	}
コード例 #6
0
 public function testGetHomepageLink()
 {
     $default = $this->objFromFixture('Page', 'home');
     SiteTree::config()->nested_urls = false;
     $this->assertEquals('home', RootURLController::get_homepage_link());
     Config::inst()->update('SiteTree', 'nested_urls', true);
     $this->assertEquals('home', RootURLController::get_homepage_link());
 }
コード例 #7
0
 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;
 }
コード例 #8
0
 function testHomepageForDomain()
 {
     $originalHost = $_SERVER['HTTP_HOST'];
     // Tests matching an HTTP_HOST value to URLSegment homepage values
     $tests = array('page.co.nz' => 'page1', 'www.page.co.nz' => 'page1', 'help.com' => 'page1', 'www.help.com' => 'page1', 'something.com' => 'page1', 'www.something.com' => 'page1', 'other.co.nz' => 'page2', 'www.other.co.nz' => 'page2', 'right' => 'page2', 'www. right' => 'page2', 'only.com' => 'page3', 'www.only.com' => 'page3', 'www.somethingelse.com' => 'home', 'somethingelse.com' => 'home', 'alternate.only.com' => 'home', 'www.alternate.only.com' => 'home', 'alternate.something.com' => 'home');
     foreach ($tests as $domain => $urlSegment) {
         $_SERVER['HTTP_HOST'] = $domain;
         $this->assertEquals($urlSegment, RootURLController::get_homepage_urlsegment(Translatable::default_locale()), "Testing {$domain} matches {$urlSegment}");
     }
     $_SERVER['HTTP_HOST'] = $originalHost;
 }
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = null)
 {
     $action = $request->param('Action');
     $res = parent::handleRequest($request, $model);
     if (!$action && AllInOneHelper::shouldProcess($request, $res->getStatusCode())) {
         $request->setUrl(self::get_homepage_link() . '/');
         $request->match('$URLSegment//$Action', true);
         $tmpContoller = Injector::inst()->create("AllInOneModelAsController");
         if ($this->session) {
             $tmpContoller->setSession($this->session);
         }
         $res = $tmpContoller->handleRequest($request, $model);
     }
     return $res;
 }
コード例 #10
0
	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;
	}
コード例 #11
0
 /**
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request)
 {
     self::$is_at_root = true;
     $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);
     $this->popCurrent();
     return $result;
 }
コード例 #12
0
 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;
 }
コード例 #13
0
 /**
  * On every URL that generates a 404, we'll capture it here and see if we can
  * find an old URL that it should be redirecting to.
  *
  * @param SS_HTTPRequest $request The request object
  * @throws SS_HTTPResponse_Exception
  */
 public function onBeforeHTTPError404($request)
 {
     // We need to get the URL ourselves because $request->allParams() only has a max of 4 params
     $params = preg_split('|/+|', $request->getURL());
     $cleanURL = trim(Director::makeRelative($request->getURL(false), '/'));
     $getvars = $request->getVars();
     unset($getvars['url']);
     $page = self::find_old_page($params);
     $cleanPage = trim(Director::makeRelative($page), '/');
     if (!$cleanPage) {
         $cleanPage = Director::makeRelative(RootURLController::get_homepage_link());
     }
     if ($page && $cleanPage != $cleanURL) {
         $res = new SS_HTTPResponse();
         $res->redirect(Controller::join_links($page, $getvars ? '?' . http_build_query($getvars) : null), 301);
         throw new SS_HTTPResponse_Exception($res);
     }
 }
コード例 #14
0
 public function init()
 {
     parent::init();
     // If we've accessed the homepage as /home/, then we should redirect to /.
     if ($this->dataRecord && $this->dataRecord instanceof SiteTree && RootURLController::should_be_on_root($this->dataRecord) && (!isset($this->urlParams['Action']) || !$this->urlParams['Action']) && !$_POST && !$_FILES && !$this->redirectedTo()) {
         $getVars = $_GET;
         unset($getVars['url']);
         if ($getVars) {
             $url = "?" . http_build_query($getVars);
         } else {
             $url = "";
         }
         $this->redirect($url, 301);
         return;
     }
     if ($this->dataRecord) {
         $this->dataRecord->extend('contentcontrollerInit', $this);
     } else {
         singleton('SiteTree')->extend('contentcontrollerInit', $this);
     }
     if ($this->redirectedTo()) {
         return;
     }
     // Check page permissions
     if ($this->dataRecord && $this->URLSegment != 'Security' && !$this->dataRecord->canView()) {
         return Security::permissionFailure($this);
     }
     // Draft/Archive security check - only CMS users should be able to look at stage/archived content
     if ($this->URLSegment != 'Security' && !Session::get('unsecuredDraftSite') && (Versioned::current_archived_date() || Versioned::current_stage() && Versioned::current_stage() != 'Live')) {
         if (!$this->dataRecord->canViewStage(Versioned::current_archived_date() ? 'Stage' : Versioned::current_stage())) {
             $link = $this->Link();
             $message = _t("ContentController.DRAFT_SITE_ACCESS_RESTRICTION", 'You must log in with your CMS password in order to view the draft or archived content. ' . '<a href="%s">Click here to go back to the published site.</a>');
             Session::clear('currentStage');
             Session::clear('archiveDate');
             $permissionMessage = sprintf(_t("ContentController.DRAFT_SITE_ACCESS_RESTRICTION", 'You must log in with your CMS password in order to view the draft or archived content. ' . '<a href="%s">Click here to go back to the published site.</a>'), Controller::join_links($this->Link(), "?stage=Live"));
             return Security::permissionFailure($this, $permissionMessage);
         }
     }
     // Use theme from the site config
     if (($config = SiteConfig::current_site_config()) && $config->Theme) {
         Config::inst()->update('SSViewer', 'theme', $config->Theme);
     }
 }
コード例 #15
0
 public function testGetHomepageLink()
 {
     $default = $this->objFromFixture('Page', 'home');
     $nested = $this->objFromFixture('Page', 'nested');
     SiteTree::disable_nested_urls();
     $this->assertEquals('home', RootURLController::get_homepage_link());
     SiteTree::enable_nested_urls();
     $this->assertEquals('home', RootURLController::get_homepage_link());
     $nested->HomepageForDomain = str_replace('www.', null, $_SERVER['HTTP_HOST']);
     $nested->write();
     RootURLController::reset();
     SiteTree::disable_nested_urls();
     $this->assertEquals('nested-home', RootURLController::get_homepage_link());
     RootURLController::reset();
     SiteTree::enable_nested_urls();
     $this->assertEquals('home/nested-home', RootURLController::get_homepage_link());
     $nested->HomepageForDomain = null;
     $nested->write();
 }
コード例 #16
0
 public function init()
 {
     parent::init();
     //Log page views
     Statistics::collect();
     // If we've accessed the homepage as /home/, then we should redirect to /.
     if ($this->dataRecord && $this->dataRecord instanceof SiteTree && RootURLController::should_be_on_root($this->dataRecord) && !$this->urlParams['Action'] && !$_POST && !$_FILES && !Director::redirected_to()) {
         $getVars = $_GET;
         unset($getVars['url']);
         if ($getVars) {
             $url = "?" . http_build_query($getVars);
         } else {
             $url = "";
         }
         Director::redirect($url);
         return;
     }
     if ($this->dataRecord) {
         $this->dataRecord->extend('contentcontrollerInit', $this);
     } else {
         singleton('SiteTree')->extend('contentcontrollerInit', $this);
     }
     if (Director::redirected_to()) {
         return;
     }
     Director::set_site_mode('site');
     // Check page permissions
     if ($this->dataRecord && $this->URLSegment != 'Security' && !$this->dataRecord->can('View')) {
         Security::permissionFailure($this);
     }
     // Draft/Archive security check - only CMS users should be able to look at stage/archived content
     if ($this->URLSegment != 'Security' && (Versioned::current_archived_date() || Versioned::current_stage() && Versioned::current_stage() != 'Live')) {
         if (!Permission::check('CMS_ACCESS_CMSMain')) {
             $link = $this->Link();
             $message = _t("ContentController.DRAFT_SITE_ACCESS_RESTRICTION", "You must log in with your CMS password in order to view the draft or archived content.  <a href=\"%s\">Click here to go back to the published site.</a>");
             Security::permissionFailure($this, sprintf($message, "{$link}?stage=Live"));
             return;
         }
     }
 }
 /**
  * @param null $id Not used.
  * @param null $fields Not used.
  * @return Form
  */
 public function getEditForm($id = null, $fields = null)
 {
     $treeClass = $this->config()->get('tree_class');
     $page = $treeClass::get()->first();
     if (!$page || !$page->exists()) {
         $currentStage = Versioned::current_stage();
         Versioned::reading_stage('Stage');
         $page = $treeClass::create();
         $page->Title = $treeClass;
         $page->write();
         $page->doPublish();
         Versioned::reading_stage($currentStage);
     }
     $fields = $page->getCMSFields();
     $fields->push(new HiddenField('PreviewURL', 'Preview URL', RootURLController::get_homepage_link()));
     $fields->push($navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()));
     $navField->setAllowHTML(true);
     $actions = new FieldList();
     $actions->push(FormAction::create('doSave', 'Save')->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
     $form = CMSForm::create($this, 'EditForm', $fields, $actions)->setHTMLID('Form_EditForm');
     $form->setResponseNegotiator($this->getResponseNegotiator());
     $form->addExtraClass('cms-content center cms-edit-form');
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->setHTMLID('Form_EditForm');
     $form->loadDataFrom($page);
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     // Use <button> to allow full jQuery UI styling
     $actions = $actions->dataFields();
     if ($actions) {
         foreach ($actions as $action) {
             $action->setUseButtonTag(true);
         }
     }
     $this->extend('updateEditForm', $form);
     return $form;
 }
コード例 #18
0
 /**
  * @return Form
  */
 function AddForm()
 {
     $record = $this->currentPage();
     $pageTypes = array();
     foreach ($this->PageTypes() as $type) {
         $html = sprintf('<span class="page-icon class-%s"></span><strong class="title">%s</strong><span class="description">%s</span>', $type->getField('ClassName'), $type->getField('AddAction'), $type->getField('Description'));
         $pageTypes[$type->getField('ClassName')] = $html;
     }
     // Ensure generic page type shows on top
     if (isset($pageTypes['Page'])) {
         $pageTitle = $pageTypes['Page'];
         $pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
     }
     $numericLabelTmpl = '<span class="step-label"><span class="flyout">%d</span><span class="arrow"></span><span class="title">%s</span></span>';
     $topTitle = _t('CMSPageAddController.ParentMode_top', 'Top level');
     $childTitle = _t('CMSPageAddController.ParentMode_child', 'Under another page');
     $fields = new FieldList($hintsField = new LiteralField('Hints', sprintf('<span class="hints" data-hints="%s"></span>', $this->SiteTreeHints())), new LiteralField('PageModeHeader', sprintf($numericLabelTmpl, 1, _t('CMSMain.ChoosePageParentMode', 'Choose where to create this page'))), $parentModeField = new SelectionGroup("ParentModeField", array("top//{$topTitle}" => null, "child//{$childTitle}" => $parentField = new TreeDropdownField("ParentID", "", 'SiteTree', 'ID', 'TreeTitle'))), $typeField = new OptionsetField("PageType", sprintf($numericLabelTmpl, 2, _t('CMSMain.ChoosePageType', 'Choose page type')), $pageTypes, 'Page'));
     // TODO Re-enable search once it allows for HTML title display,
     // see http://open.silverstripe.org/ticket/7455
     // $parentField->setShowSearch(true);
     $parentModeField->setValue($this->request->getVar('ParentID') ? 'child' : 'top');
     $parentModeField->addExtraClass('parent-mode');
     // CMSMain->currentPageID() automatically sets the homepage,
     // which we need to counteract in the default selection (which should default to root, ID=0)
     $homepageSegment = RootURLController::get_homepage_link();
     if ($record && $record->URLSegment != $homepageSegment) {
         $parentField->setValue($record->ID);
     }
     $actions = new FieldList(FormAction::create("doAdd", _t('CMSMain.Create', "Create"))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true));
     $this->extend('updatePageOptions', $fields);
     $form = new Form($this, "AddForm", $fields, $actions);
     $form->addExtraClass('cms-add-form stacked cms-content center cms-edit-form ' . $this->BaseCSSClasses());
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     if ($parentID = $this->request->getVar('ParentID')) {
         $form->Fields()->dataFieldByName('ParentID')->setValue((int) $parentID);
     }
     return $form;
 }
コード例 #19
0
	function testHomepageForDomain() {
		$originalHost = $_SERVER['HTTP_HOST'];

		// Tests matching an HTTP_HOST value to URLSegment homepage values
		$tests = array(
			'page.co.nz' => 'page1',
			'www.page.co.nz' => 'page1',
			'help.com' => 'page1',
			'www.help.com' => 'page1',
			'something.com' => 'page1',
			'www.something.com' => 'page1',

	 		'other.co.nz' => 'page2',
	 		'www.other.co.nz' => 'page2',
			'right' => 'page2',
			'www. right' => 'page2',

			'only.com' => 'page3',
			'www.only.com' => 'page3',
			
			'www.somethingelse.com' => 'home',
			'somethingelse.com' => 'home',
			
			// Test some potential false matches to page2 and page3
			'alternate.only.com' => 'home',
			'www.alternate.only.com' => 'home',
			'alternate.something.com' => 'home',
		);
		
		foreach($tests as $domain => $urlSegment) {
			$_SERVER['HTTP_HOST'] = $domain;
			$this->assertEquals($urlSegment, RootURLController::get_homepage_urlsegment(), "Testing $domain matches $urlSegment");
		}
		
		$_SERVER['HTTP_HOST'] = $originalHost;
	}
コード例 #20
0
 function setUp()
 {
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::set_date_format(null);
     i18n::set_time_format(null);
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Cookie::set_report_errors(false);
     RootURLController::reset();
     Translatable::reset();
     Versioned::reset();
     DataObject::reset();
     SiteTree::reset();
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(new Session(array()));
     }
     $this->originalTheme = SSViewer::current_theme();
     // Save nested_urls state, so we can restore it later
     $this->originalNestedURLsState = SiteTree::nested_urls();
     $className = get_class($this);
     $fixtureFile = eval("return {$className}::\$fixture_file;");
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 $fixture = new YamlFixture($fixtureFilePath);
                 $fixture->saveIntoDatabase();
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Email::send_all_emails_to(null);
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
 }
コード例 #21
0
	/**
	 * @return Form
	 */
	function AddForm() {
		// If request send from rightclick-submenu, directly add Page
		if(($pageType = $this->request->getVar('Type')) && ($parentID = $this->request->getVar('ParentID'))) {
			$data = array(
				"PageType" => (string)$pageType,
				"ParentID" => $parentID,
				"ParentModeField" => "child"
			);
			$this->doAdd($data, null);
			return;
		}


		$record = $this->currentPage();
		
		$pageTypes = array();
		foreach($this->PageTypes() as $type) {
			$html = sprintf('<span class="icon class-%s"></span><strong class="title">%s</strong><span class="description">%s</span>',
				$type->getField('ClassName'),
				$type->getField('AddAction'),
				$type->getField('Description')
			);
			$pageTypes[$type->getField('ClassName')] = $html;
		}
		// Ensure generic page type shows on top
		if(isset($pageTypes['Page'])) {
			$pageTitle = $pageTypes['Page'];
			$pageTypes = array_merge(array('Page' => $pageTitle), $pageTypes);
		}

		$numericLabelTmpl = '<span class="step-label"><span class="flyout">%d</span><span class="arrow"></span><span class="title">%s</span></span>';

		$topTitle = _t('CMSPageAddController.ParentMode_top', 'Top level');
		$childTitle = _t('CMSPageAddController.ParentMode_child', 'Under another page');

		$fields = new FieldList(
			// new HiddenField("ParentID", false, ($this->parentRecord) ? $this->parentRecord->ID : null),
			// TODO Should be part of the form attribute, but not possible in current form API
			$hintsField = new LiteralField('Hints', sprintf('<span class="hints" data-hints="%s"></span>', $this->SiteTreeHints())),
			new LiteralField('PageModeHeader', sprintf($numericLabelTmpl, 1, _t('CMSMain.ChoosePageParentMode', 'Choose where to create this page'))),
			
			$parentModeField = new SelectionGroup(
				"ParentModeField",
				array(
					"top//$topTitle" => null, //new LiteralField("Dummy", ''),
					"child//$childTitle" => $parentField = new TreeDropdownField(
						"ParentID", 
						"",
						'SiteTree'
					)
				)
			),
			$typeField = new OptionsetField(
				"PageType", 
				sprintf($numericLabelTmpl, 2, _t('CMSMain.ChoosePageType', 'Choose page type')), 
				$pageTypes, 
				'Page'
			)
		);
		$parentField->setShowSearch(true);
		$parentModeField->setValue($this->request->getVar('ParentID') ? 'child' : 'top');
		$parentModeField->addExtraClass('parent-mode');

		// CMSMain->currentPageID() automatically sets the homepage,
		// which we need to counteract in the default selection (which should default to root, ID=0)
		$homepageSegment = RootURLController::get_homepage_link();
		if($record && $record->URLSegment != $homepageSegment) {
			$parentField->setValue($record->ID);	
		}
		
		$actions = new FieldList(
			// $resetAction = new ResetFormAction('doCancel', _t('CMSMain.Cancel', 'Cancel')),
			FormAction::create("doAdd", _t('CMSMain.Create',"Create"))
				->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
				->setUseButtonTag(true)
		);
		
		$this->extend('updatePageOptions', $fields);
		
		$form = new Form($this, "AddForm", $fields, $actions);
		$form->addExtraClass('cms-add-form stacked cms-content center cms-edit-form ' . $this->BaseCSSClasses());
		$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));

		if($parentID = $this->request->getVar('ParentID')) {
			$form->Fields()->dataFieldByName('ParentID')->setValue((int)$parentID);
		}

		return $form;
	}
コード例 #22
0
 public function setUp()
 {
     // We cannot run the tests on this abstract class.
     if (get_class($this) == "SapphireTest") {
         $this->skipTest = true;
     }
     if ($this->skipTest) {
         $this->markTestSkipped(sprintf('Skipping %s ', get_class($this)));
         return;
     }
     // Mark test as being run
     $this->originalIsRunningTest = self::$is_running_test;
     self::$is_running_test = true;
     // i18n needs to be set to the defaults or tests fail
     i18n::set_locale(i18n::default_locale());
     i18n::config()->date_format = null;
     i18n::config()->time_format = null;
     // Set default timezone consistently to avoid NZ-specific dependencies
     date_default_timezone_set('UTC');
     // Remove password validation
     $this->originalMemberPasswordValidator = Member::password_validator();
     $this->originalRequirements = Requirements::backend();
     Member::set_password_validator(null);
     Config::inst()->update('Cookie', 'report_errors', false);
     if (class_exists('RootURLController')) {
         RootURLController::reset();
     }
     if (class_exists('Translatable')) {
         Translatable::reset();
     }
     Versioned::reset();
     DataObject::reset();
     if (class_exists('SiteTree')) {
         SiteTree::reset();
     }
     Hierarchy::reset();
     if (Controller::has_curr()) {
         Controller::curr()->setSession(Injector::inst()->create('Session', array()));
     }
     Security::$database_is_ready = null;
     // Add controller-name auto-routing
     Config::inst()->update('Director', 'rules', array('$Controller//$Action/$ID/$OtherID' => '*'));
     $fixtureFile = static::get_fixture_file();
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     // Set up email
     $this->originalMailer = Email::mailer();
     $this->mailer = new TestMailer();
     Email::set_mailer($this->mailer);
     Config::inst()->remove('Email', 'send_all_emails_to');
     // Todo: this could be a special test model
     $this->model = DataModel::inst();
     // Set up fixture
     if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
         if (substr(DB::get_conn()->getSelectedDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) {
             //echo "Re-creating temp database... ";
             self::create_temp_db();
             //echo "done.\n";
         }
         singleton('DataObject')->flushCache();
         self::empty_temp_db();
         foreach ($this->requireDefaultRecordsFrom as $className) {
             $instance = singleton($className);
             if (method_exists($instance, 'requireDefaultRecords')) {
                 $instance->requireDefaultRecords();
             }
             if (method_exists($instance, 'augmentDefaultRecords')) {
                 $instance->augmentDefaultRecords();
             }
         }
         if ($fixtureFile) {
             $pathForClass = $this->getCurrentAbsolutePath();
             $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile);
             $i = 0;
             foreach ($fixtureFiles as $fixtureFilePath) {
                 // Support fixture paths relative to the test class, rather than relative to webroot
                 // String checking is faster than file_exists() calls.
                 $isRelativeToFile = strpos('/', $fixtureFilePath) === false || preg_match('/^\\.\\./', $fixtureFilePath);
                 if ($isRelativeToFile) {
                     $resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath);
                     if ($resolvedPath) {
                         $fixtureFilePath = $resolvedPath;
                     }
                 }
                 $fixture = Injector::inst()->create('YamlFixture', $fixtureFilePath);
                 $fixture->writeInto($this->getFixtureFactory());
                 $this->fixtures[] = $fixture;
                 // backwards compatibility: Load first fixture into $this->fixture
                 if ($i == 0) {
                     $this->fixture = $fixture;
                 }
                 $i++;
             }
         }
         $this->logInWithPermission("ADMIN");
     }
     // Preserve memory settings
     $this->originalMemoryLimit = ini_get('memory_limit');
     // turn off template debugging
     Config::inst()->update('SSViewer', 'source_file_comments', false);
     // Clear requirements
     Requirements::clear();
 }
コード例 #23
0
 /**
  * Alternative implementation that takes into account the current site
  * as the root
  *
  * @param type $link
  * @param type $cache
  * @return boolean
  */
 public static function get_by_link($link, $cache = true)
 {
     $current = Multisites::inst()->getCurrentSiteId();
     if (trim($link, '/')) {
         $link = trim(Director::makeRelative($link), '/');
     } else {
         $link = RootURLController::get_homepage_link();
     }
     $parts = Convert::raw2sql(preg_split('|/+|', $link));
     // Grab the initial root level page to traverse down from.
     $URLSegment = array_shift($parts);
     $sitetree = DataObject::get_one('SiteTree', "\"URLSegment\" = '{$URLSegment}' AND \"ParentID\" = " . $current, $cache);
     if (!$sitetree) {
         return false;
     }
     /// Fall back on a unique URLSegment for b/c.
     if (!$sitetree && self::nested_urls() && ($page = DataObject::get('SiteTree', "\"URLSegment\" = '{$URLSegment}'")->First())) {
         return $page;
     }
     // Check if we have any more URL parts to parse.
     if (!count($parts)) {
         return $sitetree;
     }
     // Traverse down the remaining URL segments and grab the relevant SiteTree objects.
     foreach ($parts as $segment) {
         $next = DataObject::get_one('SiteTree', "\"URLSegment\" = '{$segment}' AND \"ParentID\" = {$sitetree->ID}", $cache);
         if (!$next) {
             return false;
         }
         $sitetree->destroy();
         $sitetree = $next;
     }
     return $sitetree;
 }
コード例 #24
0
 function testRootUrlDefaultsToTranslatedUrlSegment()
 {
     $origPage = $this->objFromFixture('Page', 'homepage_en');
     $origPage->publish('Stage', 'Live');
     $translationDe = $origPage->createTranslation('de_DE');
     $translationDe->URLSegment = 'heim';
     $translationDe->write();
     $translationDe->publish('Stage', 'Live');
     // test with translatable
     Translatable::set_current_locale('de_DE');
     $this->assertEquals(RootURLController::get_homepage_urlsegment(), 'heim', 'Homepage with different URLSegment in non-default language is found');
     // @todo Fix add/remove extension
     // test with translatable disabled
     // Object::remove_extension('Page', 'Translatable');
     // 		$_SERVER['HTTP_HOST'] = '/';
     // 		$this->assertEquals(
     // 			RootURLController::get_homepage_urlsegment(),
     // 			'home',
     // 			'Homepage is showing in default language if ?lang GET variable is left out'
     // 		);
     // 		Object::add_extension('Page', 'Translatable');
     // setting back to default
     Translatable::set_current_locale('en_US');
 }
コード例 #25
0
ファイル: SiteTree.php プロジェクト: eLBirador/AllAboutCity
 /**
  * Return the link for this {@link SiteTree} object relative to the SilverStripe root.
  *
  * By default, it this page is the current home page, and there is no action specified then this will return a link
  * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
  * and returned in its full form.
  *
  * @uses RootURLController::get_homepage_link()
  * @param string $action
  * @return string
  */
 public function RelativeLink($action = null)
 {
     if ($this->ParentID && self::nested_urls()) {
         $base = $this->Parent()->RelativeLink($this->URLSegment);
     } else {
         $base = $this->URLSegment;
     }
     // Unset base for homepage URLSegments in their default language.
     // Homepages with action parameters or in different languages
     // need to retain their URLSegment. We can only do this if the homepage
     // is on the root level.
     if (!$action && $base == RootURLController::get_homepage_link() && !$this->ParentID) {
         $base = null;
         if ($this->hasExtension('Translatable') && $this->Locale != Translatable::default_locale()) {
             $base = $this->URLSegment;
         }
     }
     if (is_string($action)) {
         $action = str_replace('&', '&amp;', $action);
     } elseif ($action === true) {
         $action = null;
     }
     return Controller::join_links($base, '/', $action);
 }
コード例 #26
0
ファイル: SiteTree.php プロジェクト: maent45/redefine_renos
 /**
  * Return the link for this {@link SiteTree} object relative to the SilverStripe root.
  *
  * By default, if this page is the current home page, and there is no action specified then this will return a link
  * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
  * and returned in its full form.
  *
  * @uses RootURLController::get_homepage_link()
  * 
  * @param string $action See {@link Link()}
  * @return string
  */
 public function RelativeLink($action = null)
 {
     if ($this->ParentID && self::config()->nested_urls) {
         $base = $this->Parent()->RelativeLink($this->URLSegment);
     } elseif (!$action && $this->URLSegment == RootURLController::get_homepage_link()) {
         // Unset base for root-level homepages.
         // Note: Homepages with action parameters (or $action === true)
         // need to retain their URLSegment.
         $base = null;
     } else {
         $base = $this->URLSegment;
     }
     $this->extend('updateRelativeLink', $base, $action);
     // Legacy support: If $action === true, retain URLSegment for homepages,
     // but don't append any action
     if ($action === true) {
         $action = null;
     }
     return Controller::join_links($base, '/', $action);
 }
コード例 #27
0
 /**
  * Get the RelativeLink value for a home page in another locale. This is found by searching for the default home
  * page in the default language, then returning the link to the translated version (if one exists).
  *
  * @return string
  */
 public static function get_homepage_link_by_locale($locale)
 {
     $originalLocale = self::get_current_locale();
     self::set_current_locale(self::default_locale());
     $original = SiteTree::get_by_link(RootURLController::get_default_homepage_link());
     self::set_current_locale($originalLocale);
     if ($original) {
         if ($translation = $original->getTranslation($locale)) {
             return trim($translation->RelativeLink(true), '/');
         }
     }
 }
コード例 #28
0
ファイル: CMSMain.php プロジェクト: prostart/cobblestonepath
 public function currentPageID()
 {
     $id = parent::currentPageID();
     // Fall back to homepage record
     if (!$id) {
         $homepageSegment = RootURLController::get_homepage_link();
         $homepageRecord = DataObject::get_one('SiteTree', sprintf('"URLSegment" = \'%s\'', $homepageSegment));
         if ($homepageRecord) {
             $id = $homepageRecord->ID;
         }
     }
     return $id;
 }
コード例 #29
0
 public function getHomepageCurrLang()
 {
     // @TODO: make this translatable compatible;
     //return $this->owner->get_homepage_link_by_locale($this->owner->get_current_locale());
     return SiteTree::get_by_link(RootURLController::get_default_homepage_link());
 }
コード例 #30
0
ファイル: CMSMain.php プロジェクト: hemant-chakka/awss
 public function currentPageID()
 {
     $id = parent::currentPageID();
     $this->extend('updateCurrentPageID', $id);
     // Fall back to homepage record
     if (!$id) {
         $homepageSegment = RootURLController::get_homepage_link();
         $homepageRecord = DataObject::get_one('SiteTree', sprintf('"SiteTree"."URLSegment" = \'%s\'', Convert::raw2sql($homepageSegment)));
         if ($homepageRecord) {
             $id = $homepageRecord->ID;
         }
     }
     return $id;
 }