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 run($request) { increase_time_limit_to(); $self = get_class($this); $verbose = isset($_GET['verbose']); if (isset($_GET['class']) && isset($_GET['id'])) { $item = DataObject::get($_GET['class'])->byID($_GET['id']); if (!$item || !$item->exists()) { die('not found: ' . $_GET['id']); } $item->rebuildVFI(); echo "done"; return; } if (isset($_GET['link'])) { $item = SiteTree::get_by_link($_GET['link']); if (!$item || !$item->exists()) { die('not found: ' . $_GET['link']); } $item->rebuildVFI(); echo "done"; return; } if (isset($_GET['start'])) { $this->runFrom($_GET['class'], $_GET['start'], $_GET['field']); } else { foreach (array('framework', 'sapphire') as $dirname) { $script = sprintf("%s%s{$dirname}%scli-script.php", BASE_PATH, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); if (file_exists($script)) { break; } } $classes = VirtualFieldIndex::get_classes_with_vfi(); foreach ($classes as $class) { if (isset($_GET['class']) && $class != $_GET['class']) { continue; } $singleton = singleton($class); $query = $singleton->get($class); $dtaQuery = $query->dataQuery(); $sqlQuery = $dtaQuery->getFinalisedQuery(); $singleton->extend('augmentSQL', $sqlQuery, $dtaQuery); $total = $query->count(); $startFrom = isset($_GET['startfrom']) ? $_GET['startfrom'] : 0; $field = isset($_GET['field']) ? $_GET['field'] : ''; echo "Class: {$class}, total: {$total}\n\n"; for ($offset = $startFrom; $offset < $total; $offset += $this->stat('recordsPerRequest')) { echo "{$offset}.."; $cmd = "php {$script} dev/tasks/{$self} class={$class} start={$offset} field={$field}"; if ($verbose) { echo "\n Running '{$cmd}'\n"; } $res = $verbose ? passthru($cmd) : `{$cmd}`; if ($verbose) { echo " " . preg_replace('/\\r\\n|\\n/', '$0 ', $res) . "\n"; } } } } }
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; }
/** * 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; }
/** * Add default records to database. * * This function is called whenever the database is built, after the * database tables have all been created. Overload this to add default * records when the database is built, but make sure you call * parent::requireDefaultRecords(). */ public function requireDefaultRecords() { if (!SiteTree::get_by_link(Config::inst()->get('RootURLController', 'default_homepage_link'))) { $homepage = new HomePage(); $homepage->Title = 'Home'; $homepage->URLSegment = Config::inst()->get('RootURLController', 'default_homepage_link'); $homepage->Sort = 1; $homepage->write(); $homepage->publish('Stage', 'Live'); $homepage->flushCache(); DB::alteration_message('Home page created', 'created'); } if (DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) { $aboutus = new RootPage(); $aboutus->Title = 'About Us'; $aboutus->Sort = 2; $aboutus->write(); $aboutus->publish('Stage', 'Live'); $aboutus->flushCache(); DB::alteration_message('Book 1 created', 'created'); $contactus = new RootPage(); $contactus->Title = 'Contact Us'; $contactus->Sort = 3; $contactus->write(); $contactus->publish('Stage', 'Live'); $contactus->flushCache(); DB::alteration_message('Book 2 created', 'created'); } // call it on the parent parent::requireDefaultRecords(); }
public function requireDefaultRecords() { parent::requireDefaultRecords(); if (Config::inst()->get('MailChimpController', 'redirect')) { if (!SiteTree::get_by_link(Config::inst()->get('MailChimpController', 'redirect_ok'))) { $regOk = new MailChimpLandingPage(); $regOk->Title = _t('MailChimp.SUBSCIPTION_OK ', 'MailChimp Subscription OK'); $regOk->Content = _t('MailChimp.SUBSCIPTION_OK_CONTENT', '<p>Thanks for subscribing</p>'); $regOk->URLSegment = Config::inst()->get('MailChimpController', 'redirect_ok'); $regOk->Sort = 9998; $regOk->ShowInMenus = FALSE; $regOk->ShowInSearch = FALSE; $regOk->write(); $regOk->publish('Stage', 'Live'); $regOk->flushCache(); DB::alteration_message('MailChimp Subsciption OK created', 'created'); } if (!SiteTree::get_by_link(Config::inst()->get('MailChimpController', 'redirect_ko'))) { $regOk = new MailChimpLandingPage(); $regOk->Title = _t('MailChimp.SUBSCIPTION_KO ', 'MailChimp Subscription KO'); $regOk->Content = _t('MailChimp.SUBSCIPTION_KO_CONTENT', '<p>Something goes wrong subscribing</p>'); $regOk->URLSegment = Config::inst()->get('MailChimpController', 'redirect_ko'); $regOk->Sort = 9999; $regOk->ShowInMenus = FALSE; $regOk->ShowInSearch = FALSE; $regOk->write(); $regOk->publish('Stage', 'Live'); $regOk->flushCache(); DB::alteration_message('MailChimp Subsciption KO created', 'created'); } } }
public function getParentPage() { if($parent = $this->stat('parent')) { if(is_numeric($parent)) { return DataObject::get_by_id($this->modelClass(), $parent); } elseif(is_string($parent)) { return SiteTree::get_by_link($parent); } } return false; }
/** * If no ProfiledPage exists and no Page exists called 'Profile' then creates one * titled 'Profile' and writes it to stage. * */ public function requireDefaultRecords() { if ($this->config()->get('auto_build_models')) { if (!ProfiledPage::get()->count()) { if (!SiteTree::get_by_link('/profile')) { /** @var ProfiledPage $page */ $page = ProfiledPage::create(array('Title' => CrackerjackModule::get_localised_config_string('ProfiledBuild', 'ProfiledPageTitle', 'Title'))); $page->writeToStage('Stage'); DB::alteration_message("Added ProfiledPage 'Page' at '/profile'", 'changed'); } } } }
public function transform($item, $parentObject, $duplicateStrategy) { if (Director::is_cli()) { Debug::message("Parent: #{$parentObject->ID}, {$parentObject->Title}"); Debug::message($item->AbsoluteURL); } // Sleep for 100ms to reduce load on the remote server usleep(100 * 1000); // Extract content from the page $contentFields = $this->getContentFieldsAndSelectors($item); // Default value for Title if (empty($contentFields['Title'])) { $contentFields['Title'] = array('content' => $item->Name); } // Default value for URL segment if (empty($contentFields['URLSegment'])) { $urlSegment = str_replace('/', '', $item->Name); $urlSegment = preg_replace('/\\.[^.]*$/', '', $urlSegment); $urlSegment = str_replace('.', '-', $item->Name); $contentFields['URLSegment'] = array('content' => $urlSegment); } $schema = $item->getSource()->getSchemaForURL($item->AbsoluteURL); $pageType = $schema->DataType; if (!$pageType) { throw new Exception('Pagetype for migration schema is empty!'); } // Create a page with the appropriate fields $page = new $pageType(array()); $existingPage = SiteTree::get_by_link($item->getExternalId()); if ($existingPage && $duplicateStrategy === 'Overwrite') { if (get_class($existingPage) !== $pageType) { $existingPage->ClassName = $pageType; $existingPage->write(); } if ($existingPage) { $page = $existingPage; } } $page->StaticSiteContentSourceID = $item->getSource()->ID; $page->StaticSiteURL = $item->AbsoluteURL; $page->ParentID = $parentObject ? $parentObject->ID : 0; foreach ($contentFields as $k => $v) { $page->{$k} = $v['content']; } $page->write(); if (Director::is_cli()) { Debug::message("#{$page->Title}"); Debug::message("#{$page->ID} child of #{$page->ID}"); } return new TransformResult($page, $item->stageChildren()); }
public function doAdd($data, $form) { $className = isset($data['PageType']) ? $data['PageType'] : "Page"; $parentID = isset($data['ParentID']) ? (int) $data['ParentID'] : 0; $suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null; if (!$parentID && isset($data['Parent'])) { $page = SiteTree::get_by_link($data['Parent']); if ($page) { $parentID = $page->ID; } } if (is_numeric($parentID) && $parentID > 0) { $parentObj = DataObject::get_by_id("SiteTree", $parentID); } else { $parentObj = null; } if (!$parentObj || !$parentObj->ID) { $parentID = 0; } if ($parentObj) { if (!$parentObj->canAddChildren()) { return Security::permissionFailure($this); } if (!singleton($className)->canCreate()) { return Security::permissionFailure($this); } } else { if (!SiteConfig::current_site_config()->canCreateTopLevel()) { return Security::permissionFailure($this); } } $record = $this->getNewItem("new-{$className}-{$parentID}" . $suffix, false); if (class_exists('Translatable') && $record->hasExtension('Translatable') && isset($data['Locale'])) { $record->Locale = $data['Locale']; } try { $record->write(); } catch (ValidationException $ex) { $form->sessionMessage($ex->getResult()->message(), 'bad'); return $this->getResponseNegotiator()->respond($this->request); } $editController = singleton('CMSPageEditController'); $editController->setCurrentPageID($record->ID); Session::set("FormInfo.Form_EditForm.formError.message", _t('CMSMain.PageAdded', 'Successfully created page')); Session::set("FormInfo.Form_EditForm.formError.type", 'good'); return $this->redirect(Controller::join_links(singleton('CMSPageEditController')->Link('show'), $record->ID)); }
function requireDefaultRecords() { if (self::$auto_include) { $className = $this->class; $page = $className::get()->First(); if (!$page) { $page = new TypographyTestPage(self::$defaults); $parent = SiteTree::get_by_link(self::$parent_url_segment); if ($parent) { $page->ParentID = $parent->ID; } $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); $page->URLSegment = self::$defaults['URLSegment']; $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); DB::alteration_message('TypographyTestPage', 'created'); } } }
/** * Create a new Jobamatic page with defaults set. */ public function requireDefaultRecords() { if (!SiteTree::get_by_link(self::DEFAULT_JOBPAGE_URLSEGMENT)) { $page = new JobamaticPage(); $page->Title = self::DEFAULT_JOBPAGE_TITLE; $page->MenuTitle = self::DEFAULT_JOBPAGE_MENU_TITLE; $page->URLSegment = self::DEFAULT_JOBPAGE_URLSEGMENT; $page->Content = self::DEFAULT_JOBPAGE_CONTENT; $page->ShowInSearch = FALSE; $page->write(); $page->publish('Stage', 'Live'); $message = "Created default Jobamatic Page"; $type = "created"; $page->flushCache(); } else { $message = "Failed to create default Jobamatic page – page with URLSegment "jobs" already exists."; $type = 'error'; } DB::alteration_message($message, $type); }
/** * Change the home page to HomePage type */ public function requireDefaultRecords() { if (!SiteTree::get_by_link("home")) { $homepage = new HomePage(); ${$homepage}->Title = "Home"; $homepage->URLSegment = "home"; $homepage->Sort = 1; $homepage->write(); $homepage->publish('Stage', 'Live'); $homepage->flushCache(); DB::alteration_message('Home Page created', 'created'); } else { $homepage = SiteTree::get_by_link("home"); if ($homepage->ClassName != "HomePage") { $homepage = $homepage->newClassInstance("HomePage"); $homepage->write(); $homepage->publish('Stage', 'Live'); $homepage->flushCache(); DB::alteration_message('Home changed to HomePage', 'changed'); } } parent::requireDefaultRecords(); }
/** * Change the contact-us page to ContactUsPage type */ function requireDefaultRecords() { if (!SiteTree::get_by_link("contact-us")) { $contactpage = new HomePage(); $contactpage->Title = "Contact Us"; $contactpage->URLSegment = "contact-us"; $contactpage->Sort = 3; $contactpage->write(); $contactpage->publish('Stage', 'Live'); $contactpage->flushCache(); DB::alteration_message('Contact Us created', 'created'); } else { $contactpage = SiteTree::get_by_link("contact-us"); if ($contactpage->ClassName != "ContactUsPage") { $contactpage = $contactpage->newClassInstance("ContactUsPage"); $contactpage->write(); $contactpage->publish('Stage', 'Live'); $contactpage->flushCache(); DB::alteration_message('Contact Us changed to ContactUsPage', 'changed'); } } parent::requireDefaultRecords(); }
/** * Create serialized JSON string with site tree hints data to be injected into * 'data-hints' attribute of root node of jsTree. * * @return String Serialized JSON */ public function SiteTreeHints() { $json = ''; $classes = SiteTree::page_type_classes(); $cacheCanCreate = array(); foreach ($classes as $class) { $cacheCanCreate[$class] = singleton($class)->canCreate(); } // Generate basic cache key. Too complex to encompass all variations $cache = SS_Cache::factory('CMSMain_SiteTreeHints'); $cacheKey = md5(implode('_', array(Member::currentUserID(), implode(',', $cacheCanCreate), implode(',', $classes)))); if ($this->request->getVar('flush')) { $cache->clean(Zend_Cache::CLEANING_MODE_ALL); } $json = $cache->load($cacheKey); if (!$json) { $def['Root'] = array(); $def['Root']['disallowedChildren'] = array(); // Contains all possible classes to support UI controls listing them all, // such as the "add page here" context menu. $def['All'] = array(); // Identify disallows and set globals $globalDisallowed = array(); foreach ($classes as $class) { $obj = singleton($class); $needsPerm = $obj->stat('need_permission'); if (!$obj instanceof HiddenClass) { $def['All'][$class] = array('title' => $obj->i18n_singular_name()); } if (!$obj->stat('can_be_root')) { $def['Root']['disallowedChildren'][] = $class; } if ($obj instanceof HiddenClass || (!array_key_exists($class, $cacheCanCreate) || !$cacheCanCreate[$class]) || $needsPerm && !$this->can($needsPerm)) { $globalDisallowed[] = $class; $def['Root']['disallowedChildren'][] = $class; } } // Set disallows by class foreach ($classes as $class) { $obj = singleton($class); if ($obj instanceof HiddenClass) { continue; } $def[$class] = array(); $allowed = $obj->allowedChildren(); if ($pos = array_search('SiteTree', $allowed)) { unset($allowed[$pos]); } // Start by disallowing all classes which aren't specifically allowed, // then add the ones which are globally disallowed. $disallowed = array_diff($classes, (array) $allowed); $disallowed = array_unique(array_merge($disallowed, $globalDisallowed)); // Re-index the array for JSON non sequential key issue if ($disallowed) { $def[$class]['disallowedChildren'] = array_values($disallowed); } $defaultChild = $obj->defaultChild(); if ($defaultChild != 'Page' && $defaultChild != null) { $def[$class]['defaultChild'] = $defaultChild; } $defaultParent = $obj->defaultParent(); $parent = SiteTree::get_by_link($defaultParent); $id = $parent ? $parent->id : null; if ($defaultParent != 1 && $defaultParent != null) { $def[$class]['defaultParent'] = $defaultParent; } } $this->extend('updateSiteTreeHints', $def); $json = Convert::raw2json($def); $cache->save($json, $cacheKey); } return $json; }
public function testGetByLink() { $home = $this->objFromFixture('Page', 'home'); $about = $this->objFromFixture('Page', 'about'); $staff = $this->objFromFixture('Page', 'staff'); $product = $this->objFromFixture('Page', 'product1'); $notFound = $this->objFromFixture('ErrorPage', '404'); SiteTree::config()->nested_urls = false; $this->assertEquals($home->ID, SiteTree::get_by_link('/', false)->ID); $this->assertEquals($home->ID, SiteTree::get_by_link('/home/', false)->ID); $this->assertEquals($about->ID, SiteTree::get_by_link($about->Link(), false)->ID); $this->assertEquals($staff->ID, SiteTree::get_by_link($staff->Link(), false)->ID); $this->assertEquals($product->ID, SiteTree::get_by_link($product->Link(), false)->ID); $this->assertEquals($notFound->ID, SiteTree::get_by_link($notFound->Link(), false)->ID); Config::inst()->update('SiteTree', 'nested_urls', true); $this->assertEquals($home->ID, SiteTree::get_by_link('/', false)->ID); $this->assertEquals($home->ID, SiteTree::get_by_link('/home/', false)->ID); $this->assertEquals($about->ID, SiteTree::get_by_link($about->Link(), false)->ID); $this->assertEquals($staff->ID, SiteTree::get_by_link($staff->Link(), false)->ID); $this->assertEquals($product->ID, SiteTree::get_by_link($product->Link(), false)->ID); $this->assertEquals($notFound->ID, SiteTree::get_by_link($notFound->Link(), false)->ID); $this->assertEquals($staff->ID, SiteTree::get_by_link('/my-staff/', false)->ID, 'Assert a unique URLSegment can be used for b/c.'); }
/** * @param DownloadTempFile $dl * @return HTMLText */ protected function displayCrunchingPage(DownloadTempFile $dl) { $crunchingPage = Config::inst()->get('Downloadable', 'crunching_page'); if ($crunchingPage) { $crunchingPage = SiteTree::get_by_link($crunchingPage); } if (!$crunchingPage || !$crunchingPage->exists()) { $crunchingPage = new Page(); $crunchingPage->Title = _t('Downloadable.CRUNCHINGTITLE', 'Processing Your Download'); $crunchingPage->Content = _t('Downloadable.CRUNCHINGBODY', '<p>Please wait while your download is prepared.</p>'); } // Just in case $this->dataRecord = $crunchingPage; // Add a meta tag that will refresh with the request that actually does the processing // In the future this could be wrapped in a <noscript> and we could do some better ajax // work to make this more userfriendly (such as a progress bar for multiple files, etc) Requirements::insertHeadTags('<meta http-equiv="refresh" content="1; url=' . $dl->getProcessingLink() . '">'); // And....render return $this->customise($crunchingPage)->renderWith(array('CrunchingPage', 'Page', 'Page')); }
/** * Returns the back page * * @return SiteTree * * @author Sebastian Diel <*****@*****.**> * @since 09.05.2012 */ public function BackPage() { $url = $this->BackLink(); $relativeUrl = Director::makeRelative($url); if (strpos($relativeUrl, '?') !== false) { $blankUrl = substr($relativeUrl, 0, strpos($relativeUrl, '?')); } elseif (strpos($relativeUrl, '#') !== false) { $blankUrl = substr($relativeUrl, 0, strpos($relativeUrl, '#')); } else { $blankUrl = $relativeUrl; } $backPage = SiteTree::get_by_link($blankUrl); // If no backPage has been found we could come from a product detail // page. Try to get the product title then. if (!$backPage) { $urlElems = explode('/', $blankUrl); array_pop($urlElems); $productId = array_pop($urlElems); if (is_numeric($productId)) { $silvercartProduct = DataObject::get_by_id('SilvercartProduct', Convert::raw2xml($productId)); if ($silvercartProduct) { $backPage = new DataObject(); $backPage->MenuTitle = $silvercartProduct->Title; } } else { $backPage = new DataObject(); $backPage->MenuTitle = _t('SilvercartPage.BACK_TO_DEFAULT'); } } return $backPage; }
public function addpage($data, $form) { // Protect against CSRF on destructive action if (!SecurityToken::inst()->checkRequest($this->request)) { return $this->httpError(400); } $className = isset($_REQUEST['PageType']) ? $_REQUEST['PageType'] : "Page"; $parent = isset($_REQUEST['ParentID']) ? $_REQUEST['ParentID'] : 0; $suffix = isset($_REQUEST['Suffix']) ? "-" . $_REQUEST['Suffix'] : null; if (!$parent && isset($_REQUEST['Parent'])) { $page = SiteTree::get_by_link($_REQUEST['Parent']); if ($page) { $parent = $page->ID; } } if (is_numeric($parent)) { $parentObj = DataObject::get_by_id("SiteTree", $parent); } else { $parentObj = null; } if (!$parentObj || !$parentObj->ID) { $parent = 0; } if ($parentObj) { if (!$parentObj->canAddChildren()) { return Security::permissionFailure($this); } if (!singleton($className)->canCreate()) { return Security::permissionFailure($this); } } else { if (!SiteConfig::current_site_config()->canCreateTopLevel()) { return Security::permissionFailure($this); } } $p = $this->getNewItem("new-{$className}-{$parent}" . $suffix, false); $p->Locale = $_REQUEST['Locale']; $p->write(); return $this->returnItemToUser($p); }
/** * Uses {@link Director::test()} to perform in-memory HTTP requests * on the passed-in URLs. * * @param array $urls Relative URLs * @return array Result, keyed by URL. Keys: * - "statuscode": The HTTP status code * - "redirect": A redirect location (if applicable) * - "path": The filesystem path where the cache has been written */ public function publishPages($urls) { $result = array(); //nest the config so we can make changes to the config and revert easily Config::nest(); // Do we need to map these? // Detect a numerically indexed arrays if (is_numeric(join('', array_keys($urls)))) { $urls = $this->urlsToPaths($urls); } // This can be quite memory hungry and time-consuming // @todo - Make a more memory efficient publisher increase_time_limit_to(); increase_memory_limit_to(); // Set the appropriate theme for this publication batch. // This may have been set explicitly via StaticPublisher::static_publisher_theme, // or we can use the last non-null theme. $customTheme = Config::inst()->get('StaticPublisher', 'static_publisher_theme'); if ($customTheme) { Config::inst()->update('SSViewer', 'theme', $customTheme); } // Ensure that the theme that is set gets used. Config::inst()->update('SSViewer', 'theme_enabled', true); $staticBaseUrl = Config::inst()->get('FilesystemPublisher', 'static_base_url'); if ($staticBaseUrl) { Config::inst()->update('Director', 'alternate_base_url', $staticBaseUrl); } if ($this->fileExtension == 'php') { Config::inst()->update('SSViewer', 'rewrite_hash_links', 'php'); } if (Config::inst()->get('StaticPublisher', 'echo_progress')) { echo $this->class . ": Publishing to " . $staticBaseUrl . "\n"; } $files = array(); $i = 0; $totalURLs = sizeof($urls); foreach ($urls as $url => $path) { $origUrl = $url; $result[$origUrl] = array('statuscode' => null, 'redirect' => null, 'path' => null); $i++; if ($url && !is_string($url)) { user_error("Bad url:" . var_export($url, true), E_USER_WARNING); continue; } if (Config::inst()->get('StaticPublisher', 'echo_progress')) { echo " * Publishing page {$i}/{$totalURLs}: {$url}\n"; flush(); } Requirements::clear(); if ($url == "") { $url = "/"; } if (Director::is_relative_url($url)) { $url = Director::absoluteURL($url); } $response = Director::test(str_replace('+', ' ', $url)); if (!$response) { continue; } if ($response) { $result[$origUrl]['statuscode'] = $response->getStatusCode(); } Requirements::clear(); singleton('DataObject')->flushCache(); // Check for ErrorPages generating output - we want to handle this in a special way below. $isErrorPage = false; $pageObject = null; if ($response && is_object($response) && (int) $response->getStatusCode() >= 400) { $pageObject = SiteTree::get_by_link($url); if ($pageObject && $pageObject instanceof ErrorPage) { $isErrorPage = true; } } // Skip any responses with a 404 status code unless it's the ErrorPage itself. if (!$isErrorPage && is_object($response) && $response->getStatusCode() == '404') { continue; } // Generate file content // PHP file caching will generate a simple script from a template if ($this->fileExtension == 'php') { if (is_object($response)) { if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') { $content = $this->generatePHPCacheRedirection($response->getHeader('Location')); } else { $content = $this->generatePHPCacheFile($response->getBody(), HTTP::get_cache_age(), date('Y-m-d H:i:s'), $response->getHeader('Content-Type')); } } else { $content = $this->generatePHPCacheFile($response . '', HTTP::get_cache_age(), date('Y-m-d H:i:s'), $response->getHeader('Content-Type')); } // HTML file caching generally just creates a simple file } else { if (is_object($response)) { if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') { $absoluteURL = Director::absoluteURL($response->getHeader('Location')); $result[$origUrl]['redirect'] = $response->getHeader('Location'); $content = "<meta http-equiv=\"refresh\" content=\"2; URL={$absoluteURL}\">"; } else { $content = $response->getBody(); } } else { $content = $response . ''; } } if (Config::inst()->get('StaticPublisher', 'include_caching_metadata')) { $content = str_replace('</html>', sprintf("</html>\n\n<!-- %s -->", implode(" ", $this->getMetadata($url))), $content); } if (!$isErrorPage) { $files[$origUrl] = array('Content' => $content, 'Folder' => dirname($path) . '/', 'Filename' => basename($path)); } else { // Generate a static version of the error page with a standardised name, so they can be plugged // into catch-all webserver statements such as Apache's ErrorDocument. $code = (int) $response->getStatusCode(); $files[$origUrl] = array('Content' => $content, 'Folder' => dirname($path) . '/', 'Filename' => "error-{$code}.html"); } } //return config to its previous state Config::unnest(); $base = BASE_PATH . "/{$this->destFolder}"; foreach ($files as $origUrl => $file) { Filesystem::makeFolder("{$base}/{$file['Folder']}"); $path = "{$base}/{$file['Folder']}{$file['Filename']}"; $result[$origUrl]['path'] = $path; if (isset($file['Content'])) { $fh = fopen($path, "w"); fwrite($fh, $file['Content']); fclose($fh); } else { if (isset($file['Copy'])) { copy($file['Copy'], $path); } } } return $result; }
/** * 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), '/'); } } }
public function doAdd($data, $form) { $className = isset($data['PageType']) ? $data['PageType'] : "Page"; $parentMode = isset($data['ParentModeField']) ? $data['ParentModeField'] : "top"; $parentID = isset($data['ParentID']) ? (int)$data['ParentID'] : 0; if ($parentMode == "top") $parentID = 0; $suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null; if(!$parentID && isset($data['Parent'])) { $page = SiteTree:: get_by_link(Convert::raw2sql($data['Parent'])); if($page) $parentID = $page->ID; } if(is_numeric($parentID) && $parentID > 0) $parentObj = DataObject::get_by_id("SiteTree", $parentID); else $parentObj = null; if(!$parentObj || !$parentObj->ID) $parentID = 0; if($parentObj) { if(!$parentObj->canAddChildren()) return Security::permissionFailure($this); if(!singleton($className)->canCreate()) return Security::permissionFailure($this); } else { if(!SiteConfig::current_site_config()->canCreateTopLevel()) return Security::permissionFailure($this); } $record = $this->getNewItem("new-$className-$parentID".$suffix, false); if(class_exists('Translatable') && $record->hasExtension('Translatable')) $record->Locale = $data['Locale']; $record->write(); $editController = singleton('CMSPageEditController'); $editController->setCurrentPageID($record->ID); return $this->redirect(Controller::join_links(singleton('CMSPageEditController')->Link('show'), $record->ID)); }
protected function excludeFromCache($url) { $excluded = false; //don't publish objects that are excluded from cache $candidatePage = SiteTree::get_by_link($url); if (!empty($candidatePage)) { if (!empty($candidatePage->excludeFromCache)) { $excluded = true; } } return $excluded; }
/** * @return DataObjectSet */ public function Page($link) { return SiteTree::get_by_link($link); }
public function doAdd($data, $form) { $className = isset($data['PageType']) ? $data['PageType'] : "Page"; $parentID = isset($data['ParentID']) ? (int) $data['ParentID'] : 0; $suffix = isset($data['Suffix']) ? "-" . $data['Suffix'] : null; if (!$parentID && isset($data['Parent'])) { $page = SiteTree::get_by_link(Convert::raw2sql($data['Parent'])); if ($page) { $parentID = $page->ID; } } if (is_numeric($parentID) && $parentID > 0) { $parentObj = DataObject::get_by_id("SiteTree", $parentID); } else { $parentObj = null; } if (!$parentObj || !$parentObj->ID) { $parentID = 0; } if ($parentObj) { if (!$parentObj->canAddChildren()) { return Security::permissionFailure($this); } if (!singleton($className)->canCreate()) { return Security::permissionFailure($this); } } else { if (!SiteConfig::current_site_config()->canCreateTopLevel()) { return Security::permissionFailure($this); } } $record = $this->getNewItem("new-{$className}-{$parentID}" . $suffix, false); $record->Locale = $data['Locale']; $record->write(); $form = $this->getEditForm($record->ID); if (isset($data['returnID'])) { return $record->ID; } else { if (Director::is_ajax()) { $form = $this->getEditForm($record->ID); return $form->formHtmlContent(); } else { return $this->redirect(Controller::join_links($this->Link('show'), $record->ID)); } } }
/** * Add default records to database. * * This function is called whenever the database is built, after the * database tables have all been created. Overload this to add default * records when the database is built, but make sure you call * parent::requireDefaultRecords(). */ function requireDefaultRecords() { parent::requireDefaultRecords(); // default pages if ($this->class == 'SiteTree' && self::$create_default_pages) { if (!SiteTree::get_by_link('home')) { $homepage = new Page(); $homepage->Title = _t('SiteTree.DEFAULTHOMETITLE', 'Home'); $homepage->Content = _t('SiteTree.DEFAULTHOMECONTENT', '<p>Welcome to SilverStripe! This is the default homepage. You can edit this page by opening <a href="admin/">the CMS</a>. You can now access the <a href="http://doc.silverstripe.org">developer documentation</a>, or begin <a href="http://doc.silverstripe.org/doku.php?id=tutorials">the tutorials.</a></p>'); $homepage->URLSegment = 'home'; $homepage->Status = 'Published'; $homepage->Sort = 1; $homepage->write(); $homepage->publish('Stage', 'Live'); $homepage->flushCache(); DB::alteration_message('Home page created', 'created'); } if (DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) { $aboutus = new Page(); $aboutus->Title = _t('SiteTree.DEFAULTABOUTTITLE', 'About Us'); $aboutus->Content = _t('SiteTree.DEFAULTABOUTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>'); $aboutus->Status = 'Published'; $aboutus->Sort = 2; $aboutus->write(); $aboutus->publish('Stage', 'Live'); $aboutus->flushCache(); DB::alteration_message('About Us page created', 'created'); $contactus = new Page(); $contactus->Title = _t('SiteTree.DEFAULTCONTACTTITLE', 'Contact Us'); $contactus->Content = _t('SiteTree.DEFAULTCONTACTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>'); $contactus->Status = 'Published'; $contactus->Sort = 3; $contactus->write(); $contactus->publish('Stage', 'Live'); $contactus->flushCache(); DB::alteration_message('Contact Us page created', 'created'); } } // schema migration // @todo Move to migration task once infrastructure is implemented if ($this->class == 'SiteTree') { $conn = DB::getConn(); // only execute command if fields haven't been renamed to _obsolete_<fieldname> already by the task if (array_key_exists('Viewers', $conn->fieldList('SiteTree'))) { $task = new UpgradeSiteTreePermissionSchemaTask(); $task->run(new SS_HTTPRequest('GET', '/')); } } }
/** * Create serialized JSON string with site tree hints data to be injected into * 'data-hints' attribute of root node of jsTree. * * @return String Serialized JSON */ public function SiteTreeHints() { $json = ''; $classes = ClassInfo::subclassesFor($this->stat('tree_class')); $cacheCanCreate = array(); foreach ($classes as $class) { $cacheCanCreate[$class] = singleton($class)->canCreate(); } // Generate basic cache key. Too complex to encompass all variations $cache = SS_Cache::factory('CMSMain_SiteTreeHints'); $cacheKey = md5(implode('_', array(Member::currentUserID(), implode(',', $cacheCanCreate), implode(',', $classes)))); if ($this->request->getVar('flush')) { $cache->clean(Zend_Cache::CLEANING_MODE_ALL); } $json = $cache->load($cacheKey); if (!$json) { $def['Root'] = array(); $def['Root']['disallowedParents'] = array(); foreach ($classes as $class) { $obj = singleton($class); if ($obj instanceof HiddenClass) { continue; } $allowedChildren = $obj->allowedChildren(); // SiteTree::allowedChildren() returns null rather than an empty array if SiteTree::allowed_chldren == 'none' if ($allowedChildren == null) { $allowedChildren = array(); } // Exclude SiteTree from possible Children $possibleChildren = array_diff($allowedChildren, array("SiteTree")); // Find i18n - names and build allowed children array foreach ($possibleChildren as $child) { $instance = singleton($child); if ($instance instanceof HiddenClass) { continue; } if (!$cacheCanCreate[$child]) { continue; } // skip this type if it is restricted if ($instance->stat('need_permission') && !$this->can(singleton($class)->stat('need_permission'))) { continue; } $title = $instance->i18n_singular_name(); $def[$class]['allowedChildren'][] = array("ssclass" => $child, "ssname" => $title); } $allowedChildren = array_keys(array_diff($classes, $allowedChildren)); if ($allowedChildren) { $def[$class]['disallowedChildren'] = $allowedChildren; } $defaultChild = $obj->defaultChild(); if ($defaultChild != 'Page' && $defaultChild != null) { $def[$class]['defaultChild'] = $defaultChild; } $defaultParent = $obj->defaultParent(); $parent = SiteTree::get_by_link($defaultParent); $id = $parent ? $parent->id : null; if ($defaultParent != 1 && $defaultParent != null) { $def[$class]['defaultParent'] = $defaultParent; } if (isset($def[$class]['disallowedChildren'])) { foreach ($def[$class]['disallowedChildren'] as $disallowedChild) { $def[$disallowedChild]['disallowedParents'][] = $class; } } // Are any classes allowed to be parents of root? $def['Root']['disallowedParents'][] = $class; } $json = Convert::raw2xml(Convert::raw2json($def)); $cache->save($json, $cacheKey); } return $json; }
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()); }
/** * @deprecated 4.0 Use OldPageRedirector::find_old_page instead * * @param string $URLSegment A subset of the url. i.e in /home/contact/ home and contact are URLSegment. * @param int $parent The ID of the parent of the page the URLSegment belongs to. * @param bool $ignoreNestedURLs * @return SiteTree */ public static function find_old_page($URLSegment, $parent = null, $ignoreNestedURLs = false) { Deprecation::notice('4.0', 'Use OldPageRedirector::find_old_page instead'); if ($parent) { $parent = SiteTree::get()->byId($parent); } $url = OldPageRedirector::find_old_page(array($URLSegment), $parent); return SiteTree::get_by_link($url); }
/** * Similar to {@link SubsitesVirtualPageTest->testSubsiteVirtualPageCanHaveSameUrlsegmentAsOtherSubsite()}. */ function testTwoPagesWithSameURLOnDifferentSubsites() { // Set up a couple of pages with the same URL on different subsites $s1 = $this->objFromFixture('Subsite', 'domaintest1'); $s2 = $this->objFromFixture('Subsite', 'domaintest2'); $p1 = new SiteTree(); $p1->Title = $p1->URLSegment = "test-page"; $p1->SubsiteID = $s1->ID; $p1->write(); $p2 = new SiteTree(); $p2->Title = $p1->URLSegment = "test-page"; $p2->SubsiteID = $s2->ID; $p2->write(); // Check that the URLs weren't modified in our set-up $this->assertEquals($p1->URLSegment, 'test-page'); $this->assertEquals($p2->URLSegment, 'test-page'); // Check that if we switch between the different subsites, we receive the correct pages Subsite::changeSubsite($s1); $this->assertEquals($p1->ID, SiteTree::get_by_link('test-page')->ID); Subsite::changeSubsite($s2); $this->assertEquals($p2->ID, SiteTree::get_by_link('test-page')->ID); }