public function onBeforeInit()
 {
     // Determine if this page is of a non-cacheable type
     $ignoredClasses = DynamicCache::config()->ignoredPages;
     $ignoredByClass = false;
     if ($ignoredClasses) {
         foreach ($ignoredClasses as $ignoredClass) {
             if (is_a($this->owner->data(), $ignoredClass, true)) {
                 $ignoredByClass = true;
                 break;
             }
         }
     }
     $isStage = ($stage = Versioned::current_stage()) && $stage !== 'Live';
     // Set header disabling caching if
     // - current page is an ignored page type
     // - current_stage is not live
     if ($ignoredByClass || $isStage) {
         $header = DynamicCache::config()->optOutHeaderString;
         header($header);
     }
     // Flush cache if requested
     if (isset($_GET['flush']) || isset($_GET['cache']) && $_GET['cache'] === 'flush' && Permission::check('ADMIN')) {
         DynamicCache::inst()->clear();
     }
 }
 function republish($original)
 {
     if (self::$disable_realtime) {
         return;
     }
     $urls = array();
     if ($this->owner->hasMethod('pagesAffectedByChanges')) {
         $urls = $this->owner->pagesAffectedByChanges($original);
     } else {
         $pages = Versioned::get_by_stage('SiteTree', 'Live', '', '', '', 10);
         if ($pages) {
             foreach ($pages as $page) {
                 $urls[] = $page->AbsoluteLink();
             }
         }
     }
     // Note: Similiar to RebuildStaticCacheTask->rebuildCache()
     foreach ($urls as $i => $url) {
         if (!is_string($url)) {
             user_error("Bad URL: " . var_export($url, true), E_USER_WARNING);
             continue;
         }
         // Remove leading slashes from all URLs (apart from the homepage)
         if (substr($url, -1) == '/' && $url != '/') {
             $url = substr($url, 0, -1);
         }
         $urls[$i] = $url;
     }
     $urls = array_unique($urls);
     $this->publishPages($urls);
 }
Example #3
0
 function Dates()
 {
     Requirements::themedCSS('archivewidget');
     $results = new DataObjectSet();
     $container = BlogTree::current();
     $ids = $container->BlogHolderIDs();
     $stage = Versioned::current_stage();
     $suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
     $monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
     $yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
     if ($this->DisplayMode == 'month') {
         $sqlResults = DB::query("\n\t\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
     } else {
         $sqlResults = DB::query("\n\t\t\t\tSELECT DISTINCT {$yearclause} AS \"Year\" \n\t\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\t\tORDER BY \"Year\" DESC");
     }
     if ($sqlResults) {
         foreach ($sqlResults as $sqlResult) {
             $isMonthDisplay = $this->DisplayMode == 'month';
             $monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
             $month = $isMonthDisplay ? $monthVal : 1;
             $year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
             $date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
             if ($isMonthDisplay) {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
             } else {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'];
             }
             $results->push(new ArrayData(array('Date' => $date, 'Link' => $link)));
         }
     }
     return $results;
 }
 public function testHasOnes()
 {
     $obj1 = $this->objFromFixture('DataDifferencerTest_Object', 'obj1');
     $image1 = $this->objFromFixture('DataDifferencerTest_MockImage', 'image1');
     $image2 = $this->objFromFixture('DataDifferencerTest_MockImage', 'image2');
     $relobj1 = $this->objFromFixture('DataDifferencerTest_HasOneRelationObject', 'relobj1');
     $relobj2 = $this->objFromFixture('DataDifferencerTest_HasOneRelationObject', 'relobj2');
     // in order to ensure the Filename path is correct, append the correct FRAMEWORK_DIR to the start
     // this is only really necessary to make the test pass when FRAMEWORK_DIR is not "framework"
     $image1->Filename = FRAMEWORK_DIR . substr($image1->Filename, 9);
     $image2->Filename = FRAMEWORK_DIR . substr($image2->Filename, 9);
     $origUpdateFilesystem = Config::inst()->get('File', 'update_filesystem');
     // we don't want the filesystem being updated on write, as we're only dealing with mock files
     Config::inst()->update('File', 'update_filesystem', false);
     $image1->write();
     $image2->write();
     Config::inst()->update('File', 'update_filesystem', $origUpdateFilesystem);
     // create a new version
     $obj1->ImageID = $image2->ID;
     $obj1->HasOneRelationID = $relobj2->ID;
     $obj1->write();
     $obj1v1 = Versioned::get_version('DataDifferencerTest_Object', $obj1->ID, $obj1->Version - 1);
     $obj1v2 = Versioned::get_version('DataDifferencerTest_Object', $obj1->ID, $obj1->Version);
     $differ = new DataDifferencer($obj1v1, $obj1v2);
     $obj1Diff = $differ->diffedData();
     $this->assertContains($image1->Filename, $obj1Diff->getField('Image'));
     $this->assertContains($image2->Filename, $obj1Diff->getField('Image'));
     $this->assertContains('<ins>obj2</ins><del>obj1</del>', str_replace(' ', '', $obj1Diff->getField('HasOneRelationID')));
 }
 /**
  * If there are multiple @link NewsHolderPage available, add the field for multiples.
  * This includes translation options
  */
 private function multipleNewsHolderPages()
 {
     $enabled = false;
     // If we have translations, disable translation filter to get all pages.
     if (class_exists('Translatable')) {
         $enabled = Translatable::disable_locale_filter();
     }
     $pages = Versioned::get_by_stage('NewsHolderPage', 'Live');
     // Only add the page-selection if there are multiple. Otherwise handled by onBeforeWrite();
     if ($pages->count() > 1) {
         $pagelist = array();
         if (class_exists('Translatable')) {
             foreach ($pages as $page) {
                 $pagelist['Root.Main'][$page->ID] = $page->Title . ' ' . $page->Locale;
             }
         } else {
             $pagelist = $pages->map('ID', 'Title')->toArray();
         }
         $this->field_list['Root.Main'][1] = ListboxField::create('NewsHolderPages', $this->owner->fieldLabel('NewsHolderPages'), $pagelist);
         $this->field_list['Root.Main'][1]->setMultiple(true);
     }
     if ($enabled) {
         Translatable::enable_locale_filter();
     }
 }
 /**
  *	Instantiate a search page, should one not exist.
  */
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     $mode = Versioned::get_reading_mode();
     Versioned::reading_stage('Stage');
     // Determine whether pages should be created.
     if (self::config()->create_default_pages) {
         // Determine whether an extensible search page already exists.
         if (!ExtensibleSearchPage::get()->first()) {
             // Instantiate an extensible search page.
             $page = ExtensibleSearchPage::create();
             $page->Title = 'Search Page';
             $page->write();
             DB::alteration_message('"Default" Extensible Search Page', 'created');
         }
     } else {
         if (ClassInfo::exists('Multisites')) {
             foreach (Site::get() as $site) {
                 // Determine whether an extensible search page already exists.
                 if (!ExtensibleSearchPage::get()->filter('SiteID', $site->ID)->first()) {
                     // Instantiate an extensible search page.
                     $page = ExtensibleSearchPage::create();
                     $page->ParentID = $site->ID;
                     $page->Title = 'Search Page';
                     $page->write();
                     DB::alteration_message("\"{$site->Title}\" Extensible Search Page", 'created');
                 }
             }
         }
     }
     Versioned::set_reading_mode($mode);
 }
	function handleRequest(SS_HTTPRequest $request, DataModel $model) {
		$this->setModel($model);
		Versioned::reading_stage('Live');
		$restfulserver = new RestfulServer();
		$response = $restfulserver->handleRequest($request, $model);
		return $response;
	}
 public function onAfterWrite()
 {
     parent::onAfterWrite();
     if (in_array('Searchable', class_implements($this->owner->class))) {
         if ($this->owner->IncludeInSearch()) {
             if ($this->owner->hasExtension('Versioned')) {
                 $filterID = array('ID' => $this->owner->ID);
                 $filter = $filterID + $this->owner->getSearchFilter();
                 $do = Versioned::get_by_stage($this->owner->class, 'Live')->filter($filter)->first();
             } else {
                 $filterID = "`{$this->owner->class}`.`ID`={$this->owner->ID}";
                 $do = DataObject::get($this->owner->class, $filterID, false)->filter($this->owner->getSearchFilter())->first();
             }
             if ($do) {
                 PopulateSearch::insert($do);
             } else {
                 $this->deleteDo($this->owner);
             }
         } else {
             $this->deleteDo($this->owner);
         }
     } else {
         if ($this->owner instanceof SiteTree) {
             if ($this->owner->ShowInSearch) {
                 PopulateSearch::insertPage($this->owner);
             } else {
                 $this->deleteDo($this->owner);
             }
         }
     }
 }
 /**
  * Return an ArrayList of pages with the Element Page Extension
  *
  * @return ArrayList
  */
 public function getOwnerPage()
 {
     $originalMode = Versioned::current_stage();
     Versioned::reading_stage('Stage');
     foreach (get_declared_classes() as $class) {
         if (is_subclass_of($class, 'SiteTree')) {
             $object = singleton($class);
             $classes = ClassInfo::subclassesFor('ElementPageExtension');
             $isElemental = false;
             foreach ($classes as $extension) {
                 if ($object->hasExtension($extension)) {
                     $isElemental = true;
                 }
             }
             if ($isElemental) {
                 $page = $class::get()->filter('ElementAreaID', $this->ID);
                 if ($page && $page->exists()) {
                     Versioned::reading_stage($originalMode);
                     return $page->first();
                 }
             }
         }
     }
     Versioned::reading_stage($originalMode);
     return false;
 }
 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;
 }
 /**
  * Create a new report
  *
  * @param array  $data
  * @param Form $form
  */
 public function createreport($data, $form)
 {
     // assume a user's okay if they can edit the reportholder
     // @TODO have a new create permission here?
     if ($this->data()->canEdit()) {
         $type = $data['ReportType'];
         $classes = ClassInfo::subclassesFor('AdvancedReport');
         if (!in_array($type, $classes)) {
             throw new Exception("Invalid report type");
         }
         $report = new ReportPage();
         $report->Title = $data['ReportName'];
         $report->MetaDescription = isset($data['ReportDescription']) ? $data['ReportDescription'] : '';
         $report->ReportType = $type;
         $report->ParentID = $this->data()->ID;
         $oldMode = Versioned::get_reading_mode();
         Versioned::reading_stage('Stage');
         $report->write();
         $report->doPublish();
         Versioned::reading_stage('Live');
         $this->redirect($report->Link());
     } else {
         $form->sessionMessage(_t('ReporHolder.NO_PERMISSION', 'You do not have permission to do that'), 'warning');
         $this->redirect($this->data()->Link());
     }
 }
 /**
  * Augment queries so that we don't fetch unpublished articles.
  **/
 public function augmentSQL(SQLQuery &$query)
 {
     $stage = Versioned::current_stage();
     if ($stage == 'Live' || !Permission::check("VIEW_DRAFT_CONTENT")) {
         $query->addWhere("PublishDate < '" . Convert::raw2sql(SS_Datetime::now()) . "'");
     }
 }
 /**
  * Form used for defining the conversion form
  * @return {Form} Form to be used for configuring the conversion
  */
 public function ConvertObjectForm()
 {
     //Reset the reading stage
     Versioned::reset();
     $fields = new FieldList(CompositeField::create($convertModeField = new OptionsetField('ConvertMode', '', array('ReplacePage' => _t('KapostAdmin.REPLACES_AN_EXISTING_PAGE', '_This replaces an existing page'), 'NewPage' => _t('KapostAdmin.IS_NEW_PAGE', '_This is a new page')), 'NewPage'))->addExtraClass('kapostConvertLeftSide'), CompositeField::create($replacePageField = TreeDropdownField::create('ReplacePageID', _t('KapostAdmin.REPLACE_PAGE', '_Replace this page'), 'SiteTree')->addExtraClass('replace-page-id'), TreeDropdownField::create('ParentPageID', _t('KapostAdmin.USE_AS_PARENT', '_Use this page as the parent for the new page, leave empty for a top level page'), 'SiteTree')->addExtraClass('parent-page-id'))->addExtraClass('kapostConvertRightSide'));
     $actions = new FieldList(FormAction::create('doConvertObject', _t('KapostAdmin.CONTINUE_CONVERT', '_Continue'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'kapost-convert'));
     $validator = new RequiredFields('ConvertMode');
     $form = new Form($this, 'ConvertObjectForm', $fields, $actions, $validator);
     $form->addExtraClass('KapostAdmin center')->setAttribute('data-layout-type', 'border')->setTemplate('KapostAdmin_ConvertForm');
     //Handle pages to see if the page exists
     $convertToClass = $this->getDestinationClass();
     if ($convertToClass !== false && ($convertToClass == 'SiteTree' || is_subclass_of($convertToClass, 'SiteTree'))) {
         $obj = SiteTree::get()->filter('KapostRefID', Convert::raw2sql($this->record->KapostRefID))->first();
         if (!empty($obj) && $obj !== false && $obj->ID > 0) {
             $convertModeField->setValue('ReplacePage');
             $replacePageField->setValue($obj->ID);
             $recordTitle = $this->record->Title;
             if (!empty($recordTitle) && $recordTitle != $obj->Title) {
                 $urlFieldLabel = _t('KapostAdmin.TITLE_CHANGE_DETECT', '_The title differs from the page being replaced, it was "{wastitle}" and will be changed to "{newtitle}". Do you want to update the URL Segment?', array('wastitle' => $obj->Title, 'newtitle' => $recordTitle));
                 $fields->push(CheckboxField::create('UpdateURLSegment', $urlFieldLabel)->addExtraClass('urlsegmentcheck')->setAttribute('data-replace-id', $obj->ID)->setForm($form)->setDescription(_t('KapostAdmin.NEW_URL_SEGMENT', '_The new URL Segment will be or will be close to "{newsegment}"', array('newsegment' => $obj->generateURLSegment($recordTitle)))));
             }
         }
     }
     Requirements::css(KAPOST_DIR . '/css/KapostAdmin.css');
     Requirements::add_i18n_javascript(KAPOST_DIR . '/javascript/lang/');
     Requirements::javascript(KAPOST_DIR . '/javascript/KapostAdmin_convertPopup.js');
     //Allow extensions to adjust the form
     $this->extend('updateConvertObjectForm', $form, $this->record);
     return $form;
 }
    public function BlogTags()
    {
        if ($newsIndex = $this->NewsIndex()) {
            $alRet = new ArrayList();
            $arrTags = array();
            $strTable = Versioned::current_stage() == 'Stage' ? 'NewsPost' : 'NewsPost_Live';
            $results = DB::query('SELECT `Tags` AS Tags, COUNT(1) AS Items
				FROM ' . $strTable . '
				WHERE `Tags` IS NOT NULL
				GROUP BY Tags');
            while ($row = $results->nextRecord()) {
                $arrCurrentItems = explode(',', $row['Tags']);
                foreach ($arrCurrentItems as $strItem) {
                    $strItem = trim($strItem);
                    $strLower = strtolower($strItem);
                    if (!array_key_exists($strLower, $arrTags)) {
                        $arrTags[$strLower] = new ArrayData(array('Tag' => $strItem, 'Count' => $row['Items'], 'Link' => $newsIndex->Link('tag/' . urlencode($strItem))));
                    } else {
                        $arrayData = $arrTags[$strLower];
                        $arrayData->Count += $row['Items'];
                    }
                }
            }
            foreach ($arrTags as $arrTag) {
                $alRet->push($arrTag);
            }
            return $alRet->sort('Count')->limit(SiteConfig::current_site_config()->NumberOfTags ?: PHP_INT_MAX);
        }
    }
 /**
  * Perform migration
  *
  * @param string $base Absolute base path (parent of assets folder). Will default to BASE_PATH
  * @return int Number of files successfully migrated
  */
 public function run($base = null)
 {
     if (empty($base)) {
         $base = BASE_PATH;
     }
     // Check if the File dataobject has a "Filename" field.
     // If not, cannot migrate
     if (!DB::get_schema()->hasField('File', 'Filename')) {
         return 0;
     }
     // Set max time and memory limit
     increase_time_limit_to();
     increase_memory_limit_to();
     // Loop over all files
     $count = 0;
     $originalState = \Versioned::get_reading_mode();
     \Versioned::reading_stage('Stage');
     $filenameMap = $this->getFilenameArray();
     foreach ($this->getFileQuery() as $file) {
         // Get the name of the file to import
         $filename = $filenameMap[$file->ID];
         $success = $this->migrateFile($base, $file, $filename);
         if ($success) {
             $count++;
         }
     }
     \Versioned::set_reading_mode($originalState);
     return $count;
 }
Example #16
0
 /**
  * When an error page is published, create a static HTML page with its
  * content, so the page can be shown even when SilverStripe is not
  * functioning correctly before publishing this page normally.
  * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
  * @param string $toStage Place to copy to. Must be a stage name.
  * @param boolean $createNewVersion Set this to true to create a new version number.  By default, the existing version number will be copied over.
  */
 function publish($fromStage, $toStage, $createNewVersion = false)
 {
     // Temporarily log out when producing this page
     $loggedInMember = Member::currentUser();
     Session::clear("loggedInAs");
     $alc_enc = isset($_COOKIE['alc_enc']) ? $_COOKIE['alc_enc'] : null;
     Cookie::set('alc_enc', null);
     $oldStage = Versioned::current_stage();
     // Run the page
     Requirements::clear();
     $controller = new ErrorPage_Controller($this);
     $errorContent = $controller->run(array())->getBody();
     if (!file_exists("../assets")) {
         mkdir("../assets", 02775);
     }
     if ($fh = fopen("../assets/error-{$this->ErrorCode}.html", "w")) {
         fwrite($fh, $errorContent);
         fclose($fh);
     }
     // Restore the version we're currently connected to.
     Versioned::reading_stage($oldStage);
     // Log back in
     if ($loggedInMember) {
         Session::set("loggedInAs", $loggedInMember->ID);
     }
     if (isset($alc_enc)) {
         Cookie::set('alc_enc', $alc_enc);
     }
     return $this->extension_instances['Versioned']->publish($fromStage, $toStage, $createNewVersion);
 }
 protected function deleteVersionedObjects($tags, $obj, $stage, $pageID)
 {
     $tagsArray = array();
     $tagsTempArray = array();
     if ($tags) {
         foreach ($tags as $tag) {
             array_push($tagsArray, $tag->ID);
         }
         $versionedTags = Versioned::get_by_stage($obj, $stage)->filter(array('FaqPageID' => $pageID));
         foreach ($versionedTags as $versionedTag) {
             array_push($tagsTempArray, $versionedTag->ID);
         }
         $tagsArrayDiff = array_diff($tagsTempArray, $tagsArray);
         if ($tagsArrayDiff) {
             foreach ($tagsArrayDiff as $key => $val) {
                 $thisTag = Versioned::get_by_stage($obj, $stage)->byID($val);
                 if ($thisTag) {
                     $thisTag->deleteFromStage($stage);
                 }
             }
             return true;
         }
     }
     return false;
 }
Example #18
0
	/**
	 * Test Hierarchy::AllHistoricalChildren().
	 */
	function testAllHistoricalChildren() {
		// Delete some objs
		$this->objFromFixture('HierarchyTest_Object', 'obj2b')->delete();
		$this->objFromFixture('HierarchyTest_Object', 'obj3a')->delete();
		$this->objFromFixture('HierarchyTest_Object', 'obj3')->delete();
	
		// Check that obj1-3 appear at the top level of the AllHistoricalChildren tree
		$this->assertEquals(array("Obj 1", "Obj 2", "Obj 3"), 
			singleton('HierarchyTest_Object')->AllHistoricalChildren()->column('Title'));
	
		// Check numHistoricalChildren
		$this->assertEquals(3, singleton('HierarchyTest_Object')->numHistoricalChildren());

		// Check that both obj 2 children are returned
		$obj2 = $this->objFromFixture('HierarchyTest_Object', 'obj2');
		$this->assertEquals(array("Obj 2a", "Obj 2b"), 
			$obj2->AllHistoricalChildren()->column('Title'));

		// Check numHistoricalChildren
		$this->assertEquals(2, $obj2->numHistoricalChildren());

			
		// Obj 3 has been deleted; let's bring it back from the grave
		$obj3 = Versioned::get_including_deleted("HierarchyTest_Object", "\"Title\" = 'Obj 3'")->First();
	
		// Check that both obj 3 children are returned
		$this->assertEquals(array("Obj 3a", "Obj 3b"), 
			$obj3->AllHistoricalChildren()->column('Title'));
			
		// Check numHistoricalChildren
		$this->assertEquals(2, $obj3->numHistoricalChildren());
		
	}
 /**
  * @param FieldSet $actions
  * @parma SiteTree $page
  */
 public static function update_cms_actions(&$actions, $page)
 {
     $openRequest = $page->OpenWorkflowRequest();
     // if user doesn't have publish rights
     if (!$page->canPublish() || $openRequest) {
         // authors shouldn't be able to revert, as this republishes the page.
         // they should rather change the page and re-request publication
         $actions->removeByName('action_revert');
     }
     // Remove the one click publish if they are not an admin/workflow admin.
     if (self::$force_publishers_to_use_workflow && !Permission::checkMember(Member::currentUser(), 'IS_WORKFLOW_ADMIN')) {
         $actions->removeByName('action_publish');
     }
     // Remove the save & publish button if you don't have edit rights
     if (!$page->canEdit()) {
         $actions->removeByName('action_publish');
     }
     $liveVersion = Versioned::get_one_by_stage('SiteTree', 'Live', "\"SiteTree_Live\".\"ID\" = {$page->ID}");
     if ($liveVersion && $liveVersion->ExpiryDate != null && $liveVersion->ExpiryDate != '0000-00-00 00:00:00') {
         if ($page->canApprove()) {
             $actions->push(new FormAction('cms_cancelexpiry', _t('WorkflowPublicationRequest.BUTTONCANCELEXPIRY', 'Cancel expiry')));
         }
     }
     // Optional method
     $isPublishable = $page->hasMethod('isPublishable') ? $page->isPublishable() : true;
     if (!$openRequest && $page->canEdit() && $isPublishable && $page->stagesDiffer('Stage', 'Live') && ($page->Version > 1 || $page->Title != "New Page") && !$page->IsDeletedFromStage && (!$page->canPublish() || self::$publisher_can_create_wf_requests)) {
         $actions->push($requestPublicationAction = new FormAction('cms_requestpublication', _t('SiteTreeCMSWorkflow.BUTTONREQUESTPUBLICATION', 'Request Publication')));
         // don't allow creation of a second request by another author
         if (!self::can_create(null, $page)) {
             $actions->makeFieldReadonly($requestPublicationAction->Name());
         }
     }
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     // only operate on staging content
     if (Versioned::current_stage() != 'Live') {
         if (strlen($this->owner->PublishOnDate)) {
             $changed = $this->owner->getChangedFields();
             $changed = isset($changed['PublishOnDate']);
             if ($changed && $this->owner->PublishJobID) {
                 if ($this->owner->PublishJob()->exists()) {
                     $this->owner->PublishJob()->delete();
                 }
                 $this->owner->PublishJobID = 0;
             }
             if (!$this->owner->PublishJobID && strtotime($this->owner->PublishOnDate) > time()) {
                 $job = new WorkflowPublishTargetJob($this->owner, 'publish');
                 $this->owner->PublishJobID = singleton('QueuedJobService')->queueJob($job, $this->owner->PublishOnDate);
             }
         }
         if (strlen($this->owner->UnPublishOnDate)) {
             $changed = $this->owner->getChangedFields();
             $changed = isset($changed['UnPublishOnDate']);
             if ($changed && $this->owner->UnPublishJobID) {
                 if ($this->owner->UnPublishJob()->exists()) {
                     $this->owner->UnPublishJob()->delete();
                 }
                 $this->owner->UnPublishJobID = 0;
             }
             if (!$this->owner->UnPublishJobID && strtotime($this->owner->UnPublishOnDate) > time()) {
                 $job = new WorkflowPublishTargetJob($this->owner, 'unpublish');
                 $this->owner->UnPublishJobID = singleton('QueuedJobService')->queueJob($job, $this->owner->UnPublishOnDate);
             }
         }
     }
 }
 function Dates()
 {
     Requirements::themedCSS('archivewidget');
     $results = new DataObjectSet();
     $container = BlogTree::current();
     $ids = $container->BlogHolderIDs();
     $stage = Versioned::current_stage();
     $suffix = !$stage || $stage == 'Stage' ? "" : "_{$stage}";
     $monthclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%m') : 'MONTH("Date")';
     $yearclause = method_exists(DB::getConn(), 'formattedDatetimeClause') ? DB::getConn()->formattedDatetimeClause('"Date"', '%Y') : 'YEAR("Date")';
     $sqlResults = DB::query("\n\t\t\tSELECT DISTINCT CAST({$monthclause} AS " . DB::getConn()->dbDataType('unsigned integer') . ") AS \"Month\", {$yearclause} AS \"Year\"\n\t\t\tFROM \"SiteTree{$suffix}\" INNER JOIN \"BlogEntry{$suffix}\" ON \"SiteTree{$suffix}\".\"ID\" = \"BlogEntry{$suffix}\".\"ID\"\n\t\t\tWHERE \"ParentID\" IN (" . implode(', ', $ids) . ")\n\t\t\tORDER BY \"Year\" DESC, \"Month\" DESC;");
     if ($this->ShowLastYears == 0) {
         $cutOffYear = 0;
     } else {
         $cutOffYear = (int) date("Y") - $this->ShowLastYears;
     }
     $years = array();
     if (Director::get_current_page()->ClassName == 'BlogHolder') {
         $urlParams = Director::urlParams();
         $yearParam = $urlParams['ID'];
         $monthParam = $urlParams['OtherID'];
     } else {
         $date = new DateTime(Director::get_current_page()->Date);
         $yearParam = $date->format("Y");
         $monthParam = $date->format("m");
     }
     if ($sqlResults) {
         foreach ($sqlResults as $sqlResult) {
             $isMonthDisplay = true;
             $year = $sqlResult['Year'] ? (int) $sqlResult['Year'] : date('Y');
             $isMonthDisplay = $year > $cutOffYear;
             // $dateFormat = 'Month'; else $dateFormat = 'Year';
             $monthVal = isset($sqlResult['Month']) ? (int) $sqlResult['Month'] : 1;
             $month = $isMonthDisplay ? $monthVal : 1;
             $date = DBField::create('Date', array('Day' => 1, 'Month' => $month, 'Year' => $year));
             if ($isMonthDisplay) {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'] . '/' . sprintf("%'02d", $monthVal);
             } else {
                 $link = $container->Link('date') . '/' . $sqlResult['Year'];
             }
             if ($isMonthDisplay || !$isMonthDisplay && !in_array($year, $years)) {
                 $years[] = $year;
                 $current = false;
                 $children = new DataObjectSet();
                 $LinkingMode = "link";
                 if ($isMonthDisplay && $yearParam == $year && $monthParam == $month || !$isMonthDisplay && $yearParam == $year) {
                     $LinkingMode = "current";
                     $current = true;
                     if ($this->ShowChildren && $isMonthDisplay) {
                         $filter = $yearclause . ' = ' . $year . ' AND ' . $monthclause . ' = ' . $month;
                         $children = DataObject::get('BlogEntry', $filter, "Date DESC");
                     }
                 }
                 $results->push(new ArrayData(array('Date' => $date, 'Year' => $year, 'Link' => $link, 'NoMonth' => !$isMonthDisplay, 'LinkingMode' => $LinkingMode, 'Children' => $children)));
                 unset($children);
             }
         }
     }
     return $results;
 }
 /**
  * This returns the workflow requests outstanding for this user.
  * It does one query against draft for change requests, and another
  * request against live for the deletion requests (which are not in draft
  * any more), and merges the result sets together.
  */
 function sourceRecords($params)
 {
     increase_time_limit_to(120);
     $currentStage = Versioned::current_stage();
     $changes = WorkflowTwoStepRequest::get_by_author('WorkflowPublicationRequest', Member::currentUser(), array('AwaitingApproval'));
     if ($changes) {
         foreach ($changes as $change) {
             $change->RequestType = "Publish";
         }
     }
     Versioned::reading_stage(Versioned::get_live_stage());
     $deletions = WorkflowTwoStepRequest::get_by_author('WorkflowDeletionRequest', Member::currentUser(), array('AwaitingApproval'));
     if ($deletions) {
         foreach ($deletions as $deletion) {
             $deletion->RequestType = "Deletion";
         }
     }
     if ($changes && $deletions) {
         $changes->merge($deletions);
     } else {
         if ($deletions) {
             $changes = $deletions;
         }
     }
     return $changes;
 }
 public function updateDynamicListCMSFields($fields)
 {
     // Make sure the draft records are being looked at.
     $stage = Versioned::current_stage();
     Versioned::reading_stage('Stage');
     $used = EditableFormField::get()->filter(array('ClassName:PartialMatch' => 'DynamicList'));
     // Determine whether this dynamic list is being used anywhere.
     $found = array();
     foreach ($used as $field) {
         // This information is stored using a serialised list, therefore we need to iterate through.
         if ($field->getSetting('ListTitle') === $this->owner->Title) {
             // Make sure there are no duplicates recorded.
             if (!isset($found[$field->ParentID]) && ($form = UserDefinedForm::get()->byID($field->ParentID))) {
                 $found[$field->ParentID] = "<a href='{$form->CMSEditLink()}'>{$form->Title}</a>";
             }
         }
     }
     // Display whether there were any dynamic lists found on user defined forms.
     if (count($found)) {
         $fields->removeByName('UsedOnHeader');
         $fields->addFieldToTab('Root.Main', HeaderField::create('UsedOnHeader', 'Used On', 5));
     }
     $display = count($found) ? implode('<br>', $found) : 'This dynamic list is <strong>not</strong> used.';
     $fields->removeByName('UsedOn');
     $fields->addFieldToTab('Root.Main', LiteralField::create('UsedOn', '<div>' . $display . '</div>'));
     Versioned::reading_stage($stage);
 }
 /**
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  */
 public function run($request)
 {
     parent::run($request);
     // Disable filters
     if (class_exists('ContentNotifierExtension')) {
         ContentNotifierExtension::disable_filtering();
     }
     if (class_exists('Post')) {
         Config::inst()->update('Post', 'allow_reading_spam', true);
     }
     // Init tasks
     $taskGroup = $request->getVar('tasks') ?: 'tasks';
     $this->message("Beginning import tasks {$taskGroup}");
     $this->connectToRemoteSite();
     Versioned::reading_stage('Stage');
     // Check if we only want to do a single step
     if ($pass = $request->requestVar('pass')) {
         $this->message("Resuming at {$pass} pass");
         switch ($pass) {
             case 'identify':
                 $this->identifyPass($taskGroup);
                 return;
             case 'import':
                 $this->importPass($taskGroup);
                 return;
             case 'link':
                 $this->linkPass($taskGroup);
                 return;
         }
     }
     $this->identifyPass($taskGroup);
     $this->importPass($taskGroup);
     $this->linkPass($taskGroup);
 }
 /**
  * SSCompactNavigator first checks if you are allowed to see the navigation bar, and if so, then checks
  * if third party templates have been specified. If so, it loads them, and provides them with the required
  * variables. If not, it loads the defaults instead.
  */
 public function SSCompactNavigator()
 {
     if (Director::isDev() || Permission::check('CMS_ACCESS_CMSMain')) {
         $RenderTemplate = isset(CompactNavigator::$Template) ? CompactNavigator::$Template : $this->class;
         if (isset(CompactNavigator::$CssTheme)) {
             Requirements::css(CompactNavigator::$CssTheme);
         } else {
             Requirements::css('compactnavigator/css/CompactNavigator.css');
         }
         if (isset(CompactNavigator::$JsTheme)) {
             Requirements::javascript(CompactNavigator::$JsTheme);
         } else {
             Requirements::javascript('compactnavigator/scripts/CompactNavigator.js');
         }
         if (class_exists("CMSMain")) {
             $this->owner->cmsLink = Controller::join_links(singleton("CMSMain")->Link("edit"), "show");
         }
         $this->owner->adminLink = self::$adminLink;
         if ($date = Versioned::current_archived_date()) {
             $this->owner->DisplayMode = 'Archived';
             $this->owner->ArDate = Object::create('Datetime', $date, null);
         } else {
             $this->owner->DisplayMode = Versioned::current_stage();
         }
         return $this->owner->renderWith(array($RenderTemplate, 'CompactNavigatior'));
     }
 }
 public function setUp()
 {
     parent::setUp();
     $this->logInWithPermission('ADMIN');
     Versioned::reading_stage('Stage');
     // Set backend root to /ImageTest
     AssetStoreTest_SpyStore::activate('FileTest');
     // Create a test folders for each of the fixture references
     $folderIDs = $this->allFixtureIDs('Folder');
     foreach ($folderIDs as $folderID) {
         $folder = DataObject::get_by_id('Folder', $folderID);
         $filePath = ASSETS_PATH . '/FileTest/' . $folder->getFilename();
         SS_Filesystem::makeFolder($filePath);
     }
     // Create a test files for each of the fixture references
     $fileIDs = $this->allFixtureIDs('File');
     foreach ($fileIDs as $fileID) {
         $file = DataObject::get_by_id('File', $fileID);
         $root = ASSETS_PATH . '/FileTest/';
         if ($folder = $file->Parent()) {
             $root .= $folder->getFilename();
         }
         $path = $root . substr($file->getHash(), 0, 10) . '/' . basename($file->getFilename());
         SS_Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
     }
     // Conditional fixture creation in case the 'cms' module is installed
     if (class_exists('ErrorPage')) {
         $page = new ErrorPage(array('Title' => 'Page not Found', 'ErrorCode' => 404));
         $page->write();
         $page->publish('Stage', 'Live');
     }
 }
 function handleRequest($request)
 {
     Versioned::reading_stage('Live');
     $restfulserver = new RestfulServer();
     $response = $restfulserver->handleRequest($request);
     return $response;
 }
 /**
  * Helper method to get content languages from the live DB table.
  * Most of the code is borrowed from the Translatable::get_live_content_languages method.
  * This method operates on "SiteTree" and makes a distinction between Live and Stage.
  * @return array
  */
 public static function get_content_languages()
 {
     $table = Versioned::current_stage() == 'Live' ? 'SiteTree_Live' : 'SiteTree';
     if (class_exists('SQLSelect')) {
         $query = new SQLSelect("Distinct \"Locale\"", "\"{$table}\"");
     } else {
         // SS 3.1 compat
         $query = new SQLQuery("Distinct \"Locale\"", array("\"{$table}\""));
     }
     $query = $query->setGroupBy('"Locale"');
     $dbLangs = $query->execute()->column();
     $langlist = array_merge((array) Translatable::default_locale(), (array) $dbLangs);
     $returnMap = array();
     $allCodes = array_merge(Config::inst()->get('i18n', 'all_locales'), Config::inst()->get('i18n', 'common_locales'));
     foreach ($langlist as $langCode) {
         if ($langCode && isset($allCodes[$langCode])) {
             if (is_array($allCodes[$langCode])) {
                 $returnMap[$langCode] = $allCodes[$langCode]['name'];
             } else {
                 $returnMap[$langCode] = $allCodes[$langCode];
             }
         }
     }
     return $returnMap;
 }
 public function setUp()
 {
     parent::setUp();
     $this->logInWithPermission('ADMIN');
     Versioned::reading_stage('Stage');
     // Set backend root to /AssetFieldTest
     AssetStoreTest_SpyStore::activate('AssetFieldTest');
     $create = function ($path) {
         Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
     };
     // Write all DBFile references
     foreach (AssetFieldTest_Object::get() as $object) {
         $path = AssetStoreTest_SpyStore::getLocalPath($object->File);
         $create($path);
     }
     // Create a test files for each of the fixture references
     $files = File::get()->exclude('ClassName', 'Folder');
     foreach ($files as $file) {
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         $create($path);
     }
 }
 /**
  * Provides a front-end utility menu with administrative functions and developer tools
  * Relies on SilverStripeNavigator
  * 
  * @return string
  */
 public function BetterNavigator()
 {
     $isDev = Director::isDev();
     if ($isDev || Permission::check('CMS_ACCESS_CMSMain') || Permission::check('VIEW_DRAFT_CONTENT')) {
         if ($this->owner && $this->owner->dataRecord) {
             //Get SilverStripeNavigator links & stage info (CMS/Stage/Live/Archive)
             $nav = array();
             $navigator = new SilverStripeNavigator($this->owner->dataRecord);
             $items = $navigator->getItems();
             foreach ($items as $item) {
                 $nav[$item->getName()] = array('Link' => $item->getLink(), 'Active' => $item->isActive());
             }
             //Is the logged in member nominated as a developer?
             $member = Member::currentUser();
             $devs = Config::inst()->get('BetterNavigator', 'developers');
             $isDeveloper = $member && is_array($devs) ? in_array($member->Email, $devs) : false;
             //Add other data for template
             $nav = array_merge($nav, array('Member' => $member, 'Stage' => Versioned::current_stage(), 'LoginLink' => Config::inst()->get('Security', 'login_url'), 'Mode' => Director::get_environment_type(), 'IsDeveloper' => $isDeveloper));
             //Merge with page data, send to template and render
             $nav = new ArrayData($nav);
             $page = $this->owner->customise($nav);
             return $page->renderWith('BetterNavigator');
         }
     }
     return false;
 }