/** * Returns TRUE if a request to a certain page should be redirected to the site root (i.e. if the page acts as the * home page). * * @param SiteTree $page * @return bool */ public static function should_be_on_root(SiteTree $page) { if (!self::$is_at_root && self::get_homepage_link() == trim($page->RelativeLink(true), '/')) { return !(class_exists('Translatable') && $page->hasExtension('Translatable') && $page->Locale && $page->Locale != Translatable::default_locale()); } return false; }
/** * Test setting pagination properties and returning the object */ public function setUp() { parent::setUp(); $page = new SiteTree(['Title' => "Test Page", 'URLSegment' => 'test']); $page->write(); $page->publish('Stage', 'Live'); }
function testExternalBackUrlRedirectionDisallowed() { $page = new SiteTree(); $page->URLSegment = 'testpage'; $page->Title = 'Testpage'; $page->write(); $page->publish('Stage','Live'); // Test internal relative redirect $response = $this->doTestLoginForm('*****@*****.**', '1nitialPassword', 'testpage'); $this->assertEquals(302, $response->getStatusCode()); $this->assertRegExp('/testpage/', $response->getHeader('Location'), "Internal relative BackURLs work when passed through to login form" ); // Log the user out $this->session()->inst_set('loggedInAs', null); // Test internal absolute redirect $response = $this->doTestLoginForm('*****@*****.**', '1nitialPassword', Director::absoluteBaseURL() . 'testpage'); // for some reason the redirect happens to a relative URL $this->assertRegExp('/^' . preg_quote(Director::absoluteBaseURL(), '/') . 'testpage/', $response->getHeader('Location'), "Internal absolute BackURLs work when passed through to login form" ); // Log the user out $this->session()->inst_set('loggedInAs', null); // Test external redirect $response = $this->doTestLoginForm('*****@*****.**', '1nitialPassword', 'http://myspoofedhost.com'); $this->assertNotRegExp('/^' . preg_quote('http://myspoofedhost.com', '/') . '/', $response->getHeader('Location'), "Redirection to external links in login form BackURL gets prevented as a measure against spoofing attacks" ); // Log the user out $this->session()->inst_set('loggedInAs', null); }
/** * * @param SiteTree $page * @return boolean */ protected function canBeCached(SiteTree $page) { if (!$page->canView()) { return false; } return true; }
public function getPreviewAction(SiteTree $page, PreviewableDataObject $obj) { /* * $obj is an instance of ExampleObject in this case. * 'show' can be what ever action you wish the controller to use */ return $page->Link('show/' . $obj->ID); }
function testHasmethodBehaviour() { /* SiteTree should have all of the methods that Versioned has, because Versioned is listed in SiteTree's * extensions */ $st = new SiteTree(); $cc = new ContentController($st); $this->assertTrue($st->hasMethod('publish'), "Test SiteTree has publish"); $this->assertTrue($st->hasMethod('migrateVersion'), "Test SiteTree has migrateVersion"); /* This relationship should be case-insensitive, too */ $this->assertTrue($st->hasMethod('PuBliSh'), "Test SiteTree has PuBliSh"); $this->assertTrue($st->hasMethod('MiGratEVersIOn'), "Test SiteTree has MiGratEVersIOn"); /* In a similar manner, all of SiteTree's methods should be available on ContentController, because $failover is set */ $this->assertTrue($cc->hasMethod('canView'), "Test ContentController has canView"); $this->assertTrue($cc->hasMethod('linkorcurrent'), "Test ContentController has linkorcurrent"); /* This 'method copying' is transitive, so all of Versioned's methods should be available on ContentControler. * Once again, this is case-insensitive */ $this->assertTrue($cc->hasMethod('MiGratEVersIOn'), "Test ContentController has MiGratEVersIOn"); /* The above examples make use of SiteTree, Versioned and ContentController. Let's test defineMethods() more * directly, with some sample objects */ $objs = array(); $objs[] = new ObjectTest_T2(); $objs[] = new ObjectTest_T2(); $objs[] = new ObjectTest_T2(); // All these methods should exist and return true $trueMethods = array('testMethod','otherMethod','someMethod','t1cMethod','normalMethod'); foreach($objs as $i => $obj) { foreach($trueMethods as $method) { $methodU = strtoupper($method); $methodL = strtoupper($method); $this->assertTrue($obj->hasMethod($method), "Test that obj#$i has method $method"); $this->assertTrue($obj->hasMethod($methodU), "Test that obj#$i has method $methodU"); $this->assertTrue($obj->hasMethod($methodL), "Test that obj#$i has method $methodL"); $this->assertTrue($obj->$method(), "Test that obj#$i can call method $method"); $this->assertTrue($obj->$methodU(), "Test that obj#$i can call method $methodU"); $this->assertTrue($obj->$methodL(), "Test that obj#$i can call method $methodL"); } $this->assertTrue($obj->hasMethod('Wrapping'), "Test that obj#$i has method Wrapping"); $this->assertTrue($obj->hasMethod('WRAPPING'), "Test that obj#$i has method WRAPPING"); $this->assertTrue($obj->hasMethod('wrapping'), "Test that obj#$i has method wrapping"); $this->assertEquals("Wrapping", $obj->Wrapping(), "Test that obj#$i can call method Wrapping"); $this->assertEquals("Wrapping", $obj->WRAPPING(), "Test that obj#$i can call method WRAPPIGN"); $this->assertEquals("Wrapping", $obj->wrapping(), "Test that obj#$i can call method wrapping"); } }
/** * Go throught tree upward to find all parents */ private static function getParents(SiteTree $page) { $parents = array(); $parent = $page->parent(); while ($parent && $parent->exists()) { array_push($parents, $parent); // Keep looping $parent = $parent->parent(); } return $parents; }
public function testDataIntegrity() { $siteTree = new SiteTree(); $siteTree->MetaTitle = 'Custom meta title'; $siteTree->write(); $siteTreeTest = SiteTree::get()->byID($siteTree->ID); $this->assertEquals('Custom meta title', $siteTreeTest->MetaTitle); $obj = new MetaTitleExtensionTest_DataObject(); $obj->MetaTitle = 'Custom DO meta title'; $obj->write(); $objTest = MetaTitleExtensionTest_DataObject::get()->byID($obj->ID); $this->assertEquals('Custom DO meta title', $objTest->MetaTitle); }
/** * @param SiteConfig $config * @param SiteTree $owner * @param string $metadata * * @return void * */ public function updateMetadata(SiteConfig $config, SiteTree $owner, &$metadata) { // Facebook App ID if ($config->FacebookAppID) { $metadata .= $owner->MarkupComment('Facebook Insights'); $metadata .= $owner->MarkupFacebook('fb:app_id', $config->FacebookAppID, false); // Admins (if App ID) foreach ($config->FacebookAdmins() as $admin) { if ($admin->FacebookProfileID) { $metadata .= $owner->MarkupFacebook('fb:admins', $admin->FacebookProfileID, false); } } } }
/** * Returns a fixed navigation menu of the given level. * @return SS_List */ public function getMenu($level = 1) { if (ClassInfo::exists("SiteTree")) { if ($level == 1) { $result = SiteTree::get()->filter(array("ShowInMenus" => 1, "ParentID" => 0)); } else { $parent = $this->owner->data(); $stack = array($parent); if ($parent) { while ($parent = $parent->Parent) { array_unshift($stack, $parent); } } if (isset($stack[$level - 2]) && !$stack[$level - 2] instanceof Product) { $result = $stack[$level - 2]->Children(); } } $visible = array(); // Remove all entries the can not be viewed by the current user // We might need to create a show in menu permission if (isset($result)) { foreach ($result as $page) { if ($page->canView()) { $visible[] = $page; } } } return new ArrayList($visible); } else { return new ArrayList(); } }
public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab('Root.Main', new CheckboxField('InMainNavigation', 'In Main Navigation anzeigen')); $fields->addFieldToTab('Root.Main', new CheckboxField('InFooterNavigation', 'In Footer Navigation anzeigen')); return $fields; }
/** * Ensures that there is always a 404 page by checking if there's an * instance of ErrorPage with a 404 and 500 error code. If there is not, * one is created when the DB is built. */ public function requireDefaultRecords() { parent::requireDefaultRecords(); if ($this->class === 'ErrorPage' && SiteTree::config()->create_default_pages) { $defaultPages = $this->getDefaultRecords(); foreach ($defaultPages as $defaultData) { $code = $defaultData['ErrorCode']; $page = ErrorPage::get()->filter('ErrorCode', $code)->first(); $pageExists = !empty($page); if (!$pageExists) { $page = new ErrorPage($defaultData); $page->write(); $page->publish('Stage', 'Live'); } // Check if static files are enabled if (!self::config()->enable_static_file) { continue; } // Ensure this page has cached error content $success = true; if (!$page->hasStaticPage()) { // Update static content $success = $page->writeStaticPage(); } elseif ($pageExists) { // If page exists and already has content, no alteration_message is displayed continue; } if ($success) { DB::alteration_message(sprintf('%s error page created', $code), 'created'); } else { DB::alteration_message(sprintf('%s error page could not be created. Please check permissions', $code), 'error'); } } } }
/** * Update link mappings when replacing the default automated URL handling. */ public function onAfterWrite() { parent::onAfterWrite(); // Determine whether the default automated URL handling has been replaced. if (Config::inst()->get('MisdirectionRequestFilter', 'replace_default')) { // Determine whether the URL segment or parent ID has been updated. $changed = $this->owner->getChangedFields(); if (isset($changed['URLSegment']['before']) && isset($changed['URLSegment']['after']) && $changed['URLSegment']['before'] != $changed['URLSegment']['after'] || isset($changed['ParentID']['before']) && isset($changed['ParentID']['after']) && $changed['ParentID']['before'] != $changed['ParentID']['after']) { // The link mappings should only be created for existing pages. $URL = isset($changed['URLSegment']['before']) ? $changed['URLSegment']['before'] : $this->owner->URLSegment; if (strpos($URL, 'new-') !== 0) { // Determine the page URL. $parentID = isset($changed['ParentID']['before']) ? $changed['ParentID']['before'] : $this->owner->ParentID; $parent = SiteTree::get_one('SiteTree', "SiteTree.ID = {$parentID}"); while ($parent) { $URL = Controller::join_links($parent->URLSegment, $URL); $parent = SiteTree::get_one('SiteTree', "SiteTree.ID = {$parent->ParentID}"); } // Instantiate a link mapping for this page. singleton('MisdirectionService')->createPageMapping($URL, $this->owner->ID); // Purge any link mappings that point back to the same page. $this->owner->regulateMappings($this->owner->Link() === Director::baseURL() ? Controller::join_links(Director::baseURL(), 'home/') : $this->owner->Link(), $this->owner->ID); // Recursively create link mappings for any children. $children = $this->owner->AllChildrenIncludingDeleted(); if ($children->count()) { $this->owner->recursiveMapping($URL, $children); } } } } }
public function getSettingsFields() { $fields = parent::getSettingsFields(); // Hide ShowInSearch checkbox if we don't have a search $fields->removeByName('ShowInSearch'); return $fields; }
/** * Handles the translation of pages and its relations * * @param array $data , Form $form * @return boolean | index function **/ public function doTranslatePages($data, $form) { $language = $data['NewTransLang']; $pages = explode(',', $data['PageIDs']); $status = array('translated' => array(), 'error' => array()); foreach ($pages as $p) { $page = SiteTree::get()->byID($p); $id = $page->ID; if (!$page->hasTranslation($language)) { try { $translation = $page->createTranslation($language); $successMessage = $this->duplicateRelations($page, $translation); $status['translated'][$translation->ID] = array('TreeTitle' => $translation->TreeTitle); $translation->destroy(); unset($translation); } catch (Exception $e) { // no permission - fail gracefully $status['error'][$page->ID] = true; } } $page->destroy(); unset($page); } return '<input type="hidden" class="close-dialog" />'; }
function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab("Root.Content.Widgets", new WidgetAreaEditor("SideBar") ); return $fields; }
public static function model($url = null) { static::start(); $stage = static::getRequestedStage(); $key = $url . '|' . $stage; if (isset(static::$models[$key])) { return static::$models[$key]; } $segments = !is_null($url) ? static::segments($url) : Request::segments(); $segment = array_shift($segments); if ($segment) { $parentID = 0; do { $model = \SiteTree::get()->filter(array('URLSegment' => $segment, 'ParentID' => $parentID))->First(); if ($model) { $parentID = $model->ID; } else { break; } } while ($segment = array_shift($segments)); } else { // special case - home page $model = \SiteTree::get()->filter(array('URLSegment' => 'home', 'ParentID' => 0))->First(); } return static::$models[$url] = $model; }
public function allPagesToCache() { // Get each page type to define its sub-urls $urls = array(); // memory intensive depending on number of pages $pages = SiteTree::get()->where("ClassName != 'BlogEntry'"); //remove Blog pages from cache due to Form SecurityID issue foreach ($pages as $page) { array_push($urls, $page->Link()); if ($page->ClassName == 'ProjectPage') { //add ajax pages for each projectpage array_push($urls, $page->Link() . 'ajax'); } } //add tag pages $tags = Tag::get()->filter(array('HasTagPage' => 1)); foreach ($tags as $tag) { array_push($urls, '/tag/' . $tag->Slug); } //add location pages $locations = Location::get(); foreach ($locations as $location) { array_push($urls, '/location/' . $location->Slug); } return $urls; }
function write() { if ($this->getField("LinkedPageID")) { $this->LinkedPage()->write(); } parent::write(); }
public static function flushSiteTree($sitetreeID) { $sitetree = SiteTree::get()->byID($sitetreeID); if ($sitetree && $sitetree->exists()) { $strategy = Config::inst()->get('SectionIO', 'sitetree_flush_strategy'); switch ($strategy) { case 'single': $exp = 'obj.http.content-type ~ "' . preg_quote('text/html') . '"'; $exp .= ' && obj.http.x-url ~ "^' . preg_quote($sitetree->Link()) . '$"'; break; case 'parents': $exp = 'obj.http.content-type ~ "' . preg_quote('text/html') . '"'; $exp .= ' && (obj.http.x-url ~ "^' . preg_quote($sitetree->Link()) . '$"'; $parent = $sitetree->getParent(); while ($parent && $parent->exists()) { $exp .= ' || obj.http.x-url ~ "^' . preg_quote($parent->Link()) . '$"'; $parent = $parent->getParent(); } $exp .= ')'; break; case 'all': $exp = 'obj.http.content-type ~ "' . preg_quote('text/html') . '"'; break; case 'everyting': default: $exp = 'obj.http.x-url ~ /'; break; } return static::performFlush($exp); } return false; }
/** * Get a set of content languages (for quick language navigation) * @example * <code> * <!-- in your template --> * <ul class="langNav"> * <% loop Languages %> * <li><a href="$Link" class="$LinkingMode" title="$Title.ATT">$Language</a></li> * <% end_loop %> * </ul> * </code> * * @return ArrayList|null */ public function Languages() { $locales = TranslatableUtility::get_content_languages(); // there's no need to show a navigation when there's less than 2 languages. So return null if (count($locales) < 2) { return null; } $currentLocale = Translatable::get_current_locale(); $homeTranslated = null; if ($home = SiteTree::get_by_link('home')) { /** @var SiteTree $homeTranslated */ $homeTranslated = $home->getTranslation($currentLocale); } /** @var ArrayList $langSet */ $langSet = ArrayList::create(); foreach ($locales as $locale => $name) { Translatable::set_current_locale($locale); /** @var SiteTree $translation */ $translation = $this->owner->hasTranslation($locale) ? $this->owner->getTranslation($locale) : null; $langSet->push(new ArrayData(array('Locale' => $locale, 'RFC1766' => i18n::convert_rfc1766($locale), 'Language' => DBField::create_field('Varchar', strtoupper(i18n::get_lang_from_locale($locale))), 'Title' => DBField::create_field('Varchar', html_entity_decode(i18n::get_language_name(i18n::get_lang_from_locale($locale), true), ENT_NOQUOTES, 'UTF-8')), 'LinkingMode' => $currentLocale == $locale ? 'current' : 'link', 'Link' => $translation ? $translation->AbsoluteLink() : ($homeTranslated ? $homeTranslated->Link() : '')))); } Translatable::set_current_locale($currentLocale); i18n::set_locale($currentLocale); return $langSet; }
public function getCMSFields() { $fields = parent::getCMSFields(); $fields->insertBefore(TextareaField::create('Intro', 'Intro'), 'Content'); $fields->insertAfter(ColorPaletteField::create("Colour", "Colour", array('night' => '#333333', 'air' => '#009EE2', 'earth' => ' #79c608', 'passion' => '#b02635', 'people' => '#de347f', 'inspiration' => '#783980')), "Intro"); $fields->insertBefore($image = UploadField::create('SplashImage', 'Splash Image'), 'Content'); $image->setFolderName('Uploads/Splash-Images'); if ($this->ClassName === "Page" || $this->ClassName === "HomePage") { $fields->insertAfter(HTMLEditorField::create('ExtraContent'), 'Content'); $gridField = new GridField('FeatureItems', 'FeatureItems', $this->FeatureItems()->sort(array('Sort' => 'ASC', 'Archived' => 'ASC')), $config = GridFieldConfig_RelationEditor::create()); $gridField->setModelClass('FeatureItem'); $fields->addFieldToTab('Root.Features', $gridField); $config->addComponent(new GridFieldOrderableRows()); } else { if ($this->ClassName === "CalendarPage") { $content = $fields->dataFieldByName('Content'); $content->addExtraClass('no-pagebreak'); $events = Event::get()->sort(array('StartDateTime' => 'Desc'))->filterByCallback(function ($record) { return !$record->getIsPastEvent(); }); $gridField = new GridField('Event', 'Upcoming Events', $events, $config = GridFieldConfig_RecordEditor::create()); $gridField->setModelClass('Event'); $dataColumns = $config->getComponentByType('GridFieldDataColumns'); $dataColumns->setDisplayFields(array('Title' => 'Title', 'StartDateTime' => 'Date and Time', 'DatesAndTimeframe' => 'Presentation String')); $fields->addFieldToTab('Root.UpcomingEvents', $gridField); } } return $fields; }
protected function processRecord($record, $columnMap, &$results, $preview = false) { $siteTreeID = null; if (!empty($record['NewURL'])) { //redirect to an existing page if ($page = SiteTree::get_by_link($record['NewURL'])) { $siteTreeID = $page->ID; } else { //custom url redirect $redirect = $this->createRedirect(array('OldURL' => $record['OldURL'], 'RedirectType' => 'Custom', 'RedirectTo' => $record['NewURL'])); $results->addCreated($redirect); return $redirect->ID; } } else { if (!empty($record['PageID'])) { //pass in page id directly $siteTreeID = $record['PageID']; } else { return false; } } //check for an existing record $existing = OldURLRedirect::get()->filter(array('OldURL' => $record['OldURL'], 'PageID' => $siteTreeID))->first(); if (!$existing) { $redirect = $this->createRedirect(array('OldURL' => $record['OldURL'], 'PageID' => $siteTreeID)); $results->addCreated($redirect); return $redirect->ID; } else { $results->addUpdated($existing); return $existing->ID; } }
function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldsToTab("Root.Content.Shop", array(new TextField('ProductKey', _t("Shop.Item.ProductKey", "%ProductKey%")), new NumericField('Price', _t("Shop.Item.Price", "%Price%")), new CheckboxField('Featured', _t("Shop.Item.Featured", "%Featured%")), new TextareaField('Summary', _t("Shop.Item.Summary", "%Summary%"), 5), new TextField('StockQuantity', _t("Shop.Item.StockQuantity", "%StockQuantity%")), new DateField('StockDate', _t("Shop.Item.StockDate", "%StockDate%")), new DropdownField('Currency', _t("Shop.Item.Currency", "%Currency%"), singleton($this->ClassName)->dbObject('Currency')->enumValues()), new ReadonlyField('OrderCount', _t("Shop.Item.OrderCount", "%Orders count%", $this->OrderCount)))); $fields->addFieldsToTab('Root.Content.' . _t("Shop.Item.Pictures", "%Pictures%"), array(new FileIFrameField('Picture', _t("Shop.Item.Picture", "%Picture%")), new TreeDropdownField('PictureFolderID', _t("Shop.Item.PictureFolder", "%PictureFolder%"), "Folder"))); return $fields; }
/** * @param InputInterface $input * @param OutputInterface $output * @throws Exception * @returns null */ protected function execute(InputInterface $input, OutputInterface $output) { if (!Check::fileToUrlMapping()) { die('ERROR: Please set a valid path in $_FILE_TO_URL_MAPPING before running the seeder' . PHP_EOL); } if (\SiteTree::has_extension('SiteTreeLinkTracking')) { \SiteTree::remove_extension('SiteTreeLinkTracking'); } // Customer overrides delete to check for admin // major hack to enable ADMIN permissions // login throws cookie warning, this will hide the error message error_reporting(0); try { if ($admin = \Member::default_admin()) { $admin->logIn(); } } catch (\Exception $e) { } error_reporting(E_ALL); $writer = new RecordWriter(); if ($input->getOption('batch')) { $batchSize = intval($input->getOption('size')); $writer = new BatchedSeedWriter($batchSize); } $seeder = new Seeder($writer, new CliOutputFormatter()); $className = $input->getOption('class'); $key = $input->getOption('key'); if ($input->getOption('force')) { $seeder->setIgnoreSeeds(true); } $seeder->seed($className, $key); return; }
public static function enable($searchableClasses = array('SiteTree')) { // Chris Bolt, removed file // Chris Bolt add site tree extension SiteTree::add_extension('BoltSearchIndexedSiteTree'); $defaultColumns = array('SiteTree' => '"Title","MenuTitle","Content","MetaDescription","SearchIndex"'); if (!is_array($searchableClasses)) { $searchableClasses = array($searchableClasses); } foreach ($searchableClasses as $class) { if (!class_exists($class)) { continue; } if (isset($defaultColumns[$class])) { Config::inst()->update($class, 'create_table_options', array(MySQLSchemaManager::ID => 'ENGINE=MyISAM')); $class::add_extension("FulltextSearchable('{$defaultColumns[$class]}')"); } else { throw new Exception("FulltextSearchable::enable() I don't know the default search columns for class '{$class}'"); } } self::$searchable_classes = $searchableClasses; if (class_exists("ContentController")) { ContentController::add_extension("ContentControllerSearchExtension"); } }
/** * Migrate records of a single class * * @param string $class * @param null|string $stage */ protected function upClass($class) { if (!class_exists($class)) { return; } if (is_subclass_of($class, 'SiteTree')) { $items = SiteTree::get()->filter('ClassName', $class); } else { $items = $class::get(); } if ($count = $items->count()) { $this->message(sprintf('Migrating %s legacy %s records.', $count, $class)); foreach ($items as $item) { $cancel = $item->extend('onBeforeUp'); if ($cancel && min($cancel) === false) { continue; } /** * @var MigratableObject $item */ $result = $item->up(); $this->message($result); $item->extend('onAfterUp'); } } }
public function process() { $classes = array(); $types = $this->types; foreach ($types as $t) { if (class_exists($t)) { $pages = SiteTree::get()->filter(array('ClassName' => $t)); $urls = array(); // only used for later context $object = null; foreach ($pages as $object) { if (singleton('SimpleCachePublisher')->dontCache($object)) { continue; } if ($object->hasMethod('pagesAffectedByChanges')) { $pageUrls = $object->pagesAffectedByChanges(); foreach ($pageUrls as $url) { $urls[] = $url; } } else { $urls[] = $object->AbsoluteLink(); } } if ($object) { $job = new SimpleCachePublishingJob($object, $urls); singleton('QueuedJobService')->queueJob($job); } } $this->currentStep++; } $this->isComplete = 1; $nextRun = date('Y-m-d H:i:s', time() + $this->schedule); $job = new ScheduledRepublishJob($this->types, $this->schedule); singleton('QueuedJobService')->queueJob($job, $nextRun); }
/** * Ensures that there is always a 404 page * by checking if there's an instance of * ErrorPage with a 404 and 500 error code. If there * is not, one is created when the DB is built. */ function requireDefaultRecords() { parent::requireDefaultRecords(); if ($this->class == 'ErrorPage' && SiteTree::get_create_default_pages()) { // Ensure that an assets path exists before we do any error page creation if (!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH); } $pageNotFoundErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '404'"); $pageNotFoundErrorPageExists = $pageNotFoundErrorPage && $pageNotFoundErrorPage->exists() ? true : false; $pageNotFoundErrorPagePath = self::get_filepath_for_errorcode(404); if (!($pageNotFoundErrorPageExists && file_exists($pageNotFoundErrorPagePath))) { if (!$pageNotFoundErrorPageExists) { $pageNotFoundErrorPage = new ErrorPage(); $pageNotFoundErrorPage->ErrorCode = 404; $pageNotFoundErrorPage->Title = _t('ErrorPage.DEFAULTERRORPAGETITLE', 'Page not found'); $pageNotFoundErrorPage->Content = _t('ErrorPage.DEFAULTERRORPAGECONTENT', '<p>Sorry, it seems you were trying to access a page that doesn\'t exist.</p><p>Please check the spelling of the URL you were trying to access and try again.</p>'); $pageNotFoundErrorPage->write(); $pageNotFoundErrorPage->publish('Stage', 'Live'); } // Ensure a static error page is created from latest error page content $response = Director::test(Director::makeRelative($pageNotFoundErrorPage->Link())); $written = null; if ($fh = fopen($pageNotFoundErrorPagePath, 'w')) { $written = fwrite($fh, $response->getBody()); fclose($fh); } if ($written) { DB::alteration_message('404 error page created', 'created'); } else { DB::alteration_message(sprintf('404 error page could not be created at %s. Please check permissions', $pageNotFoundErrorPagePath), 'error'); } } $serverErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '500'"); $serverErrorPageExists = $serverErrorPage && $serverErrorPage->exists() ? true : false; $serverErrorPagePath = self::get_filepath_for_errorcode(500); if (!($serverErrorPageExists && file_exists($serverErrorPagePath))) { if (!$serverErrorPageExists) { $serverErrorPage = new ErrorPage(); $serverErrorPage->ErrorCode = 500; $serverErrorPage->Title = _t('ErrorPage.DEFAULTSERVERERRORPAGETITLE', 'Server error'); $serverErrorPage->Content = _t('ErrorPage.DEFAULTSERVERERRORPAGECONTENT', '<p>Sorry, there was a problem with handling your request.</p>'); $serverErrorPage->write(); $serverErrorPage->publish('Stage', 'Live'); } // Ensure a static error page is created from latest error page content $response = Director::test(Director::makeRelative($serverErrorPage->Link())); $written = null; if ($fh = fopen($serverErrorPagePath, 'w')) { $written = fwrite($fh, $response->getBody()); fclose($fh); } if ($written) { DB::alteration_message('500 error page created', 'created'); } else { DB::alteration_message(sprintf('500 error page could not be created at %s. Please check permissions', $serverErrorPagePath), 'error'); } } } }
/** * New tests require nested urls to be enabled, but the site might not * support nested URLs. * This setup will enable nested-urls for this test and resets the state * after the tests have been performed. */ function tearDown() { if (isset($this->orig['nested_urls']) && !$this->orig['nested_urls']) { SiteTree::disable_nested_urls(); } parent::tearDown(); }