Merge pull request #1074 from wilr/modularizesiteconfig

API: Extract siteconfig out to an external module.
This commit is contained in:
Simon Welsh 2014-08-09 15:44:55 +10:00
commit ae8911d7ae
8 changed files with 10 additions and 554 deletions

View File

@ -22,3 +22,5 @@ CMSMenu::remove_menu_item('CMSPageHistoryController');
CMSMenu::remove_menu_item('CMSPageReportsController'); CMSMenu::remove_menu_item('CMSPageReportsController');
CMSMenu::remove_menu_item('CMSPageAddController'); CMSMenu::remove_menu_item('CMSPageAddController');
CMSMenu::remove_menu_item('CMSFileAddController'); CMSMenu::remove_menu_item('CMSFileAddController');
CMSMenu::remove_menu_item("SiteConfigLeftAndMain");

View File

@ -1,110 +1,10 @@
<?php <?php
class CMSSettingsController extends LeftAndMain {
private static $url_segment = 'settings';
private static $url_rule = '/$Action/$ID/$OtherID';
private static $menu_priority = -1;
private static $menu_title = 'Settings';
private static $tree_class = 'SiteConfig';
private static $required_permission_codes = array('EDIT_SITECONFIG');
public function init() {
parent::init();
Requirements::javascript(CMS_DIR . '/javascript/CMSMain.EditForm.js');
}
public function getResponseNegotiator() {
$neg = parent::getResponseNegotiator();
$controller = $this;
$neg->setCallback('CurrentForm', function() use(&$controller) {
return $controller->renderWith($controller->getTemplatesWithSuffix('_Content'));
});
return $neg;
}
/** /**
* @param null $id Not used. * @deprecated 3.3.0
* @param null $fields Not used.
* @return Form
*/
public function getEditForm($id = null, $fields = null) {
$siteConfig = SiteConfig::current_site_config();
$fields = $siteConfig->getCMSFields();
// Tell the CMS what URL the preview should show
$fields->push(new HiddenField('PreviewURL', 'Preview URL', RootURLController::get_homepage_link()));
// Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load
$fields->push($navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()));
$navField->setAllowHTML(true);
$actions = $siteConfig->getCMSActions();
$form = CMSForm::create(
$this, 'EditForm', $fields, $actions
)->setHTMLID('Form_EditForm');
$form->setResponseNegotiator($this->getResponseNegotiator());
$form->addExtraClass('cms-content center cms-edit-form');
// don't add data-pjax-fragment=CurrentForm, its added in the content template instead
if($form->Fields()->hasTabset()) $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
$form->setHTMLID('Form_EditForm');
$form->loadDataFrom($siteConfig);
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
// Use <button> to allow full jQuery UI styling
$actions = $actions->dataFields();
if($actions) foreach($actions as $action) $action->setUseButtonTag(true);
$this->extend('updateEditForm', $form);
return $form;
}
/**
* Used for preview controls, mainly links which switch between different states of the page.
* *
* @return ArrayData * @package cms
*/ */
public function getSilverStripeNavigator() { class CMSSettingsController extends SiteConfigLeftAndMain {
return $this->renderWith('CMSSettingsController_SilverStripeNavigator');
}
/**
* Save the current sites {@link SiteConfig} into the database
*
* @param array $data
* @param Form $form
* @return String
*/
public function save_siteconfig($data, $form) {
$siteConfig = SiteConfig::current_site_config();
$form->saveInto($siteConfig);
try {
$siteConfig->write();
} catch(ValidationException $ex) {
$form->sessionMessage($ex->getResult()->message(), 'bad');
return $this->getResponseNegotiator()->respond($this->request);
}
$this->response->addHeader('X-Status', rawurlencode(_t('LeftAndMain.SAVEDUP', 'Saved.')));
return $this->getResponseNegotiator()->respond($this->request);
}
public function LinkPreview() {
$record = $this->getRecord($this->currentPageID());
$baseLink = ($record && $record instanceof Page) ? $record->Link('?stage=Stage') : Director::absoluteBaseURL();
return $baseLink;
}
public function Breadcrumbs($unlinked = false) {
$defaultTitle = self::menu_title_for_class(get_class($this));
return new ArrayList(array(
new ArrayData(array(
'Title' => _t("{$this->class}.MENUTITLE", $defaultTitle),
'Link' => ($unlinked) ? false : $this->Link()
))
));
}
} }

View File

@ -1,312 +0,0 @@
<?php
/**
* Sitewide configuration.
*
* @property string Title Title of the website.
* @property string Tagline Tagline of the website.
* @property string Theme Current theme.
* @property string CanViewType Type of restriction used for view permissions.
* @property string CanEditType Type of restriction used for edit permissions.
* @property string CanCreateTopLevelType Type of restriction used for creation of root-level pages.
*
* @method ManyManyList ViewerGroups() List of groups that can view SiteConfig.
* @method ManyManyList EditorGroups() List of groups that can edit SiteConfig.
* @method ManyManyList CreateTopLevelGroups() List of groups that can create root-level pages.
*
* @author Tom Rix
* @package cms
*/
class SiteConfig extends DataObject implements PermissionProvider {
private static $db = array(
"Title" => "Varchar(255)",
"Tagline" => "Varchar(255)",
"Theme" => "Varchar(255)",
"CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers', 'Anyone')",
"CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')",
"CanCreateTopLevelType" => "Enum('LoggedInUsers, OnlyTheseUsers', 'LoggedInUsers')",
);
private static $many_many = array(
"ViewerGroups" => "Group",
"EditorGroups" => "Group",
"CreateTopLevelGroups" => "Group"
);
/**
* @config
* @var array
*/
private static $disabled_themes = array();
/**
* @deprecated 3.2 Use the "SiteConfig.disabled_themes" config setting instead
*/
static public function disable_theme($theme) {
Deprecation::notice('3.2', 'Use the "SiteConfig.disabled_themes" config setting instead');
Config::inst()->update('SiteConfig', 'disabled_themes', array($theme));
}
public function populateDefaults()
{
$this->Title = _t('SiteConfig.SITENAMEDEFAULT', "Your Site Name");
$this->Tagline = _t('SiteConfig.TAGLINEDEFAULT', "your tagline here");
// Allow these defaults to be overridden
parent::populateDefaults();
}
/**
* Get the fields that are sent to the CMS. In
* your extensions: updateCMSFields($fields)
*
* @return FieldList
*/
public function getCMSFields() {
$groupsMap = array();
foreach(Group::get() as $group) {
// Listboxfield values are escaped, use ASCII char instead of &raquo;
$groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
}
asort($groupsMap);
$fields = new FieldList(
new TabSet("Root",
$tabMain = new Tab('Main',
$titleField = new TextField("Title", _t('SiteConfig.SITETITLE', "Site title")),
$taglineField = new TextField("Tagline", _t('SiteConfig.SITETAGLINE', "Site Tagline/Slogan")),
$themeDropdownField = new DropdownField("Theme", _t('SiteConfig.THEME', 'Theme'), $this->getAvailableThemes())
),
$tabAccess = new Tab('Access',
$viewersOptionsField = new OptionsetField("CanViewType", _t('SiteConfig.VIEWHEADER', "Who can view pages on this site?")),
$viewerGroupsField = ListboxField::create("ViewerGroups", _t('SiteTree.VIEWERGROUPS', "Viewer Groups"))
->setMultiple(true)
->setSource($groupsMap)
->setAttribute(
'data-placeholder',
_t('SiteTree.GroupPlaceholder', 'Click to select group')
),
$editorsOptionsField = new OptionsetField("CanEditType", _t('SiteConfig.EDITHEADER', "Who can edit pages on this site?")),
$editorGroupsField = ListboxField::create("EditorGroups", _t('SiteTree.EDITORGROUPS', "Editor Groups"))
->setMultiple(true)
->setSource($groupsMap)
->setAttribute(
'data-placeholder',
_t('SiteTree.GroupPlaceholder', 'Click to select group')
),
$topLevelCreatorsOptionsField = new OptionsetField("CanCreateTopLevelType", _t('SiteConfig.TOPLEVELCREATE', "Who can create pages in the root of the site?")),
$topLevelCreatorsGroupsField = ListboxField::create("CreateTopLevelGroups", _t('SiteTree.TOPLEVELCREATORGROUPS', "Top level creators"))
->setMultiple(true)
->setSource($groupsMap)
->setAttribute(
'data-placeholder',
_t('SiteTree.GroupPlaceholder', 'Click to select group')
)
)
),
new HiddenField('ID')
);
$themeDropdownField->setEmptyString(_t('SiteConfig.DEFAULTTHEME', '(Use default theme)'));
$viewersOptionsSource = array();
$viewersOptionsSource["Anyone"] = _t('SiteTree.ACCESSANYONE', "Anyone");
$viewersOptionsSource["LoggedInUsers"] = _t('SiteTree.ACCESSLOGGEDIN', "Logged-in users");
$viewersOptionsSource["OnlyTheseUsers"] = _t('SiteTree.ACCESSONLYTHESE', "Only these people (choose from list)");
$viewersOptionsField->setSource($viewersOptionsSource);
$editorsOptionsSource = array();
$editorsOptionsSource["LoggedInUsers"] = _t('SiteTree.EDITANYONE', "Anyone who can log-in to the CMS");
$editorsOptionsSource["OnlyTheseUsers"] = _t('SiteTree.EDITONLYTHESE', "Only these people (choose from list)");
$editorsOptionsField->setSource($editorsOptionsSource);
$topLevelCreatorsOptionsField->setSource($editorsOptionsSource);
if (!Permission::check('EDIT_SITECONFIG')) {
$fields->makeFieldReadonly($viewersOptionsField);
$fields->makeFieldReadonly($viewerGroupsField);
$fields->makeFieldReadonly($editorsOptionsField);
$fields->makeFieldReadonly($editorGroupsField);
$fields->makeFieldReadonly($topLevelCreatorsOptionsField);
$fields->makeFieldReadonly($topLevelCreatorsGroupsField);
$fields->makeFieldReadonly($taglineField);
$fields->makeFieldReadonly($titleField);
}
if(file_exists(BASE_PATH . '/install.php')) {
$fields->addFieldToTab("Root.Main", new LiteralField("InstallWarningHeader",
"<p class=\"message warning\">" . _t("SiteTree.REMOVE_INSTALL_WARNING",
"Warning: You should remove install.php from this SilverStripe install for security reasons.")
. "</p>"), "Title");
}
$tabMain->setTitle(_t('SiteConfig.TABMAIN', "Main"));
$tabAccess->setTitle(_t('SiteConfig.TABACCESS', "Access"));
$this->extend('updateCMSFields', $fields);
return $fields;
}
/**
* Get all available themes that haven't been marked as disabled.
* @param string $baseDir Optional alternative theme base directory for testing
* @return array of theme directory names
*/
public function getAvailableThemes($baseDir = null) {
$themes = SSViewer::get_themes($baseDir);
$disabled = (array)$this->config()->disabled_themes;
foreach($disabled as $theme) {
if(isset($themes[$theme])) unset($themes[$theme]);
}
return $themes;
}
/**
* Get the actions that are sent to the CMS. In
* your extensions: updateEditFormActions($actions)
*
* @return Fieldset
*/
public function getCMSActions() {
if (Permission::check('ADMIN') || Permission::check('EDIT_SITECONFIG')) {
$actions = new FieldList(
FormAction::create('save_siteconfig', _t('CMSMain.SAVE','Save'))
->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
);
} else {
$actions = new FieldList();
}
$this->extend('updateCMSActions', $actions);
return $actions;
}
/**
* @return String
*/
public function CMSEditLink() {
return singleton('CMSSettingsController')->Link();
}
/**
* Get the current sites SiteConfig, and creates a new one
* through {@link make_site_config()} if none is found.
*
* @return SiteConfig
*/
static public function current_site_config() {
if ($siteConfig = DataObject::get_one('SiteConfig')) return $siteConfig;
return self::make_site_config();
}
/**
* Setup a default SiteConfig record if none exists
*/
public function requireDefaultRecords() {
parent::requireDefaultRecords();
$siteConfig = DataObject::get_one('SiteConfig');
if(!$siteConfig) {
self::make_site_config();
DB::alteration_message("Added default site config","created");
}
}
/**
* Create SiteConfig with defaults from language file.
*
* @return SiteConfig
*/
static public function make_site_config() {
$config = SiteConfig::create();
$config->write();
return $config;
}
/**
* Can a user view pages on this site? This method is only
* called if a page is set to Inherit, but there is nothing
* to inherit from.
*
* @param mixed $member
* @return boolean
*/
public function canView($member = null) {
if(!$member) $member = Member::currentUserID();
if($member && is_numeric($member)) $member = DataObject::get_by_id('Member', $member);
if ($member && Permission::checkMember($member, "ADMIN")) return true;
if (!$this->CanViewType || $this->CanViewType == 'Anyone') return true;
// check for any logged-in users
if($this->CanViewType == 'LoggedInUsers' && $member) return true;
// check for specific groups
if($this->CanViewType == 'OnlyTheseUsers' && $member && $member->inGroups($this->ViewerGroups())) return true;
return false;
}
/**
* Can a user edit pages on this site? This method is only
* called if a page is set to Inherit, but there is nothing
* to inherit from.
*
* @param mixed $member
* @return boolean
*/
public function canEdit($member = null) {
if(!$member) $member = Member::currentUserID();
if($member && is_numeric($member)) $member = DataObject::get_by_id('Member', $member);
if ($member && Permission::checkMember($member, "ADMIN")) return true;
// check for any logged-in users
if(!$this->CanEditType || $this->CanEditType == 'LoggedInUsers' && $member) return true;
// check for specific groups
if($this->CanEditType == 'OnlyTheseUsers' && $member && $member->inGroups($this->EditorGroups())) return true;
return false;
}
public function providePermissions() {
return array(
'EDIT_SITECONFIG' => array(
'name' => _t('SiteConfig.EDIT_PERMISSION', 'Manage site configuration'),
'category' => _t('Permissions.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
'help' => _t('SiteConfig.EDIT_PERMISSION_HELP', 'Ability to edit global access settings/top-level page permissions.'),
'sort' => 400
)
);
}
/**
* Can a user create pages in the root of this site?
*
* @param mixed $member
* @return boolean
*/
public function canCreateTopLevel($member = null) {
if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
$member = Member::currentUserID();
}
if (Permission::check('ADMIN')) return true;
if ($member && Permission::checkMember($member, "ADMIN")) return true;
// check for any logged-in users
if($this->CanCreateTopLevelType == 'LoggedInUsers' && $member) return true;
// check for specific groups
if($member && is_numeric($member)) $member = DataObject::get_by_id('Member', $member);
if($this->CanCreateTopLevelType == 'OnlyTheseUsers' && $member && $member->inGroups($this->CreateTopLevelGroups())) return true;
return false;
}
}

View File

@ -19,7 +19,8 @@
"php": ">=5.3.2", "php": ">=5.3.2",
"composer/installers": "*", "composer/installers": "*",
"silverstripe/framework": "3.2.x-dev", "silverstripe/framework": "3.2.x-dev",
"silverstripe/reports": "*" "silverstripe/reports": "*",
"silverstripe/siteconfig": "*"
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {

View File

@ -1,27 +0,0 @@
<div id="settings-controller-cms-content" class="cms-content center cms-tabset $BaseCSSClasses" data-layout-type="border" data-pjax-fragment="Content CurrentForm" data-ignore-tab-state="true">
<div class="cms-content-header north">
<% with $EditForm %>
<div class="cms-content-header-info">
<% with $Controller %>
<% include CMSBreadcrumbs %>
<% end_with %>
</div>
<% if $Fields.hasTabset %>
<% with $Fields.fieldByName('Root') %>
<div class="cms-content-header-tabs cms-tabset-nav-primary ss-ui-tabs-nav">
<ul class="cms-tabset-nav-primary">
<% loop $Tabs %>
<li<% if $extraClass %> class="$extraClass"<% end_if %>><a href="#$id">$Title</a></li>
<% end_loop %>
</ul>
</div>
<% end_with %>
<% end_if %>
<% end_with %>
</div>
$EditForm
</div>

View File

@ -1,33 +0,0 @@
<form $FormAttributes data-layout-type="border">
<div class="cms-content-fields center">
<% if $Message %>
<p id="{$FormName}_error" class="message $MessageType">$Message</p>
<% else %>
<p id="{$FormName}_error" class="message $MessageType" style="display: none"></p>
<% end_if %>
<fieldset>
<% if $Legend %><legend>$Legend</legend><% end_if %>
<% loop $Fields %>
$FieldHolder
<% end_loop %>
<div class="clear"><!-- --></div>
</fieldset>
</div>
<div class="cms-content-actions cms-content-controls south">
<% if $Actions %>
<div class="Actions">
<% loop $Actions %>
$Field
<% end_loop %>
<% if $Controller.LinkPreview %>
<a href="$Controller.LinkPreview" class="cms-preview-toggle-link ss-ui-button" data-icon="preview">
<% _t('LeftAndMain.PreviewButton', 'Preview') %> &raquo;
</a>
<% end_if %>
</div>
<% end_if %>
</div>
</form>

View File

@ -1,37 +0,0 @@
Feature: Edit site wide settings
As a site administrator
I want to configure the sites title, tagline and theme
So that I dont have to change any templates
Background:
Given I am logged in with "ADMIN" permissions
And a "page" "home"
And I go to "/admin/settings"
@javascript
Scenario: I can edit my Site title and Tagline
Given I should see an edit page form
And I should see "Site title"
And I should see "Tagline"
When I fill in "Site title" with "Test Site"
And I fill in "Tagline" with "Site is under construction"
And I press the "Save" button
And I reload the page
Then I should see "Test Site" in the ".cms-logo" element
When I go to "/home"
Then I should see "Test Site"
And I should see "Site is under construction"
Scenario: I can change the theme of the website
Given a theme "behattest"
And a template "Page.ss" in theme "behattest" with content "<h1>This is the behat test theme</h1>"
When I go to "/admin/settings"
Then I should see an edit page form
And I should see "Theme"
When I select "behattest" from "Theme"
And I press the "Save" button
And I go to "/home?flush=1"
Then I should see "This is the behat test theme"

View File

@ -1,38 +0,0 @@
<?php
/**
* @package cms
* @subpackage tests
*
* Note: Most of the permission-related SiteConfig tests are located in
* SiteTreePermissionsTest
*/
class SiteConfigTest extends SapphireTest {
protected $illegalExtensions = array(
'SiteTree' => array('SiteTreeSubsites')
);
public function testAvailableThemes() {
$config = SiteConfig::current_site_config();
$ds = DIRECTORY_SEPARATOR;
$testThemeBaseDir = TEMP_FOLDER . $ds . 'test-themes';
if(file_exists($testThemeBaseDir)) Filesystem::removeFolder($testThemeBaseDir);
mkdir($testThemeBaseDir);
mkdir($testThemeBaseDir . $ds . 'blackcandy');
mkdir($testThemeBaseDir . $ds . 'blackcandy_blog');
mkdir($testThemeBaseDir . $ds . 'darkshades');
mkdir($testThemeBaseDir . $ds . 'darkshades_blog');
$themes = $config->getAvailableThemes($testThemeBaseDir);
$this->assertContains('blackcandy', $themes, 'Test themes contain blackcandy theme');
$this->assertContains('darkshades', $themes, 'Test themes contain darkshades theme');
SiteConfig::config()->disabled_themes = array('darkshades');
$themes = $config->getAvailableThemes($testThemeBaseDir);
$this->assertFalse(in_array('darkshades', $themes), 'Darkshades was disabled - it is no longer available');
Filesystem::removeFolder($testThemeBaseDir);
}
}