API Marked statics private, use Config API instead (#8317)

See "Static configuration properties are now immutable, you must use Config API." in the 3.1 change log for details.
This commit is contained in:
Ingo Schommer 2013-03-21 19:48:54 +01:00
parent f55bd9d3af
commit 3334eafcb1
253 changed files with 2085 additions and 1532 deletions

View File

@ -3,4 +3,6 @@ Name: coreconfig
---
Upload:
# Replace an existing file rather than renaming the new one.
replaceFile: false
replaceFile: false
MySQLDatabase:
connection_charset: utf8

View File

@ -8,7 +8,7 @@ class AdminRootController extends Controller {
* The url base that all LeftAndMain derived panels will live under
* Won't automatically update the base route if you change this - that has to be done seperately
*/
static $url_base = 'admin';
private static $url_base = 'admin';
/**
* @var string
@ -16,7 +16,7 @@ class AdminRootController extends Controller {
* The LeftAndMain child that will be used as the initial panel to display if none is selected (i.e. if you
* visit /admin)
*/
static $default_panel = 'SecurityAdmin';
private static $default_panel = 'SecurityAdmin';
/**
* @var array

View File

@ -8,9 +8,10 @@
*/
class CMSBatchActionHandler extends RequestHandler {
static $batch_actions = array();
/** @config */
private static $batch_actions = array();
static $url_handlers = array(
private static $url_handlers = array(
'$BatchAction/applicablepages' => 'handleApplicablePages',
'$BatchAction/confirmation' => 'handleConfirmation',
'$BatchAction' => 'handleBatchAction',
@ -40,9 +41,8 @@ class CMSBatchActionHandler extends RequestHandler {
*/
public static function register($urlSegment, $batchActionClass, $recordClass = 'SiteTree') {
if(is_subclass_of($batchActionClass, 'CMSBatchAction')) {
self::$batch_actions[$urlSegment] = array(
'class' => $batchActionClass,
'recordClass' => $recordClass
Config::inst()->update('CMSBatchActionHandler', 'batch_actions',
array($urlSegment => array('class' => $batchActionClass, 'recordClass' => $recordClass))
);
} else {
user_error("CMSBatchActionHandler::register() - Bad class '$batchActionClass'", E_USER_ERROR);

View File

@ -219,7 +219,7 @@ class CMSMenu extends Object implements IteratorAggregate, i18nEntityProvider
* {@link remove_menu_item}. Also used as a CSS-class for icon customization.
* @param string $menuTitle Localized title showing in the menu bar
* @param string $url A relative URL that will be linked in the menu bar.
* Make sure to add a matching route via {@link Director::addRules()} to this url.
* Make sure to add a matching route via {@link Director::$rules} to this url.
* @param string $controllerClass The controller class for this menu, used to check permisssions.
* If blank, it's assumed that this is public, and always shown to users who
* have the rights to access some other part of the admin area.

View File

@ -1,12 +1,12 @@
<?php
class CMSProfileController extends LeftAndMain {
static $url_segment = 'myprofile';
private static $url_segment = 'myprofile';
static $menu_title = 'My Profile';
private static $menu_title = 'My Profile';
static $required_permission_codes = false;
static $tree_class = 'Member';
private static $required_permission_codes = false;
private static $tree_class = 'Member';
public function getResponseNegotiator() {
$neg = parent::getResponseNegotiator();

View File

@ -16,41 +16,48 @@ class LeftAndMain extends Controller implements PermissionProvider {
* Note that if this is changed, many javascript
* behaviours need to be updated with the correct url
*
* @config
* @var string $url_base
*/
static $url_base = "admin";
private static $url_base = "admin";
/**
* The current url segment attached to the LeftAndMain instance
*
* @config
* @var string
*/
static $url_segment;
private static $url_segment;
/**
* @config
* @var string
*/
static $url_rule = '/$Action/$ID/$OtherID';
private static $url_rule = '/$Action/$ID/$OtherID';
/**
* @config
* @var string
*/
static $menu_title;
private static $menu_title;
/**
* @config
* @var string
*/
static $menu_icon;
private static $menu_icon;
/**
* @config
* @var int
*/
static $menu_priority = 0;
private static $menu_priority = 0;
/**
* @config
* @var int
*/
static $url_priority = 50;
private static $url_priority = 50;
/**
* A subclass of {@link DataObject}.
@ -58,21 +65,23 @@ class LeftAndMain extends Controller implements PermissionProvider {
* Determines what is managed in this interface, through
* {@link getEditForm()} and other logic.
*
* @config
* @var string
*/
static $tree_class = null;
private static $tree_class = null;
/**
* The url used for the link in the Help tab in the backend
*
*
* @config
* @var string
*/
static $help_link = 'http://3.0.userhelp.silverstripe.org';
private static $help_link = 'http://3.0.userhelp.silverstripe.org';
/**
* @var array
*/
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'save',
'savetreenode',
@ -88,34 +97,45 @@ class LeftAndMain extends Controller implements PermissionProvider {
);
/**
* @config
* @var Array Codes which are required from the current user to view this controller.
* If multiple codes are provided, all of them are required.
* All CMS controllers require "CMS_ACCESS_LeftAndMain" as a baseline check,
* and fall back to "CMS_ACCESS_<class>" if no permissions are defined here.
* See {@link canView()} for more details on permission checks.
*/
static $required_permission_codes;
private static $required_permission_codes;
/**
* @config
* @var String Namespace for session info, e.g. current record.
* Defaults to the current class name, but can be amended to share a namespace in case
* controllers are logically bundled together, and mainly separated
* to achieve more flexible templating.
*/
static $session_namespace;
private static $session_namespace;
/**
* Register additional requirements through the {@link Requirements} class.
* Used mainly to work around the missing "lazy loading" functionality
* for getting css/javascript required after an ajax-call (e.g. loading the editform).
*
* @var array $extra_requirements
* @config
* @var array
*/
protected static $extra_requirements = array(
'javascript' => array(),
'css' => array(),
'themedcss' => array(),
);
private static $extra_requirements_javascript = array();
/**
* @config
* @var array See {@link extra_requirements_javascript}
*/
private static $extra_requirements_css = array();
/**
* @config
* @var array See {@link extra_requirements_javascript}
*/
private static $extra_requirements_themedCss = array();
/**
* @var PjaxResponseNegotiator
@ -161,13 +181,13 @@ class LeftAndMain extends Controller implements PermissionProvider {
public function init() {
parent::init();
SSViewer::setOption('rewriteHashlinks', false);
Config::inst()->update('SSViewer', 'rewrite_hash_links', false);
// set language
$member = Member::currentUser();
if(!empty($member->Locale)) i18n::set_locale($member->Locale);
if(!empty($member->DateFormat)) i18n::set_date_format($member->DateFormat);
if(!empty($member->TimeFormat)) i18n::set_time_format($member->TimeFormat);
if(!empty($member->DateFormat)) i18n::config()->date_format = $member->DateFormat;
if(!empty($member->TimeFormat)) i18n::config()->time_format = $member->TimeFormat;
// can't be done in cms/_config.php as locale is not set yet
CMSMenu::add_link(
@ -231,8 +251,8 @@ class LeftAndMain extends Controller implements PermissionProvider {
// Use theme from the site config
if(class_exists('SiteConfig') && ($config = SiteConfig::current_site_config()) && $config->Theme) {
$theme = $config->Theme;
} elseif(SSViewer::current_theme()) {
$theme = SSViewer::current_theme();
} elseif(Config::inst()->get('SSViewer', 'theme')) {
$theme = Config::inst()->get('SSViewer', 'theme');
} else {
$theme = false;
}
@ -335,14 +355,18 @@ class LeftAndMain extends Controller implements PermissionProvider {
}
// Custom requirements
foreach (self::$extra_requirements['javascript'] as $file) {
Requirements::javascript($file[0]);
$extraJs = $this->stat('extra_requirements_javascript');
if($extraJs) foreach($extraJs as $file => $config) {
Requirements::javascript($file);
}
foreach (self::$extra_requirements['css'] as $file) {
Requirements::css($file[0], $file[1]);
$extraCss = $this->stat('extra_requirements_css');
if($extraCss) foreach($extraCss as $file => $config) {
Requirements::css($file, isset($config['media']) ? $config['media'] : null);
}
foreach (self::$extra_requirements['themedcss'] as $file) {
Requirements::themedCSS($file[0], $file[1]);
$extraThemedCss = $this->stat('extra_requirements_themedcss');
if($extraThemedCss) foreach ($extraThemedCss as $file => $config) {
Requirements::themedCSS($file, isset($config['media']) ? $config['media'] : null);
}
$dummy = null;
@ -350,7 +374,7 @@ class LeftAndMain extends Controller implements PermissionProvider {
// The user's theme shouldn't affect the CMS, if, for example, they have replaced
// TableListField.ss or Form.ss.
SSViewer::set_theme(null);
Config::inst()->update('SSViewer', 'theme', null);
}
public function handleRequest(SS_HTTPRequest $request, DataModel $model = null) {
@ -430,11 +454,15 @@ class LeftAndMain extends Controller implements PermissionProvider {
*/
public function Link($action = null) {
// Handle missing url_segments
if(!$this->stat('url_segment', true)) self::$url_segment = $this->class;
if($this->config()->url_segment) {
$segment = $this->config()->get('url_segment', Config::FIRST_SET);
} else {
$segment = $this->class;
};
$link = Controller::join_links(
$this->stat('url_base', true),
$this->stat('url_segment', true),
$segment,
'/', // trailing slash needed if $action is null!
"$action"
);
@ -1441,9 +1469,10 @@ class LeftAndMain extends Controller implements PermissionProvider {
* The href for the anchor on the Silverstripe logo.
* Set by calling LeftAndMain::set_application_link()
*
* @config
* @var String
*/
static $application_link = 'http://www.silverstripe.org/';
private static $application_link = 'http://www.silverstripe.org/';
/**
* Sets the href for the anchor on the Silverstripe logo in the menu
@ -1451,29 +1480,32 @@ class LeftAndMain extends Controller implements PermissionProvider {
* @param String $link
*/
public static function set_application_link($link) {
self::$application_link = $link;
Deprecation::notice('3.2', 'Use the "LeftAndMain.application_link" config setting instead');
Config::inst()->update('LeftAndMain', 'application_link', $link);
}
/**
* @return String
*/
public function ApplicationLink() {
return self::$application_link;
return $this->stat('application_link');
}
/**
* The application name. Customisable by calling
* LeftAndMain::setApplicationName() - the first parameter.
*
*
* @config
* @var String
*/
static $application_name = 'SilverStripe';
private static $application_name = 'SilverStripe';
/**
* @param String $name
*/
public static function setApplicationName($name) {
self::$application_name = $name;
Deprecation::notice('3.2', 'Use the "LeftAndMain.application_name" config setting instead');
Config::inst()->update('LeftAndMain', 'application_name', $name);
}
/**
@ -1482,7 +1514,7 @@ class LeftAndMain extends Controller implements PermissionProvider {
* @return string
*/
public function getApplicationName() {
return self::$application_name;
return $this->stat('application_name');
}
/**
@ -1571,7 +1603,8 @@ class LeftAndMain extends Controller implements PermissionProvider {
* Filenames should be relative to the base, eg, FRAMEWORK_DIR . '/javascript/loader.js'
*/
public static function require_javascript($file) {
self::$extra_requirements['javascript'][] = array($file);
Deprecation::notice('3.2', 'Use "LeftAndMain.extra_requirements_javascript" config setting instead');
Config::inst()->update('LeftAndMain', 'extra_requirements_javascript', array($file => array()));
}
/**
@ -1582,7 +1615,8 @@ class LeftAndMain extends Controller implements PermissionProvider {
* @see http://www.w3.org/TR/REC-CSS2/media.html
*/
public static function require_css($file, $media = null) {
self::$extra_requirements['css'][] = array($file, $media);
Deprecation::notice('3.2', 'Use "LeftAndMain.extra_requirements_css" config setting instead');
Config::inst()->update('LeftAndMain', 'extra_requirements_css', array($file => array('media' => $media)));
}
/**
@ -1594,7 +1628,8 @@ class LeftAndMain extends Controller implements PermissionProvider {
* @param $media String Comma-separated list of media-types (e.g. "screen,projector")
*/
public static function require_themed_css($name, $media = null) {
self::$extra_requirements['themedcss'][] = array($name, $media);
Deprecation::notice('3.2', 'Use "LeftAndMain.extra_requirements_css" config setting instead');
Config::inst()->update('LeftAndMain', 'extra_requirements_css', array($name => array('media' => $media)));
}
}

View File

@ -7,9 +7,9 @@
* to scaffold interfaces "out of the box", while at the same time providing
* flexibility to customize the default output.
*
* Add a route (note - this doc is not currently in sync with the code, need to update)
* Add a route
* <code>
* Director::addRules(50, array('admin/mymodel/$Class/$Action/$ID' => 'MyModelAdmin'));
* Director::config()->rules = array(array('admin/mymodel/$Class/$Action/$ID' => 'MyModelAdmin'));
* </code>
*
* @todo saving logic (should mostly use Form->saveInto() and iterate over relations)
@ -31,7 +31,7 @@
*/
abstract class ModelAdmin extends LeftAndMain {
static $url_rule = '/$ModelClass/$Action';
private static $url_rule = '/$ModelClass/$Action';
/**
* List of all managed {@link DataObject}s in this interface.
@ -51,23 +51,24 @@ abstract class ModelAdmin extends LeftAndMain {
* Available options:
* - 'title': Set custom titles for the tabs or dropdown names
*
* @config
* @var array|string
*/
public static $managed_models = null;
private static $managed_models = null;
/**
* Override menu_priority so that ModelAdmin CMSMenu objects
* are grouped together directly above the Help menu item.
* @var float
*/
public static $menu_priority = -0.5;
private static $menu_priority = -0.5;
public static $allowed_actions = array(
private static $allowed_actions = array(
'ImportForm',
'SearchForm',
);
public static $url_handlers = array(
private static $url_handlers = array(
'$ModelClass/$Action' => 'handleAction'
);
@ -91,16 +92,18 @@ abstract class ModelAdmin extends LeftAndMain {
*
* e.g. "BlogEntry" => "BlogEntryCsvBulkLoader"
*
* @config
* @var array
*/
public static $model_importers = null;
private static $model_importers = null;
/**
* Amount of results showing on a single page.
*
* @config
* @var int
*/
public static $page_length = 30;
private static $page_length = 30;
/**
* Initialize the model admin interface. Sets up embedded jquery libraries and requisite plugins.
@ -467,16 +470,22 @@ abstract class ModelAdmin extends LeftAndMain {
/**
* overwrite the static page_length of the admin panel,
* should be called in the project _config file.
*
* @deprecated 3.1 Use "ModelAdmin.page_length" config setting
*/
public static function set_page_length($length){
self::$page_length = $length;
Deprecation::notice('3.2', 'Use "ModelAdmin.page_length" config setting');
self::config()->page_length = $length;
}
/**
* Return the static page_length of the admin, default as 30
*
* @deprecated 3.1 Use "ModelAdmin.page_length" config setting
*/
public static function get_page_length(){
return self::$page_length;
Deprecation::notice('3.2', 'Use "ModelAdmin.page_length" config setting');
return self::config()->page_length;
}
}

View File

@ -6,17 +6,17 @@
*/
class SecurityAdmin extends LeftAndMain implements PermissionProvider {
static $url_segment = 'security';
private static $url_segment = 'security';
static $url_rule = '/$Action/$ID/$OtherID';
private static $url_rule = '/$Action/$ID/$OtherID';
static $menu_title = 'Security';
private static $menu_title = 'Security';
static $tree_class = 'Group';
private static $tree_class = 'Group';
static $subitem_class = 'Member';
private static $subitem_class = 'Member';
static $allowed_actions = array(
private static $allowed_actions = array(
'EditForm',
'MemberImportForm',
'memberimport',
@ -27,11 +27,6 @@ class SecurityAdmin extends LeftAndMain implements PermissionProvider {
'roles'
);
/**
* @var Array
*/
static $hidden_permissions = array();
public function init() {
parent::init();
Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/javascript/SecurityAdmin.js');
@ -310,33 +305,42 @@ class SecurityAdmin extends LeftAndMain implements PermissionProvider {
/**
* The permissions represented in the $codes will not appearing in the form
* containing {@link PermissionCheckboxSetField} so as not to be checked / unchecked.
*
*
* @deprecated 3.1 Use "Permission.hidden_permissions" config setting instead
* @param $codes String|Array
*/
public static function add_hidden_permission($codes){
if(is_string($codes)) $codes = array($codes);
self::$hidden_permissions = array_merge(self::$hidden_permissions, $codes);
Deprecation::notice('3.2', 'Use "Permission.hidden_permissions" config setting instead');
Config::inst()->update('Permission', 'hidden_permissions', $codes);
}
/**
* @deprecated 3.1 Use "Permission.hidden_permissions" config setting instead
* @param $codes String|Array
*/
public static function remove_hidden_permission($codes){
if(is_string($codes)) $codes = array($codes);
self::$hidden_permissions = array_diff(self::$hidden_permissions, $codes);
Deprecation::notice('3.2', 'Use "Permission.hidden_permissions" config setting instead');
Config::inst()->remove('Permission', 'hidden_permissions', $codes);
}
/**
* @deprecated 3.1 Use "Permission.hidden_permissions" config setting instead
* @return Array
*/
public static function get_hidden_permissions(){
return self::$hidden_permissions;
Deprecation::notice('3.2', 'Use "Permission.hidden_permissions" config setting instead');
Config::inst()->get('Permission', 'hidden_permissions', Config::FIRST_SET);
}
/**
* Clear all permissions previously hidden with {@link add_hidden_permission}
*
* @deprecated 3.1 Use "Permission.hidden_permissions" config setting instead
*/
public static function clear_hidden_permissions(){
self::$hidden_permissions = array();
Deprecation::notice('3.2', 'Use "Permission.hidden_permissions" config setting instead');
Config::inst()->remove('Permission', 'hidden_permissions', Config::anything());
}
}

View File

@ -82,7 +82,7 @@ class CMSMenuTest extends SapphireTest implements TestOnly {
}
class CMSMenuTest_LeftAndMainController extends LeftAndMain implements TestOnly {
static $url_segment = 'CMSMenuTest_LeftAndMainController';
static $menu_title = 'CMSMenuTest_LeftAndMainController';
static $menu_priority = 50;
private static $url_segment = 'CMSMenuTest_LeftAndMainController';
private static $menu_title = 'CMSMenuTest_LeftAndMainController';
private static $menu_priority = 50;
}

View File

@ -5,7 +5,7 @@
*/
class LeftAndMainTest extends FunctionalTest {
static $fixture_file = 'LeftAndMainTest.yml';
protected static $fixture_file = 'LeftAndMainTest.yml';
protected $extraDataObjects = array('LeftAndMainTest_Object');
@ -164,18 +164,18 @@ class LeftAndMainTest extends FunctionalTest {
class LeftAndMainTest_Controller extends LeftAndMain implements TestOnly {
protected $template = 'BlankPage';
static $tree_class = 'LeftAndMainTest_Object';
private static $tree_class = 'LeftAndMainTest_Object';
}
class LeftAndMainTest_Object extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
'URLSegment' => 'Varchar',
'Sort' => 'Int',
);
static $extensions = array(
private static $extensions = array(
'Hierarchy'
);

View File

@ -1,7 +1,7 @@
<?php
class ModelAdminTest extends FunctionalTest {
static $fixture_file = 'ModelAdminTest.yml';
protected static $fixture_file = 'ModelAdminTest.yml';
protected $extraDataObjects = array(
'ModelAdminTest_Admin',
@ -34,16 +34,16 @@ class ModelAdminTest extends FunctionalTest {
}
class ModelAdminTest_Admin extends ModelAdmin implements TestOnly {
static $url_segment = 'testadmin';
private static $url_segment = 'testadmin';
public static $managed_models = array(
private static $managed_models = array(
'ModelAdminTest_Contact',
);
}
class ModelAdminTest_PlayerAdmin extends ModelAdmin implements TestOnly {
static $url_segment = 'testadmin';
private static $url_segment = 'testadmin';
public static $managed_models = array(
private static $managed_models = array(
'ModelAdminTest_Player'
);
@ -55,21 +55,21 @@ class ModelAdminTest_PlayerAdmin extends ModelAdmin implements TestOnly {
}
}
class ModelAdminTest_Contact extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Phone' => 'Varchar',
);
static $summary_fields = array(
private static $summary_fields = array(
'Name' => 'Name',
'Phone' => 'Phone'
);
}
class ModelAdminTest_Player extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Position' => 'Varchar',
);
static $has_one = array(
private static $has_one = array(
'Contact' => 'ModelAdminTest_Contact'
);
}

View File

@ -5,7 +5,7 @@
*/
class SecurityAdminTest extends FunctionalTest {
static $fixture_file = 'LeftAndMainTest.yml';
protected static $fixture_file = 'LeftAndMainTest.yml';
protected $extraDataObjects = array('LeftAndMainTest_Object');
@ -45,37 +45,12 @@ class SecurityAdminTest extends FunctionalTest {
// $this->assertEquals($lines[1], '', "Empty export only has no content row");
// }
public function testAddHiddenPermission() {
SecurityAdmin::add_hidden_permission('CMS_ACCESS_ReportAdmin');
$this->assertContains('CMS_ACCESS_ReportAdmin', SecurityAdmin::get_hidden_permissions());
// reset to defaults
SecurityAdmin::clear_hidden_permissions();
}
public function testRemoveHiddenPermission() {
SecurityAdmin::add_hidden_permission('CMS_ACCESS_ReportAdmin');
$this->assertContains('CMS_ACCESS_ReportAdmin', SecurityAdmin::get_hidden_permissions());
SecurityAdmin::remove_hidden_permission('CMS_ACCESS_ReportAdmin');
$this->assertNotContains('CMS_ACCESS_ReportAdmin', SecurityAdmin::get_hidden_permissions());
// reset to defaults
SecurityAdmin::clear_hidden_permissions();
}
public function testClearHiddenPermission() {
SecurityAdmin::add_hidden_permission('CMS_ACCESS_ReportAdmin');
$this->assertContains('CMS_ACCESS_ReportAdmin', SecurityAdmin::get_hidden_permissions());
SecurityAdmin::clear_hidden_permissions('CMS_ACCESS_ReportAdmin');
$this->assertNotContains('CMS_ACCESS_ReportAdmin', SecurityAdmin::get_hidden_permissions());
}
public function testPermissionFieldRespectsHiddenPermissions() {
$this->session()->inst_set('loggedInAs', $this->idFromFixture('Member', 'admin'));
$group = $this->objFromFixture('Group', 'admin');
SecurityAdmin::add_hidden_permission('CMS_ACCESS_ReportAdmin');
Config::inst()->update('Permission', 'hidden_permissions', array('CMS_ACCESS_ReportAdmin'));
$response = $this->get(sprintf('admin/security/EditForm/field/Groups/item/%d/edit', $group->ID));
$this->assertContains(
@ -86,9 +61,6 @@ class SecurityAdminTest extends FunctionalTest {
'CMS_ACCESS_ReportAdmin',
$response->getBody()
);
// reset to defaults
SecurityAdmin::clear_hidden_permissions();
}
}

View File

@ -5,9 +5,10 @@
*/
class JSONDataFormatter extends DataFormatter {
/**
* @config
* @todo pass this from the API to the data formatter somehow
*/
static $api_base = "api/v1/";
private static $api_base = "api/v1/";
protected $outputContentType = 'application/json';
@ -70,9 +71,9 @@ class JSONDataFormatter extends DataFormatter {
$fieldName = $relName . 'ID';
if($obj->$fieldName) {
$href = Director::absoluteURL(self::$api_base . "$relClass/" . $obj->$fieldName);
$href = Director::absoluteURL($this->config()->api_base . "$relClass/" . $obj->$fieldName);
} else {
$href = Director::absoluteURL(self::$api_base . "$className/$id/$relName");
$href = Director::absoluteURL($this->config()->api_base . "$className/$id/$relName");
}
$serobj->$relName = ArrayData::array_to_object(array(
"className" => $relClass,
@ -91,8 +92,8 @@ class JSONDataFormatter extends DataFormatter {
$innerParts = array();
$items = $obj->$relName();
foreach($items as $item) {
//$href = Director::absoluteURL(self::$api_base . "$className/$id/$relName/$item->ID");
$href = Director::absoluteURL(self::$api_base . "$relClass/$item->ID");
//$href = Director::absoluteURL($this->config()->api_base . "$className/$id/$relName/$item->ID");
$href = Director::absoluteURL($this->config()->api_base . "$relClass/$item->ID");
$innerParts[] = ArrayData::array_to_object(array(
"className" => $relClass,
"href" => "$href.json",
@ -112,8 +113,8 @@ class JSONDataFormatter extends DataFormatter {
$innerParts = array();
$items = $obj->$relName();
foreach($items as $item) {
//$href = Director::absoluteURL(self::$api_base . "$className/$id/$relName/$item->ID");
$href = Director::absoluteURL(self::$api_base . "$relClass/$item->ID");
//$href = Director::absoluteURL($this->config()->api_base . "$className/$id/$relName/$item->ID");
$href = Director::absoluteURL($this->config()->api_base . "$relClass/$item->ID");
$innerParts[] = ArrayData::array_to_object(array(
"className" => $relClass,
"href" => "$href.json",

View File

@ -13,7 +13,7 @@ class RSSFeed extends ViewableData {
* Casting information for this object's methods.
* Let's us use $Title.XML in templates
*/
public static $casting = array(
private static $casting = array(
"Title" => "Varchar",
"Description" => "Varchar",
);
@ -186,8 +186,8 @@ class RSSFeed extends ViewableData {
* Output the feed to the browser
*/
public function outputToBrowser() {
$prevState = SSViewer::get_source_file_comments();
SSViewer::set_source_file_comments(false);
$prevState = Config::inst()->get('SSViewer', 'source_file_comments');
Config::inst()->update('SSViewer', 'source_file_comments', false);
$response = Controller::curr()->getResponse();
@ -204,7 +204,7 @@ class RSSFeed extends ViewableData {
$response->addHeader("Content-Type", "application/rss+xml");
}
SSViewer::set_source_file_comments($prevState);
Config::inst()->update('SSViewer', 'source_file_comments', $prevState);
return $this->renderWith($this->getTemplate());
}

View File

@ -16,27 +16,40 @@ class RestfulService extends ViewableData {
protected $authUsername, $authPassword;
protected $customHeaders = array();
protected $proxy;
protected static $default_proxy;
protected static $default_curl_options = array();
/**
* @config
* @var array
*/
private static $default_proxy;
/**
* @config
* @var array
*/
private static $default_curl_options = array();
/**
* set a curl option that will be applied to all requests as default
* {@see http://php.net/manual/en/function.curl-setopt.php#refsect1-function.curl-setopt-parameters}
*
* @deprecated 3.2 Use the "RestfulService.default_curl_options" config setting instead
* @param int $option The cURL opt Constant
* @param mixed $value The cURL opt value
*/
public static function set_default_curl_option($option, $value) {
self::$default_curl_options[$option] = $value;
Deprecation::notice('3.2', 'Use the "RestfulService.default_curl_options" config setting instead');
Config::inst()->update('RestfulService', 'default_curl_options', array($option => $value));
}
/**
* set many defauly curl options at once
*
* @deprecated 3.2 Use the "RestfulService.default_curl_options" config setting instead
*/
public static function set_default_curl_options($optionArray) {
foreach ($optionArray as $option => $value) {
self::set_default_curl_option($option, $value);
}
Deprecation::notice('3.2', 'Use the "RestfulService.default_curl_options" config setting instead');
Config::inst()->update('RestfulService', 'default_curl_options', $optionArray);
}
/**
@ -47,14 +60,21 @@ class RestfulService extends ViewableData {
* @param string $user The proxy auth user name
* @param string $password The proxy auth password
* @param boolean $socks Set true to use socks5 proxy instead of http
* @deprecated 3.2 Use the "RestfulService.default_curl_options" config setting instead,
* with direct reference to the CURL_* options
*/
public static function set_default_proxy($proxy, $port = 80, $user = "", $password = "", $socks = false) {
self::$default_proxy = array(
Deprecation::notice(
'3.1',
'Use the "RestfulService.default_curl_options" config setting instead, '
. 'with direct reference to the CURL_* options'
);
Config::set('RestfulService', 'default_proxy', array(
CURLOPT_PROXY => $proxy,
CURLOPT_PROXYUSERPWD => "{$user}:{$password}",
CURLOPT_PROXYPORT => $port,
CURLOPT_PROXYTYPE => ($socks ? CURLPROXY_SOCKS5 : CURLPROXY_HTTP)
);
));
}
/**
@ -65,8 +85,8 @@ class RestfulService extends ViewableData {
public function __construct($base, $expiry=3600){
$this->baseURL = $base;
$this->cache_expire = $expiry;
$this->proxy = self::$default_proxy;
parent::__construct();
$this->proxy = $this->config()->default_proxy;
}
/**
@ -140,7 +160,7 @@ class RestfulService extends ViewableData {
$method,
$data,
array_merge((array)$this->customHeaders, (array)$headers),
$curlOptions + self::$default_curl_options,
$curlOptions + (array)$this->config()->default_curl_options,
$this->getBasicAuthString()
));
@ -196,7 +216,7 @@ class RestfulService extends ViewableData {
$timeout = 5;
$sapphireInfo = new SapphireInfo();
$useragent = 'SilverStripe/' . $sapphireInfo->Version();
$curlOptions = $curlOptions + self::$default_curl_options;
$curlOptions = $curlOptions + (array)$this->config()->default_curl_options;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

View File

@ -4,10 +4,12 @@
* @subpackage formatters
*/
class XMLDataFormatter extends DataFormatter {
/**
* @config
* @todo pass this from the API to the data formatter somehow
*/
static $api_base = "api/v1/";
private static $api_base = "api/v1/";
protected $outputContentType = 'text/xml';
@ -43,7 +45,7 @@ class XMLDataFormatter extends DataFormatter {
public function convertDataObjectWithoutHeader(DataObject $obj, $fields = null, $relations = null) {
$className = $obj->class;
$id = $obj->ID;
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID");
$objHref = Director::absoluteURL($this->config()->api_base . "$obj->class/$obj->ID");
$xml = "<$className href=\"$objHref.xml\">\n";
foreach($this->getFieldsForObj($obj) as $fieldName => $fieldType) {
@ -75,9 +77,9 @@ class XMLDataFormatter extends DataFormatter {
$fieldName = $relName . 'ID';
if($obj->$fieldName) {
$href = Director::absoluteURL(self::$api_base . "$relClass/" . $obj->$fieldName);
$href = Director::absoluteURL($this->config()->api_base . "$relClass/" . $obj->$fieldName);
} else {
$href = Director::absoluteURL(self::$api_base . "$className/$id/$relName");
$href = Director::absoluteURL($this->config()->api_base . "$className/$id/$relName");
}
$xml .= "<$relName linktype=\"has_one\" href=\"$href.xml\" id=\"" . $obj->$fieldName
. "\"></$relName>\n";
@ -94,8 +96,8 @@ class XMLDataFormatter extends DataFormatter {
$items = $obj->$relName();
if ($items) {
foreach($items as $item) {
//$href = Director::absoluteURL(self::$api_base . "$className/$id/$relName/$item->ID");
$href = Director::absoluteURL(self::$api_base . "$relClass/$item->ID");
//$href = Director::absoluteURL($this->config()->api_base . "$className/$id/$relName/$item->ID");
$href = Director::absoluteURL($this->config()->api_base . "$relClass/$item->ID");
$xml .= "<$relClass href=\"$href.xml\" id=\"{$item->ID}\"></$relClass>\n";
}
}
@ -113,7 +115,7 @@ class XMLDataFormatter extends DataFormatter {
$items = $obj->$relName();
if ($items) {
foreach($items as $item) {
$href = Director::absoluteURL(self::$api_base . "$relClass/$item->ID");
$href = Director::absoluteURL($this->config()->api_base . "$relClass/$item->ID");
$xml .= "<$relClass href=\"$href.xml\" id=\"{$item->ID}\"></$relClass>\n";
}
}

View File

@ -11,7 +11,7 @@
*/
abstract class CliController extends Controller {
static $allowed_actions = array(
private static $allowed_actions = array(
'index'
);

View File

@ -67,7 +67,7 @@ if(defined('SS_ENVIRONMENT_FILE')) {
}
if(defined('SS_ENVIRONMENT_TYPE')) {
Director::set_environment_type(SS_ENVIRONMENT_TYPE);
Config::inst()->update('Director', 'environment_type', SS_ENVIRONMENT_TYPE);
}
global $database;
@ -128,7 +128,7 @@ if(defined('SS_DEFAULT_ADMIN_USERNAME')) {
Security::setDefaultAdmin(SS_DEFAULT_ADMIN_USERNAME, SS_DEFAULT_ADMIN_PASSWORD);
}
if(defined('SS_USE_BASIC_AUTH') && SS_USE_BASIC_AUTH) {
BasicAuth::protect_entire_site();
Config::inst()->update('BasicAuth', 'entire_site_protected', SS_USE_BASIC_AUTH);
}
if(defined('SS_ERROR_LOG')) {

View File

@ -26,42 +26,66 @@
* devs might know what they're doing and don't want contentnegotiator messing with their HTML4 doctypes,
* but still find it useful to have self-closing tags removed.
*/
class ContentNegotiator {
class ContentNegotiator extends Object {
protected static $content_type = '';
/**
* @config
* @var string
*/
private static $content_type = '';
protected static $encoding = 'utf-8';
/**
* @config
* @var string
*/
private static $encoding = 'utf-8';
protected static $enabled = false;
/**
* @config
* @var boolean
*/
private static $enabled = false;
/**
* Set the character set encoding for this page. By default it's utf-8, but you could change it to, say,
* windows-1252, to improve interoperability with extended characters being imported from windows excel.
*
* @deprecated 3.2 Use the "ContentNegotiator.encoding" config setting instead
*/
public static function set_encoding($encoding) {
self::$encoding = $encoding;
Deprecation::notice('3.2', 'Use the "ContentNegotiator.encoding" config setting instead');
Config::inst()->update('ContentNegotiator', 'encoding', $encoding);
}
/**
* Return the character encoding set bhy ContentNegotiator::set_encoding(). It's recommended that all classes
* that need to specify the character set make use of this function.
*
* @deprecated 3.2 Use the "ContentNegotiator.encoding" config setting instead
*/
public static function get_encoding() {
return self::$encoding;
Deprecation::notice('3.2', 'Use the "ContentNegotiator.encoding" config setting instead');
return Config::inst()->get('ContentNegotiator', 'encoding');
}
/**
* Enable content negotiation for all templates, not just those with the xml header.
*
* @deprecated 3.2 Use the "ContentNegotiator.enabled" config setting instead
*/
public static function enable() {
self::$enabled = true;
Deprecation::notice('3.2', 'Use the "ContentNegotiator.enabled" config setting instead');
Config::inst()->update('ContentNegotiator', 'enabled', true);
}
/*
/**
* Disable content negotiation for all templates, not just those with the xml header.
*
* @deprecated 3.2 Use the "ContentNegotiator.enabled" config setting instead
*/
public static function disable() {
self::$enabled = false;
Deprecation::notice('3.2', 'Use the "ContentNegotiator.enabled" config setting instead');
Config::inst()->update('ContentNegotiator', 'enabled', false);
}
/**
@ -77,7 +101,7 @@ class ContentNegotiator {
return false;
}
if(self::$enabled) return true;
if(Config::inst()->get('ContentNegotiator', 'enabled')) return true;
else return (substr($response->getBody(),0,5) == '<' . '?xml');
}
@ -135,12 +159,13 @@ class ContentNegotiator {
*/
public function xhtml(SS_HTTPResponse $response) {
$content = $response->getBody();
$encoding = Config::inst()->get('ContentNegotiator', 'encoding');
$contentType = Config::inst()->get('ContentNegotiator', 'content_type');
if (empty($contentType)) {
$response->addHeader("Content-Type", "application/xhtml+xml; charset=" . self::$encoding);
$response->addHeader("Content-Type", "application/xhtml+xml; charset=" . $encoding);
} else {
$response->addHeader("Content-Type", $contentType . "; charset=" . self::$encoding);
$response->addHeader("Content-Type", $contentType . "; charset=" . $encoding);
}
$response->addHeader("Vary" , "Accept");
@ -167,12 +192,12 @@ class ContentNegotiator {
* Removes "xmlns" attributes and any <?xml> Pragmas.
*/
public function html(SS_HTTPResponse $response) {
$encoding = Config::inst()->get('ContentNegotiator', 'encoding');
$contentType = Config::inst()->get('ContentNegotiator', 'content_type');
if (empty($contentType)) {
$response->addHeader("Content-Type", "text/html; charset=" . self::$encoding);
$response->addHeader("Content-Type", "text/html; charset=" . $encoding);
} else {
$response->addHeader("Content-Type", $contentType . "; charset=" . self::$encoding);
$response->addHeader("Content-Type", $contentType . "; charset=" . $encoding);
}
$response->addHeader("Vary", "Accept");

View File

@ -54,11 +54,11 @@ class Controller extends RequestHandler implements TemplateGlobalProvider {
/**
* Default URL handlers - (Action)/(ID)/(OtherID)
*/
static $url_handlers = array(
private static $url_handlers = array(
'$Action//$ID/$OtherID' => 'handleAction',
);
static $allowed_actions = array(
private static $allowed_actions = array(
'handleAction',
'handleIndex',
);

View File

@ -8,9 +8,10 @@
class Cookie {
/**
* @config
* @var boolean
*/
static $report_errors = true;
private static $report_errors = true;
/**
* @var string cookie class
@ -74,16 +75,20 @@ class Cookie {
}
/**
* @deprecated 3.2 Use "Cookie.report_errors" config setting instead
* @param bool
*/
public static function set_report_errors($reportErrors) {
Deprecation::notice('3.2', 'Use "Cookie.report_errors" config setting instead');
self::get_inst()->inst_set_report_errors($reportErrors);
}
/**
* @deprecated 3.2 Use "Cookie.report_errors" config setting instead
* @return bool
*/
public static function report_errors() {
Deprecation::notice('3.2', 'Use "Cookie.report_errors" config setting instead');
return self::get_inst()->inst_report_errors();
}
@ -106,7 +111,7 @@ class Cookie {
$path = ($path) ? $path : Director::baseURL();
setcookie($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
} else {
if(self::$report_errors) {
if(Config::inst()->get('Cookie', 'report_errors')) {
user_error("Cookie '$name' can't be set. The site started outputting content at line $line in $file",
E_USER_WARNING);
}
@ -131,16 +136,20 @@ class Cookie {
}
/**
* @deprecated 3.2 Use the "Cookie.report_errors" config setting instead
* @param bool
*/
protected function inst_set_report_errors($reportErrors) {
self::$report_errors = $reportErrors;
Deprecation::notice('3.2', 'Use the "Cookie.report_errors" config setting instead');
Config::inst()->update('Cookie', 'report_errors', $reportErrors);
}
/**
* @deprecated 3.2 Use the "Cookie.report_errors" config setting instead
* @return bool
*/
protected function inst_report_errors() {
return self::$report_errors;
Deprecation::notice('3.2', 'Use the "Cookie.report_errors" config setting instead');
return Config::inst()->get('Cookie', 'report_errors');
}
}

View File

@ -6,11 +6,13 @@
* appropriate controller.
*
* Director also has a number of static methods that provide information about the environment, such as
* {@link Director::set_environment_type()}.
* {@link Director::$environment_type}.
*
* @package framework
* @subpackage control
* @see Director::direct(),Director::addRules(),Director::set_environment_type()
* @see Director::direct()
* @see Director::$rules
* @see Director::$environment_type
*/
class Director implements TemplateGlobalProvider {
@ -23,21 +25,42 @@ class Director implements TemplateGlobalProvider {
*/
private static $current_page;
static $alternateBaseFolder;
/**
* @config
* @var string
*/
private static $alternate_base_folder;
static $alternateBaseURL;
/**
* @config
* @var array
*/
private static $dev_servers = array();
static $dev_servers = array();
/**
* @config
* @var array
*/
private static $test_servers = array();
static $test_servers = array();
/**
* @config
* @var string
*/
private static $alternate_base_url;
static protected $environment_type;
/**
* @config
* @var string
*/
private static $environment_type;
/**
* Add URL matching rules to the Director.
*
* The director is responsible for turning URLs into Controller objects.
*
*
* @deprecated 3.2 Use the "Director.rules" config setting instead
* @param $priority The priority of the rules; higher values will get your rule checked first. We recommend
* priority 100 for your site's rules. The built-in rules are priority 10, standard modules are
* priority 50.
@ -47,6 +70,7 @@ class Director implements TemplateGlobalProvider {
Deprecation::notice('3.0', 'Priority argument is now ignored - use the default of 100. You should really'
. ' be setting routes via _config yaml fragments though.', Deprecation::SCOPE_GLOBAL);
}
Deprecation::notice('3.2', 'Use the "Director.rules" config setting instead');
Config::inst()->update('Director', 'rules', $rules);
}
@ -193,10 +217,10 @@ class Director implements TemplateGlobalProvider {
$existingCookies = isset($_COOKIE) ? $_COOKIE : array();
$existingServer = isset($_SERVER) ? $_SERVER : array();
$existingCookieReportErrors = Cookie::report_errors();
$existingCookieReportErrors = Config::inst()->get('Cookie', 'report_errors');
$existingRequirementsBackend = Requirements::backend();
Cookie::set_report_errors(false);
Config::inst()->update('Cookie', 'report_errors', false);
Requirements::set_backend(new Requirements_Backend());
// Handle absolute URLs
@ -244,7 +268,7 @@ class Director implements TemplateGlobalProvider {
$_COOKIE = $existingCookies;
$_SERVER = $existingServer;
Cookie::set_report_errors($existingCookieReportErrors);
Config::inst()->update('Cookie', 'report_errors', $existingCookieReportErrors);
Requirements::set_backend($existingRequirementsBackend);
// These are needed so that calling Director::test() doesnt muck with whoever is calling it.
@ -364,8 +388,9 @@ class Director implements TemplateGlobalProvider {
* set.
*/
public static function protocolAndHost() {
if(self::$alternateBaseURL) {
if(preg_match('/^(http[^:]*:\/\/[^\/]+)(\/|$)/', self::$alternateBaseURL, $matches)) {
$alternate = Config::inst()->get('Director', 'alternate_base_url');
if($alternate) {
if(preg_match('/^(http[^:]*:\/\/[^\/]+)(\/|$)/', $alternate, $matches)) {
return $matches[1];
}
}
@ -405,8 +430,10 @@ class Director implements TemplateGlobalProvider {
* It will be automatically calculated unless it is overridden with {@link setBaseURL()}.
*/
public static function baseURL() {
if(self::$alternateBaseURL) return self::$alternateBaseURL;
else {
$alternate = Config::inst()->get('Director', 'alternate_base_url');
if($alternate) {
return $alternate;
} else {
$base = BASE_URL;
if($base == '/' || $base == '/.' || $base == '\\') $baseURL = '/';
else $baseURL = $base . '/';
@ -419,9 +446,12 @@ class Director implements TemplateGlobalProvider {
/**
* Sets the root URL for the website.
* If the site isn't accessible from the URL you provide, weird things will happen.
*
* @deprecated 3.2 Use the "Director.alternate_base_url" config setting instead
*/
public static function setBaseURL($baseURL) {
self::$alternateBaseURL = $baseURL;
Deprecation::notice('3.2', 'Use the "Director.alternate_base_url" config setting instead');
Config::inst()->update('Director', 'alternate_base_url', $baseURL);
}
/**
@ -429,16 +459,19 @@ class Director implements TemplateGlobalProvider {
* It will be automatically calculated unless it is overridden with {@link setBaseFolder()}.
*/
public static function baseFolder() {
if(self::$alternateBaseFolder) return self::$alternateBaseFolder;
else return BASE_PATH;
$alternate = Config::inst()->get('Director', 'alternate_base_folder');
return ($alternate) ? $alternate : BASE_PATH;
}
/**
* Sets the root folder for the website.
* If the site isn't accessible from the folder you provide, weird things will happen.
*
* @deprecated 3.2 Use the "Director.alternate_base_folder" config setting instead
*/
public static function setBaseFolder($baseFolder) {
self::$alternateBaseFolder = $baseFolder;
Deprecation::notice('3.2', 'Use the "Director.alternate_base_folder" config setting instead');
Config::inst()->update('Director', 'alternate_base_folder', $baseFolder);
}
/**
@ -769,7 +802,7 @@ class Director implements TemplateGlobalProvider {
* test, or live.
*
* You can set it explicitly with Director::set_environment_tpye(). Or you can use
* {@link Director::set_dev_servers()} and {@link Director::set_test_servers()} to set it implicitly, based on the
* {@link Director::$dev_servers} and {@link Director::$test_servers} to set it implicitly, based on the
* value of $_SERVER['HTTP_HOST']. If the HTTP_HOST value is one of the servers listed, then the environment type
* will be test or dev. Otherwise, the environment type will be live.
*
@ -783,7 +816,8 @@ class Director implements TemplateGlobalProvider {
*
* Once the environment type is set, it can be checked with {@link Director::isDev()}, {@link Director::isTest()},
* and {@link Director::isLive()}.
*
*
* @deprecated 3.2 Use the "Director.environment_type" config setting instead
* @param $et string The environment type: dev, test, or live.
*/
public static function set_environment_type($et) {
@ -791,7 +825,8 @@ class Director implements TemplateGlobalProvider {
user_error("Director::set_environment_type passed '$et'. It should be passed dev, test, or live",
E_USER_WARNING);
} else {
self::$environment_type = $et;
Deprecation::notice('3.2', 'Use the "Director.environment_type" config setting instead');
Config::inst()->update('Director', 'environment_type', $et);
}
}
@ -814,7 +849,7 @@ class Director implements TemplateGlobalProvider {
/*
* This function will return true if the site is in a live environment.
* For information about environment types, see {@link Director::set_environment_type()}.
* For information about environment types, see {@link Director::$environment_type}.
*/
public static function isLive() {
return !(Director::isDev() || Director::isTest());
@ -822,7 +857,7 @@ class Director implements TemplateGlobalProvider {
/**
* This function will return true if the site is in a development environment.
* For information about environment types, see {@link Director::set_environment_type()}.
* For information about environment types, see {@link Director::$environment_type}.
* @param $dontTouchDB If true, the database checks are not performed, which allows certain DB checks
* to not fail before the DB is ready. If false (default), DB checks are included.
*/
@ -833,7 +868,13 @@ class Director implements TemplateGlobalProvider {
$result = false;
if(isset($_SESSION['isDev']) && $_SESSION['isDev']) $result = true;
if(self::$environment_type && self::$environment_type == 'dev') $result = true;
if(Config::inst()->get('Director', 'environment_type') == 'dev') $result = true;
// Check if we are running on one of the test servers
$devServers = (array)Config::inst()->get('Director', 'dev_servers');
if(isset($_SERVER['HTTP_HOST']) && in_array($_SERVER['HTTP_HOST'], $devServers)) {
return true;
}
// Use ?isDev=1 to get development access on the live server
if(!$dontTouchDB && !$result && isset($_GET['isDev'])) {
@ -860,7 +901,7 @@ class Director implements TemplateGlobalProvider {
/**
* This function will return true if the site is in a test environment.
* For information about environment types, see {@link Director::set_environment_type()}.
* For information about environment types, see {@link Director::$environment_type}.
*/
public static function isTest() {
// Use ?isTest=1 to get test access on the live server, or explicitly set your environment
@ -874,12 +915,13 @@ class Director implements TemplateGlobalProvider {
}
if(self::isDev()) return false;
if(self::$environment_type) {
return self::$environment_type == 'test';
if(Config::inst()->get('Director', 'environment_type')) {
return Config::inst()->get('Director', 'environment_type') == 'test';
}
// Check if we are running on one of the test servers
if(isset($_SERVER['HTTP_HOST']) && in_array($_SERVER['HTTP_HOST'], Director::$test_servers)) {
$testServers = (array)Config::inst()->get('Director', 'test_servers');
if(isset($_SERVER['HTTP_HOST']) && in_array($_SERVER['HTTP_HOST'], $testServers)) {
return true;
}

View File

@ -64,8 +64,9 @@ class RequestHandler extends ViewableData {
*
* The values of the array are the method to be called if the rule matches. If this value starts with a '$', then
* the named parameter of the parsed URL wil be used to determine the method name.
* @config
*/
static $url_handlers = array(
private static $url_handlers = array(
'$Action' => '$Action',
);
@ -92,8 +93,9 @@ class RequestHandler extends ViewableData {
* these are handled separately through {@link Form->httpSubmission}. You can control access on form actions
* either by conditionally removing {@link FormAction} in the form construction,
* or by defining $allowed_actions in your {@link Form} class.
* @config
*/
static $allowed_actions = null;
private static $allowed_actions = null;
public function __construct() {
$this->brokenOnConstruct = false;

View File

@ -87,18 +87,39 @@ class Session {
/**
* @var $timeout Set session timeout
* @config
*/
protected static $timeout = 0;
private static $timeout = 0;
protected static $session_ips = array();
/**
* @config
* @var array
*/
private static $session_ips = array();
protected static $cookie_domain;
/**
* @config
* @var string
*/
private static $cookie_domain;
protected static $cookie_path;
/**
* @config
* @var string
*/
private static $cookie_path;
protected static $session_store_path;
/**
* @config
* @var string
*/
private static $session_store_path;
protected static $cookie_secure = false;
/**
* @config
* @var boolean
*/
private static $cookie_secure = false;
/**
* Session data
@ -123,38 +144,52 @@ class Session {
*
* To make cookies visible on all subdomains then the domain
* must be prefixed with a dot like '.php.net'.
*
* @deprecated 3.2 Use the "Session.cookie_domain" config setting instead
*
* @param string $domain The domain to set
*/
public static function set_cookie_domain($domain) {
self::$cookie_domain = $domain;
Deprecation::notice('3.2', 'Use the "Session.cookie_domain" config setting instead');
Config::inst()->update('Session', 'cookie_domain', $age);
}
/**
* Get the cookie domain.
*
* @deprecated 3.2 Use the "Session.cookie_domain" config setting instead
*
* @return string
*/
public static function get_cookie_domain() {
return self::$cookie_domain;
Deprecation::notice('3.2', 'Use the "Session.cookie_domain" config setting instead');
return Config::inst()->get('Session', 'cookie_domain');
}
/**
* Path to set on the domain where the session cookie will work.
* Use a single slash ('/') for all paths on the domain.
*
* @deprecated 3.2 Use the "Session.cookie_path" config setting instead
*
* @param string $path The path to set
*/
public static function set_cookie_path($path) {
self::$cookie_path = $path;
Deprecation::notice('3.2', 'Use the "Session.cookie_path" config setting instead');
Config::inst()->update('Session', 'cookie_path', $path);
}
/**
* Get the path on the domain where the session cookie will work.
*
* @deprecated 3.2 Use the "Session.cookie_path" config setting instead
*
* @return string
*/
public static function get_cookie_path() {
if(self::$cookie_path) {
return self::$cookie_path;
Deprecation::notice('3.2', 'Use the "Session.cookie_path" config setting instead');
if(Config::inst()->get('Session', 'cookie_path')) {
return Config::inst()->get('Session', 'cookie_path');
} else {
return Director::baseURL();
}
@ -162,26 +197,38 @@ class Session {
/**
* Secure cookie, tells the browser to only send it over SSL.
*
* @deprecated 3.2 Use the "Session.cookie_secure" config setting instead
*
* @param boolean $secure
*/
public static function set_cookie_secure($secure) {
self::$cookie_secure = (bool) $secure;
Deprecation::notice('3.2', 'Use the "Session.cookie_secure" config setting instead');
Config::inst()->update('Session', 'cookie_secure', (bool)$secure);
}
/**
* Get if the cookie is secure
*
* @deprecated 3.2 Use the "Session.cookie_secure" config setting instead
*
* @return boolean
*/
public static function get_cookie_secure() {
return (bool) self::$cookie_secure;
Deprecation::notice('3.2', 'Use the "Session.cookie_secure" config setting instead');
return Config::inst()->get('Session', 'cookie_secure');
}
/**
* Set the session store path
*
* @deprecated 3.2 Use the "Session.session_store_path" config setting instead
*
* @param string $path Filesystem path to the session store
*/
public static function set_session_store_path($path) {
self::$session_store_path = $path;
Deprecation::notice('3.2', 'Use the "Session.session_store_path" config setting instead');
Config::inst()->update('Session', 'session_store_path', $path);
}
/**
@ -189,7 +236,8 @@ class Session {
* @return string
*/
public static function get_session_store_path() {
return self::$session_store_path;
Deprecation::notice('3.2', 'Use the "Session.session_store_path" config setting instead');
return Config::inst()->get('Session', 'session_store_path');
}
/**
@ -204,16 +252,14 @@ class Session {
* Any user connecting from 127.0.0.1 (localhost) will have their session expired after 10 hours.
*
* Session::set_timeout is used to set the timeout value for any users whose address is not in the given IP range.
*
* @deprecated 3.2 Use the "Session.timeout_ips" config setting instead
*
* @param array $session_ips Array of IPv4 rules.
*/
public static function set_timeout_ips($session_ips) {
if(!is_array($session_ips)) {
user_error("Session::set_timeout_ips expects an array as its argument", E_USER_NOTICE);
self::$session_ips = array();
} else {
self::$session_ips = $session_ips;
}
public static function set_timeout_ips($ips) {
Deprecation::notice('3.2', 'Use the "Session.timeout_ips" config setting instead');
Config::inst()->update('Session', 'timeout_ips', $ips);
}
/**
@ -450,16 +496,17 @@ class Session {
* @param string $sid Start the session with a specific ID
*/
public static function start($sid = null) {
$path = self::get_cookie_path();
$domain = self::get_cookie_domain();
$secure = self::get_cookie_secure();
$session_path = self::get_session_store_path();
$path = Config::inst()->get('Session', 'cookie_path');
$domain = Config::inst()->get('Session', 'cookie_domain');
$secure = Config::inst()->get('Session', 'cookie_secure');
$session_path = Config::inst()->get('Session', 'session_store_path');
$timeout = Config::inst()->get('Session', 'timeout');
if(!session_id() && !headers_sent()) {
if($domain) {
session_set_cookie_params(self::$timeout, $path, $domain, $secure /* secure */, true /* httponly */);
session_set_cookie_params($timeout, $path, $domain, $secure /* secure */, true /* httponly */);
} else {
session_set_cookie_params(self::$timeout, $path, null, $secure /* secure */, true /* httponly */);
session_set_cookie_params($timeout, $path, null, $secure /* secure */, true /* httponly */);
}
// Allow storing the session in a non standard location
@ -480,9 +527,9 @@ class Session {
public static function destroy($removeCookie = true) {
if(session_id()) {
if($removeCookie) {
$path = self::get_cookie_path();
$domain = self::get_cookie_domain();
$secure = self::get_cookie_secure();
$path = Config::inst()->get('cookie_path');
$domain = Config::inst()->get('cookie_domain');
$secure = Config::inst()->get('cookie_secure');
if($domain) {
setcookie(session_name(), '', null, $path, $domain, $secure, true);
@ -500,13 +547,20 @@ class Session {
/**
* Set the timeout of a Session value
*
* @deprecated 3.2 Use the "Session.timeout" config setting instead
*
* @param int $timeout Time until a session expires in seconds. Defaults to expire when browser is closed.
*/
public static function set_timeout($timeout) {
self::$timeout = intval($timeout);
Deprecation::notice('3.2', 'Use the "Session.timeout" config setting instead');
Config::inst()->update('Session', 'timeout', (int)$timeout);
}
/**
* @deprecated 3.2 Use the "Session.timeout" config setting instead
*/
public static function get_timeout() {
return self::$timeout;
Deprecation::notice('3.2', 'Use the "Session.timeout" config setting instead');
return Config::inst()->update('Session', 'timeout');
}
}

View File

@ -13,7 +13,7 @@
* Initialized constants:
* - BASE_URL: Full URL to the webroot, e.g. "http://my-host.com/my-webroot" (no trailing slash).
* - BASE_PATH: Absolute path to the webroot, e.g. "/var/www/my-webroot" (no trailing slash).
* See Director::baseFolder(). Can be overwritten by Director::setBaseFolder().
* See Director::baseFolder(). Can be overwritten by Config::inst()->update('Director', 'alternate_base_folder', ).
* - TEMP_FOLDER: Absolute path to temporary folder, used for manifest and template caches. Example: "/var/tmp"
* See getTempFolder(). No trailing slash.
* - MODULES_DIR: Not used at the moment

View File

@ -16,7 +16,7 @@ abstract class Extension {
* This is used by extensions designed to be applied to controllers.
* It works the same way as {@link Controller::$allowed_actions}.
*/
public static $allowed_actions = null;
private static $allowed_actions = null;
/**
* The object this extension is applied to.

View File

@ -21,7 +21,7 @@ abstract class Object {
*
* Example:
* <code>
* public static $extensions = array (
* private static $extensions = array (
* 'Hierarchy',
* "Version('Stage', 'Live')"
* );
@ -33,8 +33,9 @@ abstract class Object {
* Extensions are instanciated together with the object and stored in {@link $extension_instances}.
*
* @var array $extensions
* @config
*/
public static $extensions = null;
private static $extensions = null;
private static
$classes_constructed = array(),

View File

@ -225,7 +225,7 @@ class SS_ConfigManifest {
else {
// If we got an odd number of parts the config file doesn't have a header for every document
if (count($parts) % 2 != 0) {
user_error("Configuration file $basename does not have an equal number of headers and config blocks");
user_error("Configuration file '$pathname' does not have an equal number of headers and config blocks");
}
// Step through each pair

View File

@ -19,7 +19,7 @@ class ManifestFileFinder extends SS_FileFinder {
const LANG_DIR = 'lang';
const TESTS_DIR = 'tests';
public static $default_options = array(
protected static $default_options = array(
'include_themes' => false,
'ignore_tests' => true,
'min_depth' => 1

View File

@ -12,7 +12,7 @@ class SS_Backtrace {
* PHP's debug_backtrace() doesn't allow to inspect the argument names,
* so all arguments of the provided functions will be filtered out.
*/
static $ignore_function_args = array(
private static $ignore_function_args = array(
'mysql_connect',
'mssql_connect',
'pg_connect',
@ -85,17 +85,19 @@ class SS_Backtrace {
array_shift($bt);
}
$ignoredArgs = Config::inst()->get('SS_Backtrace', 'ignore_function_args');
// Filter out arguments
foreach($bt as $i => $frame) {
$match = false;
if(@$bt[$i]['class']) {
foreach(self::$ignore_function_args as $fnSpec) {
foreach($ignoredArgs as $fnSpec) {
if(is_array($fnSpec) && $bt[$i]['class'] == $fnSpec[0] && $bt[$i]['function'] == $fnSpec[1]) {
$match = true;
}
}
} else {
if(in_array($bt[$i]['function'], self::$ignore_function_args)) $match = true;
if(in_array($bt[$i]['function'], $ignoredArgs)) $match = true;
}
if($match) {
foreach($bt[$i]['args'] as $j => $arg) $bt[$i]['args'][$j] = '<filtered>';

View File

@ -99,7 +99,7 @@ abstract class BulkLoader extends ViewableData {
* isn't Email, you need to ensure that Member is correctly set to the unique field
* you want, as it will merge any duplicates during {@link Member::onBeforeWrite()}.
*
* {@see Member::set_unique_identifier_field()}.
* {@see Member::$unique_identifier_field}.
*
* If multiple checks are specified, the first one "wins".
*

View File

@ -25,38 +25,38 @@
class Debug {
/**
* @var $custom_smtp_server string Custom mailserver for sending mails.
* @config
* @var string Email address to send error notifications
*/
protected static $custom_smtp_server = '';
private static $send_errors_to;
/**
* @var $send_errors_to string Email address to send error notifications
* @config
* @var string Email address to send warning notifications
*/
protected static $send_errors_to;
private static $send_warnings_to;
/**
* @var $send_warnings_to string Email address to send warning notifications
*/
protected static $send_warnings_to;
/**
* String indicating the file where errors are logged.
* @config
* @var String indicating the file where errors are logged.
* Filename is relative to the site root.
* The named file will have a terse log sent to it, and the full log (an
* encoded file containing backtraces and things) will go to a file of a similar
* name, but with the suffix ".full" added.
*/
protected static $log_errors_to = null;
private static $log_errors_to = null;
/**
* The header of the message shown to users on the live site when a fatal error occurs.
* @config
* @var string The header of the message shown to users on the live site when a fatal error occurs.
*/
public static $friendly_error_header = 'There has been an error';
private static $friendly_error_header = 'There has been an error';
/**
* The body of the message shown to users on the live site when a fatal error occurs.
* @config
* @var string The body of the message shown to users on the live site when a fatal error occurs.
*/
public static $friendly_error_detail = 'The website server has not been able to respond to your request.';
private static $friendly_error_detail = 'The website server has not been able to respond to your request.';
/**
* Show the contents of val in a debug-friendly way.
@ -182,7 +182,7 @@ class Debug {
}
// Keep track of how many headers have been sent
static $headerCount = 0;
private static $headerCount = 0;
/**
* Send a debug message in an HTTP header. Only works if you are
@ -257,9 +257,9 @@ class Debug {
if(error_reporting() == 0) return;
ini_set('display_errors', 0);
if(self::$send_warnings_to) {
if(Config::inst()->get('Debug', 'send_warnings_to')) {
return self::emailError(
self::$send_warnings_to,
Config::inst()->get('Debug', 'send_warnings_to'),
$errno,
$errstr,
$errfile,
@ -281,7 +281,7 @@ class Debug {
SS_Log::WARN
);
if(self::$log_errors_to) {
if(Config::inst()->get('Debug', 'log_errors_to')) {
self::log_error_if_necessary( $errno, $errstr, $errfile, $errline, $errcontext, "Warning");
}
@ -306,8 +306,11 @@ class Debug {
public static function fatalHandler($errno, $errstr, $errfile, $errline, $errcontext) {
ini_set('display_errors', 0);
if(self::$send_errors_to) {
self::emailError(self::$send_errors_to, $errno, $errstr, $errfile, $errline, $errcontext, "Error");
if(Config::inst()->get('Debug', 'send_errors_to')) {
self::emailError(
Config::inst()->get('Debug', 'send_errors_to'), $errno,
$errstr, $errfile, $errline, $errcontext, "Error"
);
}
// Send out the error details to the logger for writing
@ -322,7 +325,7 @@ class Debug {
SS_Log::ERR
);
if(self::$log_errors_to) {
if(Config::inst()->get('Debug', 'log_errors_to')) {
self::log_error_if_necessary( $errno, $errstr, $errfile, $errline, $errcontext, "Error");
}
@ -348,8 +351,13 @@ class Debug {
* @return string HTML error message for non-ajax requests, plaintext for ajax-request.
*/
public static function friendlyError($statusCode=500, $friendlyErrorMessage=null, $friendlyErrorDetail=null) {
if(!$friendlyErrorMessage) $friendlyErrorMessage = self::$friendly_error_header;
if(!$friendlyErrorDetail) $friendlyErrorDetail = self::$friendly_error_detail;
if(!$friendlyErrorMessage) {
$friendlyErrorMessage = Config::inst()->get('Debug', 'friendly_error_header');
}
if(!$friendlyErrorDetail) {
$friendlyErrorDetail = Config::inst()->get('Debug', 'friendly_error_detail');
}
if(!headers_sent()) {
$currController = Controller::curr();
@ -381,8 +389,8 @@ class Debug {
$renderer->writeHeader();
$renderer->writeInfo("Website Error", $friendlyErrorMessage, $friendlyErrorDetail);
if(Email::getAdminEmail()) {
$mailto = Email::obfuscate(Email::getAdminEmail());
if(Email::config()->admin_email) {
$mailto = Email::obfuscate(Email::config()->admin_email);
$renderer->writeParagraph('Contact an administrator: ' . $mailto . '');
}

View File

@ -10,14 +10,14 @@
*/
class DevelopmentAdmin extends Controller {
static $url_handlers = array(
private static $url_handlers = array(
'' => 'index',
'build/defaults' => 'buildDefaults',
'$Action' => '$Action',
'$Action//$Action/$ID' => 'handleAction',
);
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'tests',
'jstests',

View File

@ -33,7 +33,8 @@ class FixtureBlueprint {
'afterCreate' => array(),
);
static $dependencies = array(
/** @config */
private static $dependencies = array(
'factory' => '%$FixtureFactory'
);
@ -69,8 +70,8 @@ class FixtureBlueprint {
public function createObject($identifier, $data = null, $fixtures = null) {
// We have to disable validation while we import the fixtures, as the order in
// which they are imported doesnt guarantee valid relations until after the import is complete.
$validationenabled = DataObject::get_validation_enabled();
DataObject::set_validation_enabled(false);
$validationenabled = Config::inst()->get('DataObject', 'validation_enabled');
Config::inst()->update('DataObject', 'validation_enabled', false);
$this->invokeCallbacks('beforeCreate', array($identifier, &$data, &$fixtures));
@ -169,11 +170,11 @@ class FixtureBlueprint {
));
}
} catch(Exception $e) {
DataObject::set_validation_enabled($validationenabled);
Config::inst()->update('DataObject', 'validation_enabled', $validationenabled);
throw $e;
}
DataObject::set_validation_enabled($validationenabled);
Config::inst()->update('DataObject', 'validation_enabled', $validationenabled);
$this->invokeCallbacks('afterCreate', array($obj, $identifier, &$data, &$fixtures));

View File

@ -28,12 +28,12 @@ class FunctionalTest extends SapphireTest {
* This can be handy for functional testing of modules without having to worry about whether a user has changed
* behaviour by replacing the theme.
*/
static $disable_themes = false;
protected static $disable_themes = false;
/**
* Set this to true on your sub-class to use the draft site by default for every test in this class.
*/
static $use_draft_site = false;
protected static $use_draft_site = false;
protected $mainSession = null;
@ -64,10 +64,10 @@ class FunctionalTest extends SapphireTest {
$this->mainSession = new TestSession();
// Disable theme, if necessary
if($this->stat('disable_themes')) SSViewer::set_theme(null);
if(static::get_disable_themes()) Config::inst()->update('SSViewer', 'theme', null);
// Switch to draft site, if necessary
if($this->stat('use_draft_site')) {
if(static::get_use_draft_site()) {
$this->useDraftSite();
}
@ -323,10 +323,22 @@ class FunctionalTest extends SapphireTest {
/**
* Return a static variable from this class.
* Gets around PHP's lack of late static binding.
*/
public function stat($varName) {
$className = get_class($this);
return eval("return {$className}::\$$varName;");
return static::$varName;
}
/**
* @return Boolean
*/
public static function get_disable_themes() {
return static::$disable_themes;
}
/**
* @return Boolean
*/
public static function get_use_draft_site() {
return static::$use_draft_site;
}
}

View File

@ -6,7 +6,7 @@
*/
class InstallerTest extends Controller {
static $allowed_actions = array(
private static $allowed_actions = array(
'testrewrite'
);

View File

@ -37,12 +37,12 @@ class JSTestRunner extends Controller {
/** @ignore */
private static $default_reporter;
static $url_handlers = array(
private static $url_handlers = array(
'' => 'browse',
'$TestCase' => 'only',
);
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'all',
'browse',

View File

@ -68,7 +68,7 @@ class SS_Log {
* Caution: Depends on logger implementation (mainly targeted at {@link SS_LogEmailWriter}).
* @see http://framework.zend.com/manual/en/zend.log.overview.html#zend.log.overview.understanding-fields
*/
static $log_globals = array(
protected static $log_globals = array(
'_SERVER' => array(
'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET',

View File

@ -12,9 +12,10 @@ require_once 'Zend/Log/Writer/Abstract.php';
class SS_LogEmailWriter extends Zend_Log_Writer_Abstract {
/**
* @config
* @var $send_from Email address to send log information from
*/
protected static $send_from = 'errors@silverstripe.com';
private static $send_from = 'errors@silverstripe.com';
protected $emailAddress;
@ -29,12 +30,20 @@ class SS_LogEmailWriter extends Zend_Log_Writer_Abstract {
return new SS_LogEmailWriter($emailAddress, $customSmtpServer);
}
/**
* @deprecated 3.2 Use the "SS_LogEmailWriter.send_from" config setting instead
*/
public static function set_send_from($address) {
self::$send_from = $address;
Deprecation::notice('3.2', 'Use the "SS_LogEmailWriter.send_from" config setting instead');
Config::inst()->update('SS_LogEmailWriter', 'send_from', $address);
}
/**
* @deprecated 3.2 Use the "SS_LogEmailWriter.send_from" config setting instead
*/
public static function get_send_from() {
return self::$send_from;
Deprecation::notice('3.2', 'Use the "SS_LogEmailWriter.send_from" config setting instead');
return Config::inst()->get('SS_LogEmailWriter', 'send_from');
}
/**
@ -51,6 +60,7 @@ class SS_LogEmailWriter extends Zend_Log_Writer_Abstract {
$formattedData = $this->_formatter->format($event);
$subject = $formattedData['subject'];
$data = $formattedData['data'];
$from = Config::inst()->get('SS_LogEmailWriter', 'send_from');
// override the SMTP server with a custom one if required
$originalSMTP = ini_get('SMTP');
@ -66,14 +76,14 @@ class SS_LogEmailWriter extends Zend_Log_Writer_Abstract {
$subject,
$data,
null,
"Content-type: text/html\nFrom: " . self::$send_from
"Content-type: text/html\nFrom: " . $from
);
} else {
mail(
$this->emailAddress,
$subject,
$data,
"Content-type: text/html\nFrom: " . self::$send_from
"Content-type: text/html\nFrom: " . $from
);
}

View File

@ -5,7 +5,7 @@
* @subpackage control
*/
class SapphireInfo extends Controller {
static $allowed_actions = array(
private static $allowed_actions = array(
'baseurl',
'version',
'environmenttype',

View File

@ -24,7 +24,7 @@ define('30719',E_ALL);
*/
class SapphireREPL extends Controller {
static $allowed_actions = array(
private static $allowed_actions = array(
'index'
);

View File

@ -11,7 +11,8 @@ require_once 'TestRunner.php';
*/
class SapphireTest extends PHPUnit_Framework_TestCase {
static $dependencies = array(
/** @config */
private static $dependencies = array(
'fixtureFactory' => '%$FixtureFactory',
);
@ -23,7 +24,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
*
* @var string|array
*/
static $fixture_file = null;
protected static $fixture_file = null;
/**
* @var FixtureFactory
@ -148,7 +149,14 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
public static function get_test_class_manifest() {
return self::$test_class_manifest;
}
/**
* @return String
*/
public static function get_fixture_file() {
return static::$fixture_file;
}
/**
* @var array $fixtures Array of {@link YamlFixture} instances
* @deprecated 3.1 Use $fixtureFactory instad
@ -172,11 +180,11 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
// Mark test as being run
$this->originalIsRunningTest = self::$is_running_test;
self::$is_running_test = true;
// i18n needs to be set to the defaults or tests fail
i18n::set_locale(i18n::default_locale());
i18n::set_date_format(null);
i18n::set_time_format(null);
i18n::config()->date_format = null;
i18n::config()->time_format = null;
// Set default timezone consistently to avoid NZ-specific dependencies
date_default_timezone_set('UTC');
@ -185,7 +193,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
$this->originalMemberPasswordValidator = Member::password_validator();
$this->originalRequirements = Requirements::backend();
Member::set_password_validator(null);
Cookie::set_report_errors(false);
Config::inst()->update('Cookie', 'report_errors', false);
if(class_exists('RootURLController')) RootURLController::reset();
if(class_exists('Translatable')) Translatable::reset();
@ -196,15 +204,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
if(Controller::has_curr()) Controller::curr()->setSession(new Session(array()));
Security::$database_is_ready = null;
$this->originalTheme = SSViewer::current_theme();
if(class_exists('SiteTree')) {
// Save nested_urls state, so we can restore it later
$this->originalNestedURLsState = SiteTree::nested_urls();
}
$className = get_class($this);
$fixtureFile = eval("return {$className}::\$fixture_file;");
$fixtureFile = static::get_fixture_file();
$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
@ -213,7 +213,6 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
$this->mailer = new TestMailer();
Email::set_mailer($this->mailer);
Config::inst()->remove('Email', 'send_all_emails_to');
Email::send_all_emails_to(null);
// Todo: this could be a special test model
$this->model = DataModel::inst();
@ -271,7 +270,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
$this->originalMemoryLimit = ini_get('memory_limit');
// turn off template debugging
SSViewer::set_source_file_comments(false);
Config::inst()->update('SSViewer', 'source_file_comments', false);
// Clear requirements
Requirements::clear();
@ -346,7 +345,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
}
}
}
if($this->extensionsToReapply || $this->extensionsToRemove || $this->extraDataObjects) {
$this->resetDBSchema();
}
@ -485,22 +484,9 @@ class SapphireTest extends PHPUnit_Framework_TestCase {
self::$is_running_test = $this->originalIsRunningTest;
$this->originalIsRunningTest = null;
// Reset theme setting
if($this->originalTheme) {
SSViewer::set_theme($this->originalTheme);
}
// Reset mocked datetime
SS_Datetime::clear_mock_now();
if(class_exists('SiteTree')) {
// Restore nested_urls state
if ( $this->originalNestedURLsState )
SiteTree::enable_nested_urls();
else
SiteTree::disable_nested_urls();
}
// Stop the redirection that might have been requested in the test.
// Note: Ideally a clean Controller should be created for each test.
// Now all tests executed in a batch share the same controller.

View File

@ -5,12 +5,12 @@
*/
class TaskRunner extends Controller {
static $url_handlers = array(
private static $url_handlers = array(
'' => 'index',
'$TaskName' => 'runTask'
);
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'runTask',
);

View File

@ -24,7 +24,7 @@ class TestRunner extends Controller {
/** @ignore */
private static $default_reporter;
static $url_handlers = array(
private static $url_handlers = array(
'' => 'browse',
'coverage/module/$ModuleName' => 'coverageModule',
'coverage/$TestCase!' => 'coverageOnly',
@ -36,7 +36,7 @@ class TestRunner extends Controller {
'$TestCase' => 'only'
);
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'browse',
'coverage',

View File

@ -10,7 +10,7 @@
*/
class DatabaseAdapterRegistry {
static $default_fields = array(
private static $default_fields = array(
'server' => array(
'title' => 'Database server',
'envVar' => 'SS_DATABASE_SERVER',

View File

@ -1089,17 +1089,8 @@ global \$database;
require_once('conf/ConfigureFromEnv.php');
MySQLDatabase::set_connection_charset('utf8');
// Set the current theme. More themes can be downloaded from
// http://www.silverstripe.org/themes/
SSViewer::set_theme('$theme');
// Set the site locale
i18n::set_locale('$locale');
// Enable nested URLs for this site (e.g. page/sub-page/)
if (class_exists('SiteTree')) SiteTree::enable_nested_urls();
PHP
);
@ -1122,17 +1113,8 @@ global \$databaseConfig;
"path" => '{$dbConfig['path']}',
);
MySQLDatabase::set_connection_charset('utf8');
// Set the current theme. More themes can be downloaded from
// http://www.silverstripe.org/themes/
SSViewer::set_theme('$theme');
// Set the site locale
i18n::set_locale('$locale');
// Enable nested URLs for this site (e.g. page/sub-page/)
if (class_exists('SiteTree')) SiteTree::enable_nested_urls();
PHP
);
}

View File

@ -31,7 +31,7 @@ class PhpUnitWrapper_3_4 extends PhpUnitWrapper {
// blacklist selected folders from coverage report
$modules = $this->moduleDirectories();
foreach(TestRunner::$coverage_filter_dirs as $dir) {
foreach(TestRunner::config()->coverage_filter_dirs as $dir) {
if($dir[0] == '*') {
$dir = substr($dir, 1);
foreach ($modules as $module) {

View File

@ -43,7 +43,7 @@ class PhpUnitWrapper_3_5 extends PhpUnitWrapper {
$filter = $coverage->filter();
$modules = $this->moduleDirectories();
foreach(TestRunner::$coverage_filter_dirs as $dir) {
foreach(TestRunner::config()->coverage_filter_dirs as $dir) {
if($dir[0] == '*') {
$dir = substr($dir, 1);
foreach ($modules as $module) {

View File

@ -157,7 +157,7 @@ you can use `add_to_class()` as a replacement to `extraStatics()`.
}
// after
static $db = array(
private static $db = array(
'Title' => 'Varchar'
);

View File

@ -40,17 +40,89 @@ The configuration system added in SilverStripe 3.0 builds on this by using this
of defining the default value.
In SilverStripe 3.0, it was possible to edit this value at run-time and have the change propagate into the
configuration system. This is no longer the case, for performance reasons.
Many of the configuration variables have been changed to "private" so that attempts to change them throw an
error, but if you do have a configuration static that is able to be changed, and you change it, then the
configuration system will silently ignore it.
configuration system. This is no longer the case, for performance reasons. If you change a static value
through direct assignment, then the configuration system will silently ignore it.
Reading a static value directly will give you stale data.
When using static setters or getters, the system throws a deprecation warning.
Notable exceptions to this rule are all static setters which accept objects, such as `SS_Cache::add_backend()`.
Please change all run-time manipulation of configuration to use `Config::inst()->update()` or
`$this->config()->update()`. This mostly applies to changes in `_config.php`, which is
processed after the YAML and PHP statics configuration are compiled.
`$this->config()->update()`. You can keep using procedural configuration through `_config.php`
through this new notation, although its encouraged to use the (faster) YAML config wherever possible.
For this purpose, we have added a `mysite/_config/config.yml` file.
For more information about how to use the config system, see the ["Configuration" topic](/topic/configuration).
Here's an example on how to rewrite a common `_config.php` configuration:
:::php
<?php
global $project;
$project = 'mysite';
global $database;
$database = 'SS_mydb';
require_once('conf/ConfigureFromEnv.php');
SSViewer::set_theme('simple');
if(class_exists('SiteTree')) SiteTree::enable_nested_urls();
if(Director::isLive()) Email::setAdminEmail('support@mydomain.com');
if(is_defined('MY_REDIRECT_EMAILS')) Email::send_all_emails_to('developer@mydomain.com');
SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/mylog.log'), SS_Log::WARN);
if(strpos('Internet Explorer', $_SERVER['HTTP_USER_AGENT']) !== false) {
SSViewer::set_theme('basic');
}
The ugpraded `_config.php`:
:::php
<?php
global $project;
$project = 'mysite';
global $database;
$database = 'SS_mydb';
require_once('conf/ConfigureFromEnv.php');
// Removed SiteTree::enable_nested_urls() since its configured by default
// Requires PHP objects, keep in PHP config
SS_Log::add_writer(new SS_LogFileWriter(BASE_PATH . '/mylog.log'), SS_Log::WARN);
// Non-trivial conditional, keep in PHP config
if(strpos('Internet Explorer', $_SERVER['HTTP_USER_AGENT']) !== false) {
// Overwrites any earlier YAML config
Config::inst()->update('SSViewer'. 'theme', 'basic');
}
The upgraded `config.yml`:
:::yml
---
Name: mysite
After: 'framework/*','cms/*'
---
SSViewer:
theme: 'simple'
---
Only:
environment: 'live'
---
Email:
admin_email: 'support@mydomain.com'
Some examples of changed notations (not exhaustive, there's over a hundred in total):
* `SSViewer::set_theme()`: Use `SSViewer.theme` instead
* `SecurityAdmin::$hidden_permissions`: Use `Permission.hidden_permissions` instead
* `Director::setBaseFolder`: Use `Director.alternate_base_folder` instead
* `Director::setBaseURL`: Use `Director.alternate_base_url` instead
* `SSViewer::setOption('rewriteHashlinks', ...)`: Use `SSViewer.rewrite_hashlinks` instead
For more information about how to use the config system, see the ["Configuration" topic](/topic/configuration).
### default_cast is now Text
@ -68,7 +140,7 @@ or by defining the casting of the accessor method, like:
:::php
class Page extends SiteTree {
static $casting = array(
private static $casting = array(
'MyDiv' => 'HTMLText'
)

View File

@ -15,7 +15,7 @@ Default setting:
Overriding these defaults
* `[api:HTTP::set_cache_age()]` can be used to set the max-age component of the cache-control line, in seconds.
* `[api:HTTP::$cache_age]` can be used to set the max-age component of the cache-control line, in seconds.
Set it to 0 to disable caching; the "no-cache" clause in `Cache-Control` and `Pragma` will be included.
* `[api:HTTP::register_modification_date()]` can be used to set the modification date to something more recent than the default.

View File

@ -116,10 +116,9 @@ extras.
Continuing our example let's add a "constructive" style to our *Clean-up* button. First you need to be able to add
custom JS code into the CMS. You can do this by adding a new source file, here
`mysite/javascript/CMSMain.CustomActionsExtension.js`, and requiring it from the config.
:::ss
LeftAndMain::require_javascript('mysite/javascript/CMSMain.CustomActionsExtension.js');
`mysite/javascript/CMSMain.CustomActionsExtension.js`, and requiring it
through a YAML configuration value: `LeftAndMain.extra_requirements_javascript`.
Set it to 'mysite/javascript/CMSMain.CustomActionsExtension.js'.
You can now add the styling in response to `afterrefreshalternate` event. Let's use entwine to avoid accidental memory
leaks. The only complex part here is how the entwine handle is constructed. `onbuttonafterrefreshalternate` can be

View File

@ -48,13 +48,13 @@ The simplest way to use [api:CsvBulkLoader] is through a [api:ModelAdmin] interf
:::php
<?php
class PlayerAdmin extends ModelAdmin {
static $managed_models = array(
private static $managed_models = array(
'Player'
);
static $model_importers = array(
private static $model_importers = array(
'Player' => 'PlayerCsvBulkLoader',
);
static $url_segment = 'players';
private static $url_segment = 'players';
}
?>
@ -69,7 +69,7 @@ You can have more customized logic and interface feedback through a custom contr
<?php
class MyController extends Controller {
static $allowed_actions = array('Form');
private static $allowed_actions = array('Form');
protected $template = "BlankPage";
@ -126,13 +126,13 @@ Datamodel for Player
:::php
<?php
class Player extends DataObject {
static $db = array(
private static $db = array(
'PlayerNumber' => 'Int',
'FirstName' => 'Text',
'LastName' => 'Text',
'Birthday' => 'Date',
);
static $has_one = array(
private static $has_one = array(
'Team' => 'FootballTeam'
);
}
@ -144,10 +144,10 @@ Datamodel for FootballTeam:
:::php
<?php
class FootballTeam extends DataObject {
static $db = array(
private static $db = array(
'Title' => 'Text',
);
static $has_many = array(
private static $has_many = array(
'Players' => 'Player'
);
}

View File

@ -15,7 +15,7 @@ In this case we'll place the icon in `mysite/images`, but you are free to use an
:::php
class ProductAdmin extends ModelAdmin {
// ...
static $menu_icon = 'mysite/images/product-icon.png';
private static $menu_icon = 'mysite/images/product-icon.png';
}
## Defining a Custom Title ##
@ -27,7 +27,7 @@ removing the "Admin" bit at the end.
:::php
class ProductAdmin extends ModelAdmin {
// ...
static $menu_title = 'My Custom Admin';
private static $menu_title = 'My Custom Admin';
}
In order to localize the menu title in different languages, use the `<classname>.MENUTITLE`

View File

@ -20,12 +20,12 @@ hypothetical `NewsPageHolder` type, which contains `NewsPage` children.
:::php
// mysite/code/NewsPageHolder.php
class NewsPageHolder extends Page {
static $allowed_children = array('NewsPage');
private static $allowed_children = array('NewsPage');
}
// mysite/code/NewsPage.php
class NewsPage extends Page {
static $has_one = array(
private static $has_one = array(
'Author' => 'Member',
);
}

View File

@ -61,11 +61,8 @@ Paste the following content into a new file called `mysite/css/BookmarkedPages.c
.cms-bottom-bar ul li {float: left; margin-left: 1em;}
.cms-bottom-bar a {color: #444444;}
Load the new CSS file into the CMS, by adding the following line to `mysite/_config.php`:
:::php
<?php
LeftAndMain::require_css('mysite/css/BookmarkedPages.css');
Load the new CSS file into the CMS, by setting the `LeftAndMain.extra_requirements_css`
[configuration value](/topics/configuration) to 'mysite/css/BookmarkedPages.css'.
## Create a "bookmark" flag on pages ##
@ -76,7 +73,7 @@ Create a new file called `mysite/code/BookmarkedPageExtension.php` and insert th
:::php
<?php
class BookmarkedPageExtension extends DataExtension {
public static $db = array('IsBookmarked' => 'Boolean');
private static $db = array('IsBookmarked' => 'Boolean');
public function updateCMSFields(FieldList $fields) {
$fields->addFieldToTab('Root.Main',

View File

@ -36,7 +36,7 @@ will be used both for grouping and for the title in the template.
:::php
class Module extends DataObject {
public static $db = array(
private static $db = array(
'Title' => 'Text'
);

View File

@ -9,7 +9,7 @@ Let's start by defining a new `ContactPage` page type:
class ContactPage extends Page {
}
class ContactPage_Controller extends Page_Controller {
static $allowed_actions = array('Form');
private static $allowed_actions = array('Form');
public function Form() {
$fields = new FieldList(
new TextField('Name'),
@ -61,7 +61,7 @@ Now that we have a contact form, we need some way of collecting the data submitt
:::php
class ContactPage_Controller extends Page_Controller {
static $allowed_actions = array('Form');
private static $allowed_actions = array('Form');
public function Form() {
// ...
}

View File

@ -12,11 +12,13 @@ detailed error messages for security reasons. You'll typically need to get your
information.
If you can log-in to the CMS as an administrator, append `?isDev=1` to any URL to temporarily set your browsing session into
"dev mode". If you can't log-in in the first place because of the error, add this directive to your `mysite/_config.php`
"dev mode". If you can't log-in in the first place because of the error, add this directive to your `mysite/_config/config.yml`
(don't forget to remove it afterwards!):
:::php
Director::set_environment_type('dev'); // temporary debugging statement
Director:
# temporary debugging statement
environment_type: 'dev'
<div class="warning" markdown='1'>
On "live" environments, the `?isDev=1` solution is preferred, as it means that your other visitors don't see ugly

View File

@ -231,7 +231,7 @@ in a single Ajax request.
:::php
// mysite/code/MyAdmin.php
class MyAdmin extends LeftAndMain {
static $url_segment = 'myadmin';
private static $url_segment = 'myadmin';
public function getResponseNegotiator() {
$negotiator = parent::getResponseNegotiator();
$controller = $this;

View File

@ -52,10 +52,10 @@ The function should return a map where the keys are the names of the static vari
:::php
class CustomMember extends DataExtension {
static $db = array(
private static $db = array(
'AvatarURL' => 'Varchar',
);
static $has_one = array(
private static $has_one = array(
'RelatedMember' => 'Member',
);
}
@ -127,9 +127,9 @@ extended by.
:::php
class Customer extends DataObject {
static $has_one = array('Account'=>'Account');
private static $has_one = array('Account'=>'Account');
static $extensions = array(
private static $extensions = array(
'CustomerWorkflow'
);
@ -137,11 +137,11 @@ extended by.
class Account extends DataObject {
static $db = array(
private static $db = array(
'IsMarkedForDeletion'=>'Boolean'
);
static $has_many = array('Customers'=>'Customer');
private static $has_many = array('Customers'=>'Customer');
}

View File

@ -79,7 +79,7 @@ Example: Simple Definition
:::php
class MyDataObject extends DataObject {
static $searchable_fields = array(
private static $searchable_fields = array(
'Name',
'ProductCode'
);
@ -92,7 +92,7 @@ on `$searchable_fields`:
:::php
class MyDataObject extends DataObject {
static $searchable_fields = array(
private static $searchable_fields = array(
'Name' => 'PartialMatchFilter',
'ProductCode' => 'NumericField'
);
@ -104,7 +104,7 @@ assign an array:
:::php
class MyDataObject extends DataObject {
static $searchable_fields = array(
private static $searchable_fields = array(
'Name' => array(
'field' => 'TextField',
'filter' => 'PartialMatchFilter',
@ -122,23 +122,23 @@ To include relations (''$has_one'', `$has_many` and `$many_many`) in your search
:::php
class Team extends DataObject {
static $db = array(
private static $db = array(
'Title' => 'Varchar'
);
static $many_many = array(
private static $many_many = array(
'Players' => 'Player'
);
static $searchable_fields = array(
private static $searchable_fields = array(
'Title',
'Players.Name',
);
}
class Player extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Birthday' => 'Date'
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Teams' => 'Team'
);
}
@ -159,12 +159,12 @@ Example: Simple Definition
:::php
class MyDataObject extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Text',
'OtherProperty' => 'Text',
'ProductCode' => 'Int',
);
static $summary_fields = array(
private static $summary_fields = array(
'Name',
'ProductCode'
);
@ -175,18 +175,18 @@ To include relations in your summaries, you can use a dot-notation.
:::php
class OtherObject extends DataObject {
static $db = array(
private static $db = array(
'Title' => 'Varchar'
);
}
class MyDataObject extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Text'
);
static $has_one = array(
private static $has_one = array(
'OtherObject' => 'OtherObject'
);
static $summary_fields = array(
private static $summary_fields = array(
'Name',
'OtherObject.Title'
);

View File

@ -13,7 +13,7 @@ enter a date manually.
:::php
class Page extends SiteTree {
static $db = array(
private static $db = array(
'MyDate' => 'Date',
);

View File

@ -80,7 +80,7 @@ You can access the following controller-method with /team/signup
class Team_Controller extends Controller {
static $allowed_actions = array('signup');
private static $allowed_actions = array('signup');
public function signup($id, $otherId) {
return $this->renderWith('MyTemplate');

View File

@ -42,7 +42,7 @@ Here is an example where we display a basic gridfield with the default settings:
:::php
class GridController extends Page_Controller {
static $allowed_actions = array('index');
private static $allowed_actions = array('index');
public function index(SS_HTTPRequest $request) {
$this->Content = $this->AllPages();
@ -171,7 +171,7 @@ Example:
:::php
class Player extends DataObject {
public static $db = array('Name' => 'Text');
private static $db = array('Name' => 'Text');
public static $many_many = array('Teams' => 'Team');
public static $many_many_extraFields = array(
'Teams' => array('Position' => 'Text')
@ -197,7 +197,7 @@ Example:
}
class Team extends DataObject {
public static $db = array('Name' => 'Text');
private static $db = array('Name' => 'Text');
public static $many_many = array('Players' => 'Player');
}

View File

@ -45,7 +45,7 @@ You can defined subclasses of `[api:Member]` to add extra fields or functionalit
:::php
class MyMember extends Member {
static $db = array(
private static $db = array(
"Age" => "Int",
"Address" => "Text",
);
@ -113,11 +113,11 @@ things, you should add appropriate `[api:Permission::checkMember()]` calls to th
}
// define additional properties
static $db = array();
static $has_one = array();
static $has_many = array();
static $many_many = array();
static $belongs_many_many = array();
private static $db = array();
private static $has_one = array();
private static $has_many = array();
private static $many_many = array();
private static $belongs_many_many = array();
public function somethingElse() {
// You can add any other methods you like, which you can call directly on the member object.

View File

@ -20,12 +20,12 @@ A product can have a name, price, and a category.
:::php
class Product extends DataObject {
static $db = array('Name' => 'Varchar', 'ProductCode' => 'Varchar', 'Price' => 'Currency');
static $has_one = array('Category' => 'Category');
private static $db = array('Name' => 'Varchar', 'ProductCode' => 'Varchar', 'Price' => 'Currency');
private static $has_one = array('Category' => 'Category');
}
class Category extends DataObject {
static $db = array('Title' => 'Text');
static $has_many = array('Products' => 'Product');
private static $db = array('Title' => 'Text');
private static $has_many = array('Products' => 'Product');
}
To create your own `ModelAdmin`, simply extend the base class,
@ -36,9 +36,9 @@ We'll name it `MyAdmin`, but the class name can be anything you want.
:::php
class MyAdmin extends ModelAdmin {
public static $managed_models = array('Product','Category'); // Can manage multiple models
static $url_segment = 'products'; // Linked as /admin/products/
static $menu_title = 'My Product Admin';
private static $managed_models = array('Product','Category'); // Can manage multiple models
private static $url_segment = 'products'; // Linked as /admin/products/
private $menu_title = 'My Product Admin';
}
This will automatically add a new menu entry to the CMS, and you're ready to go!
@ -85,7 +85,7 @@ static on your model class (see `[SearchContext](/reference/searchcontext)` docs
:::php
class Product extends DataObject {
// ...
static $searchable_fields = array(
private static $searchable_fields = array(
'Name',
'ProductCode'
// leaves out the 'Price' field, removing it from the search
@ -105,10 +105,10 @@ where you can add or remove columns. To change the title, use `[api:DataObject::
:::php
class Product extends DataObject {
// ...
static $field_labels = array(
private static $field_labels = array(
'Price' => 'Cost' // renames the column to "Cost"
);
static $summary_fields = array(
private static $summary_fields = array(
'Name',
'Price',
// leaves out the 'ProductCode' field, removing the column

View File

@ -63,10 +63,13 @@ Note how the configuration happens in different entwine namespaces
});
}(jQuery));
Load the file in the CMS via an addition to `mysite/_config.php`:
Load the file in the CMS via setting adding 'mysite/javascript/MyLeftAndMain.Preview.js'
to the `LeftAndMain.extra_requirements_javascript` [configuration value](/topics/configuration)
:::php
LeftAndMain::require_javascript('mysite/javascript/MyLeftAndMain.Preview.js');
:::yml
LeftAndMain
extra_requirements_javascript:
- 'mysite/javascript/MyLeftAndMain.Preview.js'
In order to find out which configuration values are available, the source code
is your best reference at the moment - have a look in `framework/admin/javascript/LeftAndMain.Preview.js`.

View File

@ -45,13 +45,10 @@ reducing HTTP requests. Note that for debugging purposes combined files is disab
);
By default it stores the generated file in the assets/ folder but you can configure this by setting
By default it stores the generated file in the assets/ folder but you can configure this by pointing
the `Requirements.combined_files_folder` configuration setting to a specific folder.
:::php
// relative from the base folder
Requirements::set_combined_files_folder('folder');
If SilverStripe doesn't have permissions on your server to write these files it will default back to including them
individually .
@ -127,13 +124,8 @@ inheritance and overlays - please be careful when messing with the order of Requ
NOTE:
By default, SilverStripe includes all Javascript files at the bottom of the page body. If this causes problems for you,
for example if you're using animation that ends up showing everything until the bottom of the page loads, or shows
buttons before pushing them will actually work, you can change this behaviour:
In your controller's init() function, add:
:::php
Requirements::set_write_js_to_body(false);
buttons before pushing them will actually work, you can change this behaviour through
the `Requirements.write_js_to_body` configuration setting.
## CMS Requirements

View File

@ -36,7 +36,7 @@ method, we're building our own `getCustomSearchContext()` variant.
:::php
class MyDataObject extends DataObject {
static $db = array(
private static $db = array(
'PublicProperty' => 'Text'
'HiddenProperty' => 'Text',
'MyDate' => 'Date'

View File

@ -39,7 +39,7 @@ Create a mysite/code/CustomSiteConfig.php file.
class CustomSiteConfig extends DataExtension {
static $db = array(
private static $db = array(
'FooterContent' => 'HTMLText'
);

View File

@ -85,21 +85,21 @@ Example: Restrict blog entry pages to nesting underneath their blog holder
:::php
class BlogHolder extends Page {
// Blog holders can only contain blog entries
static $allowed_children = array("BlogEntry");
static $default_child = "BlogEntry";
private static $allowed_children = array("BlogEntry");
private static $default_child = "BlogEntry";
// ...
}
class BlogEntry extends Page {
// Blog entries can't contain children
static $allowed_children = "none";
static $can_be_root = false;
private static $allowed_children = "none";
private static $can_be_root = false;
// ...
}
class Page extends SiteTree {
// Don't let BlogEntry pages be underneath Pages. Only underneath Blog holders.
static $allowed_children = array("*Page,", "BlogHolder");
private static $allowed_children = array("*Page,", "BlogHolder");
}
@ -130,10 +130,10 @@ when navigating the tree or adding a new page:
:::php
class StaggPage extends Page {
static $singular_name = 'Staff Directory';
static $plural_name = 'Staff Directories';
static $description = 'Two-column layout with a list of staff members';
static $icon = 'mysite/images/staff-icon.png';
private static $singular_name = 'Staff Directory';
private static $plural_name = 'Staff Directories';
private static $description = 'Two-column layout with a list of staff members';
private static $icon = 'mysite/images/staff-icon.png';
// ...
}

View File

@ -125,7 +125,7 @@ An alternative approach would be a custom getter in the object definition.
:::php
class Player extends DataObject {
static $db = array(
private static $db = array(
'Name' =>
'Birthdate' => 'Date'
);

View File

@ -569,7 +569,7 @@ default if it exists and there is no action in the url parameters.
:::php
class MyPage_Controller extends Page_Controller {
static $allowed_actions = array('index');
private static $allowed_actions = array('index');
public function init(){
parent::init();
@ -614,10 +614,8 @@ would be created:
There are cases where this can be unhelpful. HTML fragments created from Ajax responses are the most common. In these
situations, you can disable fragment link rewriting like so:
:::php
SSViewer::setOption('rewriteHashlinks', false);
situations, you can disable fragment link rewriting by setting the
`SSViewer.rewrite_hash_links` configuration value to `false`.
### More Advanced Controls

View File

@ -21,7 +21,7 @@ based on a has_one relation:
:::php
class GalleryPage extends Page {
static $has_one = array(
private static $has_one = array(
'SingleImage' => 'Image'
);
@ -53,7 +53,7 @@ UploadField will detect the relation based on its $name property value:
:::php
class GalleryPage extends Page {
static $many_many = array(
private static $many_many = array(
'GalleryImages' => 'Image'
);
@ -110,7 +110,8 @@ the folder doesn't exist, it will be created.
## Limit the allowed filetypes
`AllowedExtensions` is by default `File::$allowed_extensions` but can be overwritten for each UploadField:
`AllowedExtensions` defaults to the `File.allowed_extensions` configuration setting,
but can be overwritten for each UploadField:
:::php
$uploadField->getValidator()->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif'));
@ -157,7 +158,7 @@ like this:
:::php
class GalleryImage extends DataExtension {
static $db = array(
private static $db = array(
'Description' => 'Text'
);
@ -169,7 +170,7 @@ like this:
Now register the DataExtension for the Image class in your _config.php:
:::php
Object::add_extension('Image', 'GalleryImage');
Image::add_extension('GalleryImage');
NOTE: although you can subclass the Image class instead of using a DataExtension, this is not advisable. For instance: when using a subclass, the 'From files' button will only return files that were uploaded for that subclass, it won't recognize any other images!
### Edit uploaded images

View File

@ -272,9 +272,8 @@ Notice that we can leave out the header in this case because there is only a sin
## Setting configuration via statics
The final location that a property can get it's value from is a static set on the associated class.
Statics should be considered immutable. Although in 3.0 the configuration system will include modified
statics during the merge, this is not guaranteed to always be the case.
Statics should be considered immutable, and therefore the majority of statics in SilverStripe
are marked `private`.
They should primarily be used to set the initial or default value for any given configuration property. It's also
a handy place to hand a docblock to indicate what a property is for. However, it's worth noting that you
@ -306,11 +305,6 @@ classes (see [common-problems](/installation/common-problems)).
Some constants are user-defineable within *_ss_environment.php*.
| Name | | Description |
| ---- | | ----------- |
| *TEMP_FOLDER* | | Absolute file path to store temporary files such as cached templates or the class manifest. Needs to be writeable by the webserver user. Defaults to *sys_get_temp_dir()*, and falls back to *silverstripe-cache* in the webroot. See *getTempFolder()* in *framework/core/Core.php* |
## No GUI configuration
SilverStripe framework does not provide a method to set configuration via a web panel
@ -324,7 +318,7 @@ In addition to these principle, some settings are
* Group-related configuration like `[api:HTMLEditorField]` settings can be found in the "Security" section (`admin/security`).
* Site-wide settings like page titles can be set (and extended) on the root tree element in the CMS "Content" section (through the [siteconfig](/reference/siteconfig) API).
## _ss_environment.php
## Constants and the _ss_environment.php File
See [environment-management](/topics/environment-management).

View File

@ -157,7 +157,7 @@ through `/fastfood/drivethrough/` to use the same order function.
:::php
class FastFood_Controller extends Controller {
static $allowed_actions = array('drivethrough');
private static $allowed_actions = array('drivethrough');
public static $url_handlers = array(
'drivethrough/$Action/$ID/$Name' => 'order'
);
@ -230,7 +230,7 @@ either `301` for permanent redirects, or `302` for temporary redirects (default)
You can also limit access to actions on a controller using the static `$allowed_actions` array. This allows you to always allow an action, or restrict it to a specific permission or to call a method that checks if the action is allowed.
For example, the default `Controller::$allowed_actions` is
static $allowed_actions = array(
private static $allowed_actions = array(
'handleAction',
'handleIndex',
);
@ -241,14 +241,14 @@ To allow any action on your controller to be called you can either leave your `$
The recommended approach is to explicitly state the actions that can be called via a URL. Any action not in the `$allowed_actions` array, excluding the default `index` method, is then unable to be called.
To always allow an action to be called, you can either add the name of the action to the array or add a value of `true` to the array, using the name of the method as its index. For example
static $allowed_actions = array(
private static $allowed_actions = array(
'MyAwesomeAction',
'MyOtherAction' => true
);
To require that the current user has a certain permission before being allowed to call an action you add the action to the array as an index with the value being the permission code that user must have. For example
static $allowed_actions = array(
private static $allowed_actions = array(
'MyAwesomeAction',
'MyOtherAction' => true,
'MyLimitedAction' => 'CMS_ACCESS_CMSMain',
@ -256,7 +256,7 @@ To require that the current user has a certain permission before being allowed t
);
If neither of these are enough to decide if an action should be called, you can have the check use a method. The method must be on the controller class and return true if the action is allowed or false if it isn't. To do this add the action to the array as an index with the value being the name of the method to called preceded by '->'. You are able to pass static arguments to the method in much the same way as you can with extensions. Strings are enclosed in quotes, numeric values are written as numbers and true and false are written as true and false. For example
static $allowed_actions = array(
private static $allowed_actions = array(
'MyAwesomeAction',
'MyOtherAction' => true,
'MyLimitedAction' => 'CMS_ACCESS_CMSMain',

View File

@ -327,7 +327,7 @@ Data is defined in the static variable $db on each class, in the format:
:::php
class Player extends DataObject {
public static $db = array(
private static $db = array(
"FirstName" => "Varchar",
"Surname" => "Varchar",
"Description" => "Text",
@ -346,7 +346,7 @@ default behaviour by making a function called "get`<fieldname>`" or "set`<fieldn
:::php
class Player extends DataObject {
public static $db = array(
private static $db = array(
"Status" => "Enum('Active, Injured, Retired')"
);
@ -616,7 +616,7 @@ Example: Validate postcodes based on the selected country
:::php
class MyObject extends DataObject {
public static $db = array(
private static $db = array(
'Country' => 'Varchar',
'Postcode' => 'Varchar'
);

View File

@ -6,20 +6,22 @@ Silverstripe knows three different environment-types (or "debug-levels"). Each o
and functionality. "dev", "test" and "live". You can either configure the environment of the site in the
mysite/_config.php file or in your [environment configuration file](/topics/environment-management).
The definition of setting an environment in your mysite/_config.php looks like
The definition of setting an environment in your `mysite/_config/config.yml` looks like
:::php
Director::set_environment_type("dev");
:::yml
Director:
environment_type: 'dev'
### Dev Mode
When developing your websites, adding page types or installing modules you should run your site in devmode. In this mode
you will be able to view full error backtraces and view the development tools without logging in as admin.
To set your site to dev mode set this in your mysite/_config.php file
To set your site to dev mode set this in your `mysite/_config/config.yml` file
:::php
Director::set_environment_type("dev");
:::yml
Director:
environment_type: 'dev'
Please note **devmode should not be enabled long term on live sites for security reasons**. In devmode by outputting
@ -35,18 +37,23 @@ not need to use test mode if you do not have a staging environment or a place fo
In this mode error messages are hidden from the user and it includes `[api:BasicAuth]` integration if you want to password
protect the site.
To set your site to test mode set this in your `mysite/_config.php` file
To set your site to test mode set this in your `mysite/_config/config.yml` file
:::php
Director::set_environment_type("test");
:::yml
Director:
environment_type: 'test'
A common situation is to enable password protected site viewing on your test site only. You can enable that but adding
this to your `mysite/_config` file
:::php
if(Director::isTest()) BasicAuth::protect_entire_site();
A common situation is to enable password protected site viewing on your test site only.
You can enable that but adding this to your `mysite/_config/config.yml` file:
:::yml
---
Only:
environment: 'test'
---
BasicAuth:
entire_site_protected: true
### Live Mode
@ -54,40 +61,37 @@ Live sites should always run in live mode. Error messages are suppressed from th
to email the developers. This enables near real time reporting of any fatal errors or warnings on the site and can help
find any bugs users run into.
To set your site to live mode set this in your `mysite/_config.php` file
:::php
Director::set_environment_type("live");
To set your site to live mode set this in your `mysite/_config/config.yml` file
:::yml
Director:
environment_type: 'live'
### Checking Environment Types
Use the following methods:
You can check for the current environment type in [config files](/topics/configuration) through the "environment" variant.
This is useful for example when you have various API keys on your site and separate ones for dev / live or for configuring
environment settings based on type .
---
Only:
environment: 'test'
---
MyClass:
myvar: myval
In addition, you can use the following methods in PHP code:
:::php
Director::isDev();
Director::isTest();
Director::isLive();
This is useful when you have various API keys on your site and separate ones for dev / live or for configuring
environment settings based on type
:::php
if(Director::isDev()) {
// this is for dev only
}
else {
// this is for the live site
}
## Email Errors
:::php
if(Director::isLive()) Debug::send_errors_to("your@email.com");
:::yml
Debug:
send_errors_to: 'your@email.com'
## Customizing Error-Output
@ -106,14 +110,13 @@ The Debug class contains a number of static methods
* *Debug::show($myVariable)*: performs a kind of *print_r($myVariable)*, but shows it in a more useful format.
* *Debug::message("Wow, that's great")*: prints a short debugging message.
* *SS_Backtrace::backtrace()*: prints a calls-stack
* *Debug::send_errors_to("sam@silverstripe.com")*: All errors will get sent to this address.
### Error handling
On development sites, we deal harshly with any warnings or errors: a full call-stack is shown and execution stops. This
is basically so that we deal with them promptly, since most warnings are indication that **something** is broken.
On live sites, all errors are emailed to the address specified in Debug::sendLiveErrorsTo($email)
On live sites, all errors are emailed to the address specified in the `Debug.send_errors_to` config setting.
### Debugging techniques

View File

@ -82,19 +82,21 @@ Usage:
### Administrator Emails
The static function `Email::setAdminEmail()` can be called from a `_config.php` file to set the address that these
emails should originate from. This address is used if the `from` field is empty.
You can influence the default sender address of emails through the `Email.admin_email`
[configuration setting](/topics/configuration). This address is used if the `from` field is empty.
### Redirecting Emails
* `Email::send_all_emails_to($address)` will redirect all emails sent to the given address. Handy for testing!
* `Email::cc_all_emails_to()` and `Email::bcc_all_emails_to()` will keep the email going to its original recipients, but
Further [configuration settings](/topics/configuration) relating to email rewriting:
* `Email.send_all_emails_to` will redirect all emails sent to the given address. Handy for testing!
* `Email.cc_all_emails_to` and `Email.bcc_all_emails_to` will keep the email going to its original recipients, but
add an additional recipient in the BCC/CC header. Good for monitoring system-generated correspondence on the live
systems.
:::php
if(Director::isLive()) Email::bcc_all_emails_to("client@example.com");
else Email::send_all_emails_to("developer@example.com");
if(Director::isLive()) Config::inst()->update('Email', 'bcc_all_emails_to', "client@example.com");
else Config::inst()->update('Email', 'send_all_emails_to', "developer@example.com");
### Setting Custom Headers

View File

@ -100,3 +100,32 @@ This is my `_ss_environment.php` file. I have it placed in `/var`, as each of th
// This is used by sake to know which directory points to which URL
global $_FILE_TO_URL_MAPPING;
$_FILE_TO_URL_MAPPING['/var/www'] = 'http://simon.geek.nz';
## Available Constants
| Name | Description |
| ---- | ----------- |
| `TEMP_FOLDER` | Absolute file path to store temporary files such as cached templates or the class manifest. Needs to be writeable by the webserver user. Defaults to *sys_get_temp_dir()*, and falls back to *silverstripe-cache* in the webroot. See *getTempFolder()* in *framework/core/Core.php* |
SS_DATABASE_CLASS: The database class to use, MySQLDatabase, MSSQLDatabase, etc. defaults to MySQLDatabase
| `SS_DATABASE_SERVER`| The database server to use, defaulting to localhost|
| `SS_DATABASE_USERNAME`| The database username (mandatory)|
| `SS_DATABASE_PASSWORD`| The database password (mandatory)|
| `SS_DATABASE_PORT`| The database port|
| `SS_DATABASE_SUFFIX`| A suffix to add to the database name.|
| `SS_DATABASE_PREFIX`| A prefix to add to the database name.|
| `SS_DATABASE_TIMEZONE`| Set the database timezone to something other than the system timezone.
| `SS_DATABASE_CHOOSE_NAME`| Boolean/Int. If set, then the system will choose a default database name for you if
one isn't give in the $database variable. The database name will be "SS_" followed by the name of the folder
into which you have installed SilverStripe. If this is enabled, it means that the phpinstaller will work out of
the box without the installer needing to alter any files. This helps prevent accidental changes to the
environment. If SS_DATABASE_CHOOSE_NAME is an integer greater than one, then an ancestor folder will be used for the
database name. This is handy for a site that's hosted from /sites/examplesite/www or /buildbot/allmodules-2.3/build.
If it's 2, the parent folder will be chosen; if it's 3 the grandparent, and so on.|
| `SS_ENVIRONMENT_TYPE`| The environment type: dev, test or live.|
| `SS_DEFAULT_ADMIN_USERNAME`| The username of the default admin - this is a non-database user with
administrative privileges.|
| `SS_DEFAULT_ADMIN_PASSWORD`| The password of the default admin.|
| `SS_USE_BASIC_AUTH`| Protect the site with basic auth (good for test sites)|
| `SS_SEND_ALL_EMAILS_TO`| If you set this define, all emails will be redirected to this address.|
| `SS_SEND_ALL_EMAILS_FROM`| If you set this define, all emails will be send from this address.|
| `SS_ERROR_LOG` | |

View File

@ -49,7 +49,7 @@ Example: Validate postcodes based on the selected country (on the controller).
:::php
class MyController extends Controller {
static $allowed_actions = array('Form');
private static $allowed_actions = array('Form');
public function Form() {
return Form::create($this, 'Form',
new FieldList(

View File

@ -85,7 +85,8 @@ while keeping characters recognizeable. For example, vowels with french accents
are replaced with their base characters, `pâté` becomes `pate`.
In order to allow for so called "multibyte" characters outside of the ASCII subset,
limit the character filtering in the underlying class: `URLSegmentFilter::$default_use_transliterator = false`
limit the character filtering in the underlying configuration setting,
by setting `URLSegmentFilter.default_use_transliterator` to `false` in your YAML configuration.
Please refer to [W3C: Introduction to IDN and IRI](http://www.w3.org/International/articles/idn-and-iri/) for more details.
@ -99,9 +100,9 @@ Date- and time related form fields support i18n ([api:DateField], [api:TimeField
$field->setLocale('de_DE'); // will not update the date formats
$field->setConfig('dateformat', 'dd. MMMM YYYY'); // sets typical 'de_DE' date format, shows as "23. Juni 1982"
Defaults can be applied globally for all field instances through [api:DateField::set_default_config()]
and [api:TimeField::set_default_config()]. If no 'locale' default is set on the field, [api:i18n::get_locale()]
will be used.
Defaults can be applied globally for all field instances through the `DateField.default_config`
and `TimeField.default_config` [configuration arrays](/topics/configuration).
If no 'locale' default is set on the field, [api:i18n::get_locale()] will be used.
**Important:** Form fields in the CMS are automatically configured according to the profile settings for the logged-in user (`Member->Locale`, `Member->DateFormat` and `Member->TimeFormat`). This means that in most cases,
fields created through [api:DataObject::getCMSFields()] will get their i18n settings from a specific member

View File

@ -52,7 +52,7 @@ especially useful if you know how long your source data needs to be.
:::php
class StaffPage extends Page {
static $db = array(
private static $db = array(
'Author' => 'Varchar(50)'
);
}

View File

@ -14,7 +14,7 @@ functionality. It is usually added through the `[api:DataObject->getCMSFields()]
:::php
class MyObject extends DataObject {
static $db = array('Content' => 'HTMLText');
private static $db = array('Content' => 'HTMLText');
public function getCMSFields() {
return new FieldList(new HTMLEditorField('Content'));

View File

@ -21,7 +21,7 @@ engine.
You can do so by adding this static variable to your class definition:
:::php
static $create_table_options = array(
private static $create_table_options = array(
'MySQLDatabase' => 'ENGINE=MyISAM'
);

View File

@ -79,7 +79,7 @@ Example:
:::php
class MyController extends Controller {
static $allowed_actions = array('myurlaction');
private static $allowed_actions = array('myurlaction');
public function myurlaction($RAW_urlParams) {
$SQL_urlParams = Convert::raw2sql($RAW_urlParams); // works recursively on an array
$objs = Player::get()->where("Name = '{$SQL_data[OtherID]}'");
@ -136,7 +136,7 @@ PHP:
:::php
class MyObject extends DataObject {
public static $db = array(
private static $db = array(
'MyEscapedValue' => 'Text', // Example value: <b>not bold</b>
'MyUnescapedValue' => 'HTMLText' // Example value: <b>bold</b>
);
@ -220,7 +220,7 @@ PHP:
:::php
class MyController extends Controller {
static $allowed_actions = array('search');
private static $allowed_actions = array('search');
public function search($request) {
$htmlTitle = '<p>Your results for:' . Convert::raw2xml($request->getVar('Query')) . '</p>';
return $this->customise(array(
@ -250,7 +250,7 @@ PHP:
:::php
class MyController extends Controller {
static $allowed_actions = array('search');
private static $allowed_actions = array('search');
public function search($request) {
$rssRelativeLink = "/rss?Query=" . urlencode($_REQUEST['query']) . "&sortOrder=asc";
$rssLink = Controller::join_links($this->Link(), $rssRelativeLink);

View File

@ -12,7 +12,7 @@ URLs. Here is an example from the subsites module:
:::php
class SubsiteAdminTest extends SapphireTest {
static $fixture_file = 'subsites/tests/SubsiteTest.yml';
private static $fixture_file = 'subsites/tests/SubsiteTest.yml';
/**
* Return a session that has a user logged in as an administrator

View File

@ -8,7 +8,7 @@ provides us the basics of creating unit tests.
class SiteTreeTest extends SapphireTest {
// Define the fixture file to use for this test class
static $fixture_file = 'SiteTreeTest.yml';
private static $fixture_file = 'SiteTreeTest.yml';
/**
* Test generation of the URLSegment values.

View File

@ -101,10 +101,12 @@ our theme in action. The code for mine is below.
$Form
All you have to do now is tell your site to use your new theme - This is defined in the **mysite/_config.php** file
All you have to do now is tell your site to use your new theme. This is defined through
the YAML config, for example in `mysite/_config/config.yml`.
:::php
SSViewer::set_theme('mythemename');
:::yml
SSViewer:
theme: 'mythemename'
Go to yoursite.com/?flush=1 and check it out. You should be using your new theme! Not really that awesome or amazing is

View File

@ -14,7 +14,7 @@ as a .tar.gz file.
1. Unpack the contents of the zip file into the `themes` directory in your SilverStripe installation.
2. Change the site to the theme. You can do this either by:
- putting the following line in your ./mysite/_config.php: `SSViewer::set_theme("themename");`
- Altering the `SSViewer.theme` setting in your `mysite/_config/config.yml`
- changing the theme in the Site Configuration panel in the CMS
3. Visit your homepage with ?flush=all appended to the URL. `http://yoursite.com?flush=all`

View File

@ -79,7 +79,7 @@ Let's create the *ArticleHolder* page type.
:::php
<?php
class ArticleHolder extends Page {
static $allowed_children = array('ArticlePage');
private static $allowed_children = array('ArticlePage');
}
class ArticleHolder_Controller extends Page_Controller {
}
@ -107,7 +107,7 @@ it. Add a *$db* property definition in the *ArticlePage* class:
:::php
<?php
class ArticlePage extends Page {
static $db = array(
private static $db = array(
'Date' => 'Date',
'Author' => 'Text'
);
@ -335,13 +335,13 @@ Let's now make a purely cosmetic change that nevertheless helps to make the info
Add the following field to the *ArticleHolder* and *ArticlePage* classes:
:::php
static $icon = "framework/docs/en/tutorials/_images/treeicons/news-file.gif";
private static $icon = "framework/docs/en/tutorials/_images/treeicons/news-file.gif";
And this one to the *HomePage* class:
:::php
static $icon = "framework/docs/en/tutorials/_images/treeicons/home-file.gif";
private static $icon = "framework/docs/en/tutorials/_images/treeicons/home-file.gif";
This will change the icons for the pages in the CMS.
@ -422,12 +422,9 @@ Now that we have a complete news section, let's take a look at the staff section
<?php
class StaffHolder extends Page {
static $db = array(
);
static $has_one = array(
);
static $allowed_children = array('StaffPage');
private static $db = array();
private static $has_one = array();
private static $allowed_children = array('StaffPage');
}
class StaffHolder_Controller extends Page_Controller {
@ -442,9 +439,9 @@ Nothing here should be new. The *StaffPage* page type is more interesting though
:::php
<?php
class StaffPage extends Page {
static $db = array(
private static $db = array(
);
static $has_one = array(
private static $has_one = array(
'Photo' => 'Image'
);

View File

@ -21,7 +21,7 @@ The poll we will be creating on our homepage will ask the user for their name an
:::php
class HomePage_Controller extends Page_Controller {
static $allowed_actions = array('BrowserPollForm');
private static $allowed_actions = array('BrowserPollForm');
// ...
@ -175,7 +175,7 @@ If you recall, in the [second tutorial](2-extending-a-basic-site) we said that a
:::php
<?php
class BrowserPollSubmission extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Text',
'Browser' => 'Text'
);

View File

@ -34,11 +34,11 @@ Let's create the `Student` and `Project` objects.
:::php
<?php
class Student extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'University' => 'Varchar',
);
static $has_one = array(
private static $has_one = array(
'Project' => 'Project'
);
}
@ -48,7 +48,7 @@ Let's create the `Student` and `Project` objects.
:::php
<?php
class Project extends Page {
static $has_many = array(
private static $has_many = array(
'Students' => 'Student'
);
}
@ -90,7 +90,7 @@ The restriction is enforced through the `$allowed_children` directive.
:::php
<?php
class ProjectsHolder extends Page {
static $allowed_children = array(
private static $allowed_children = array(
'Project'
);
}
@ -194,10 +194,10 @@ The first step is to create the `Mentor` object and set the relation with the `P
:::php
<?php
class Mentor extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Projects' => 'Project'
);
}
@ -207,7 +207,7 @@ The first step is to create the `Mentor` object and set the relation with the `P
:::php
class Project extends Page {
// ...
static $many_many = array(
private static $many_many = array(
'Mentors' => 'Mentor'
);
}

View File

@ -112,10 +112,11 @@ class Email extends ViewableData {
protected $template_data = null;
/**
* @param sring $admin_email_address The default administrator email address.
* @config
* @var string The default administrator email address.
* This will be set in the config on a site-by-site basis
*/
static $admin_email_address = '';
private static $admin_email_address = '';
/**
* Send every email generated by the Email class to the given address.
@ -124,10 +125,11 @@ class Email extends ViewableData {
*
* To set this, set Email.send_all_emails_to in your yml config file.
* It can also be set in _ss_environment.php with SS_SEND_ALL_EMAILS_TO.
*
*
* @config
* @param string $send_all_emails_to Email-Address
*/
protected static $send_all_emails_to = null;
private static $send_all_emails_to = null;
/**
* Send every email generated by the Email class *from* the given address.
@ -135,40 +137,23 @@ class Email extends ViewableData {
*
* To set this, set Email.send_all_emails_from in your yml config file.
* It can also be set in _ss_environment.php with SS_SEND_ALL_EMAILS_FROM.
*
*
* @config
* @param string $send_all_emails_from Email-Address
*/
protected static $send_all_emails_from = null;
private static $send_all_emails_from = null;
/**
* BCC every email generated by the Email class to the given address.
* It won't affect the original delivery in the same way that send_all_emails_to does. It just adds a BCC header
* with the given email address. Note that you can only call this once - subsequent calls will overwrite the
* configuration variable.
*
* This can be used when you have a system that relies heavily on email and you want someone to be checking all
* correspondence.
*
* To set this, set Email.bcc_all_emails_to in your yml config file.
*
* @param string $bcc_all_emails_to Email-Address
* @config
* @param string BCC every email generated by the Email class to the given address.
*/
protected static $bcc_all_emails_to = null;
private static $bcc_all_emails_to = null;
/**
* CC every email generated by the Email class to the given address.
* It won't affect the original delivery in the same way that send_all_emails_to does. It just adds a CC header
* with the given email address. Note that you can only call this once - subsequent calls will overwrite the
* configuration variable.
*
* This can be used when you have a system that relies heavily on email and you want someone to be checking all
* correspondence.
*
* To set this, set Email.cc_all_emails_to in your yml config file.
*
* @param string $cc_all_emails_to Email-Address
* @config
* @param string CC every email generated by the Email class to the given address.
*/
protected static $cc_all_emails_to = null;
private static $cc_all_emails_to = null;
/**
* Create a new email.
@ -364,7 +349,7 @@ class Email extends ViewableData {
* and it won't be plain email :)
*/
protected function parseVariables($isPlain = false) {
SSViewer::set_source_file_comments(false);
Config::inst()->update('SSViewer', 'source_file_comments', false);
if(!$this->parseVariables_done) {
$this->parseVariables_done = true;
@ -417,7 +402,7 @@ class Email extends ViewableData {
$this->parseVariables(true);
if(empty($this->from)) $this->from = Email::getAdminEmail();
if(empty($this->from)) $this->from = Email::config()->admin_email;
$headers = $this->customHeaders;
@ -482,7 +467,7 @@ class Email extends ViewableData {
$this->parseVariables();
if(empty($this->from)) $this->from = Email::getAdminEmail();
if(empty($this->from)) $this->from = Email::config()->admin_email;
$headers = $this->customHeaders;
@ -542,18 +527,22 @@ class Email extends ViewableData {
* as a contact address on system error pages.
*
* Used by {@link Email->send()}, {@link Email->sendPlain()}, {@link Debug->friendlyError()}.
*
*
* @deprecated 3.2 Use the "Email.admin_email" config setting instead
* @param string $newEmail
*/
public static function setAdminEmail($newEmail) {
self::$admin_email_address = $newEmail;
Deprecation::notice('3.2', 'Use the "Email.admin_email" config setting instead');
Config::inst()->update('Email', 'admin_email', $newEmail);
}
/**
* @deprecated 3.2 Use the "Email.admin_email" config setting instead
* @return string
*/
public static function getAdminEmail() {
return self::$admin_email_address;
Deprecation::notice('3.2', 'Use the "Email.admin_email" config setting instead');
return Config::inst()->get('Email', 'admin_email');
}
/**
@ -562,9 +551,12 @@ class Email extends ViewableData {
* This can be used when testing, by putting a command like this in your _config.php file
*
* if(!Director::isLive()) Email::send_all_emails_to("someone@example.com")
*
* @deprecated 3.2 Use the "Email.send_all_emails_to" config setting instead
*/
public static function send_all_emails_to($emailAddress) {
self::$send_all_emails_to = $emailAddress;
Deprecation::notice('3.2', 'Use the "Email.send_all_emails_to" config setting instead');
Config::inst()->update('Email', 'send_all_emails_to', $emailAddress);
}
/**
@ -577,9 +569,12 @@ class Email extends ViewableData {
* correspondence.
*
* if(Director::isLive()) Email::cc_all_emails_to("supportperson@example.com")
*
* @deprecated 3.2 Use the "Email.cc_all_emails_to" config setting instead
*/
public static function cc_all_emails_to($emailAddress) {
self::$cc_all_emails_to = $emailAddress;
Deprecation::notice('3.2', 'Use the "Email.cc_all_emails_to" config setting instead');
Config::inst()->update('Email', 'cc_all_emails_to', $emailAddress);
}
/**
@ -592,9 +587,12 @@ class Email extends ViewableData {
* correspondence.
*
* if(Director::isLive()) Email::cc_all_emails_to("supportperson@example.com")
*
* @deprecated 3.2 Use the "Email.bcc_all_emails_to" config setting instead
*/
public static function bcc_all_emails_to($emailAddress) {
self::$bcc_all_emails_to = $emailAddress;
Deprecation::notice('3.2', 'Use the "Email.bcc_all_emails_to" config setting instead');
Config::inst()->update('Email', 'bcc_all_emails_to', $emailAddress);
}
/**

View File

@ -64,13 +64,13 @@
*/
class File extends DataObject {
static $default_sort = "\"Name\"";
private static $default_sort = "\"Name\"";
static $singular_name = "File";
private static $singular_name = "File";
static $plural_name = "Files";
private static $plural_name = "Files";
static $db = array(
private static $db = array(
"Name" => "Varchar(255)",
"Title" => "Varchar(255)",
"Filename" => "Text",
@ -79,24 +79,25 @@ class File extends DataObject {
'ShowInSearch' => 'Boolean(1)',
);
static $has_one = array(
private static $has_one = array(
"Parent" => "File",
"Owner" => "Member"
);
static $has_many = array();
private static $has_many = array();
static $many_many = array();
private static $many_many = array();
static $defaults = array(
private static $defaults = array(
"ShowInSearch" => 1,
);
static $extensions = array(
private static $extensions = array(
"Hierarchy",
);
/**
* @config
* @var array List of allowed file extensions, enforced through {@link validate()}.
*
* Note: if you modify this, you should also change a configuration file in the assets directory.
@ -108,7 +109,7 @@ class File extends DataObject {
*
* Instructions for the change you need to make are included in a comment in the config file.
*/
public static $allowed_extensions = array(
private static $allowed_extensions = array(
'','html','htm','xhtml','js','css',
'bmp','png','gif','jpg','jpeg','ico','pcx','tif','tiff',
'au','mid','midi','mpa','mp3','ogg','m4a','ra','wma','wav','cda',
@ -120,9 +121,10 @@ class File extends DataObject {
);
/**
* @config
* @var array Category identifiers mapped to commonly used extensions.
*/
static $app_categories = array(
private static $app_categories = array(
'audio' => array(
"aif" ,"au" ,"mid" ,"midi" ,"mp3" ,"ra" ,"ram" ,"rm","mp3" ,"wav" ,"m4a" ,"snd" ,"aifc" ,"aiff" ,"wma",
"apl", "avr" ,"cda" ,"mp4" ,"ogg"
@ -145,13 +147,18 @@ class File extends DataObject {
);
/**
* @config
* @var If this is true, then restrictions set in {@link $allowed_max_file_size} and
* {@link $allowed_extensions} will be applied to users with admin privileges as
* well.
*/
public static $apply_restrictions_to_admin = true;
private static $apply_restrictions_to_admin = true;
public static $update_filesystem = true;
/**
* @config
* @var boolean
*/
private static $update_filesystem = true;
/**
* Cached result of a "SHOW FIELDS" call
@ -322,7 +329,10 @@ class File extends DataObject {
public function getCMSFields() {
// Preview
if($this instanceof Image) {
$formattedImage = $this->getFormattedImage('SetWidth', Image::$asset_preview_width);
$formattedImage = $this->getFormattedImage(
'SetWidth',
Config::inst()->get('Image', 'asset_preview_width')
);
$thumbnail = $formattedImage ? $formattedImage->URL : '';
$previewField = new LiteralField("ImageFull",
"<img id='thumbnailImage' class='thumbnail-preview' src='{$thumbnail}?r="
@ -399,7 +409,7 @@ class File extends DataObject {
*/
public static function get_app_category($ext) {
$ext = strtolower($ext);
foreach(self::$app_categories as $category => $exts) {
foreach(Config::inst()->get('File', 'app_categories') as $category => $exts) {
if(in_array($ext, $exts)) return $category;
}
return false;
@ -488,7 +498,7 @@ class File extends DataObject {
* (it might have been influenced by {@link setName()} or {@link setParentID()} before).
*/
public function updateFilesystem() {
if(!self::$update_filesystem) return false;
if(!$this->config()->update_filesystem) return false;
// Regenerate "Filename", just to be sure
$this->setField('Filename', $this->getRelativePath());
@ -860,11 +870,11 @@ class File extends DataObject {
}
public function validate() {
if(File::$apply_restrictions_to_admin || !Permission::check('ADMIN')) {
if($this->config()->apply_restrictions_to_admin || !Permission::check('ADMIN')) {
// Extension validation
// TODO Merge this with Upload_Validator
$extension = $this->getExtension();
$allowed = array_map('strtolower', self::$allowed_extensions);
$allowed = array_map('strtolower', $this->config()->allowed_extensions);
if($extension && !in_array(strtolower($extension), $allowed)) {
$exts = $allowed;
sort($exts);
@ -888,9 +898,10 @@ class File extends DataObject {
}
/**
* @config
* @var Array Only use lowercase extensions in here.
*/
static $class_for_file_extension = array(
private static $class_for_file_extension = array(
'*' => 'File',
'jpg' => 'Image',
'jpeg' => 'Image',
@ -914,7 +925,7 @@ class File extends DataObject {
* @return String Classname for a subclass of {@link File}
*/
public static function get_class_for_file_extension($ext) {
$map = array_change_key_case(self::$class_for_file_extension, CASE_LOWER);
$map = array_change_key_case(self::config()->class_for_file_extension, CASE_LOWER);
return (array_key_exists(strtolower($ext), $map)) ? $map[strtolower($ext)] : $map['*'];
}
@ -933,7 +944,7 @@ class File extends DataObject {
sprintf('Class "%s" (for extension "%s") is not a valid subclass of File', $class, $ext)
);
}
self::$class_for_file_extension[$ext] = $class;
self::config()->class_for_file_extension = array($ext => $class);
}
}

View File

@ -32,7 +32,7 @@ class SS_FileFinder {
/**
* @var array
*/
public static $vcs_dirs = array(
protected static $vcs_dirs = array(
'.git', '.svn', '.hg', '.bzr'
);
@ -45,7 +45,7 @@ class SS_FileFinder {
*
* @var array
*/
public static $default_options = array(
protected static $default_options = array(
'name_regex' => null,
'accept_callback' => null,
'accept_dir_callback' => null,

View File

@ -18,10 +18,11 @@
* via overriding {@link FileNameFilter_DefaultFilter::$default_replacements}.
*
* To leave uploaded filenames as they are (being aware of filesystem restrictions),
* add the following code to your _config.php:
* add the following code to your YAML config:
* <code>
* FileNameFilter::$default_use_transliterator = false;
* FileNameFilter::$default_replacements = array();
* FileNameFilter:
* default_use_transliterator: false
* default_replacements:
* </code>
*
* See {@link URLSegmentFilter} for a more generic implementation.
@ -29,14 +30,16 @@
class FileNameFilter extends Object {
/**
* @config
* @var Boolean
*/
static $default_use_transliterator = true;
private static $default_use_transliterator = true;
/**
* @config
* @var Array See {@link setReplacements()}.
*/
static $default_replacements = array(
private static $default_replacements = array(
'/\s/' => '-', // remove whitespace
'/_/' => '-', // underscores to dashes
'/[^A-Za-z0-9+.\-]+/' => '', // remove non-ASCII chars, only allow alphanumeric plus dash and dot
@ -87,7 +90,7 @@ class FileNameFilter extends Object {
* @return Array
*/
public function getReplacements() {
return ($this->replacements) ? $this->replacements : self::$default_replacements;
return ($this->replacements) ? $this->replacements : (array)$this->config()->default_replacements;
}
/**
@ -99,7 +102,7 @@ class FileNameFilter extends Object {
* @return SS_Transliterator|NULL
*/
public function getTransliterator() {
if($this->transliterator === null && self::$default_use_transliterator) {
if($this->transliterator === null && $this->config()->default_use_transliterator) {
$this->transliterator = SS_Transliterator::create();
}
return $this->transliterator;

View File

@ -7,9 +7,17 @@
*/
class Filesystem extends Object {
public static $file_create_mask = 02775;
/**
* @config
* @var integer Integer
*/
private static $file_create_mask = 02775;
public static $folder_create_mask = 02775;
/**
* @config
* @var integer Integer
*/
private static $folder_create_mask = 02775;
protected static $cache_folderModTime;
@ -23,7 +31,7 @@ class Filesystem extends Object {
*/
public static function makeFolder($folder) {
if(!file_exists($base = dirname($folder))) self::makeFolder($base);
if(!file_exists($folder)) mkdir($folder, Filesystem::$folder_create_mask);
if(!file_exists($folder)) mkdir($folder, Config::inst()->get('Filesystem', 'folder_create_mask'));
}
/**

View File

@ -19,11 +19,11 @@
*/
class Folder extends File {
static $singular_name = "Folder";
private static $singular_name = "Folder";
static $plural_name = "Folders";
private static $plural_name = "Folders";
static $default_sort = "\"Name\"";
private static $default_sort = "\"Name\"";
/**
*

View File

@ -8,15 +8,22 @@ class GDBackend extends Object implements Image_Backend {
protected $gd, $width, $height;
protected $quality;
protected static $default_quality = 75;
/**
* @config
* @var integer
*/
private static $default_quality = 75;
/**
* Set the default image quality.
*
* @deprecated 3.2 Use the "GDBackend.default_quality" config setting instead
* @param quality int A number from 0 to 100, 100 being the best quality.
*/
public static function set_default_quality($quality) {
Deprecation::notice('3.2', 'Use the "GDBackend.default_quality" config setting instead');
if(is_numeric($quality) && (int) $quality >= 0 && (int) $quality <= 100) {
self::$default_quality = (int) $quality;
Config::inst()->set('GDBackend', 'default_quality', (int) $quality);
}
}
@ -46,8 +53,9 @@ class GDBackend extends Object implements Image_Backend {
}
}
$this->quality = self::$default_quality;
parent::__construct();
$this->quality = $this->config()->default_quality;
}
public function setImageResource($resource) {
@ -431,7 +439,7 @@ class GDBackend extends Object implements Image_Backend {
public function makeDir($dirname) {
if(!file_exists(dirname($dirname))) $this->makeDir(dirname($dirname));
if(!file_exists($dirname)) mkdir($dirname, Filesystem::$folder_create_mask);
if(!file_exists($dirname)) mkdir($dirname, Config::inst()->get('Filesystem', 'folder_create_mask'));
}
public function writeTo($filename) {
@ -471,12 +479,12 @@ class GDBackend extends Object implements Image_Backend {
* Backwards compatibility
*/
class GD extends GDBackend {
/**
* @deprecated 3.2 Use the "GDBackend.default_quality" config setting instead
*/
public static function set_default_quality($quality) {
Deprecation::notice(
'3.1',
'GDBackend::set_default_quality instead',
Deprecation::SCOPE_CLASS
);
Deprecation::notice('3.2', 'Use the "GDBackend.default_quality" config setting instead');
GDBackend::set_default_quality($quality);
}
}

View File

@ -9,9 +9,10 @@ if(class_exists('Imagick')) {
class ImagickBackend extends Imagick implements Image_Backend {
/**
* @config
* @var int
*/
protected static $default_quality = 75;
private static $default_quality = 75;
/**
* __construct
@ -23,7 +24,7 @@ class ImagickBackend extends Imagick implements Image_Backend {
if(is_string($filename)) {
parent::__construct($filename);
} else {
self::setImageCompressionQuality(self::$default_quality);
self::setImageCompressionQuality($this->config()->default_quality);
}
}
@ -42,12 +43,15 @@ class ImagickBackend extends Imagick implements Image_Backend {
/**
* set_default_quality
*
* @static
* @deprecated 3.2 Use the "IMagickBackend.default_quality" config setting instead
* @param int $quality
* @return void
*/
public static function set_default_quality($quality) {
self::$default_quality = $quality;
Deprecation::notice('3.2', 'Use the "IMagickBackend.default_quality" config setting instead');
if(is_numeric($quality) && (int) $quality >= 0 && (int) $quality <= 100) {
Config::inst()->set('IMagickBackend', 'default_quality', (int) $quality);
}
}
/**

View File

@ -21,7 +21,7 @@
*/
class Upload extends Controller {
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'load'
);
@ -64,14 +64,15 @@ class Upload extends Controller {
* A foldername relative to /assets,
* where all uploaded files are stored by default.
*
* @config
* @var string
*/
public static $uploads_folder = "Uploads";
private static $uploads_folder = "Uploads";
public function __construct() {
parent::__construct();
$this->validator = new Upload_Validator();
$this->replaceFile = $this->config()->get('replaceFile');
$this->replaceFile = $this->config()->replaceFile;
}
/**
@ -105,7 +106,7 @@ class Upload extends Controller {
public function load($tmpFile, $folderPath = false) {
$this->clearErrors();
if(!$folderPath) $folderPath = self::$uploads_folder;
if(!$folderPath) $folderPath = $this->config()->uploads_folder;
if(!is_array($tmpFile)) {
user_error("Upload::load() Not passed an array. Most likely, the form hasn't got the right enctype",
@ -127,10 +128,10 @@ class Upload extends Controller {
// Create a folder for uploading.
if(!file_exists(ASSETS_PATH)){
mkdir(ASSETS_PATH, Filesystem::$folder_create_mask);
mkdir(ASSETS_PATH, Config::inst()->get('Filesystem', 'folder_create_mask'));
}
if(!file_exists(ASSETS_PATH . "/" . $folderPath)){
mkdir(ASSETS_PATH . "/" . $folderPath, Filesystem::$folder_create_mask);
mkdir(ASSETS_PATH . "/" . $folderPath, Config::inst()->get('Filesystem', 'folder_create_mask'));
}
// Generate default filename

View File

@ -13,13 +13,13 @@ class CountryDropdownField extends DropdownField {
* Should we default the dropdown to the region determined from the user's locale?
* @var bool
*/
static $default_to_locale = true;
private static $default_to_locale = true;
/**
* The region code to default to if default_to_locale is set to false, or we can't determine a region from a locale
* @var string
*/
static $default_country = 'NZ';
private static $default_country = 'NZ';
protected $extraClasses = array('dropdown');
@ -59,7 +59,7 @@ class CountryDropdownField extends DropdownField {
$source = $this->getSource();
if (!$this->value || !isset($source[$this->value])) {
if ($this->config()->get('default_to_locale') && $this->locale()) {
if ($this->config()->default_to_locale && $this->locale()) {
$locale = new Zend_Locale();
$locale->setLocale($this->locale());
$this->value = $locale->getRegion();
@ -67,7 +67,7 @@ class CountryDropdownField extends DropdownField {
}
if (!$this->value || !isset($source[$this->value])) {
$this->value = $this->config()->get('default_country');
$this->value = $this->config()->default_country;
}
return parent::Field();

View File

@ -58,9 +58,10 @@ require_once 'Zend/Date.php';
class DateField extends TextField {
/**
* @config
* @var array
*/
static $default_config = array(
private static $default_config = array(
'showcalendar' => false,
'jslocale' => null,
'dmyfields' => false,
@ -94,13 +95,12 @@ class DateField extends TextField {
$this->locale = i18n::get_locale();
}
$this->config = self::$default_config;
$this->config = $this->config()->default_config;
if(!$this->getConfig('dateformat')) {
$this->setConfig('dateformat', i18n::get_date_format());
}
foreach (self::$default_config AS $defaultK => $defaultV) {
foreach ($this->config()->default_config AS $defaultK => $defaultV) {
if ($defaultV) {
if ($defaultK=='locale')
$this->locale = $defaultV;
@ -321,16 +321,14 @@ class DateField extends TextField {
}
/**
* @deprecated 3.2 Use the "DateField.default_config" config setting instead
* @param String $k
* @param mixed $v
* @return boolean
*/
public static function set_default_config($k, $v) {
if (array_key_exists($k,self::$default_config)) {
self::$default_config[$k]=$v;
return true;
}
return false;
Deprecation::notice('3.2', 'Use the "DateField.default_config" config setting instead');
return Config::inst()->update('DateField', 'default_config', array($k => $v));
}
/**
@ -457,7 +455,11 @@ class DateField extends TextField {
* @return mixed|array
*/
public function getConfig($name = null) {
return $name ? $this->config[$name] : $this->config;
if($name) {
return isset($this->config[$name]) ? $this->config[$name] : null;
} else {
return $this->config;
}
}
}
@ -517,10 +519,10 @@ class DateField_View_JQuery extends Object {
protected $jqueryLocaleFile = '';
/**
* @var array Maps values from {@link i18n::$all_locales()} to
* @var array Maps values from {@link i18n::$all_locales} to
* localizations existing in jQuery UI.
*/
static $locale_map = array(
private static $locale_map = array(
'en_GB' => 'en-GB',
'en_US' => 'en',
'en_NZ' => 'en-GB',
@ -595,12 +597,13 @@ class DateField_View_JQuery extends Object {
*/
protected function getLang() {
$locale = $this->getField()->getLocale();
$map = $this->config()->locale_map;
if($this->getField()->getConfig('jslocale')) {
// Undocumented config property for now, might move to the jQuery view helper
$lang = $this->getField()->getConfig('jslocale');
} else if(array_key_exists($locale, self::$locale_map)) {
} else if(array_key_exists($locale, $map)) {
// Specialized mapping for combined lang properties
$lang = self::$locale_map[$locale];
$lang = $map[$locale];
} else {
// Fall back to default lang (meaning "en_US" turns into "en")
$lang = i18n::get_lang_from_locale($locale);

View File

@ -42,9 +42,10 @@ class DatetimeField extends FormField {
protected $timeField = null;
/**
* @config
* @var array
*/
static $default_config = array(
private static $default_config = array(
'datavalueformat' => 'YYYY-MM-dd HH:mm:ss',
'usertimezone' => null,
'datetimeorder' => '%s %s',
@ -56,7 +57,7 @@ class DatetimeField extends FormField {
protected $config;
public function __construct($name, $title = null, $value = ""){
$this->config = self::$default_config;
$this->config = $this->config()->default_config;
$this->dateField = DateField::create($name . '[date]', false)
->addExtraClass('fieldgroup-field');
@ -302,7 +303,11 @@ class DatetimeField extends FormField {
* @return mixed
*/
public function getConfig($name = null) {
return $name ? $this->config[$name] : $this->config;
if($name) {
return isset($this->config[$name]) ? $this->config[$name] : null;
} else {
return $this->config;
}
}
public function validate($validator) {

View File

@ -160,7 +160,7 @@ class FileField extends FormField {
* @return string
*/
public function getFolderName() {
return ($this->folderName !== false) ? $this->folderName : Upload::$uploads_folder;
return ($this->folderName !== false) ? $this->folderName : Config::inst()->get('Upload', 'uploads_folder');
}
public function validate($validator) {

View File

@ -197,7 +197,7 @@ class Form extends RequestHandler {
$this->securityToken = ($securityEnabled) ? new SecurityToken() : new NullSecurityToken();
}
static $url_handlers = array(
private static $url_handlers = array(
'field/$FieldName!' => 'handleField',
'POST ' => 'httpSubmission',
'GET ' => 'httpSubmission',

View File

@ -13,8 +13,9 @@
*/
class HtmlEditorConfig {
static $configs = array();
static $current = null;
private static $configs = array();
private static $current = null;
/**
* Get the HtmlEditorConfig object for the given identifier. This is a correct way to get an HtmlEditorConfig

View File

@ -9,9 +9,10 @@
class HtmlEditorField extends TextareaField {
/**
* @config
* @var Boolean Use TinyMCE's GZIP compressor
*/
static $use_gzip = true;
private static $use_gzip = true;
protected $rows = 30;
@ -23,7 +24,7 @@ class HtmlEditorField extends TextareaField {
$configObj = HtmlEditorConfig::get_active();
if(self::$use_gzip) {
if(Config::inst()->get('HtmlEditorField', 'use_gzip')) {
$internalPlugins = array();
foreach($configObj->getPlugins() as $plugin => $path) if(!$path) $internalPlugins[] = $plugin;
$tag = TinyMCE_Compressor::renderTag(array(
@ -241,7 +242,7 @@ class HtmlEditorField_Readonly extends ReadonlyField {
*/
class HtmlEditorField_Toolbar extends RequestHandler {
static $allowed_actions = array(
private static $allowed_actions = array(
'LinkForm',
'MediaForm',
'viewfile'
@ -424,7 +425,7 @@ class HtmlEditorField_Toolbar extends RequestHandler {
$computerUploadField->addExtraClass('ss-assetuploadfield');
$computerUploadField->removeExtraClass('ss-uploadfield');
$computerUploadField->setTemplate('HtmlEditorField_UploadField');
$computerUploadField->setFolderName(Upload::$uploads_folder);
$computerUploadField->setFolderName(Config::inst()->get('Upload', 'uploads_folder'));
$tabSet = new TabSet(
"MediaFormInsertMediaTabs",

View File

@ -24,9 +24,10 @@ require_once 'Zend/Date.php';
class TimeField extends TextField {
/**
* @config
* @var array
*/
static $default_config = array(
private static $default_config = array(
'timeformat' => null,
'use_strtotime' => true,
'datavalueformat' => 'HH:mm:ss'
@ -54,7 +55,7 @@ class TimeField extends TextField {
$this->locale = i18n::get_locale();
}
$this->config = self::$default_config;
$this->config = $this->config()->default_config;
if(!$this->getConfig('timeformat')) {
$this->setConfig('timeformat', i18n::get_time_format());
@ -184,7 +185,11 @@ class TimeField extends TextField {
* @return mixed|array
*/
public function getConfig($name = null) {
return $name ? $this->config[$name] : $this->config;
if($name) {
return isset($this->config[$name]) ? $this->config[$name] : null;
} else {
return $this->config;
}
}
/**

View File

@ -42,11 +42,11 @@
class TreeDropdownField extends FormField {
public static $url_handlers = array(
private static $url_handlers = array(
'$Action!/$ID' => '$Action'
);
public static $allowed_actions = array(
private static $allowed_actions = array(
'tree'
);

View File

@ -31,7 +31,7 @@ class UploadField extends FileField {
/**
* @var array
*/
public static $allowed_actions = array(
private static $allowed_actions = array(
'upload',
'attach',
'handleItem',
@ -41,7 +41,7 @@ class UploadField extends FileField {
/**
* @var array
*/
public static $url_handlers = array(
private static $url_handlers = array(
'item/$ID' => 'handleItem',
'select' => 'handleSelect',
'$Action!' => '$Action',
@ -158,7 +158,9 @@ class UploadField extends FileField {
if($items) $this->setItems($items);
// filter out '' since this would be a regex problem on JS end
$this->getValidator()->setAllowedExtensions(array_filter(File::$allowed_extensions));
$this->getValidator()->setAllowedExtensions(
array_filter(Config::inst()->get('File', 'allowed_extensions'))
);
// get the lower max size
$this->getValidator()->setAllowedMaxFileSize(min(File::ini2bytes(ini_get('upload_max_filesize')),
File::ini2bytes(ini_get('post_max_size'))));
@ -688,7 +690,7 @@ class UploadField_ItemHandler extends RequestHandler {
*/
protected $itemID;
public static $url_handlers = array(
private static $url_handlers = array(
'$Action!' => '$Action',
'' => 'index',
);
@ -918,7 +920,7 @@ class UploadField_SelectHandler extends RequestHandler {
*/
protected $folderName;
public static $url_handlers = array(
private static $url_handlers = array(
'$Action!' => '$Action',
'' => 'index',
);

View File

@ -24,7 +24,7 @@ class GridField extends FormField {
*
* @var array
*/
public static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'gridFieldAlterAction'
);

View File

@ -220,7 +220,7 @@ class GridFieldDetailForm_ItemRequest extends RequestHandler {
*/
protected $template = 'GridFieldItemEditView';
static $url_handlers = array(
private static $url_handlers = array(
'$Action!' => '$Action',
'' => 'edit',
);

View File

@ -32,10 +32,11 @@ class GridFieldPageCount implements GridField_HTMLProvider {
/**
* Flag indicating whether or not this control should throw an error if a
* {@link GridFieldPaginator} is not present on the same {@link GridField}
*
*
* @config
* @var boolean
*/
public static $require_paginator = true;
private static $require_paginator = true;
/**
* Retrieves an instance of a GridFieldPaginator attached to the same control
@ -46,7 +47,7 @@ class GridFieldPageCount implements GridField_HTMLProvider {
protected function getPaginator($gridField) {
$paginator = $gridField->getConfig()->getComponentByType('GridFieldPaginator');
if(!$paginator && self::$require_paginator) {
if(!$paginator && Config::inst()->get('GridFieldPageCount', 'require_paginator')) {
throw new LogicException(
get_class($this) . " relies on a GridFieldPaginator to be added " .
"to the same GridField, but none are present."

View File

@ -69,24 +69,28 @@ class i18n extends Object implements TemplateGlobalProvider {
protected static $current_locale = '';
/**
* @config
* @var string
*/
protected static $default_locale = 'en_US';
private static $default_locale = 'en_US';
/**
* @config
* @var boolean
*/
protected static $js_i18n = true;
private static $js_i18n = true;
/**
* @config
* @var string
*/
protected static $date_format;
private static $date_format;
/**
* @config
* @var string
*/
protected static $time_format;
private static $time_format;
/**
* @var array Array of priority keys to instances of Zend_Translate, mapped by name.
@ -107,24 +111,30 @@ class i18n extends Object implements TemplateGlobalProvider {
*
* @see Requirements::process_i18n_javascript()
*
* @deprecated 3.2 Use the "i18n.js_i18n" config setting instead
* @param bool $bool
*/
public static function set_js_i18n($bool) {
self::$js_i18n = $bool;
Deprecation::notice('3.2', 'Use the "i18n.js_i18n" config setting instead');
Config::inst()->update('i18n', 'js_i18n', $bool);
}
/**
* @deprecated 3.2 Use the "i18n.js_i18n" config setting instead
* @return bool
*/
public static function get_js_i18n() {
Deprecation::notice('3.2', 'Use the "i18n.js_i18n" config setting instead');
return self::$js_i18n;
}
/**
* @deprecated 3.2 Use the "i18n.date_format" config setting instead
* @param string ISO date format
*/
public static function set_date_format($format) {
self::$date_format = $format;
Deprecation::notice('3.2', 'Use the "i18n.date_format" config setting instead');
Config::inst()->update('i18n', 'date_format', $format);
}
/**
@ -132,14 +142,17 @@ class i18n extends Object implements TemplateGlobalProvider {
*/
public static function get_date_format() {
require_once 'Zend/Date.php';
return (self::$date_format) ? self::$date_format : Zend_Locale_Format::getDateFormat(self::get_locale());
$dateFormat = Config::inst()->get('i18n', 'date_format');
return ($dateFormat) ? $dateFormat : Zend_Locale_Format::getDateFormat(self::get_locale());
}
/**
* @deprecated 3.2 Use the "i18n.time_format" config setting instead
* @param string ISO time format
*/
public static function set_time_format($format) {
self::$time_format = $format;
Deprecation::notice('3.2', 'Use the "i18n.time_format" config setting instead');
Config::inst()->update('i18n', 'time_format', $format);
}
/**
@ -147,15 +160,17 @@ class i18n extends Object implements TemplateGlobalProvider {
*/
public static function get_time_format() {
require_once 'Zend/Date.php';
return (self::$time_format) ? self::$time_format : Zend_Locale_Format::getTimeFormat(self::get_locale());
$timeFormat = Config::inst()->get('i18n', 'time_format');
return ($timeFormat) ? $timeFormat : Zend_Locale_Format::getTimeFormat(self::get_locale());
}
/**
* An exhaustive list of possible locales (code => language and country)
*
* @config
* @var array
*/
public static $all_locales = array (
private static $all_locales = array (
'aa_DJ' => 'Afar (Djibouti)',
'ab_GE' => 'Abkhazian (Georgia)',
'abr_GH' => 'Abron (Ghana)',
@ -731,11 +746,12 @@ class i18n extends Object implements TemplateGlobalProvider {
);
/**
* @config
* @var array $common_locales
* Sorted alphabtically by the common language name,
* not the locale key.
*/
public static $common_locales = array(
private static $common_locales = array(
'af_ZA' => array('Afrikaans', 'Afrikaans'),
'sq_AL' => array('Albanian', 'shqip'),
'ar_EG' => array('Arabic', '&#1575;&#1604;&#1593;&#1585;&#1576;&#1610;&#1577;'),
@ -822,7 +838,11 @@ class i18n extends Object implements TemplateGlobalProvider {
'zu_ZA' => array('Zulu', 'isiZulu'),
);
static $tinymce_lang = array(
/**
* @config
* @var array
*/
private static $tinymce_lang = array(
'ca_AD' => 'ca',
'ca_ES' => 'ca',
'cs_CZ' => 'cs',
@ -986,13 +1006,14 @@ class i18n extends Object implements TemplateGlobalProvider {
);
/**
* @config
* @var array $likely_subtags Provides you "likely locales"
* for a given "short" language code. This is a guess,
* as we can't disambiguate from e.g. "en" to "en_US" - it
* could also mean "en_UK".
* @see http://www.unicode.org/cldr/data/charts/supplemental/likely_subtags.html
*/
static $likely_subtags = array(
private static $likely_subtags = array(
'aa' => 'aa_ET',
'ab' => 'ab_GE',
'ady' => 'ady_RU',
@ -1666,7 +1687,7 @@ class i18n extends Object implements TemplateGlobalProvider {
*/
public static function get_common_locales($native = false) {
$languages = array();
foreach (self::$common_locales as $code => $name) {
foreach (Config::inst()->get('i18n', 'common_locales') as $code => $name) {
$languages[$code] = ($native ? $name[1] : $name[0]);
}
return $languages;
@ -1678,7 +1699,8 @@ class i18n extends Object implements TemplateGlobalProvider {
* @return list of languages in the form 'code' => 'name'
*/
public static function get_locale_list() {
return self::$all_locales;
Deprecation::notice('3.2', 'Use the "i18n.all_locales" config setting instead');
return (array)Config::inst()->get('i18n', 'all_locales');
}
/**
@ -1697,6 +1719,7 @@ class i18n extends Object implements TemplateGlobalProvider {
foreach($modules as $module) {
if(!file_exists("{$module}/lang/")) continue;
$allLocales = Config::inst()->get('i18n', 'all_locales');
$moduleLocales = scandir("{$module}/lang/");
foreach($moduleLocales as $moduleLocale) {
preg_match('/(.*)\.[\w\d]+$/',$moduleLocale, $matches);
@ -1704,7 +1727,7 @@ class i18n extends Object implements TemplateGlobalProvider {
// Normalize locale to include likely region tag.
// TODO Replace with CLDR list of actually available languages/regions
$locale = str_replace('-', '_', self::get_locale_from_lang($locale));
$locales[$locale] = (@self::$all_locales[$locale]) ? self::$all_locales[$locale] : $locale;
$locales[$locale] = (isset($allLocales[$locale])) ? $allLocales[$locale] : $locale;
}
}
}
@ -1763,8 +1786,9 @@ class i18n extends Object implements TemplateGlobalProvider {
* @return Language
*/
public static function get_tinymce_lang() {
if(isset(self::$tinymce_lang[self::get_locale()])) {
return self::$tinymce_lang[self::get_locale()];
$lang = Config::inst()->get('i18n', 'tinymce_lang');
if(isset($lang[self::get_locale()])) {
return $lang[self::get_locale()];
}
return 'en';
@ -1819,10 +1843,11 @@ class i18n extends Object implements TemplateGlobalProvider {
* @return string Long locale, e.g. "en_US"
*/
public static function get_locale_from_lang($lang) {
$subtags = Config::inst()->get('i18n', 'likely_subtags');
if(preg_match('/\-|_/', $lang)) {
return $lang;
} else if(isset(self::$likely_subtags[$lang])) {
return self::$likely_subtags[$lang];
} else if(isset($subtags[$lang])) {
return $subtags[$lang];
} else {
return $lang . '_' . strtoupper($lang);
}
@ -1880,7 +1905,7 @@ class i18n extends Object implements TemplateGlobalProvider {
public static function validate_locale($locale) {
// Convert en-US to en_US
$locale = str_replace('-', '_', $locale);
return (array_key_exists($locale, self::$all_locales));
return (array_key_exists($locale, Config::inst()->get('i18n', 'all_locales')));
}
/**
@ -1983,7 +2008,7 @@ class i18n extends Object implements TemplateGlobalProvider {
if(is_dir($themesBase)) {
foreach(scandir($themesBase) as $theme) {
if(
strpos($theme, SSViewer::current_theme()) === 0
strpos($theme, Config::inst()->get('SSViewer', 'theme')) === 0
&& file_exists("{$themesBase}/{$theme}/lang/")
) {
$filename = $adapter->getFilenameForLocale($locale);

View File

@ -462,7 +462,7 @@ class i18nTextCollector_Writer_Php implements i18nTextCollector_Writer {
// Create folder for lang files
$langFolder = $path . '/lang';
if(!file_exists($langFolder)) {
Filesystem::makeFolder($langFolder, Filesystem::$folder_create_mask);
Filesystem::makeFolder($langFolder, Config::inst()->get('Filesystem', 'folder_create_mask'));
touch($langFolder . '/_manifest_exclude');
}
@ -539,7 +539,7 @@ class i18nTextCollector_Writer_RailsYaml implements i18nTextCollector_Writer {
// Create folder for lang files
$langFolder = $path . '/lang';
if(!file_exists($langFolder)) {
Filesystem::makeFolder($langFolder, Filesystem::$folder_create_mask);
Filesystem::makeFolder($langFolder, Config::inst()->get('Filesystem', 'folder_create_mask'));
touch($langFolder . '/_manifest_exclude');
}
@ -587,8 +587,9 @@ class i18nTextCollector_Writer_RailsYaml implements i18nTextCollector_Writer {
*/
class i18nTextCollector_Parser extends SSTemplateParser {
static $entities = array();
static $currentEntity = array();
private static $entities = array();
private static $currentEntity = array();
public function Translate__construct(&$res) {
self::$currentEntity = array(null,null,null); //start with empty array

View File

@ -31,7 +31,7 @@ if (version_compare(phpversion(), '5.3.2', '<')) {
* - Sets up error handlers with {@link Debug::loadErrorHandlers()}
* - Calls {@link DB::connect()}, passing it the global variable $databaseConfig that should
* be defined in an _config.php
* - Sets up the default director rules using {@link Director::addRules()}
* - Sets up the default director rules using {@link Director::$rules}
*
* After that, it calls {@link Director::direct()}, which is responsible for doing most of the
* real work.

View File

@ -35,7 +35,7 @@
*/
class Aggregate extends ViewableData {
static $cache = null;
private static $cache = null;
/** Build & cache the cache object */
protected static function cache() {

View File

@ -71,20 +71,23 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
/**
* Human-readable singular name.
* @var string
* @config
*/
public static $singular_name = null;
private static $singular_name = null;
/**
* Human-readable pluaral name
* @var string
* @config
*/
public static $plural_name = null;
private static $plural_name = null;
/**
* Allow API access to this object?
* @todo Define the options that can be set here
* @config
*/
public static $api_access = false;
private static $api_access = false;
/**
* True if this DataObject has been destroyed.
@ -136,7 +139,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
protected $brokenOnWrite = false;
/**
* Should dataobjects be validated before they are written?
* @config
* @var boolean Should dataobjects be validated before they are written?
*/
private static $validation_enabled = true;
@ -164,19 +168,24 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
/**
* Returns when validation on DataObjects is enabled.
*
* @deprecated 3.2 Use the "DataObject.validation_enabled" config setting instead
* @return bool
*/
public static function get_validation_enabled() {
return self::$validation_enabled;
Deprecation::notice('3.2', 'Use the "DataObject.validation_enabled" config setting instead');
return Config::inst()->get('DataObject', 'validation_enabled');
}
/**
* Set whether DataObjects should be validated before they are written.
* @param $enable bool
* @see DataObject::validate()
* @deprecated 3.2 Use the "DataObject.validation_enabled" config setting instead
*/
public static function set_validation_enabled($enable) {
self::$validation_enabled = (bool) $enable;
Deprecation::notice('3.2', 'Use the "DataObject.validation_enabled" config setting instead');
Config::inst()->update('DataObject', 'validation_enabled', (bool)$enable);
}
/**
@ -1066,7 +1075,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
E_USER_WARNING
);
}
else if(self::get_validation_enabled()) {
else if(Config::inst()->get('DataObject', 'validation_enabled')) {
$valid = $this->validate();
if (!$valid->valid()) {
$writeException = new ValidationException(
@ -3335,14 +3344,14 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* @var array
* @config
*/
public static $db = null;
private static $db = null;
/**
* Use a casting object for a field. This is a map from
* field name to class name of the casting object.
* @var array
*/
public static $casting = array(
private static $casting = array(
"LastEdited" => "SS_Datetime",
"Created" => "SS_Datetime",
"Title" => 'Text',
@ -3364,8 +3373,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* included in the next major release. Please use with care.
*
* @var array
* @config
*/
static $create_table_options = array(
private static $create_table_options = array(
'MySQLDatabase' => 'ENGINE=InnoDB'
);
@ -3375,8 +3385,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
*
* @var array
* @config
*/
public static $indexes = null;
private static $indexes = null;
/**
* Inserts standard column-values when a DataObject
@ -3388,8 +3399,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* or false in your subclass. Setting it to null won't work.
*
* @var array
* @config
*/
public static $defaults = null;
private static $defaults = null;
/**
* Multidimensional array which inserts default data into the database
@ -3404,8 +3416,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* ).
*
* @var array
* @config
*/
public static $default_records = null;
private static $default_records = null;
/**
* One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a
@ -3414,8 +3427,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* Note that you cannot have a has_one and belongs_to relationship with the same name.
*
* @var array
* @config
*/
public static $has_one = null;
private static $has_one = null;
/**
* A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.
@ -3427,8 +3441,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* Note that you cannot have a has_one and belongs_to relationship with the same name.
*
* @var array
* @config
*/
public static $belongs_to;
private static $belongs_to;
/**
* This defines a one-to-many relationship. It is a map of component name to the remote data class.
@ -3439,15 +3454,17 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* which foreign key to use.
*
* @var array
* @config
*/
public static $has_many = null;
private static $has_many = null;
/**
* many-many relationship definitions.
* This is a map from component name to data type.
* @var array
* @config
*/
public static $many_many = null;
private static $many_many = null;
/**
* Extra fields to include on the connecting many-many table.
@ -3463,22 +3480,25 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* </code>
*
* @var array
* @config
*/
public static $many_many_extraFields = null;
private static $many_many_extraFields = null;
/**
* The inverse side of a many-many relationship.
* This is a map from component name to data type.
* @var array
* @config
*/
public static $belongs_many_many = null;
private static $belongs_many_many = null;
/**
* The default sort expression. This will be inserted in the ORDER BY
* clause of a SQL query if no other sort expression is provided.
* @var string
* @config
*/
public static $default_sort = null;
private static $default_sort = null;
/**
* Default list of fields that can be scaffolded by the ModelAdmin
@ -3512,20 +3532,23 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* )
* );
* </code>
* @config
*/
public static $searchable_fields = null;
private static $searchable_fields = null;
/**
* User defined labels for searchable_fields, used to override
* default display in the search form.
* @config
*/
public static $field_labels = null;
private static $field_labels = null;
/**
* Provides a default list of fields to be used by a 'summary'
* view of this object.
* @config
*/
public static $summary_fields = null;
private static $summary_fields = null;
/**
* Provides a list of allowed methods that can be called via RESTful api.

View File

@ -6,23 +6,20 @@
* @subpackage model
*/
abstract class SS_Database {
/**
* Connection object to the database.
* @param resource
*/
static $globalConn;
/**
* @config
* @var boolean Check tables when running /dev/build, and repair them if necessary.
* In case of large databases or more fine-grained control on how to handle
* data corruption in tables, you can disable this behaviour and handle it
* outside of this class, e.g. through a nightly system task with extended logging capabilities.
*/
static $check_and_repair_on_build = true;
private static $check_and_repair_on_build = true;
/**
* If this is false, then information about database operations
* will be displayed, eg creation of tables.
*
* @param boolean
*/
protected $supressOutput = false;
@ -329,7 +326,9 @@ abstract class SS_Database {
$this->transCreateTable($table, $options, $extensions);
$this->alterationMessage("Table $table: created","created");
} else {
if(self::$check_and_repair_on_build) $this->checkAndRepairTable($table, $options);
if(Config::inst()->get('Database', 'check_and_repair_on_build')) {
$this->checkAndRepairTable($table, $options);
}
// Check if options changed
$tableOptionsChanged = false;

View File

@ -14,7 +14,7 @@ require_once("model/DB.php");
class DatabaseAdmin extends Controller {
/// SECURITY ///
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'build',
'cleanup',

View File

@ -12,54 +12,59 @@ class Image extends File {
const ORIENTATION_PORTRAIT = 1;
const ORIENTATION_LANDSCAPE = 2;
static $backend = "GDBackend";
private static $backend = "GDBackend";
static $casting = array(
private static $casting = array(
'Tag' => 'HTMLText',
);
/**
* The width of an image thumbnail in a strip.
* @var int
* @config
* @var int The width of an image thumbnail in a strip.
*/
public static $strip_thumbnail_width = 50;
private static $strip_thumbnail_width = 50;
/**
* The height of an image thumbnail in a strip.
* @var int
* @config
* @var int The height of an image thumbnail in a strip.
*/
public static $strip_thumbnail_height = 50;
private static $strip_thumbnail_height = 50;
/**
* The width of an image thumbnail in the CMS.
* @var int
* @config
* @var int The width of an image thumbnail in the CMS.
*/
public static $cms_thumbnail_width = 100;
private static $cms_thumbnail_width = 100;
/**
* The height of an image thumbnail in the CMS.
* @config
* @var int The height of an image thumbnail in the CMS.
*/
public static $cms_thumbnail_height = 100;
private static $cms_thumbnail_height = 100;
/**
* The width of an image thumbnail in the Asset section.
* @config
* @var int The width of an image thumbnail in the Asset section.
*/
public static $asset_thumbnail_width = 100;
private static $asset_thumbnail_width = 100;
/**
* The height of an image thumbnail in the Asset section.
* @config
* @var int The height of an image thumbnail in the Asset section.
*/
public static $asset_thumbnail_height = 100;
private static $asset_thumbnail_height = 100;
/**
* The width of an image preview in the Asset section.
* @config
* @var int The width of an image preview in the Asset section.
*/
public static $asset_preview_width = 400;
private static $asset_preview_width = 400;
/**
* The height of an image preview in the Asset section.
* @config
* @var int The height of an image preview in the Asset section.
*/
public static $asset_preview_height = 200;
private static $asset_preview_height = 200;
public static function set_backend($backend) {
self::$backend = $backend;
@ -158,11 +163,11 @@ class Image extends File {
// Create a folder
if(!file_exists(ASSETS_PATH)) {
mkdir(ASSETS_PATH, Filesystem::$folder_create_mask);
mkdir(ASSETS_PATH, Config::inst()->get('Filesystem', 'folder_create_mask'));
}
if(!file_exists(ASSETS_PATH . "/$class")) {
mkdir(ASSETS_PATH . "/$class", Filesystem::$folder_create_mask);
mkdir(ASSETS_PATH . "/$class", Config::inst()->get('Filesystem', 'folder_create_mask'));
}
// Generate default filename

View File

@ -24,16 +24,7 @@ interface Image_Backend {
* @return void
*/
public function writeTo($path);
/**
* set_default_quality
*
* @static
* @param int $quality
* @return void
*/
public static function set_default_quality($quality);
/**
* setQuality
*

View File

@ -26,6 +26,10 @@ class MySQLDatabase extends SS_Database {
*/
private $database;
/**
* @config
* @var String
*/
private static $connection_charset = null;
private $supportsTransactions = true;
@ -39,9 +43,12 @@ class MySQLDatabase extends SS_Database {
* However, sites created before version 2.4.0 should leave this unset or data that isn't 7-bit
* safe will be corrupted. As such, the installer comes with this set in mysite/_config.php by
* default in versions 2.4.0 and later.
*
* @deprecated 3.1 Use "MySQLDatabase.connection_charset" config setting instead
*/
public static function set_connection_charset($charset = 'utf8') {
self::$connection_charset = $charset;
Deprecation::notice('3.2', 'Use "MySQLDatabase.connection_charset" config setting instead');
Config::inst()->update('MySQLDatabase', 'connection_charset', $charset);
}
/**
@ -67,8 +74,8 @@ class MySQLDatabase extends SS_Database {
$this->query("SET sql_mode = 'ANSI'");
if(self::$connection_charset) {
$this->dbConn->set_charset(self::$connection_charset);
if(Config::inst()->get('MySQLDatabase', 'connection_charset')) {
$this->dbConn->set_charset(Config::inst()->get('MySQLDatabase', 'connection_charset'));
}
$this->active = $this->dbConn->select_db($parameters['database']);

View File

@ -15,16 +15,17 @@
*/
class SS_Transliterator extends Object {
/**
* Allow the use of iconv() to perform transliteration. Set to false to disable.
* @config
* @var boolean Allow the use of iconv() to perform transliteration. Set to false to disable.
* Even if this variable is true, iconv() won't be used if it's not installed.
*/
static $use_iconv = false;
private static $use_iconv = false;
/**
* Convert the given utf8 string to a safe ASCII source
*/
public function toASCII($source) {
if(function_exists('iconv') && self::$use_iconv) return $this->useIconv($source);
if(function_exists('iconv') && $this->config()->use_iconv) return $this->useIconv($source);
else return $this->useStrTr($source);
}

View File

@ -17,14 +17,16 @@
class URLSegmentFilter extends Object {
/**
* @config
* @var Boolean
*/
static $default_use_transliterator = true;
private static $default_use_transliterator = true;
/**
* @config
* @var Array See {@link setReplacements()}.
*/
static $default_replacements = array(
private static $default_replacements = array(
'/&amp;/u' => '-and-',
'/&/u' => '-and-',
'/\s/u' => '-', // remove whitespace
@ -39,10 +41,11 @@ class URLSegmentFilter extends Object {
* Useful for character sets that have little overlap with ASCII (e.g. far eastern),
* as well as better search engine optimization for URLs.
* @see http://www.ietf.org/rfc/rfc3987
*
*
* @config
* @var boolean
*/
static $default_allow_multibyte = false;
private static $default_allow_multibyte = false;
/**
* @var Array See {@link setReplacements()}
@ -92,7 +95,7 @@ class URLSegmentFilter extends Object {
* @return Array
*/
public function getReplacements() {
return ($this->replacements) ? $this->replacements : self::$default_replacements;
return ($this->replacements) ? $this->replacements : (array)$this->config()->default_replacements;
}
/**
@ -104,7 +107,7 @@ class URLSegmentFilter extends Object {
* @return SS_Transliterator|NULL
*/
public function getTransliterator() {
if($this->transliterator === null && self::$default_use_transliterator) {
if($this->transliterator === null && $this->config()->default_use_transliterator) {
$this->transliterator = SS_Transliterator::create();
}
return $this->transliterator;
@ -133,6 +136,6 @@ class URLSegmentFilter extends Object {
* @return boolean
*/
public function getAllowMultibyte() {
return ($this->allowMultibyte !== null) ? $this->allowMultibyte : self::$default_allow_multibyte;
return ($this->allowMultibyte !== null) ? $this->allowMultibyte : $this->config()->default_allow_multibyte;
}
}

View File

@ -55,7 +55,7 @@ class Versioned extends DataExtension {
*
* @var array $db_for_versions_table
*/
static $db_for_versions_table = array(
private static $db_for_versions_table = array(
"RecordID" => "Int",
"Version" => "Int",
"WasPublished" => "Boolean",
@ -69,7 +69,7 @@ class Versioned extends DataExtension {
*
* @var array $indexes_for_versions_table
*/
static $indexes_for_versions_table = array(
private static $indexes_for_versions_table = array(
'RecordID_Version' => '("RecordID","Version")',
'RecordID' => true,
'Version' => true,
@ -103,7 +103,7 @@ class Versioned extends DataExtension {
$this->liveStage = array_pop($stages);
}
static $db = array(
private static $db = array(
'Version' => 'Int'
);
@ -152,7 +152,7 @@ class Versioned extends DataExtension {
$query->replaceText("`{$table}_versions`.`ID`", "`{$table}_versions`.`RecordID`");
// Add all <basetable>_versions columns
foreach(self::$db_for_versions_table as $name => $type) {
foreach(Config::inst()->get('Versioned', 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name);
}
$query->selectField(sprintf('"%s_versions"."%s"', $baseTable, 'RecordID'), "ID");
@ -230,7 +230,7 @@ class Versioned extends DataExtension {
}
// Add all <basetable>_versions columns
foreach(self::$db_for_versions_table as $name => $type) {
foreach(Config::inst()->get('Versioned', 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name);
}
@ -406,12 +406,12 @@ class Versioned extends DataExtension {
if($isRootClass) {
// Create table for all versions
$versionFields = array_merge(
self::$db_for_versions_table,
Config::inst()->get('Versioned', 'db_for_versions_table'),
(array)$fields
);
$versionIndexes = array_merge(
self::$indexes_for_versions_table,
Config::inst()->get('Versioned', 'indexes_for_versions_table'),
(array)$indexes
);
} else {
@ -809,7 +809,7 @@ class Versioned extends DataExtension {
}
// Add all <basetable>_versions columns
foreach(self::$db_for_versions_table as $name => $type) {
foreach(Config::inst()->get('Versioned', 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name);
}

View File

@ -16,7 +16,12 @@
* @subpackage model
*/
class Currency extends Decimal {
protected static $currencySymbol = '$';
/**
* @config
* @var string
*/
private static $currency_symbol = '$';
public function __construct($name = null, $wholeSize = 9, $decimalSize = 2, $defaultValue = 0) {
parent::__construct($name, $wholeSize, $decimalSize, $defaultValue);
@ -27,7 +32,7 @@ class Currency extends Decimal {
*/
public function Nice() {
// return "<span title=\"$this->value\">$" . number_format($this->value, 2) . '</span>';
$val = self::$currencySymbol . number_format(abs($this->value), 2);
$val = $this->config()->currency_symbol . number_format(abs($this->value), 2);
if($this->value < 0) return "($val)";
else return $val;
}
@ -36,7 +41,7 @@ class Currency extends Decimal {
* Returns the number as a whole-number currency, eg $1,000.
*/
public function Whole() {
$val = self::$currencySymbol . number_format(abs($this->value), 0);
$val = $this->config()->currency_symbol . number_format(abs($this->value), 0);
if($this->value < 0) return "($val)";
else return $val;
}
@ -47,15 +52,21 @@ class Currency extends Decimal {
$this->value = $value;
} else if(preg_match('/-?\$?[0-9,]+(.[0-9]+)?([Ee][0-9]+)?/', $value, $matches)) {
$this->value = str_replace(array('$',',',self::$currencySymbol),'',$matches[0]);
$this->value = str_replace(array('$',',',$this->config()->currency_symbol),'',$matches[0]);
} else {
$this->value = 0;
}
}
/**
* @deprecated 3.2 Use the "Currency.currency_symbol" config setting instead
* @param [type] $value [description]
*/
public static function setCurrencySymbol($value) {
self::$currencySymbol = $value;
Deprecation::notice('3.2', 'Use the "Currency.currency_symbol" config setting instead');
$this->config()->currency_symbol = $value;
}
}

View File

@ -41,15 +41,17 @@ abstract class DBField extends ViewableData {
* The escape type for this field when inserted into a template - either "xml" or "raw".
*
* @var string
* @config
*/
public static $escape_type = 'raw';
private static $escape_type = 'raw';
/**
* Subclass of {@link SearchFilter} for usage in {@link defaultSearchFilter()}.
*
* @var string
* @config
*/
public static $default_search_filter_class = 'PartialMatchFilter';
private static $default_search_filter_class = 'PartialMatchFilter';
/**
* @var $default mixed Default-value in the database.

View File

@ -11,7 +11,7 @@ class Enum extends StringField {
protected $enum, $default;
public static $default_search_filter_class = 'ExactMatchFilter';
private static $default_search_filter_class = 'ExactMatchFilter';
/**
* Create a new Enum field.

View File

@ -19,7 +19,7 @@ class ForeignKey extends Int {
*/
protected $object;
public static $default_search_filter_class = 'ExactMatchFilter';
private static $default_search_filter_class = 'ExactMatchFilter';
public function __construct($name, $object = null) {
$this->object = $object;

View File

@ -11,9 +11,9 @@
* @subpackage model
*/
class HTMLText extends Text {
public static $escape_type = 'xml';
private static $escape_type = 'xml';
static $casting = array(
private static $casting = array(
"AbsoluteLinks" => "HTMLText",
"BigSummary" => "HTMLText",
"ContextSummary" => "HTMLText",

View File

@ -8,7 +8,7 @@
*/
class HTMLVarchar extends Varchar {
public static $escape_type = 'xml';
private static $escape_type = 'xml';
protected $processShortcodes = true;

View File

@ -58,7 +58,7 @@ class Money extends DBField implements CompositeDBField {
/**
* @param array
*/
static $composite_db = array(
private static $composite_db = array(
"Currency" => "Varchar(3)",
"Amount" => 'Decimal(19,4)'
);
@ -112,7 +112,7 @@ class Money extends DBField implements CompositeDBField {
if($record[$this->name . 'Amount']) {
if(!empty($record[$this->name . 'Currency'])) {
$this->setCurrency($record[$this->name . 'Currency'], $markChanged);
} else if($currency = (string)$this->config()->get('default_currency')) {
} else if($currency = (string)$this->config()->default_currency) {
$this->setCurrency($currency, $markChanged);
}

View File

@ -13,7 +13,7 @@ class PrimaryKey extends Int {
*/
protected $object;
public static $default_search_filter_class = 'ExactMatchFilter';
private static $default_search_filter_class = 'ExactMatchFilter';
/**
* @param string $name

View File

@ -9,7 +9,7 @@
abstract class StringField extends DBField {
protected $nullifyEmpty = true;
static $casting = array(
private static $casting = array(
"LimitCharacters" => "Text",
"LowerCase" => "Text",
"UpperCase" => "Text",

View File

@ -18,7 +18,7 @@
*/
class Text extends StringField {
static $casting = array(
private static $casting = array(
"AbsoluteLinks" => "Text",
"BigSummary" => "Text",
"ContextSummary" => "Text",

View File

@ -11,7 +11,7 @@
*/
class Varchar extends StringField {
static $casting = array(
private static $casting = array(
"Initial" => "Text",
"URL" => "Text",
);

View File

@ -205,7 +205,7 @@ class Oembed_Result extends ViewableData {
*/
protected $extraClass;
public static $casting = array(
private static $casting = array(
'html' => 'HTMLText',
);

View File

@ -17,48 +17,73 @@ unset($options);
class BBCodeParser extends TextParser {
/**
* Set whether phrases starting with http:// or www. are automatically linked
* @var Boolean
* @config
* @var Boolean Set whether phrases starting with http:// or www. are automatically linked
*/
protected static $autolinkUrls = true;
private static $autolink_urls = true;
/**
* Set whether similies :), :(, :P are converted to images
* @var Boolean
* @config
* @var Boolean Set whether similies :), :(, :P are converted to images
*/
protected static $allowSimilies = false;
private static $allow_similies = false;
/**
* Set the location of the smiles folder. By default use the ones in framework
* @config
* @var string Set the location of the smiles folder. By default use the ones in framework
* but this can be overridden by setting BBCodeParser::set_icon_folder('themes/yourtheme/images/');
* @var string
*/
protected static $smilies_location = null;
private static $smilies_location = null;
/**
* @deprecated 3.2 Use the "BBCodeParser.smilies_location" config setting instead
*/
public static function smilies_location() {
Deprecation::notice('3.2', 'Use the "BBCodeParser.smilies_location" config setting instead');
if(!BBCodeParser::$smilies_location) {
return FRAMEWORK_DIR . '/images/smilies';
}
return BBCodeParser::$smilies_location;
return $this->config()->smilies_location;
}
/**
* @deprecated 3.2 Use the "BBCodeParser.smilies_location" config setting instead
*/
public static function set_icon_folder($path) {
BBCodeParser::$smilies_location = $path;
Deprecation::notice('3.2', 'Use the "BBCodeParser.smilies_location" config setting instead');
$this->config()->smilies_location = $path;
}
/**
* @deprecated 3.2 Use the "BBCodeParser.autolink_urls" config setting instead
*/
public static function autolinkUrls() {
return (self::$autolinkUrls != null) ? true : false;
Deprecation::notice('3.2', 'Use the "BBCodeParser.autolink_urls" config setting instead');
return $this->config()->autolink_urls;
}
/**
* @deprecated 3.2 Use the "BBCodeParser.autolink_urls" config setting instead
*/
public static function disable_autolink_urls($autolink = false) {
BBCodeParser::$autolinkUrls = $autolink;
Deprecation::notice('3.2', 'Use the "BBCodeParser.autolink_urls" config setting instead');
$this->config()->autolink_urls = $autolink;
}
/**
* @deprecated 3.2 Use the "BBCodeParser.allow_smilies" config setting instead
*/
public static function smiliesAllowed() {
return (self::$allowSimilies != null) ? true : false;
Deprecation::notice('3.2', 'Use the "BBCodeParser.allow_smilies" config setting instead');
return $this->config()->allow_smilies;
}
/**
* @deprecated 3.2 Use the "BBCodeParser.allow_smilies" config setting instead
*/
public static function enable_smilies() {
BBCodeParser::$allowSimilies = true;
Deprecation::notice('3.2', 'Use the "BBCodeParser.allow_smilies" config setting instead');
$this->config()->allow_similies = true;
}

View File

@ -13,11 +13,13 @@
*/
class BasicAuth {
/**
* @config
* @var Boolean Flag set by {@link self::protect_entire_site()}
*/
private static $entire_site_protected = false;
/**
* @config
* @var String|array Holds a {@link Permission} code that is required
* when calling {@link protect_site_if_necessary()}. Set this value through
* {@link protect_entire_site()}.
@ -25,6 +27,7 @@ class BasicAuth {
private static $entire_site_protected_code = 'ADMIN';
/**
* @config
* @var String Message that shows in the authentication box.
* Set this value through {@link protect_entire_site()}.
*/
@ -109,9 +112,9 @@ class BasicAuth {
* of the permission codes a user has.
*/
public static function protect_entire_site($protect = true, $code = 'ADMIN', $message = null) {
self::$entire_site_protected = $protect;
self::$entire_site_protected_code = $code;
if($message) self::$entire_site_protected_message = $message;
Config::inst()->update('BasicAuth', 'entire_site_protected', $protect);
Config::inst()->update('BasicAuth', 'entire_site_protected_code', $code);
Config::inst()->update('BasicAuth', 'entire_site_protected_message', $message);
}
/**
@ -122,8 +125,9 @@ class BasicAuth {
* please use {@link protect_entire_site()}.
*/
public static function protect_site_if_necessary() {
if(self::$entire_site_protected) {
self::requireLogin(self::$entire_site_protected_message, self::$entire_site_protected_code, false);
$config = Config::inst()->forClass('BasicAuth');
if($config->entire_site_protected) {
self::requireLogin($config->entire_site_protected_message, $config->entire_site_protected_code, false);
}
}

View File

@ -7,7 +7,7 @@
*/
class Group extends DataObject {
static $db = array(
private static $db = array(
"Title" => "Varchar",
"Description" => "Text",
"Code" => "Varchar",
@ -16,21 +16,21 @@ class Group extends DataObject {
"HtmlEditorConfig" => "Varchar"
);
static $has_one = array(
private static $has_one = array(
"Parent" => "Group",
);
static $has_many = array(
private static $has_many = array(
"Permissions" => "Permission",
"Groups" => "Group"
);
static $many_many = array(
private static $many_many = array(
"Members" => "Member",
"Roles" => "PermissionRole",
);
static $extensions = array(
private static $extensions = array(
"Hierarchy",
);
@ -90,7 +90,7 @@ class Group extends DataObject {
// Filter permissions
// TODO SecurityAdmin coupling, not easy to get to the form fields through GridFieldDetailForm
$permissionsField->setHiddenPermissions(SecurityAdmin::$hidden_permissions);
$permissionsField->setHiddenPermissions((array)Config::inst()->get('SecurityAdmin', 'hidden_permissions'));
if($this->ID) {
$group = $this;

View File

@ -3,10 +3,7 @@
* Record all login attempts through the {@link LoginForm} object.
* This behaviour is disabled by default.
*
* Enable through a setting in your _config.php:
* <code>
* Security::set_login_recording(true);
* </code>
* Enable through {@link Security::$login_recording}.
*
* Caution: Please make sure that enabling logging
* complies with your privacy standards. We're logging
@ -17,21 +14,21 @@
*/
class LoginAttempt extends DataObject {
static $db = array(
private static $db = array(
'Email' => 'Varchar(255)',
'Status' => "Enum('Success,Failure')",
'IP' => 'Varchar(255)',
);
static $has_one = array(
private static $has_one = array(
'Member' => 'Member', // only linked if the member actually exists
);
static $has_many = array();
private static $has_many = array();
static $many_many = array();
private static $many_many = array();
static $belongs_many_many = array();
private static $belongs_many_many = array();
/**
*

View File

@ -7,7 +7,7 @@
*/
class Member extends DataObject implements TemplateGlobalProvider {
static $db = array(
private static $db = array(
'FirstName' => 'Varchar',
'Surname' => 'Varchar',
'Email' => 'Varchar(256)', // See RFC 5321, Section 4.5.3.1.3.
@ -33,27 +33,31 @@ class Member extends DataObject implements TemplateGlobalProvider {
'TimeFormat' => 'Varchar(30)',
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Groups' => 'Group',
);
static $has_one = array();
private static $has_one = array();
static $has_many = array();
private static $has_many = array();
static $many_many = array();
private static $many_many = array();
static $many_many_extraFields = array();
private static $many_many_extraFields = array();
static $default_sort = '"Surname", "FirstName"';
private static $default_sort = '"Surname", "FirstName"';
static $indexes = array(
private static $indexes = array(
'Email' => true,
//Removed due to duplicate null values causing MSSQL problems
//'AutoLoginHash' => Array('type'=>'unique', 'value'=>'AutoLoginHash', 'ignoreNulls'=>true)
);
static $notify_password_change = false;
/**
* @config
* @var boolean
*/
private static $notify_password_change = false;
/**
* All searchable database columns
@ -66,50 +70,59 @@ class Member extends DataObject implements TemplateGlobalProvider {
* with definition for different searching algorithms
* (LIKE, FULLTEXT) and default FormFields to construct a searchform.
*/
static $searchable_fields = array(
private static $searchable_fields = array(
'FirstName',
'Surname',
'Email',
);
static $summary_fields = array(
private static $summary_fields = array(
'FirstName' => 'First Name',
'Surname' => 'Last Name',
'Email' => 'Email',
);
/**
* @config
* @var Array See {@link set_title_columns()}
*/
static $title_format = null;
private static $title_format = null;
/**
* The unique field used to identify this member.
* By default, it's "Email", but another common
* field could be Username.
*
*
* @config
* @var string
*/
protected static $unique_identifier_field = 'Email';
private static $unique_identifier_field = 'Email';
/**
* @config
* {@link PasswordValidator} object for validating user's password
*/
protected static $password_validator = null;
private static $password_validator = null;
/**
* @config
* The number of days that a password should be valid for.
* By default, this is null, which means that passwords never expire
*/
protected static $password_expiry_days = null;
private static $password_expiry_days = null;
protected static $lock_out_after_incorrect_logins = null;
/**
* @config
* @var Int
*/
private static $lock_out_after_incorrect_logins = null;
/**
* If this is set, then a session cookie with the given name will be set on log-in,
* @config
* @var String If this is set, then a session cookie with the given name will be set on log-in,
* and cleared on logout.
*/
protected static $login_marker_cookie = null;
private static $login_marker_cookie = null;
/**
* Indicates that when a {@link Member} logs in, Member:session_regenerate_id()
@ -117,13 +130,18 @@ class Member extends DataObject implements TemplateGlobalProvider {
*
* This doesn't always work, especially if you're trying to set session cookies
* across an entire site using the domain parameter to session_set_cookie_params()
*
*
* @config
* @var boolean
*/
protected static $session_regenerate_id = true;
private static $session_regenerate_id = true;
/**
* @deprecated 3.2 Use the "Member.session_regenerate_id" config setting instead
*/
public static function set_session_regenerate_id($bool) {
self::$session_regenerate_id = $bool;
Deprecation::notice('3.2', 'Use the "Member.session_regenerate_id" config setting instead');
self::config()->session_regenerate_id = $bool;
}
/**
@ -174,11 +192,13 @@ class Member extends DataObject implements TemplateGlobalProvider {
* <pre>
* RewriteCond %{HTTP_COOKIE} !SS_LOGGED_IN=1
* </pre>
*
*
* @deprecated 3.2 Use the "Member.login_marker_cookie" config setting instead
* @param $cookieName string The name of the cookie to set.
*/
public static function set_login_marker_cookie($cookieName) {
self::$login_marker_cookie = $cookieName;
Deprecation::notice('3.2', 'Use the "Member.login_marker_cookie" config setting instead');
self::config()->login_marker_cookie = $cookieName;
}
/**
@ -254,21 +274,25 @@ class Member extends DataObject implements TemplateGlobalProvider {
/**
* Get the field used for uniquely identifying a member
* in the database. {@see Member::$unique_identifier_field}
*
*
* @deprecated 3.2 Use the "Member.unique_identifier_field" config setting instead
* @return string
*/
public static function get_unique_identifier_field() {
return self::$unique_identifier_field;
Deprecation::notice('3.2', 'Use the "Member.unique_identifier_field" config setting instead');
return Member::config()->unique_identifier_field;
}
/**
* Set the field used for uniquely identifying a member
* in the database. {@see Member::$unique_identifier_field}
*
*
* @deprecated 3.2 Use the "Member.unique_identifier_field" config setting instead
* @param $field The field name to set as the unique field
*/
public static function set_unique_identifier_field($field) {
self::$unique_identifier_field = $field;
Deprecation::notice('3.2', 'Use the "Member.unique_identifier_field" config setting instead');
Member::config()->unique_identifier_field = $field;
}
/**
@ -288,16 +312,22 @@ class Member extends DataObject implements TemplateGlobalProvider {
/**
* Set the number of days that a password should be valid for.
* Set to null (the default) to have passwords never expire.
*
* @deprecated 3.2 Use the "Member.password_expiry_days" config setting instead
*/
public static function set_password_expiry($days) {
self::$password_expiry_days = $days;
Deprecation::notice('3.2', 'Use the "Member.password_expiry_days" config setting instead');
self::config()->password_expiry_days = $days;
}
/**
* Configure the security system to lock users out after this many incorrect logins
*
* @deprecated 3.2 Use the "Member.lock_out_after_incorrect_logins" config setting instead
*/
public static function lock_out_after_incorrect_logins($numLogins) {
self::$lock_out_after_incorrect_logins = $numLogins;
Deprecation::notice('3.2', 'Use the "Member.lock_out_after_incorrect_logins" config setting instead');
self::config()->lock_out_after_incorrect_logins = $numLogins;
}
@ -316,7 +346,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
Session::set("loggedInAs", $this->ID);
// This lets apache rules detect whether the user has logged in
if(self::$login_marker_cookie) Cookie::set(self::$login_marker_cookie, 1, 0);
if(Member::config()->login_marker_cookie) Cookie::set(Member::config()->login_marker_cookie, 1, 0);
$this->NumVisit++;
@ -334,7 +364,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
}
// Clear the incorrect log-in count
if(self::$lock_out_after_incorrect_logins) {
if(self::config()->lock_out_after_incorrect_logins) {
$this->FailedLoginCount = 0;
}
@ -394,7 +424,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
self::session_regenerate_id();
Session::set("loggedInAs", $member->ID);
// This lets apache rules detect whether the user has logged in
if(self::$login_marker_cookie) Cookie::set(self::$login_marker_cookie, 1, 0, null, null, false, true);
if(Member::config()->login_marker_cookie) Cookie::set(Member::config()->login_marker_cookie, 1, 0, null, null, false, true);
$generator = new RandomGenerator();
$token = $generator->randomToken('sha1');
@ -416,7 +446,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
*/
public function logOut() {
Session::clear("loggedInAs");
if(self::$login_marker_cookie) Cookie::set(self::$login_marker_cookie, null, 0);
if(Member::config()->login_marker_cookie) Cookie::set(Member::config()->login_marker_cookie, null, 0);
self::session_regenerate_id();
$this->extend('memberLoggedOut');
@ -632,7 +662,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
// If a member with the same "unique identifier" already exists with a different ID, don't allow merging.
// Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form),
// but rather a last line of defense against data inconsistencies.
$identifierField = self::$unique_identifier_field;
$identifierField = Member::config()->unique_identifier_field;
if($this->$identifierField) {
// Note: Same logic as Member_Validator class
$idClause = ($this->ID) ? sprintf(" AND \"Member\".\"ID\" <> %d", (int)$this->ID) : '';
@ -665,7 +695,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
(Director::isLive() || Email::mailer() instanceof TestMailer)
&& $this->isChanged('Password')
&& $this->record['Password']
&& Member::$notify_password_change
&& $this->config()->notify_password_change
) {
$e = Member_ChangePasswordEmail::create();
$e->populateTemplate($this);
@ -681,7 +711,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
$encryption_details = Security::encrypt_password(
$this->Password, // this is assumed to be cleartext
$this->Salt,
($this->PasswordEncryption) ? $this->PasswordEncryption : Security::get_password_encryption_algorithm(),
($this->PasswordEncryption) ? $this->PasswordEncryption : Security::config()->password_encryption_algorithm,
$this
);
@ -693,8 +723,8 @@ class Member extends DataObject implements TemplateGlobalProvider {
// If we haven't manually set a password expiry
if(!$this->isChanged('PasswordExpiry')) {
// then set it for us
if(self::$password_expiry_days) {
$this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::$password_expiry_days);
if(self::config()->password_expiry_days) {
$this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::config()->password_expiry_days);
} else {
$this->PasswordExpiry = null;
}
@ -812,7 +842,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
*/
public static function set_title_columns($columns, $sep = ' ') {
if (!is_array($columns)) $columns = array($columns);
self::$title_format = array('columns' => $columns, 'sep' => $sep);
self::config()->title_format = array('columns' => $columns, 'sep' => $sep);
}
//------------------- HELPER METHODS -----------------------------------//
@ -828,12 +858,13 @@ class Member extends DataObject implements TemplateGlobalProvider {
* of the member is equal 0, only the surname is returned.
*/
public function getTitle() {
if (self::$title_format) {
$format = $this->config()->title_format;
if ($format) {
$values = array();
foreach(self::$title_format['columns'] as $col) {
foreach($format['columns'] as $col) {
$values[] = $this->getField($col);
}
return join(self::$title_format['sep'], $values);
return join($format['sep'], $values);
}
if($this->getField('ID') === 0)
return $this->getField('Surname');
@ -861,13 +892,14 @@ class Member extends DataObject implements TemplateGlobalProvider {
// This should be abstracted to SSDatabase concatOperator or similar.
$op = (DB::getConn() instanceof MSSQLDatabase) ? " + " : " || ";
if (self::$title_format) {
$format = self::config()->title_format;
if ($format) {
$columnsWithTablename = array();
foreach(self::$title_format['columns'] as $column) {
foreach($format['columns'] as $column) {
$columnsWithTablename[] = "\"$tableName\".\"$column\"";
}
return "(".join(" $op '".self::$title_format['sep']."' $op ", $columnsWithTablename).")";
return "(".join(" $op '".$format['sep']."' $op ", $columnsWithTablename).")";
} else {
return "(\"$tableName\".\"Surname\" $op ' ' $op \"$tableName\".\"FirstName\")";
}
@ -1126,7 +1158,7 @@ class Member extends DataObject implements TemplateGlobalProvider {
$mainFields->removeByName('PasswordExpiry');
$mainFields->removeByName('LockedOutUntil');
if(!self::$lock_out_after_incorrect_logins) {
if(!self::config()->lock_out_after_incorrect_logins) {
$mainFields->removeByName('FailedLoginCount');
}
@ -1363,12 +1395,12 @@ class Member extends DataObject implements TemplateGlobalProvider {
* This can be used to lock the user out temporarily if too many failed attempts are made.
*/
public function registerFailedLogin() {
if(self::$lock_out_after_incorrect_logins) {
if(self::config()->lock_out_after_incorrect_logins) {
// Keep a tally of the number of failed log-ins so that we can lock people out
$this->FailedLoginCount = $this->FailedLoginCount + 1;
$this->write();
if($this->FailedLoginCount >= self::$lock_out_after_incorrect_logins) {
if($this->FailedLoginCount >= self::config()->lock_out_after_incorrect_logins) {
$this->LockedOutUntil = date('Y-m-d H:i:s', time() + 15*60);
$this->write();
}
@ -1531,8 +1563,7 @@ class Member_Validator extends RequiredFields {
public function php($data) {
$valid = parent::php($data);
$identifierField = Member::get_unique_identifier_field();
$identifierField = Member::config()->unique_identifier_field;
$SQL_identifierField = Convert::raw2sql($data[$identifierField]);
$member = DataObject::get_one('Member', "\"$identifierField\" = '{$SQL_identifierField}'");

View File

@ -13,7 +13,7 @@ class MemberAuthenticator extends Authenticator {
* If set, will migrate to new precision-safe password hashing
* upon login. See http://open.silverstripe.org/ticket/3004.
*/
static $migrate_legacy_hashes = array(
private static $migrate_legacy_hashes = array(
'md5' => 'md5_v2.4',
'sha1' => 'sha1_v2.4'
);
@ -45,7 +45,7 @@ class MemberAuthenticator extends Authenticator {
} else {
$member = DataObject::get_one(
"Member",
"\"" . Member::get_unique_identifier_field() . "\" = '$SQL_user' AND \"Password\" IS NOT NULL"
"\"" . Member::config()->unique_identifier_field . "\" = '$SQL_user' AND \"Password\" IS NOT NULL"
);
if($member) {
@ -64,7 +64,7 @@ class MemberAuthenticator extends Authenticator {
/**
* TODO We could handle this with an extension
*/
if(Security::login_recording()) {
if(Security::config()->login_recording) {
$attempt = new LoginAttempt();
if($member) {
// successful login (member is existing with matching password)
@ -77,7 +77,7 @@ class MemberAuthenticator extends Authenticator {
// failed login - we're trying to see if a user exists with this email (disregarding wrong passwords)
$existingMember = DataObject::get_one(
"Member",
"\"" . Member::get_unique_identifier_field() . "\" = '$SQL_user'"
"\"" . Member::config()->unique_identifier_field . "\" = '$SQL_user'"
);
if($existingMember) {
$attempt->MemberID = $existingMember->ID;

View File

@ -58,7 +58,7 @@ class MemberLoginForm extends LoginForm {
);
} else {
if(!$fields) {
$label=singleton('Member')->fieldLabel(Member::get_unique_identifier_field());
$label=singleton('Member')->fieldLabel(Member::config()->unique_identifier_field);
$fields = new FieldList(
new HiddenField("AuthenticationMethod", null, $this->authenticator_class, $this),
// Regardless of what the unique identifer field is (usually 'Email'), it will be held in the
@ -66,7 +66,7 @@ class MemberLoginForm extends LoginForm {
new TextField("Email", $label, Session::get('SessionForms.MemberLoginForm.Email'), null, $this),
new PasswordField("Password", _t('Member.PASSWORD', 'Password'))
);
if(Security::$autologin_enabled) {
if(Security::config()->autologin_enabled) {
$fields->push(new CheckboxField(
"Remember",
_t('Member.REMEMBERME', "Remember me next time?")
@ -184,8 +184,8 @@ JS
}
// If a default login dest has been set, redirect to that.
if (Security::default_login_dest()) {
return $this->controller->redirect(Director::absoluteBaseURL() . Security::default_login_dest());
if (Security::config()->default_login_dest) {
return $this->controller->redirect(Director::absoluteBaseURL() . Security::config()->default_login_dest);
}
// Redirect the user to the page where he came from

View File

@ -5,21 +5,21 @@
* @subpackage security
*/
class MemberPassword extends DataObject {
static $db = array(
private static $db = array(
'Password' => 'Varchar(160)',
'Salt' => 'Varchar(50)',
'PasswordEncryption' => 'Varchar(50)',
);
static $has_one = array(
private static $has_one = array(
'Member' => 'Member'
);
static $has_many = array();
private static $has_many = array();
static $many_many = array();
private static $many_many = array();
static $belongs_many_many = array();
private static $belongs_many_many = array();
/**
* Log a password change from the given member.

View File

@ -15,8 +15,9 @@ abstract class PasswordEncryptor {
/**
* @var array
* @config
*/
protected static $encryptors = array();
private static $encryptors = array();
/**
* @return Array Map of encryptor code to the used class.

View File

@ -16,7 +16,8 @@
* @subpackage security
*/
class PasswordValidator extends Object {
static $character_strength_tests = array(
private static $character_strength_tests = array(
'lowercase' => '/[a-z]/',
'uppercase' => '/[A-Z]/',
'digits' => '/[0-9]/',
@ -73,7 +74,7 @@ class PasswordValidator extends Object {
$score = 0;
$missedTests = array();
foreach($this->testNames as $name) {
if(preg_match(self::$character_strength_tests[$name], $password)) $score++;
if(preg_match(self::config()->character_strength_tests[$name], $password)) $score++;
else $missedTests[] = $name;
}

View File

@ -8,25 +8,25 @@ class Permission extends DataObject implements TemplateGlobalProvider {
// the (1) after Type specifies the DB default value which is needed for
// upgrades from older SilverStripe versions
static $db = array(
private static $db = array(
"Code" => "Varchar",
"Arg" => "Int",
"Type" => "Int(1)"
);
static $has_one = array(
private static $has_one = array(
"Group" => "Group"
);
static $indexes = array(
private static $indexes = array(
"Code" => true
);
static $defaults = array(
private static $defaults = array(
"Type" => 1
);
static $has_many = array();
private static $has_many = array();
static $many_many = array();
private static $many_many = array();
static $belongs_many_many = array();
private static $belongs_many_many = array();
/**
* This is the value to use for the "Type" field if a permission should be
@ -53,42 +53,38 @@ class Permission extends DataObject implements TemplateGlobalProvider {
*
* @var bool
*/
static $declared_permissions = null;
private static $declared_permissions = null;
/**
* Linear list of declared permissions in the system.
*
* @var array
*/
protected static $declared_permissions_list = null;
private static $declared_permissions_list = null;
/**
* @config
* @var $strict_checking Boolean Method to globally disable "strict" checking,
* which means a permission will be granted if the key does not exist at all.
*/
static $strict_checking = true;
/**
* If this setting is set, then permissions can imply other permissions
*
* @var bool
*/
static $implied_permissions = false;
private static $strict_checking = true;
/**
* Set to false to prevent the 'ADMIN' permission from implying all
* permissions in the system
*
* @config
* @var bool
*/
static $admin_implies_all = true;
private static $admin_implies_all = true;
/**
* a list of permission codes which doesn't appear in the Permission list
* when make the {@link PermissionCheckboxSetField}
* @config
* @var array;
*/
static $hidden_permissions = array();
private static $hidden_permissions = array();
/**
* Check that the current member has the given permission.
@ -157,7 +153,7 @@ class Permission extends DataObject implements TemplateGlobalProvider {
// If $admin_implies_all was false then this would be inefficient, but that's an edge
// case and this keeps the code simpler
if(!is_array($code)) $code = array($code);
if(self::$admin_implies_all) $code[] = "ADMIN";
if(Config::inst()->get('Permission', 'admin_implies_all')) $code[] = "ADMIN";
// Multiple $code values - return true if at least one matches, ie, intersection exists
return (bool)array_intersect($code, self::$cache_permissions[$memberID]);
@ -195,7 +191,7 @@ class Permission extends DataObject implements TemplateGlobalProvider {
$SQL_code = Convert::raw2sql($code);
$adminFilter = (self::$admin_implies_all) ? ",'ADMIN'" : '';
$adminFilter = (Config::inst()->get('Permission', 'admin_implies_all')) ? ",'ADMIN'" : '';
// Raw SQL for efficiency
$permission = DB::query("
@ -212,7 +208,7 @@ class Permission extends DataObject implements TemplateGlobalProvider {
if($permission) return $permission;
// Strict checking disabled?
if(!self::$strict_checking || !$strict) {
if(!Config::inst()->get('Permission', 'strict_checking') || !$strict) {
$hasPermission = DB::query("
SELECT COUNT(*)
FROM \"Permission\"
@ -534,21 +530,27 @@ class Permission extends DataObject implements TemplateGlobalProvider {
/**
* add a permission represented by the $code to the {@link slef::$hidden_permissions} list
*
* @deprecated 3.1 Use "Permission.hidden_permissions" config setting instead
* @param $code string - the permissions code
* @return void
*/
public static function add_to_hidden_permissions($code){
self::$hidden_permissions[] = $code;
if(is_string($codes)) $codes = array($codes);
Deprecation::notice('3.2', 'Use "Permission.hidden_permissions" config setting instead');
Config::inst()->update('Permission', 'hidden_permissions', $codes);
}
/**
* remove a permission represented by the $code from the {@link slef::$hidden_permissions} list
*
* @deprecated 3.1 Use "Permission.hidden_permissions" config setting instead
* @param $code string - the permissions code
* @return void
*/
public static function remove_from_hidden_permissions($code){
self::$hidden_permissions = array_diff(self::$hidden_permissions, array($code));
if(is_string($codes)) $codes = array($codes);
Deprecation::notice('3.2', 'Use "Permission.hidden_permissions" config setting instead');
Config::inst()->remove('Permission', 'hidden_permissions', $codes);
}
/**
@ -557,17 +559,13 @@ class Permission extends DataObject implements TemplateGlobalProvider {
* Permissions can be grouped by nesting arrays. Scalar values are always
* treated as permissions.
*
* @deprecated 3.2 Use "Permission.declared_permissions" config setting instead
* @param array $permArray A (possibly nested) array of permissions to
* declare for the system.
*/
public static function declare_permissions($permArray) {
if(is_array(self::$declared_permissions)) {
self::$declared_permissions =
array_merge_recursive(self::$declared_permissions, $permArray);
}
else {
self::$declared_permissions = $permArray;
}
Deprecation::notice('3.2', 'Use "Permission.declared_permissions" config setting instead');
self::config()->declared_permissions = $permArray;
}

View File

@ -160,13 +160,14 @@ class PermissionCheckboxSetField extends FormField {
$odd = 0;
$options = '';
$globalHidden = (array)Config::inst()->get('Permission', 'hidden_permissions');
if($this->source) {
// loop through all available categorized permissions and see if they're assigned for the given groups
foreach($this->source as $categoryName => $permissions) {
$options .= "<li><h5>$categoryName</h5></li>";
foreach($permissions as $code => $permission) {
if(in_array($code, $this->hiddenPermissions)) continue;
if(in_array($code, Permission::$hidden_permissions)) continue;
if(in_array($code, $globalHidden)) continue;
$value = $permission['name'];

View File

@ -14,24 +14,24 @@
* @subpackage security
*/
class PermissionRole extends DataObject {
static $db = array(
private static $db = array(
"Title" => "Varchar",
"OnlyAdminCanApply" => "Boolean"
);
static $has_many = array(
private static $has_many = array(
"Codes" => "PermissionRoleCode",
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
"Groups" => "Group",
);
static $default_sort = '"Title"';
private static $default_sort = '"Title"';
static $singular_name = 'Role';
private static $singular_name = 'Role';
static $plural_name = 'Roles';
private static $plural_name = 'Roles';
public function getCMSFields() {
$fields = parent::getCMSFields();
@ -48,7 +48,9 @@ class PermissionRole extends DataObject {
'RoleID'
)
);
$permissionField->setHiddenPermissions(SecurityAdmin::$hidden_permissions);
$permissionField->setHiddenPermissions(
Config::inst()->get('Permission', 'hidden_permissions')
);
return $fields;
}

View File

@ -6,11 +6,11 @@
* @subpackage security
*/
class PermissionRoleCode extends DataObject {
static $db = array(
private static $db = array(
"Code" => "Varchar",
);
static $has_one = array(
private static $has_one = array(
"Role" => "PermissionRole",
);
}

View File

@ -6,7 +6,7 @@
*/
class Security extends Controller {
static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'login',
'logout',
@ -40,48 +40,53 @@ class Security extends Controller {
* If set to TRUE to prevent sharing of the session across several sites
* in the domain.
*
* @config
* @var bool
*/
protected static $strictPathChecking = false;
protected static $strict_path_checking = false;
/**
* The password encryption algorithm to use by default.
* This is an arbitrary code registered through {@link PasswordEncryptor}.
*
* @config
* @var string
*/
protected static $encryptionAlgorithm = 'blowfish';
private static $password_encryption_algorithm = 'blowfish';
/**
* Showing "Remember me"-checkbox
* on loginform, and saving encrypted credentials to a cookie.
*
*
* @config
* @var bool
*/
public static $autologin_enabled = true;
private static $autologin_enabled = true;
/**
* Location of word list to use for generating passwords
*
*
* @config
* @var string
*/
protected static $wordlist = './wordlist.txt';
protected static $word_list = './wordlist.txt';
static $template = 'BlankPage';
private static $template = 'BlankPage';
/**
* Template thats used to render the pages.
*
* @var string
* @config
*/
public static $template_main = 'Page';
private static $template_main = 'Page';
/**
* Default message set used in permission failures.
*
* @var array|string
*/
protected static $default_message_set = '';
private static $default_message_set = '';
/**
* Random secure token, can be used as a crypto key internally.
@ -93,18 +98,22 @@ class Security extends Controller {
/**
* Get location of word list file
*
* @deprecated 3.2 Use the "Security.word_list" config setting instead
*/
public static function get_word_list() {
return Security::$wordlist;
Deprecation::notice('3.2', 'Use the "Security.word_list" config setting instead');
return self::config()->word_list;
}
/**
* Enable or disable recording of login attempts
* through the {@link LoginRecord} object.
*
*
* @config
* @var boolean $login_recording
*/
protected static $login_recording = false;
private static $login_recording = false;
/**
* @var boolean If set to TRUE or FALSE, {@link database_is_ready()}
@ -122,20 +131,24 @@ class Security extends Controller {
/**
* Set location of word list file
*
*
* @deprecated 3.2 Use the "Security.word_list" config setting instead
* @param string $wordListFile Location of word list file
*/
public static function set_word_list($wordListFile) {
Security::$wordlist = $wordListFile;
Deprecation::notice('3.2', 'Use the "Security.word_list" config setting instead');
self::config()->word_list = $wordListFile;
}
/**
* Set the default message set used in permissions failures.
*
* @deprecated 3.2 Use the "Security.default_message_set" config setting instead
* @param string|array $messageSet
*/
public static function set_default_message_set($messageSet) {
self::$default_message_set = $messageSet;
Deprecation::notice('3.2', 'Use the "Security.default_message_set" config setting instead');
self::config()->default_message_set = $messageSet;
}
@ -761,43 +774,49 @@ class Security extends Controller {
* This prevents sharing of the session across several sites in the
* domain.
*
* @deprecated 3.2 Use the "Security.strict_path_checking" config setting instead
* @param boolean $strictPathChecking To enable or disable strict patch
* checking.
*/
public static function setStrictPathChecking($strictPathChecking) {
self::$strictPathChecking = $strictPathChecking;
Deprecation::notice('3.2', 'Use the "Security.strict_path_checking" config setting instead');
self::config()->strict_path_checking = $strictPathChecking;
}
/**
* Get strict path checking
*
* @deprecated 3.2 Use the "Security.strict_path_checking" config setting instead
* @return boolean Status of strict path checking
*/
public static function getStrictPathChecking() {
return self::$strictPathChecking;
Deprecation::notice('3.2', 'Use the "Security.strict_path_checking" config setting instead');
return self::config()->strict_path_checking;
}
/**
* Set the password encryption algorithm
*
* @deprecated 3.2 Use the "Security.password_encryption_algorithm" config setting instead
* @param string $algorithm One of the available password encryption
* algorithms determined by {@link Security::get_encryption_algorithms()}
* @return bool Returns TRUE if the passed algorithm was valid, otherwise FALSE.
*/
public static function set_password_encryption_algorithm($algorithm) {
if(!array_key_exists($algorithm, PasswordEncryptor::get_encryptors())) return false;
Deprecation::notice('3.2', 'Use the "Security.password_encryption_algorithm" config setting instead');
self::$encryptionAlgorithm = $algorithm;
return true;
self::config()->encryption_algorithm = $algorithm;
}
/**
* @deprecated 3.2 Use the "Security.password_encryption_algorithm" config setting instead
* @return String
*/
public static function get_password_encryption_algorithm() {
return self::$encryptionAlgorithm;
Deprecation::notice('3.2', 'Use the "Security.password_encryption_algorithm" config setting instead');
return self::config()->encryption_algorithm;
}
/**
@ -826,11 +845,10 @@ class Security extends Controller {
* If the passed algorithm is invalid, FALSE will be returned.
*
* @see encrypt_passwords()
* @see set_password_encryption_algorithm()
*/
public static function encrypt_password($password, $salt = null, $algorithm = null, $member = null) {
// Fall back to the default encryption algorithm
if(!$algorithm) $algorithm = self::$encryptionAlgorithm;
if(!$algorithm) $algorithm = self::config()->encryption_algorithm;
$e = PasswordEncryptor::create_for_algorithm($algorithm);
@ -886,38 +904,49 @@ class Security extends Controller {
/**
* Enable or disable recording of login attempts
* through the {@link LoginRecord} object.
*
*
* @deprecated 3.2 Use the "Security.login_recording" config setting instead
* @param boolean $bool
*/
public static function set_login_recording($bool) {
Deprecation::notice('3.2', 'Use the "Security.login_recording" config setting instead');
self::$login_recording = (bool)$bool;
}
/**
* @deprecated 3.2 Use the "Security.login_recording" config setting instead
* @return boolean
*/
public static function login_recording() {
Deprecation::notice('3.2', 'Use the "Security.login_recording" config setting instead');
return self::$login_recording;
}
protected static $default_login_dest = "";
/**
* Set the default login dest
* @config
* @var string Set the default login dest
* This is the URL that users will be redirected to after they log in,
* if they haven't logged in en route to access a secured page.
*
* By default, this is set to the homepage
* By default, this is set to the homepage.
*/
private static $default_login_dest = "";
/**
* @deprecated 3.2 Use the "Security.default_login_dest" config setting instead
*/
public static function set_default_login_dest($dest) {
self::$default_login_dest = $dest;
Deprecation::notice('3.2', 'Use the "Security.default_login_dest" config setting instead');
self::config()->default_login_dest = $dest;
}
/**
* Get the default login dest
* Get the default login dest.
*
* @deprecated 3.2 Use the "Security.default_login_dest" config setting instead
*/
public static function default_login_dest() {
return self::$default_login_dest;
Deprecation::notice('3.2', 'Use the "Security.default_login_dest" config setting instead');
return self::config()->default_login_dest;
}
protected static $ignore_disallowed_actions = false;
@ -935,7 +964,8 @@ class Security extends Controller {
return self::$ignore_disallowed_actions;
}
protected static $login_url = "Security/login";
/** @config */
private static $login_url = "Security/login";
/**
* Set a custom log-in URL if you have built your own log-in page.

21
statics.diff Normal file
View File

@ -0,0 +1,21 @@
--- /Users/ingo/Silverstripe/ss-3.1/framework/security/Security.php
+++ /Users/ingo/Silverstripe/ss-3.1/framework/security/Security.php
@@ -52,2 +52,3 @@
+ * @config
*/
- protected static $encryption_algorithm = 'blowfish';
+ private static $encryption_algorithm = 'blowfish';
--- /Users/ingo/Silverstripe/ss-3.1/framework/security/Security.php
+++ /Users/ingo/Silverstripe/ss-3.1/framework/security/Security.php
@@ -52,2 +52,3 @@
+ * @config
*/
- protected static $encryption_algorithm = 'blowfish';
+ private static $encryption_algorithm = 'blowfish';
--- /Users/ingo/Silverstripe/ss-3.1/framework/security/Security.php
+++ /Users/ingo/Silverstripe/ss-3.1/framework/security/Security.php
@@ -52,2 +52,3 @@
+ * @config
*/
- protected static $encryption_algorithm = 'blowfish';
+ private static $encryption_algorithm = 'blowfish';

View File

@ -28,7 +28,7 @@ class EncryptAllPasswordsTask extends BuildTask {
}
public function run($request) {
$algo = Security::get_password_encryption_algorithm();
$algo = Security::config()->password_encryption_algorithm;
if($algo == 'none') {
$this->debugMessage('Password encryption disabled');
return;

View File

@ -58,21 +58,21 @@ class RSSFeedTest extends SapphireTest {
public function setUp() {
parent::setUp();
Director::setBaseURL('/');
Config::inst()->update('Director', 'alternate_base_url', '/');
if(!self::$original_host) self::$original_host = $_SERVER['HTTP_HOST'];
$_SERVER['HTTP_HOST'] = 'www.example.org';
}
public function tearDown() {
parent::tearDown();
Director::setBaseURL(null);
Config::inst()->update('Director', 'alternate_base_url', null);
$_SERVER['HTTP_HOST'] = self::$original_host;
}
}
class RSSFeedTest_ItemA extends ViewableData {
// RSS-feed items must have $casting/$db information.
static $casting = array(
private static $casting = array(
'Title' => 'Varchar',
'Content' => 'Text',
'AltContent' => 'Text',
@ -117,7 +117,7 @@ class RSSFeedTest_ItemB extends ViewableData {
class RSSFeedTest_ItemC extends ViewableData {
// ItemC tests fields - Title has casting, Content doesn't.
public static $casting = array(
private static $casting = array(
'Title' => 'Varchar',
'AltContent' => 'Text',
);

View File

@ -10,9 +10,9 @@ class RestfulServiceTest extends SapphireTest {
public function setUp() {
// backup the project unique identifier field
$this->member_unique_identifier_field = Member::get_unique_identifier_field();
$this->member_unique_identifier_field = Member::config()->unique_identifier_field;
Member::set_unique_identifier_field('Email');
Member::config()->unique_identifier_field = 'Email';
parent::setUp();
}
@ -20,9 +20,9 @@ class RestfulServiceTest extends SapphireTest {
public function tearDown() {
parent::tearDown();
// set old member::get_unique_identifier_field value
// set old Member::config()->unique_identifier_field value
if ($this->member_unique_identifier_field) {
Member::set_unique_identifier_field($this->member_unique_identifier_field);
Member::config()->unique_identifier_field = $this->member_unique_identifier_field;
}
}
@ -198,7 +198,7 @@ class RestfulServiceTest extends SapphireTest {
class RestfulServiceTest_Controller extends Controller implements TestOnly {
public static $allowed_actions = array(
private static $allowed_actions = array(
'index',
'httpErrorWithoutCache',
'httpErrorWithCache'

View File

@ -2,7 +2,7 @@
class XMLDataFormatterTest extends SapphireTest {
protected $arguments, $contents, $tagName;
public static $fixture_file = 'XMLDataFormatterTest.yml';
protected static $fixture_file = 'XMLDataFormatterTest.yml';
public function setUp() {
ShortcodeParser::get_active()->register('test_shortcode', array($this, 'shortcodeSaver'));
@ -75,7 +75,7 @@ class XMLDataFormatterTest extends SapphireTest {
}
class XMLDataFormatterTest_DataObject extends DataObject implements TestOnly {
public static $db = array(
private static $db = array(
'Name' => 'Varchar(50)',
'Company' => 'Varchar(50)',
'Content' => 'HTMLText'

View File

@ -1,7 +1,7 @@
<?php
class CMSProfileControllerTest extends FunctionalTest {
public static $fixture_file = 'CMSProfileControllerTest.yml';
protected static $fixture_file = 'CMSProfileControllerTest.yml';
public $autoFollowRedirection = false;

View File

@ -2,7 +2,7 @@
class ControllerTest extends FunctionalTest {
static $fixture_file = 'ControllerTest.yml';
protected static $fixture_file = 'ControllerTest.yml';
protected $autoFollowRedirection = false;
@ -285,7 +285,7 @@ class ControllerTest extends FunctionalTest {
/* Controller::BaseURL no longer exists, but was just a direct call to Director::BaseURL, so not sure what this
* code was supposed to test
public function testBaseURL() {
Director::setBaseURL('/baseurl/');
Config::inst()->update('Director', 'alternate_base_url', '/baseurl/');
$this->assertEquals(Controller::BaseURL(), Director::BaseURL());
}
*/
@ -345,7 +345,7 @@ class ControllerTest_Controller extends Controller implements TestOnly {
public $Content = "default content";
public static $allowed_actions = array(
private static $allowed_actions = array(
'methodaction',
'stringaction',
'redirectbacktest',
@ -380,7 +380,7 @@ class ControllerTest_UnsecuredController extends Controller implements TestOnly
class ControllerTest_AccessBaseController extends Controller implements TestOnly {
static $allowed_actions = array();
private static $allowed_actions = array();
// Denied for all
public function method1() {}
@ -391,7 +391,7 @@ class ControllerTest_AccessBaseController extends Controller implements TestOnly
class ControllerTest_AccessSecuredController extends ControllerTest_AccessBaseController implements TestOnly {
static $allowed_actions = array(
private static $allowed_actions = array(
"method1", // denied because only defined in parent
"method2" => true, // granted because its redefined
"adminonly" => "ADMIN",
@ -408,7 +408,7 @@ class ControllerTest_AccessSecuredController extends ControllerTest_AccessBaseCo
class ControllerTest_AccessWildcardSecuredController extends ControllerTest_AccessBaseController implements TestOnly {
static $allowed_actions = array(
private static $allowed_actions = array(
"*" => "ADMIN", // should throw exception
);
@ -416,7 +416,7 @@ class ControllerTest_AccessWildcardSecuredController extends ControllerTest_Acce
class ControllerTest_IndexSecuredController extends ControllerTest_AccessBaseController implements TestOnly {
static $allowed_actions = array(
private static $allowed_actions = array(
"index" => "ADMIN",
);
@ -424,7 +424,7 @@ class ControllerTest_IndexSecuredController extends ControllerTest_AccessBaseCon
class ControllerTest_AccessBaseControllerExtension extends Extension implements TestOnly {
static $allowed_actions = array(
private static $allowed_actions = array(
"extensionmethod1" => true, // granted because defined on this class
"method1" => true, // ignored because method not defined on this class
"method2" => true, // ignored because method not defined on this class
@ -446,7 +446,7 @@ class ControllerTest_AccessBaseControllerExtension extends Extension implements
class ControllerTest_HasAction extends Controller {
public static $allowed_actions = array (
private static $allowed_actions = array (
'allowed_action',
//'other_action' => 'lowercase_permission'
);

View File

@ -57,20 +57,20 @@ class DirectorTest extends SapphireTest {
public function testAlternativeBaseURL() {
// relative base URLs - you should end them in a /
Director::setBaseURL('/relativebase/');
Config::inst()->update('Director', 'alternate_base_url', '/relativebase/');
$this->assertEquals('/relativebase/', Director::baseURL());
$this->assertEquals(Director::protocolAndHost() . '/relativebase/', Director::absoluteBaseURL());
$this->assertEquals(Director::protocolAndHost() . '/relativebase/subfolder/test',
Director::absoluteURL('subfolder/test'));
// absolute base URLs - you should end them in a /
Director::setBaseURL('http://www.example.org/');
Config::inst()->update('Director', 'alternate_base_url', 'http://www.example.org/');
$this->assertEquals('http://www.example.org/', Director::baseURL());
$this->assertEquals('http://www.example.org/', Director::absoluteBaseURL());
$this->assertEquals('http://www.example.org/subfolder/test', Director::absoluteURL('subfolder/test'));
// Setting it to false restores functionality
Director::setBaseURL(false);
Config::inst()->update('Director', 'alternate_base_url', false);
$this->assertEquals(BASE_URL.'/', Director::baseURL());
$this->assertEquals(Director::protocolAndHost().BASE_URL.'/', Director::absoluteBaseURL(BASE_URL));
$this->assertEquals(Director::protocolAndHost().BASE_URL . '/subfolder/test',

View File

@ -1,7 +1,7 @@
<?php
class HTTPRequestTest extends SapphireTest {
static $fixture_file = null;
protected static $fixture_file = null;
public function testMatch() {
$request = new SS_HTTPRequest("GET", "admin/crm/add");

View File

@ -193,9 +193,9 @@ class HTTPTest extends SapphireTest {
* @param callable $callback The test to run
*/
protected function withBaseURL($url, $callback) {
$oldBase = Director::$alternateBaseURL;
Director::setBaseURL($url);
$oldBase = Config::inst()->get('Director', 'alternate_base_url');
Config::inst()->update('Director', 'alternate_base_url', $url);
$callback($this);
Director::setBaseURL($oldBase);
Config::inst()->update('Director', 'alternate_base_url', $oldBase);
}
}

View File

@ -5,7 +5,7 @@
* We've set up a simple URL handling model based on
*/
class RequestHandlingTest extends FunctionalTest {
static $fixture_file = null;
protected static $fixture_file = null;
// public function testRequestHandlerChainingLatestParams() {
// $c = new RequestHandlingTest_Controller();
@ -292,7 +292,7 @@ Config::inst()->update('Director', 'rules', array(
*/
class RequestHandlingTest_Controller extends Controller implements TestOnly {
static $allowed_actions = array(
private static $allowed_actions = array(
'method',
'legacymethod',
'virtualfile',
@ -302,12 +302,12 @@ class RequestHandlingTest_Controller extends Controller implements TestOnly {
'throwhttperror',
);
static $url_handlers = array(
private static $url_handlers = array(
// The double-slash is need here to ensure that
'$Action//$ID/$OtherID' => "handleAction",
);
static $extensions = array(
private static $extensions = array(
'RequestHandlingTest_ControllerExtension',
'RequestHandlingTest_AllowedControllerExtension',
);
@ -364,7 +364,7 @@ class RequestHandlingTest_FormActionController extends Controller {
protected $template = 'BlankPage';
static $allowed_actions = array(
private static $allowed_actions = array(
'controlleraction',
'Form',
'formactionInAllowedActions'
@ -447,19 +447,19 @@ class RequestHandlingTest_ControllerExtension extends Extension {
* Controller for the test
*/
class RequestHandlingTest_AllowedController extends Controller implements TestOnly {
static $url_handlers = array(
private static $url_handlers = array(
// The double-slash is need here to ensure that
'$Action//$ID/$OtherID' => "handleAction",
);
static $allowed_actions = array(
private static $allowed_actions = array(
'failoverMethod', // part of the failover object
'extendedMethod', // part of the RequestHandlingTest_ControllerExtension object
'blockMethod' => '->provideAccess(false)',
'allowMethod' => '->provideAccess',
);
static $extensions = array(
private static $extensions = array(
'RequestHandlingTest_ControllerExtension',
'RequestHandlingTest_AllowedControllerExtension',
);
@ -490,7 +490,7 @@ class RequestHandlingTest_AllowedController extends Controller implements TestOn
* Simple extension for the test controller - with allowed_actions define
*/
class RequestHandlingTest_AllowedControllerExtension extends Extension {
static $allowed_actions = array(
private static $allowed_actions = array(
'otherExtendedMethod'
);
@ -509,14 +509,14 @@ class RequestHandlingTest_ControllerFailover extends ViewableData {
* Form for the test
*/
class RequestHandlingTest_Form extends Form {
static $url_handlers = array(
private static $url_handlers = array(
'fields/$FieldName' => 'handleField',
"POST " => "handleSubmission",
"GET " => "handleGet",
);
// These are a different case from those in url_handlers to confirm that it's all case-insensitive
static $allowed_actions = array(
private static $allowed_actions = array(
'handlesubmission',
'handlefield',
'handleget',
@ -552,7 +552,7 @@ class RequestHandlingTest_ControllerFormWithAllowedActions extends Controller im
class RequestHandlingTest_FormWithAllowedActions extends Form {
static $allowed_actions = array(
private static $allowed_actions = array(
'allowedformaction' => 1,
'httpSubmission' => 1, // TODO This should be an exception on the parent class
);
@ -571,14 +571,14 @@ class RequestHandlingTest_FormWithAllowedActions extends Form {
* Form field for the test
*/
class RequestHandlingTest_FormField extends FormField {
static $url_handlers = array(
private static $url_handlers = array(
"POST " => "handleInPlaceEdit",
'' => 'handleField',
'$Action' => '$Action',
);
// These contain uppercase letters to test that allowed_actions doesn't need to be all lowercase
static $allowed_actions = array(
private static $allowed_actions = array(
'TEST',
'handleField',
'handleInPLACEEDIT',
@ -604,7 +604,7 @@ class RequestHandlingTest_FormField extends FormField {
class RequestHandlingTest_SubclassedFormField extends RequestHandlingTest_FormField {
// We have some url_handlers defined that override RequestHandlingTest_FormField handlers.
// We will confirm that the url_handlers inherit.
static $url_handlers = array(
private static $url_handlers = array(
'something' => 'customSomething',
);
@ -634,7 +634,7 @@ class RequestHandlingFieldTest_Controller extends Controller implements TestOnly
*/
class RequestHandlingTest_HandlingField extends FormField {
static $allowed_actions = array(
private static $allowed_actions = array(
'actionOnField'
);

View File

@ -77,9 +77,9 @@ class SessionTest extends SapphireTest {
}
public function testNonStandardPath(){
Session::set_session_store_path(realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
Config::inst()->update('Session', 'store_path', (realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session')));
Session::start();
$this->assertEquals(Session::get_session_store_path(), '');
$this->assertEquals(Config::inst()->get('Session', 'store_path'), '');
}
}

View File

@ -107,9 +107,9 @@ class ClassInfoTest_GrandChildClass extends ClassInfoTest_ChildClass {
}
class ClassInfoTest_BaseDataClass extends DataObject {
public static $db = array('Title' => 'Varchar');
private static $db = array('Title' => 'Varchar');
}
class ClassInfoTest_NoFields extends ClassInfoTest_BaseDataClass {}
class ClassInfoTest_HasFields extends ClassInfoTest_NoFields {
public static $db = array('Description' => 'Varchar');
private static $db = array('Description' => 'Varchar');
}

View File

@ -18,28 +18,38 @@ class ConfigTest_DefinesFooDoesntExtendObject {
}
class ConfigStaticTest_First extends Config {
public static $first = array('test_1');
public static $second = array('test_1');
public static $third = 'test_1';
/** @config */
private static $first = array('test_1');
/** @config */
private static $second = array('test_1');
/** @config */
private static $third = 'test_1';
public static $bool = true;
public static $int = 42;
public static $string = 'value';
public static $nullable = 'value';
/** @config */
private static $bool = true;
/** @config */
private static $int = 42;
/** @config */
private static $string = 'value';
/** @config */
private static $nullable = 'value';
public static $default_false = false;
public static $default_null = null;
public static $default_zero = 0;
/** @config */
private static $default_false = false;
/** @config */
private static $default_null = null;
/** @config */
private static $default_zero = 0;
public static $default_emtpy_string = '';
}
class ConfigStaticTest_Second extends ConfigStaticTest_First {
public static $first = array('test_2');
private static $first = array('test_2');
}
class ConfigStaticTest_Third extends ConfigStaticTest_Second {
public static $first = array('test_3');
public static $second = array('test_3');
private static $first = array('test_3');
private static $second = array('test_3');
public static $fourth = array('test_3');
}
@ -48,18 +58,20 @@ class ConfigStaticTest_Fourth extends ConfigStaticTest_Third {
}
class ConfigStaticTest_Combined1 extends Config {
public static $first = array('test_1');
public static $second = array('test_1');
/** @config */
private static $first = array('test_1');
/** @config */
private static $second = array('test_1');
}
class ConfigStaticTest_Combined2 extends ConfigStaticTest_Combined1 {
public static $first = array('test_2');
public static $second = null;
private static $first = array('test_2');
private static $second = null;
}
class ConfigStaticTest_Combined3 extends ConfigStaticTest_Combined2 {
public static $first = array('test_3');
public static $second = array('test_3');
private static $first = array('test_3');
private static $second = array('test_3');
}
class ConfigTest extends SapphireTest {
@ -88,6 +100,7 @@ class ConfigTest extends SapphireTest {
array('test_3_2', 'test_3'));
Config::inst()->remove('ConfigStaticTest_Third', 'second');
$this->assertEquals(array(), Config::inst()->get('ConfigStaticTest_Third', 'second'));
Config::inst()->update('ConfigStaticTest_Third', 'second', array('test_3_2'));
$this->assertEquals(Config::inst()->get('ConfigStaticTest_Third', 'second', Config::FIRST_SET),
array('test_3_2'));

View File

@ -131,13 +131,13 @@ class ConvertTest extends SapphireTest {
* @todo test toASCII()
*/
public function testRaw2URL() {
$orig = URLSegmentFilter::$default_allow_multibyte;
URLSegmentFilter::$default_allow_multibyte = false;
$orig = Config::inst()->get('URLSegmentFilter', 'default_allow_multibyte');
Config::inst()->update('URLSegmentFilter', 'default_allow_multibyte', false);
$this->assertEquals('foo', Convert::raw2url('foo'));
$this->assertEquals('foo-and-bar', Convert::raw2url('foo & bar'));
$this->assertEquals('foo-and-bar', Convert::raw2url('foo &amp; bar!'));
$this->assertEquals('foos-bar-2', Convert::raw2url('foo\'s [bar] (2)'));
URLSegmentFilter::$default_allow_multibyte = $orig;
Config::inst()->update('URLSegmentFilter', 'default_allow_multibyte', $orig);
}
/**

View File

@ -74,7 +74,7 @@ class ObjectTest extends SapphireTest {
public function testStaticGetterMethod() {
$obj = singleton('ObjectTest_MyObject');
$this->assertEquals(
ObjectTest_MyObject::$mystaticProperty,
'MyObject',
$obj->stat('mystaticProperty'),
'Uninherited statics through stat() on a singleton behave the same as built-in PHP statics'
);
@ -444,13 +444,14 @@ class ObjectTest_T2 extends Object {
class ObjectTest_MyObject extends Object {
public $title = 'my object';
static $mystaticProperty = "MyObject";
/** @config */
private static $mystaticProperty = "MyObject";
static $mystaticArray = array('one');
}
class ObjectTest_MySubObject extends ObjectTest_MyObject {
public $title = 'my subobject';
static $mystaticProperty = "MySubObject";
private static $mystaticProperty = "MySubObject";
static $mystaticSubProperty = "MySubObject";
static $mystaticArray = array('two');
}
@ -471,7 +472,7 @@ class ObjectTest_CreateTest3 extends Object {}
class ObjectTest_ExtensionTest extends Object {
public static $extensions = array (
private static $extensions = array (
'oBjEcTTEST_ExtendTest1',
"ObjectTest_ExtendTest2('FOO', 'BAR')",
);
@ -479,12 +480,12 @@ class ObjectTest_ExtensionTest extends Object {
}
class ObjectTest_ExtensionTest2 extends Object {
public static $extensions = array('ObjectTest_Extension');
private static $extensions = array('ObjectTest_Extension');
}
class ObjectTest_ExtensionRemoveTest extends Object {
public static $extensions = array (
private static $extensions = array (
'ObjectTest_ExtendTest1',
);
@ -508,7 +509,7 @@ class ObjectTest_CacheTest extends Object {
}
class ObjectTest_ExtendTest extends Object {
public static $extensions = array('ObjectTest_ExtendTest1', 'ObjectTest_ExtendTest2');
private static $extensions = array('ObjectTest_ExtendTest1', 'ObjectTest_ExtendTest2');
public function extendableMethod($argument = null) { return "ExtendTest($argument)"; }
}

View File

@ -24,8 +24,6 @@ class BacktraceTest extends SapphireTest {
}
public function testIgnoredFunctionArgs() {
$orig = SS_Backtrace::$ignore_function_args;
$bt = array(
array(
'type' => '->',
@ -51,8 +49,13 @@ class BacktraceTest extends SapphireTest {
'args' => array('myarg' => 'myval')
)
);
SS_Backtrace::$ignore_function_args[] = array('MyClass', 'myIgnoredClassFunction');
SS_Backtrace::$ignore_function_args[] = 'myIgnoredGlobalFunction';
$orig = Config::inst()->get('SS_Backtrace', 'ignore_function_args');
Config::inst()->update('SS_Backtrace', 'ignore_function_args',
array(
array('MyClass', 'myIgnoredClassFunction'),
'myIgnoredGlobalFunction'
)
);
$filtered = SS_Backtrace::filter_backtrace($bt);
@ -60,7 +63,8 @@ class BacktraceTest extends SapphireTest {
$this->assertEquals('<filtered>', $filtered[1]['args']['password'], 'Filters class functions');
$this->assertEquals('myval', $filtered[2]['args']['myarg'], 'Doesnt filter other functions');
SS_Backtrace::$ignore_function_args = $orig;
Config::inst()->remove('SS_Backtrace', 'ignore_function_args');
Config::inst()->update('SS_Backtrace', 'ignore_function_args', $orig);
}
}

View File

@ -5,7 +5,7 @@
* @todo Test with columnn headers and custom mappings
*/
class CsvBulkLoaderTest extends SapphireTest {
static $fixture_file = 'CsvBulkLoaderTest.yml';
protected static $fixture_file = 'CsvBulkLoaderTest.yml';
protected $extraDataObjects = array(
'CsvBulkLoaderTest_Team',
@ -206,12 +206,12 @@ class CsvBulkLoaderTest_CustomLoader extends CsvBulkLoader implements TestOnly {
class CsvBulkLoaderTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar(255)',
'TeamSize' => 'Int',
);
static $has_many = array(
private static $has_many = array(
'Players' => 'CsvBulkLoaderTest_Player',
);
@ -219,7 +219,7 @@ class CsvBulkLoaderTest_Team extends DataObject implements TestOnly {
class CsvBulkLoaderTest_Player extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'FirstName' => 'Varchar(255)',
'Biography' => 'HTMLText',
'Birthday' => 'Date',
@ -227,7 +227,7 @@ class CsvBulkLoaderTest_Player extends DataObject implements TestOnly {
'IsRegistered' => 'Boolean'
);
static $has_one = array(
private static $has_one = array(
'Team' => 'CsvBulkLoaderTest_Team',
'Contract' => 'CsvBulkLoaderTest_PlayerContract'
);
@ -250,7 +250,7 @@ class CsvBulkLoaderTest_Player extends DataObject implements TestOnly {
}
class CsvBulkLoaderTest_PlayerContract extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Amount' => 'Currency',
);
}

View File

@ -152,19 +152,19 @@ class FixtureFactoryTest extends SapphireTest {
}
class FixtureFactoryTest_DataObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar"
);
static $many_many = array(
private static $many_many = array(
"ManyMany" => "FixtureFactoryTest_DataObjectRelation"
);
}
class FixtureFactoryTest_DataObjectRelation extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar"
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
"TestParent" => "FixtureFactoryTest_DataObject"
);
}

View File

@ -5,7 +5,7 @@
*/
class FileTest extends SapphireTest {
static $fixture_file = 'FileTest.yml';
protected static $fixture_file = 'FileTest.yml';
protected $extraDataObjects = array('FileTest_MyCustomFile');
@ -95,8 +95,9 @@ class FileTest extends SapphireTest {
public function testValidateExtension() {
Session::set('loggedInAs', null);
$origExts = File::$allowed_extensions;
File::$allowed_extensions = array('txt');
$orig = Config::inst()->get('File', 'allowed_extensions');
Config::inst()->remove('File', 'allowed_extensions');
Config::inst()->update('File', 'allowed_extensions', array('txt'));
$file = $this->objFromFixture('File', 'asdf');
@ -115,8 +116,9 @@ class FileTest extends SapphireTest {
$file->Name = 'asdf.TXT';
$v = $file->validate();
$this->assertTrue($v->valid());
File::$allowed_extensions = $origExts;
Config::inst()->remove('File', 'allowed_extensions');
Config::inst()->update('File', 'allowed_extensions', $orig);
}
public function testSetNameChangesFilesystemOnWrite() {
@ -168,8 +170,9 @@ class FileTest extends SapphireTest {
* @expectedException ValidationException
*/
public function testSetNameWithInvalidExtensionDoesntChangeFilesystem() {
$origExts = File::$allowed_extensions;
File::$allowed_extensions = array('txt');
$orig = Config::inst()->get('File', 'allowed_extensions');
Config::inst()->remove('File', 'allowed_extensions');
Config::inst()->update('File', 'allowed_extensions', array('txt'));
$file = $this->objFromFixture('File', 'asdf');
$oldPath = $file->getFullPath();
@ -178,7 +181,8 @@ class FileTest extends SapphireTest {
try {
$file->write();
} catch(ValidationException $e) {
File::$allowed_extensions = $origExts;
Config::inst()->remove('File', 'allowed_extensions');
Config::inst()->update('File', 'allowed_extensions', $orig);
throw $e;
}
}
@ -321,9 +325,9 @@ class FileTest extends SapphireTest {
public function testGetClassForFileExtension() {
$orig = File::$class_for_file_extension;
File::$class_for_file_extension['*'] = 'MyGenericFileClass';
File::$class_for_file_extension['foo'] = 'MyFooFileClass';
$orig = File::config()->class_for_file_extension;
File::config()->class_for_file_extension = array('*' => 'MyGenericFileClass');
File::config()->class_for_file_extension = array('foo' => 'MyFooFileClass');
$this->assertEquals(
'MyFooFileClass',
@ -341,19 +345,19 @@ class FileTest extends SapphireTest {
'Falls back to generic class for unknown extensions'
);
File::$class_for_file_extension = $orig;
File::config()->class_for_file_extension = $orig;
}
public function testFolderConstructChild() {
$orig = File::$class_for_file_extension;
File::$class_for_file_extension['gif'] = 'FileTest_MyCustomFile';
$orig = File::config()->class_for_file_extension;
File::config()->class_for_file_extension = array('gif' => 'FileTest_MyCustomFile');
$folder1 = $this->objFromFixture('Folder', 'folder1');
$fileID = $folder1->constructChild('myfile.gif');
$file = DataObject::get_by_id('File', $fileID);
$this->assertEquals('FileTest_MyCustomFile', get_class($file));
File::$class_for_file_extension = $orig;
File::config()->class_for_file_extension = $orig;
}
public function testSetsOwnerOnFirstWrite() {

View File

@ -8,7 +8,7 @@
*/
class FolderTest extends SapphireTest {
static $fixture_file = 'FileTest.yml';
protected static $fixture_file = 'FileTest.yml';
public function testCreateFromNameAndParentIDSetsFilename() {
$folder1 = $this->objFromFixture('Folder', 'folder1');

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class UploadTest extends SapphireTest {
static $fixture_file = 'UploadTest.yml';
protected static $fixture_file = 'UploadTest.yml';
public function testUpload() {
// create tmp file
@ -36,7 +36,13 @@ class UploadTest extends SapphireTest {
'File upload to standard directory in /assets'
);
$this->assertTrue(
(strpos($file1->getFullPath(), Director::baseFolder() . '/assets/' . Upload::$uploads_folder) !== false),
(
strpos(
$file1->getFullPath(),
Director::baseFolder() . '/assets/' . Config::inst()->get('Upload', 'uploads_folder')
)
!== false
),
'File upload to standard directory in /assets'
);
$file1->delete();
@ -214,7 +220,7 @@ class UploadTest extends SapphireTest {
// @param String $namePattern A regular expression applied to files in the directory. If the name matches
// the pattern, it is deleted. Directories, . and .. are excluded.
public function deleteTestUploadFiles($namePattern) {
$tmpFolder = ASSETS_PATH . "/" . Upload::$uploads_folder;
$tmpFolder = ASSETS_PATH . "/" . Config::inst()->get('Upload', 'uploads_folder');
$files = scandir($tmpFolder);
foreach ($files as $f) {
if ($f == "." || $f == ".." || is_dir("$tmpFolder/$f")) continue;

View File

@ -142,7 +142,7 @@ class CheckboxFieldTest extends SapphireTest {
}
class CheckboxFieldTest_Article extends DataObject implements TestOnly {
public static $db = array(
private static $db = array(
'IsChecked' => 'Boolean'
);

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class CheckboxSetFieldTest extends SapphireTest {
static $fixture_file = 'CheckboxSetFieldTest.yml';
protected static $fixture_file = 'CheckboxSetFieldTest.yml';
protected $extraDataObjects = array(
'CheckboxSetFieldTest_Article',
@ -125,18 +125,18 @@ class CheckboxSetFieldTest extends SapphireTest {
}
class CheckboxSetFieldTest_Article extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Content" => "Text",
);
static $many_many = array(
private static $many_many = array(
"Tags" => "CheckboxSetFieldTest_Tag",
);
}
class CheckboxSetFieldTest_Tag extends DataObject implements TestOnly {
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Articles' => 'CheckboxSetFieldTest_Article'
);
}

View File

@ -10,15 +10,16 @@ class DateFieldTest extends SapphireTest {
$this->originalLocale = i18n::get_locale();
i18n::set_locale('en_NZ');
$this->origDateFormat = DateField::$default_config['dateformat'];
DateField::$default_config['dateformat'] = 'dd/MM/yyyy';
$this->origConfig = Config::inst()->get('DateField', 'default_config');
Config::inst()->update('DateField', 'default_config', array('dateformat' => 'dd/MM/yyyy'));
}
public function tearDown() {
parent::tearDown();
i18n::set_locale($this->originalLocale);
DateField::$default_config['dateformat'] = $this->origDateFormat;
Config::inst()->remove('DateField', 'default_config');
Config::inst()->update('DateField', 'default_config', $this->origConfig);
}
public function testValidateMinDate() {

View File

@ -10,18 +10,20 @@ class DatetimeFieldTest extends SapphireTest {
$this->originalLocale = i18n::get_locale();
i18n::set_locale('en_NZ');
$this->origDateFormat = DateField::$default_config['dateformat'];
DateField::$default_config['dateformat'] = 'dd/MM/yyyy';
$this->origTimeFormat = TimeField::$default_config['timeformat'];
TimeField::$default_config['timeformat'] = 'HH:mm:ss';
$this->origDateConfig = Config::inst()->get('DateField', 'default_config');
$this->origTimeConfig = Config::inst()->get('TimeField', 'default_config');
Config::inst()->update('DateField', 'default_config', array('dateformat' => 'dd/MM/yyyy'));
Config::inst()->update('TimeField', 'default_config', array('timeformat' => 'HH:mm:ss'));
}
public function tearDown() {
parent::tearDown();
i18n::set_locale($this->originalLocale);
DateField::$default_config['dateformat'] = $this->origDateFormat;
TimeField::$default_config['timeformat'] = $this->origTimeFormat;
Config::inst()->remove('DateField', 'default_config');
Config::inst()->update('DateField', 'default_config', $this->origDateConfig);
Config::inst()->remove('TimeField', 'default_config');
Config::inst()->update('TimeField', 'default_config', $this->origTimeConfig);
}
public function testFormSaveInto() {
@ -230,7 +232,7 @@ class DatetimeFieldTest extends SapphireTest {
*/
class DatetimeFieldTest_Model extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'MyDatetime' => 'SS_Datetime'
);

View File

@ -73,7 +73,7 @@ class EmailFieldTest_Validator extends Validator {
class EmailFieldTest_Controller extends Controller implements TestOnly {
static $url_handlers = array(
private static $url_handlers = array(
'$Action//$ID/$OtherID' => "handleAction",
);

View File

@ -9,7 +9,7 @@
*/
class FormScaffolderTest extends SapphireTest {
static $fixture_file = 'FormScaffolderTest.yml';
protected static $fixture_file = 'FormScaffolderTest.yml';
protected $extraDataObjects = array(
'FormScaffolderTest_Article',
@ -106,36 +106,36 @@ class FormScaffolderTest extends SapphireTest {
}
class FormScaffolderTest_Article extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
'Content' => 'HTMLText'
);
static $has_one = array(
private static $has_one = array(
'Author' => 'FormScaffolderTest_Author'
);
static $many_many = array(
private static $many_many = array(
'Tags' => 'FormScaffolderTest_Tag',
);
}
class FormScaffolderTest_Author extends Member implements TestOnly {
static $has_one = array(
private static $has_one = array(
'ProfileImage' => 'Image'
);
static $has_many = array(
private static $has_many = array(
'Articles' => 'FormScaffolderTest_Article'
);
}
class FormScaffolderTest_Tag extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Articles' => 'FormScaffolderTest_Article'
);
}
class FormScaffolderTest_ArticleExtension extends DataExtension implements TestOnly {
static $db = array(
private static $db = array(
'ExtendedField' => 'Varchar'
);

View File

@ -5,7 +5,7 @@
*/
class FormTest extends FunctionalTest {
static $fixture_file = 'FormTest.yml';
protected static $fixture_file = 'FormTest.yml';
protected $extraDataObjects = array(
'FormTest_Player',
@ -408,17 +408,17 @@ class FormTest extends FunctionalTest {
}
class FormTest_Player extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Biography' => 'Text',
'Birthday' => 'Date'
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Teams' => 'FormTest_Team'
);
static $has_one = array(
private static $has_one = array(
'FavouriteTeam' => 'FormTest_Team',
);
@ -429,18 +429,18 @@ class FormTest_Player extends DataObject implements TestOnly {
}
class FormTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Region' => 'Varchar',
);
static $many_many = array(
private static $many_many = array(
'Players' => 'FormTest_Player'
);
}
class FormTest_Controller extends Controller implements TestOnly {
static $url_handlers = array(
private static $url_handlers = array(
'$Action//$ID/$OtherID' => "handleAction",
);
@ -502,7 +502,7 @@ class FormTest_Controller extends Controller implements TestOnly {
}
class FormTest_ControllerWithSecurityToken extends Controller implements TestOnly {
static $url_handlers = array(
private static $url_handlers = array(
'$Action//$ID/$OtherID' => "handleAction",
);

View File

@ -466,16 +466,16 @@ class GridFieldTest_Component2 implements GridField_DataManipulator, TestOnly {
}
class GridFieldTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar'
);
static $many_many = array('Players' => 'GridFieldTest_Player');
private static $many_many = array('Players' => 'GridFieldTest_Player');
static $has_many = array('Cheerleaders' => 'GridFieldTest_Cheerleader');
private static $has_many = array('Cheerleaders' => 'GridFieldTest_Cheerleader');
static $searchable_fields = array(
private static $searchable_fields = array(
'Name',
'City',
'Cheerleaders.Name'
@ -483,20 +483,20 @@ class GridFieldTest_Team extends DataObject implements TestOnly {
}
class GridFieldTest_Player extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Email' => 'Varchar',
);
static $belongs_many_many = array('Teams' => 'GridFieldTest_Team');
private static $belongs_many_many = array('Teams' => 'GridFieldTest_Team');
}
class GridFieldTest_Cheerleader extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar'
);
static $has_one = array('Team' => 'GridFieldTest_Team');
private static $has_one = array('Team' => 'GridFieldTest_Team');
}
class GridFieldTest_HTMLFragments implements GridField_HTMLProvider, TestOnly{
@ -510,12 +510,12 @@ class GridFieldTest_HTMLFragments implements GridField_HTMLProvider, TestOnly{
}
class GridFieldTest_Permissions extends DataObject implements TestOnly {
public static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Email' => 'Varchar',
);
public static $summary_fields = array(
private static $summary_fields = array(
'Name',
'Email'
);

View File

@ -5,9 +5,9 @@
*/
class HtmlEditorFieldTest extends FunctionalTest {
public static $fixture_file = 'HtmlEditorFieldTest.yml';
protected static $fixture_file = 'HtmlEditorFieldTest.yml';
public static $use_draft_site = true;
protected static $use_draft_site = true;
protected $requiredExtensions = array(
'HtmlEditorField_Toolbar' => array('HtmlEditorFieldTest_DummyMediaFormFieldExtension')
@ -110,7 +110,7 @@ class HtmlEditorFieldTest_DummyMediaFormFieldExtension extends Extension impleme
}
class HtmlEditorFieldTest_Object extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
'Content' => 'HTMLText'
);

View File

@ -6,7 +6,7 @@
class ListboxFieldTest extends SapphireTest {
static $fixture_file = 'ListboxFieldTest.yml';
protected static $fixture_file = 'ListboxFieldTest.yml';
protected $extraDataObjects = array('ListboxFieldTest_DataObject', 'ListboxFieldTest_Article',
'ListboxFieldTest_Tag');
@ -197,24 +197,24 @@ class ListboxFieldTest extends SapphireTest {
}
class ListboxFieldTest_DataObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Choices' => 'Text'
);
}
class ListboxFieldTest_Article extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Content" => "Text",
);
static $many_many = array(
private static $many_many = array(
"Tags" => "ListboxFieldTest_Tag",
);
}
class ListboxFieldTest_Tag extends DataObject implements TestOnly {
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Articles' => 'ListboxFieldTest_Article'
);
}

View File

@ -6,7 +6,7 @@
class LookupFieldTest extends SapphireTest {
static $fixture_file = 'LookupFieldTest.yml';
protected static $fixture_file = 'LookupFieldTest.yml';
public function testNullValueWithNumericArraySource() {
$source = array(1 => 'one', 2 => 'two', 3 => 'three');

View File

@ -5,7 +5,7 @@
*/
class MemberDatetimeOptionsetFieldTest extends SapphireTest {
public static $fixture_file = 'MemberDatetimeOptionsetFieldTest.yml';
protected static $fixture_file = 'MemberDatetimeOptionsetFieldTest.yml';
protected function createDateFormatFieldForMember($member) {
require_once 'Zend/Date.php';

View File

@ -68,7 +68,7 @@ class MoneyFieldTest extends SapphireTest {
}
class MoneyFieldTest_Object extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'MyMoney' => 'Money',
);
}
@ -78,7 +78,7 @@ class MoneyFieldTest_Object extends DataObject implements TestOnly {
* MyMoney.
*/
class MoneyFieldTest_CustomSetter_Object extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'MyMoney' => 'Money',
);

View File

@ -10,15 +10,16 @@ class TimeFieldTest extends SapphireTest {
$this->originalLocale = i18n::get_locale();
i18n::set_locale('en_NZ');
$this->origTimeFormat = TimeField::$default_config['timeformat'];
TimeField::$default_config['timeformat'] = 'HH:mm:ss';
$this->origTimeConfig = Config::inst()->get('TimeField', 'default_config');
Config::inst()->update('TimeField', 'default_config', array('timeformat' => 'HH:mm:ss'));
}
public function tearDown() {
parent::tearDown();
i18n::set_locale($this->originalLocale);
TimeField::$default_config['timeformat'] = $this->origTimeFormat;
Config::inst()->remove('TimeField', 'default_config');
Config::inst()->update('TimeField', 'default_config', $this->origTimeConfig);
}
public function testConstructorWithoutArgs() {

View File

@ -1,7 +1,7 @@
<?php
class GridFieldAddExistingAutocompleterTest extends FunctionalTest {
static $fixture_file = 'GridFieldTest.yml';
protected static $fixture_file = 'GridFieldTest.yml';
protected $extraDataObjects = array('GridFieldTest_Team', 'GridFieldTest_Player', 'GridFieldTest_Cheerleader');

View File

@ -12,7 +12,7 @@ class GridFieldDeleteActionTest extends SapphireTest {
protected $form;
/** @var string */
public static $fixture_file = 'GridFieldActionTest.yml';
protected static $fixture_file = 'GridFieldActionTest.yml';
/** @var array */
protected $extraDataObjects = array('GridFieldAction_Delete_Team', 'GridFieldAction_Edit_Team');
@ -88,7 +88,7 @@ class GridFieldDeleteActionTest extends SapphireTest {
}
class GridFieldAction_Delete_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar'
);

View File

@ -1,7 +1,7 @@
<?php
class GridFieldDetailFormTest extends FunctionalTest {
static $fixture_file = 'GridFieldDetailFormTest.yml';
protected static $fixture_file = 'GridFieldDetailFormTest.yml';
protected $extraDataObjects = array(
'GridFieldDetailFormTest_Person',
@ -223,26 +223,26 @@ class GridFieldDetailFormTest extends FunctionalTest {
}
class GridFieldDetailFormTest_Person extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'FirstName' => 'Varchar',
'Surname' => 'Varchar'
);
static $has_one = array(
private static $has_one = array(
'Group' => 'GridFieldDetailFormTest_PeopleGroup'
);
static $many_many = array(
private static $many_many = array(
'Categories' => 'GridFieldDetailFormTest_Category'
);
static $many_many_extraFields = array(
private static $many_many_extraFields = array(
'Categories' => array(
'IsPublished' => 'Boolean'
)
);
static $default_sort = 'FirstName';
private static $default_sort = 'FirstName';
public function getCMSFields() {
$fields = parent::getCMSFields();
@ -258,15 +258,15 @@ class GridFieldDetailFormTest_Person extends DataObject implements TestOnly {
}
class GridFieldDetailFormTest_PeopleGroup extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar'
);
static $has_many = array(
private static $has_many = array(
'People' => 'GridFieldDetailFormTest_Person'
);
static $default_sort = 'Name';
private static $default_sort = 'Name';
public function getCMSFields() {
$fields = parent::getCMSFields();
@ -282,15 +282,15 @@ class GridFieldDetailFormTest_PeopleGroup extends DataObject implements TestOnly
}
class GridFieldDetailFormTest_Category extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar'
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'People' => 'GridFieldDetailFormTest_Person'
);
static $default_sort = 'Name';
private static $default_sort = 'Name';
public function getCMSFields() {
$fields = parent::getCMSFields();

View File

@ -12,7 +12,7 @@ class GridFieldEditButtonTest extends SapphireTest {
protected $form;
/** @var string */
public static $fixture_file = 'GridFieldActionTest.yml';
protected static $fixture_file = 'GridFieldActionTest.yml';
/** @var array */
protected $extraDataObjects = array('GridFieldAction_Delete_Team', 'GridFieldAction_Edit_Team');
@ -46,7 +46,7 @@ class GridFieldEditButtonTest extends SapphireTest {
}
class GridFieldAction_Edit_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar'
);

View File

@ -7,7 +7,7 @@ class GridFieldExportButtonTest extends SapphireTest {
protected $form;
public static $fixture_file = 'GridFieldExportButtonTest.yml';
protected static $fixture_file = 'GridFieldExportButtonTest.yml';
protected $extraDataObjects = array(
'GridFieldExportButtonTest_Team'
@ -77,7 +77,7 @@ class GridFieldExportButtonTest extends SapphireTest {
}
class GridFieldExportButtonTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'City' => 'Varchar'
);

View File

@ -7,7 +7,7 @@ class GridFieldPaginatorTest extends FunctionalTest {
protected $gridField;
/** @var string */
static $fixture_file = 'GridFieldTest.yml';
protected static $fixture_file = 'GridFieldTest.yml';
/** @var Form */
protected $form;

View File

@ -6,7 +6,7 @@
class UploadFieldTest extends FunctionalTest {
static $fixture_file = 'UploadFieldTest.yml';
protected static $fixture_file = 'UploadFieldTest.yml';
protected $extraDataObjects = array('UploadFieldTest_Record');
@ -726,23 +726,23 @@ class UploadFieldTest extends FunctionalTest {
class UploadFieldTest_Record extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Text',
);
static $has_one = array(
private static $has_one = array(
'HasOneFile' => 'File',
'HasOneFileMaxOne' => 'File',
'HasOneFileMaxTwo' => 'File',
'HasOneExtendedFile' => 'UploadFieldTest_ExtendedFile'
);
static $has_many = array(
private static $has_many = array(
'HasManyFiles' => 'File',
'HasManyFilesMaxTwo' => 'File',
);
static $many_many = array(
private static $many_many = array(
'ManyManyFiles' => 'File',
);
@ -750,7 +750,7 @@ class UploadFieldTest_Record extends DataObject implements TestOnly {
class UploadFieldTest_FileExtension extends DataExtension implements TestOnly {
public static $has_one = array(
private static $has_one = array(
'Record' => 'UploadFieldTest_Record'
);

View File

@ -12,14 +12,14 @@ class i18nSSLegacyAdapterTest extends SapphireTest {
$this->alternateBasePath = $this->getCurrentAbsolutePath() . "/_fakewebroot";
$this->alternateBaseSavePath = TEMP_FOLDER . '/i18nTextCollectorTest_webroot';
FileSystem::makeFolder($this->alternateBaseSavePath);
Director::setBaseFolder($this->alternateBasePath);
Config::inst()->update('Director', 'alternate_base_folder', $this->alternateBasePath);
// Push a template loader running from the fake webroot onto the stack.
$templateManifest = new SS_TemplateManifest($this->alternateBasePath, null, false, true);
$templateManifest->regenerate(false);
SS_TemplateLoader::instance()->pushManifest($templateManifest);
$this->_oldTheme = SSViewer::current_theme();
SSViewer::set_theme('testtheme1');
$this->_oldTheme = Config::inst()->get('SSViewer', 'theme');
Config::inst()->update('SSViewer', 'theme', 'testtheme1');
$classManifest = new SS_ClassManifest($this->alternateBasePath, null, true, true, false);
SS_ClassLoader::instance()->pushManifest($classManifest);
@ -43,8 +43,8 @@ class i18nSSLegacyAdapterTest extends SapphireTest {
SS_TemplateLoader::instance()->popManifest();
SS_ClassLoader::instance()->popManifest();
i18n::set_locale($this->originalLocale);
Director::setBaseFolder(null);
SSViewer::set_theme($this->_oldTheme);
Config::inst()->update('Director', 'alternate_base_folder', null);
Config::inst()->update('SSViewer', 'theme', $this->_oldTheme);
i18n::register_translator($this->origAdapter, 'core');
parent::tearDown();

View File

@ -31,14 +31,14 @@ class i18nTest extends SapphireTest {
$this->alternateBasePath = $this->getCurrentAbsolutePath() . "/_fakewebroot";
$this->alternateBaseSavePath = TEMP_FOLDER . '/i18nTextCollectorTest_webroot';
FileSystem::makeFolder($this->alternateBaseSavePath);
Director::setBaseFolder($this->alternateBasePath);
Config::inst()->update('Director', 'alternate_base_folder', $this->alternateBasePath);
// Push a template loader running from the fake webroot onto the stack.
$templateManifest = new SS_TemplateManifest($this->alternateBasePath, null, false, true);
$templateManifest->regenerate(false);
SS_TemplateLoader::instance()->pushManifest($templateManifest);
$this->_oldTheme = SSViewer::current_theme();
SSViewer::set_theme('testtheme1');
$this->_oldTheme = Config::inst()->get('SSViewer', 'theme');
Config::inst()->update('SSViewer', 'theme', 'testtheme1');
$this->originalLocale = i18n::get_locale();
@ -58,8 +58,8 @@ class i18nTest extends SapphireTest {
public function tearDown() {
SS_TemplateLoader::instance()->popManifest();
i18n::set_locale($this->originalLocale);
Director::setBaseFolder(null);
SSViewer::set_theme($this->_oldTheme);
Config::inst()->update('Director', 'alternate_base_folder', null);
Config::inst()->update('SSViewer', 'theme', $this->_oldTheme);
i18n::register_translator($this->origAdapter, 'core');
parent::tearDown();
@ -84,14 +84,14 @@ class i18nTest extends SapphireTest {
public function testDateFormatCustom() {
i18n::set_locale('en_US');
$this->assertEquals('MMM d, y', i18n::get_date_format());
i18n::set_date_format('d/MM/yyyy');
i18n::config()->date_format = 'd/MM/yyyy';
$this->assertEquals('d/MM/yyyy', i18n::get_date_format());
}
public function testTimeFormatCustom() {
i18n::set_locale('en_US');
$this->assertEquals('h:mm:ss a', i18n::get_time_format());
i18n::set_time_format('HH:mm:ss');
i18n::config()->time_format = 'HH:mm:ss';
$this->assertEquals('HH:mm:ss', i18n::get_time_format());
}
@ -567,20 +567,20 @@ class i18nTest extends SapphireTest {
class i18nTest_DataObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'MyProperty' => 'Varchar',
'MyUntranslatedProperty' => 'Text'
);
static $has_one = array(
private static $has_one = array(
'HasOneRelation' => 'Member'
);
static $has_many = array(
private static $has_many = array(
'HasManyRelation' => 'Member'
);
static $many_many = array(
private static $many_many = array(
'ManyManyRelation' => 'Member'
);

View File

@ -470,8 +470,8 @@ YAML;
public function testCollectFromThemesTemplates() {
$c = new i18nTextCollector();
$theme = SSViewer::current_theme();
SSViewer::set_theme('testtheme1');
$theme = Config::inst()->get('SSViewer', 'theme');
Config::inst()->update('SSViewer', 'theme', 'testtheme1');
$templateFilePath = $this->alternateBasePath . '/themes/testtheme1/templates/Layout/i18nTestTheme1.ss';
$html = file_get_contents($templateFilePath);
@ -523,7 +523,7 @@ YAML;
array('Theme1 My include replacement no namespace: %s')
);
SSViewer::set_theme($theme);
Config::inst()->update('SSViewer', 'theme', $theme);
}
public function testCollectFromFilesystemAndWriteMasterTables() {

View File

@ -4,16 +4,16 @@
* @subpackage tests
*/
class i18nTextCollectorTestMyObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'FirstProperty' => 'Varchar',
'SecondProperty' => 'Int'
);
static $has_many = array(
private static $has_many = array(
'Relation' => 'Group'
);
static $singular_name = "My Object";
private static $singular_name = "My Object";
static $plural_name = "My Objects";
private static $plural_name = "My Objects";
}

View File

@ -4,15 +4,15 @@
* @subpackage tests
*/
class i18nTextCollectorTestMySubObject extends i18nTextCollectorTestMyObject implements TestOnly {
static $db = array(
private static $db = array(
'SubProperty' => 'Varchar',
);
static $has_many = array(
private static $has_many = array(
'SubRelation' => 'Group'
);
static $singular_name = "My Sub Object";
private static $singular_name = "My Sub Object";
static $plural_name = "My Sub Objects";
private static $plural_name = "My Sub Objects";
}

View File

@ -647,7 +647,8 @@ class NewRequirementsBackend implements TestOnly {
class TestStaticInjections implements TestOnly {
public $backend;
static $dependencies = array(
/** @config */
private static $dependencies = array(
'backend' => '%$NewRequirementsBackend'
);

View File

@ -10,48 +10,48 @@
* removed from DataObject.
*/
class AggregateTest_Foo extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Foo" => "Int"
);
static $has_one = array('Bar' => 'AggregateTest_Bar');
static $belongs_many_many = array('Bazi' => 'AggregateTest_Baz');
private static $has_one = array('Bar' => 'AggregateTest_Bar');
private static $belongs_many_many = array('Bazi' => 'AggregateTest_Baz');
}
class AggregateTest_Fab extends AggregateTest_Foo {
static $db = array(
private static $db = array(
"Fab" => "Int"
);
}
class AggregateTest_Fac extends AggregateTest_Fab {
static $db = array(
private static $db = array(
"Fac" => "Int"
);
}
class AggregateTest_Bar extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Bar" => "Int"
);
static $has_many = array(
private static $has_many = array(
"Foos" => "AggregateTest_Foo"
);
}
class AggregateTest_Baz extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Baz" => "Int"
);
static $many_many = array(
private static $many_many = array(
"Foos" => "AggregateTest_Foo"
);
}
class AggregateTest extends SapphireTest {
static $fixture_file = 'AggregateTest.yml';
protected static $fixture_file = 'AggregateTest.yml';
protected $extraDataObjects = array(
'AggregateTest_Foo',

View File

@ -5,7 +5,7 @@
*/
class ComponentSetTest extends SapphireTest {
static $fixture_file = 'ComponentSetTest.yml';
protected static $fixture_file = 'ComponentSetTest.yml';
protected $extraDataObjects = array(
'ComponentSetTest_Player',
@ -57,18 +57,18 @@ class ComponentSetTest extends SapphireTest {
}
class ComponentSetTest_Player extends Member implements TestOnly {
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Teams' => 'ComponentSetTest_Team'
);
}
class ComponentSetTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
);
static $many_many = array(
private static $many_many = array(
'Players' => 'ComponentSetTest_Player'
);
}

View File

@ -38,14 +38,14 @@ class CompositeDBFieldTest extends SapphireTest {
}
class CompositeDBFieldTest_DataObject extends DataObject {
static $db = array(
private static $db = array(
'Title' => 'Text',
'MyMoney' => 'Money',
);
}
class SubclassedDBFieldObject extends CompositeDBFieldTest_DataObject {
static $db = array(
private static $db = array(
'OtherField' => 'Text',
'OtherMoney' => 'Money',
);

View File

@ -5,32 +5,18 @@
*/
class DBTest extends SapphireTest {
protected $origEnvType;
function setUp() {
$this->origEnvType = Director::get_environment_type();
Director::set_environment_type('dev');
parent::setUp();
}
function tearDown() {
Director::set_environment_type($this->origEnvType);
parent::tearDown();
}
function testValidAlternativeDatabaseName() {
Config::inst()->update('Director', 'environment_type', 'dev');
$this->assertTrue(DB::valid_alternative_database_name('ss_tmpdb1234567'));
$this->assertFalse(DB::valid_alternative_database_name('ss_tmpdb12345678'));
$this->assertFalse(DB::valid_alternative_database_name('tmpdb1234567'));
$this->assertFalse(DB::valid_alternative_database_name('random'));
$this->assertFalse(DB::valid_alternative_database_name(''));
$origEnvType = Director::get_environment_type();
Director::set_environment_type('live');
Config::inst()->update('Director', 'environment_type', 'live');
$this->assertFalse(DB::valid_alternative_database_name('ss_tmpdb1234567'));
Director::set_environment_type($origEnvType);
Config::inst()->update('Director', 'environment_type', 'dev');
}
}

View File

@ -6,7 +6,7 @@
class DataDifferencerTest extends SapphireTest {
static $fixture_file = 'DataDifferencerTest.yml';
protected static $fixture_file = 'DataDifferencerTest.yml';
protected $extraDataObjects = array(
'DataDifferencerTest_Object',
@ -39,12 +39,12 @@ class DataDifferencerTest extends SapphireTest {
// 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 = File::$update_filesystem;
$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
File::$update_filesystem = false;
Config::inst()->update('File', 'update_filesystem', false);
$image1->write();
$image2->write();
File::$update_filesystem = $origUpdateFilesystem;
Config::inst()->update('File', 'update_filesystem', $origUpdateFilesystem);
// create a new version
$obj1->ImageID = $image2->ID;
@ -64,13 +64,13 @@ class DataDifferencerTest extends SapphireTest {
class DataDifferencerTest_Object extends DataObject implements TestOnly {
static $extensions = array('Versioned("Stage", "Live")');
private static $extensions = array('Versioned("Stage", "Live")');
static $db = array(
private static $db = array(
'Choices' => "Varchar",
);
static $has_one = array(
private static $has_one = array(
'Image' => 'DataDifferencerTest_MockImage',
'HasOneRelation' => 'DataDifferencerTest_HasOneRelationObject'
);
@ -100,11 +100,11 @@ class DataDifferencerTest_Object extends DataObject implements TestOnly {
class DataDifferencerTest_HasOneRelationObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar'
);
static $has_many = array(
private static $has_many = array(
'Objects' => 'DataDifferencerTest_Object'
);
}

View File

@ -1,7 +1,7 @@
<?php
class DataExtensionTest extends SapphireTest {
static $fixture_file = 'DataExtensionTest.yml';
protected static $fixture_file = 'DataExtensionTest.yml';
protected $extraDataObjects = array(
'DataExtensionTest_Member',
@ -160,7 +160,7 @@ class DataExtensionTest extends SapphireTest {
class DataExtensionTest_Member extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar",
"Email" => "Varchar"
);
@ -169,7 +169,7 @@ class DataExtensionTest_Member extends DataObject implements TestOnly {
class DataExtensionTest_Player extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar'
);
@ -200,31 +200,31 @@ class DataExtensionTest_PlayerExtension extends DataExtension implements TestOnl
class DataExtensionTest_ContactRole extends DataExtension implements TestOnly {
public static $db = array(
private static $db = array(
'Website' => 'Varchar',
'Phone' => 'Varchar(255)',
);
public static $has_many = array(
private static $has_many = array(
'RelatedObjects' => 'DataExtensionTest_RelatedObject'
);
public static $defaults = array(
private static $defaults = array(
'Phone' => '123'
);
public static $api_access = true;
private static $api_access = true;
}
class DataExtensionTest_RelatedObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"FieldOne" => "Varchar",
"FieldTwo" => "Varchar"
);
static $has_one = array(
private static $has_one = array(
"Contact" => "DataExtensionTest_Member"
);
@ -234,7 +234,7 @@ DataExtensionTest_Member::add_extension('DataExtensionTest_ContactRole');
class DataExtensionTest_MyObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
);
@ -295,7 +295,7 @@ class DataExtensionTest_Ext2 extends DataExtension implements TestOnly {
class DataExtensionTest_Faves extends DataExtension implements TestOnly {
public static $many_many = array(
private static $many_many = array(
'Faves' => 'DataExtensionTest_RelatedObject'
);

View File

@ -3,7 +3,7 @@
class DataListTest extends SapphireTest {
// Borrow the model from DataObjectTest
static $fixture_file = 'DataObjectTest.yml';
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',

View File

@ -74,26 +74,26 @@ class DataObjectDuplicationTest extends SapphireTest {
class DataObjectDuplicateTestClass1 extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'text' => 'Varchar'
);
static $has_many = array(
private static $has_many = array(
'twos' => 'DataObjectDuplicateTestClass2'
);
static $many_many = array(
private static $many_many = array(
'threes' => 'DataObjectDuplicateTestClass3'
);
}
class DataObjectDuplicateTestClass2 extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'text' => 'Varchar'
);
static $has_one = array(
private static $has_one = array(
'one' => 'DataObjectDuplicateTestClass1'
);
@ -101,11 +101,11 @@ class DataObjectDuplicateTestClass2 extends DataObject implements TestOnly {
class DataObjectDuplicateTestClass3 extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'text' => 'Varchar'
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'ones' => 'DataObjectDuplicateTestClass1'
);
}

View File

@ -6,7 +6,7 @@
class DataObjectLazyLoadingTest extends SapphireTest {
static $fixture_file = array(
protected static $fixture_file = array(
'DataObjectTest.yml',
'VersionedTest.yml'
);
@ -395,19 +395,19 @@ class DataObjectLazyLoadingTest extends SapphireTest {
/** Additional classes for versioned lazy loading testing */
class VersionedLazy_DataObject extends DataObject {
static $db = array(
private static $db = array(
"PageName" => "Varchar"
);
static $extensions = array(
private static $extensions = array(
"Versioned('Stage', 'Live')"
);
}
class VersionedLazySub_DataObject extends VersionedLazy_DataObject {
static $db = array(
private static $db = array(
"ExtraField" => "Varchar",
);
static $extensions = array(
private static $extensions = array(
"Versioned('Stage', 'Live')"
);
}

View File

@ -127,7 +127,7 @@ class DataObjectSchemaGenerationTest extends SapphireTest {
}
class DataObjectSchemaGenerationTest_DO extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Enum1' => 'Enum("A, B, C, D","")',
'Enum2' => 'Enum("A, B, C, D","A")',
);
@ -135,12 +135,12 @@ class DataObjectSchemaGenerationTest_DO extends DataObject implements TestOnly {
class DataObjectSchemaGenerationTest_IndexDO extends DataObjectSchemaGenerationTest_DO implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar(255)',
'Content' => 'Text'
);
static $indexes = array(
private static $indexes = array(
'NameIndex' => 'unique ("Title")',
'SearchFields' => array(
'type' => 'fulltext',
@ -149,7 +149,8 @@ class DataObjectSchemaGenerationTest_IndexDO extends DataObjectSchemaGenerationT
)
);
static $indexes_alt = array(
/** @config */
private static $indexes_alt = array(
'NameIndex' => array(
'type' => 'unique',
'name' => 'NameIndex',

View File

@ -5,7 +5,7 @@
*/
class DataObjectTest extends SapphireTest {
static $fixture_file = 'DataObjectTest.yml';
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',
@ -1120,48 +1120,48 @@ class DataObjectTest extends SapphireTest {
}
class DataObjectTest_Player extends Member implements TestOnly {
static $db = array(
private static $db = array(
'IsRetired' => 'Boolean',
'ShirtNumber' => 'Varchar',
);
static $has_one = array(
private static $has_one = array(
'FavouriteTeam' => 'DataObjectTest_Team',
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
'Teams' => 'DataObjectTest_Team'
);
}
class DataObjectTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar',
'DatabaseField' => 'HTMLVarchar'
);
static $has_one = array(
private static $has_one = array(
"Captain" => 'DataObjectTest_Player',
'HasOneRelationship' => 'DataObjectTest_Player',
);
static $has_many = array(
private static $has_many = array(
'SubTeams' => 'DataObjectTest_SubTeam',
'Comments' => 'DataObjectTest_TeamComment'
);
static $many_many = array(
private static $many_many = array(
'Players' => 'DataObjectTest_Player'
);
static $many_many_extraFields = array(
private static $many_many_extraFields = array(
'Players' => array(
'Position' => 'Varchar(100)'
)
);
static $default_sort = "Title";
private static $default_sort = "Title";
public function MyTitle() {
return 'Team ' . $this->Title;
@ -1174,7 +1174,7 @@ class DataObjectTest_Team extends DataObject implements TestOnly {
}
class DataObjectTest_Fixture extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
// Funny field names
'Data' => 'Varchar',
'Duplicate' => 'Varchar',
@ -1188,7 +1188,7 @@ class DataObjectTest_Fixture extends DataObject implements TestOnly {
'MyFieldWithAltDefault' => 'Varchar'
);
static $defaults = array(
private static $defaults = array(
'MyFieldWithDefault' => 'Default Value',
);
@ -1201,16 +1201,16 @@ class DataObjectTest_Fixture extends DataObject implements TestOnly {
}
class DataObjectTest_SubTeam extends DataObjectTest_Team implements TestOnly {
static $db = array(
private static $db = array(
'SubclassDatabaseField' => 'Varchar'
);
static $has_one = array(
private static $has_one = array(
"ParentTeam" => 'DataObjectTest_Team',
);
}
class OtherSubclassWithSameField extends DataObjectTest_Team implements TestOnly {
static $db = array(
private static $db = array(
'SubclassDatabaseField' => 'Varchar',
);
}
@ -1225,11 +1225,11 @@ class DataObjectTest_FieldlessSubTable extends DataObjectTest_Team implements Te
class DataObjectTest_Team_Extension extends DataExtension implements TestOnly {
static $db = array(
private static $db = array(
'ExtendedDatabaseField' => 'Varchar'
);
static $has_one = array(
private static $has_one = array(
'ExtendedHasOneRelationship' => 'DataObjectTest_Player'
);
@ -1241,7 +1241,7 @@ class DataObjectTest_Team_Extension extends DataExtension implements TestOnly {
class DataObjectTest_ValidatedObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Name' => 'Varchar(50)'
);
@ -1255,38 +1255,38 @@ class DataObjectTest_ValidatedObject extends DataObject implements TestOnly {
}
class DataObjectTest_Company extends DataObject {
public static $has_one = array (
private static $has_one = array (
'CEO' => 'DataObjectTest_CEO',
'PreviousCEO' => 'DataObjectTest_CEO'
);
public static $has_many = array (
private static $has_many = array (
'CurrentStaff' => 'DataObjectTest_Staff.CurrentCompany',
'PreviousStaff' => 'DataObjectTest_Staff.PreviousCompany'
);
}
class DataObjectTest_Staff extends DataObject {
public static $has_one = array (
private static $has_one = array (
'CurrentCompany' => 'DataObjectTest_Company',
'PreviousCompany' => 'DataObjectTest_Company'
);
}
class DataObjectTest_CEO extends DataObjectTest_Staff {
public static $belongs_to = array (
private static $belongs_to = array (
'Company' => 'DataObjectTest_Company.CEO',
'PreviousCompany' => 'DataObjectTest_Company.PreviousCEO'
);
}
class DataObjectTest_TeamComment extends DataObject {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
'Comment' => 'Text'
);
static $has_one = array(
private static $has_one = array(
'Team' => 'DataObjectTest_Team'
);

View File

@ -7,7 +7,7 @@ namespace DataObjectTest;
* Note that it was deliberated named to include "\N" to try and trip bad code up.
*/
class NamespacedClass extends \DataObject {
static $db = array(
private static $db = array(
'Name' => 'Varchar',
);
}

View File

@ -119,38 +119,38 @@ class DataQueryTest extends SapphireTest {
class DataQueryTest_A extends DataObject implements TestOnly {
public static $db = array(
private static $db = array(
'Name' => 'Varchar',
);
public static $has_one = array(
private static $has_one = array(
'TestC' => 'DataQueryTest_C',
);
}
class DataQueryTest_B extends DataQueryTest_A {
public static $db = array(
private static $db = array(
'Title' => 'Varchar',
);
public static $has_one = array(
private static $has_one = array(
'TestC' => 'DataQueryTest_C',
);
}
class DataQueryTest_C extends DataObject implements TestOnly {
public static $has_one = array(
private static $has_one = array(
'TestA' => 'DataQueryTest_A',
'TestB' => 'DataQueryTest_B',
);
public static $has_many = array(
private static $has_many = array(
'TestAs' => 'DataQueryTest_A',
'TestBs' => 'DataQueryTest_B',
);
public static $many_many = array(
private static $many_many = array(
'ManyTestAs' => 'DataQueryTest_A',
'ManyTestBs' => 'DataQueryTest_B',
);
@ -158,7 +158,7 @@ class DataQueryTest_C extends DataObject implements TestOnly {
class DataQueryTest_D extends DataObject implements TestOnly {
public static $has_one = array(
private static $has_one = array(
'Relation' => 'DataQueryTest_B',
);
}

View File

@ -150,9 +150,9 @@ class DatabaseTest extends SapphireTest {
class DatabaseTest_MyObject extends DataObject implements TestOnly {
static $create_table_options = array('MySQLDatabase' => 'ENGINE=InnoDB');
private static $create_table_options = array('MySQLDatabase' => 'ENGINE=InnoDB');
static $db = array(
private static $db = array(
'MyField' => 'Varchar'
);
}

View File

@ -2,7 +2,7 @@
class DbDatetimeTest extends FunctionalTest {
static $fixture_file = 'DbDatetimeTest.yml';
protected static $fixture_file = 'DbDatetimeTest.yml';
protected $extraDataObjects = array('DbDatetimeTest_Team');
@ -139,7 +139,7 @@ class DbDatetimeTest extends FunctionalTest {
}
class DbDateTimeTest_Team extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar'
);
}

View File

@ -5,7 +5,7 @@
*/
class DecimalTest extends SapphireTest {
public static $fixture_file = 'DecimalTest.yml';
protected static $fixture_file = 'DecimalTest.yml';
protected $testDataObject;
@ -46,7 +46,7 @@ class DecimalTest extends SapphireTest {
*/
class DecimalTest_DataObject extends DataObject implements TestOnly {
public static $db = array(
private static $db = array(
'Name' => 'Varchar',
'MyDecimal1' => 'Decimal',
'MyDecimal2' => 'Decimal(5,3,2.5)',
@ -54,7 +54,7 @@ class DecimalTest_DataObject extends DataObject implements TestOnly {
'MyDecimal4' => 'Decimal'
);
public static $defaults = array(
private static $defaults = array(
'MyDecimal4' => 4
);

View File

@ -3,7 +3,7 @@
class HasManyListTest extends SapphireTest {
// Borrow the model from DataObjectTest
public static $fixture_file = 'DataObjectTest.yml';
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',

View File

@ -2,7 +2,7 @@
class HierarchyTest extends SapphireTest {
static $fixture_file = 'HierarchyTest.yml';
protected static $fixture_file = 'HierarchyTest.yml';
protected $requiredExtensions = array(
'HierarchyTest_Object' => array('Hierarchy', 'Versioned')
@ -415,11 +415,11 @@ class HierarchyTest extends SapphireTest {
}
class HierarchyTest_Object extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar'
);
static $extensions = array(
private static $extensions = array(
'Hierarchy',
"Versioned('Stage', 'Live')",
);

View File

@ -6,7 +6,7 @@
*/
class ImageTest extends SapphireTest {
static $fixture_file = 'ImageTest.yml';
protected static $fixture_file = 'ImageTest.yml';
protected $origBackend;

View File

@ -3,7 +3,7 @@
class ManyManyListTest extends SapphireTest {
// Borrow the model from DataObjectTest
public static $fixture_file = 'DataObjectTest.yml';
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',

View File

@ -2,7 +2,7 @@
class SS_MapTest extends SapphireTest {
// Borrow the model from DataObjectTest
static $fixture_file = 'DataObjectTest.yml';
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',

View File

@ -13,7 +13,7 @@
*/
class MoneyTest extends SapphireTest {
static $fixture_file = 'MoneyTest.yml';
protected static $fixture_file = 'MoneyTest.yml';
protected $extraDataObjects = array(
'MoneyTest_DataObject',
@ -271,7 +271,7 @@ class MoneyTest extends SapphireTest {
}
class MoneyTest_DataObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'MyMoney' => 'Money',
//'MyOtherMoney' => 'Money',
);

View File

@ -11,7 +11,7 @@ class MySQLDatabaseTest extends SapphireTest {
public function setUp() {
if(DB::getConn() instanceof MySQLDatabase) {
MySQLDatabaseTest_DO::$db = array(
MySQLDatabaseTest_DO::config()->db = array(
'MultiEnum1' => 'MultiEnum("A, B, C, D","")',
'MultiEnum2' => 'MultiEnum("A, B, C, D","A")',
'MultiEnum3' => 'MultiEnum("A, B, C, D","A, B")',
@ -43,6 +43,6 @@ class MySQLDatabaseTest extends SapphireTest {
}
class MySQLDatabaseTest_DO extends DataObject implements TestOnly {
static $db = array();
private static $db = array();
}

View File

@ -7,7 +7,7 @@
*/
class PaginatedListTest extends SapphireTest {
static $fixture_file = 'DataObjectTest.yml';
protected static $fixture_file = 'DataObjectTest.yml';
protected $extraDataObjects = array(
'DataObjectTest_Team',

View File

@ -2,7 +2,7 @@
class SQLQueryTest extends SapphireTest {
public static $fixture_file = 'SQLQueryTest.yml';
protected static $fixture_file = 'SQLQueryTest.yml';
protected $extraDataObjects = array(
'SQLQueryTest_DO',
@ -409,7 +409,7 @@ class SQLQueryTest extends SapphireTest {
}
class SQLQueryTest_DO extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar",
"Meta" => "Varchar",
"Common" => "Varchar",
@ -418,16 +418,16 @@ class SQLQueryTest_DO extends DataObject implements TestOnly {
}
class SQLQueryTestBase extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Title" => "Varchar",
);
}
class SQLQueryTestChild extends SQLQueryTestBase {
static $db = array(
private static $db = array(
"Name" => "Varchar",
);
static $has_one = array(
private static $has_one = array(
);
}

View File

@ -57,7 +57,7 @@ class TransactionTest extends SapphireTest {
}
class TransactionTest_Object extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
'Title' => 'Varchar(255)'
);
}

View File

@ -1,7 +1,7 @@
<?php
class UnsavedRelationListTest extends SapphireTest {
public static $fixture_file = 'UnsavedRelationListTest.yml';
protected static $fixture_file = 'UnsavedRelationListTest.yml';
protected $extraDataObjects = array('UnsavedRelationListTest_DataObject');
@ -186,23 +186,23 @@ class UnsavedRelationListTest extends SapphireTest {
}
class UnsavedRelationListTest_DataObject extends DataObject implements TestOnly {
public static $db = array(
private static $db = array(
'Name' => 'Varchar',
);
public static $has_one = array(
private static $has_one = array(
'Parent' => 'UnsavedRelationListTest_DataObject',
);
public static $has_many = array(
private static $has_many = array(
'Children' => 'UnsavedRelationListTest_DataObject',
);
public static $many_many = array(
private static $many_many = array(
'Siblings' => 'UnsavedRelationListTest_DataObject',
);
public static $many_many_extraFields = array(
private static $many_many_extraFields = array(
'Siblings' => array(
'Number' => 'Int',
),

View File

@ -1,7 +1,7 @@
<?php
class VersionedTest extends SapphireTest {
static $fixture_file = 'VersionedTest.yml';
protected static $fixture_file = 'VersionedTest.yml';
protected $extraDataObjects = array(
'VersionedTest_DataObject',
@ -410,27 +410,27 @@ class VersionedTest extends SapphireTest {
}
class VersionedTest_DataObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar",
'Title' => 'Varchar',
'Content' => 'HTMLText'
);
static $extensions = array(
private static $extensions = array(
"Versioned('Stage', 'Live')"
);
static $has_one = array(
private static $has_one = array(
'Parent' => 'VersionedTest_DataObject'
);
}
class VersionedTest_Subclass extends VersionedTest_DataObject implements TestOnly {
static $db = array(
private static $db = array(
"ExtraField" => "Varchar",
);
static $extensions = array(
private static $extensions = array(
"Versioned('Stage', 'Live')"
);
}
@ -439,5 +439,5 @@ class VersionedTest_Subclass extends VersionedTest_DataObject implements TestOnl
* @ignore
*/
class VersionedTest_UnversionedWithField extends DataObject implements TestOnly {
public static $db = array('Version' => 'Varchar(255)');
private static $db = array('Version' => 'Varchar(255)');
}

View File

@ -2,7 +2,7 @@
class SearchContextTest extends SapphireTest {
static $fixture_file = 'SearchContextTest.yml';
protected static $fixture_file = 'SearchContextTest.yml';
protected $extraDataObjects = array(
'SearchContextTest_Person',
@ -165,14 +165,14 @@ class SearchContextTest extends SapphireTest {
class SearchContextTest_Person extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar",
"Email" => "Varchar",
"HairColor" => "Varchar",
"EyeColor" => "Varchar"
);
static $searchable_fields = array(
private static $searchable_fields = array(
"Name", "HairColor", "EyeColor"
);
@ -180,7 +180,7 @@ class SearchContextTest_Person extends DataObject implements TestOnly {
class SearchContextTest_Book extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Title" => "Varchar",
"Summary" => "Varchar"
);
@ -189,17 +189,17 @@ class SearchContextTest_Book extends DataObject implements TestOnly {
class SearchContextTest_Company extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar",
"Industry" => "Varchar",
"AnnualProfit" => "Int"
);
static $summary_fields = array(
private static $summary_fields = array(
"Industry"
);
static $searchable_fields = array(
private static $searchable_fields = array(
"Name" => "PartialMatchFilter",
"Industry" => array(
'field' => "TextareaField"
@ -215,19 +215,19 @@ class SearchContextTest_Company extends DataObject implements TestOnly {
class SearchContextTest_Project extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar"
);
static $has_one = array(
private static $has_one = array(
"Deadline" => "SearchContextTest_Deadline"
);
static $has_many = array(
private static $has_many = array(
"Actions" => "SearchContextTest_Action"
);
static $searchable_fields = array(
private static $searchable_fields = array(
"Name" => "PartialMatchFilter",
"Actions.SolutionArea" => "ExactMatchFilter",
"Actions.Description" => "PartialMatchFilter"
@ -237,11 +237,11 @@ class SearchContextTest_Project extends DataObject implements TestOnly {
class SearchContextTest_Deadline extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"CompletionDate" => "SS_Datetime"
);
static $has_one = array(
private static $has_one = array(
"Project" => "SearchContextTest_Project"
);
@ -249,12 +249,12 @@ class SearchContextTest_Deadline extends DataObject implements TestOnly {
class SearchContextTest_Action extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Description" => "Text",
"SolutionArea" => "Varchar"
);
static $has_one = array(
private static $has_one = array(
"Project" => "SearchContextTest_Project"
);
@ -262,7 +262,7 @@ class SearchContextTest_Action extends DataObject implements TestOnly {
class SearchContextTest_AllFilterTypes extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"ExactMatch" => "Varchar",
"PartialMatch" => "Varchar",
"SubstringMatch" => "Varchar",
@ -273,7 +273,7 @@ class SearchContextTest_AllFilterTypes extends DataObject implements TestOnly {
'FulltextField' => 'Text',
);
static $searchable_fields = array(
private static $searchable_fields = array(
"ExactMatch" => "ExactMatchFilter",
"PartialMatch" => "PartialMatchFilter",
"CollectionMatch" => "ExactMatchFilter",

View File

@ -9,7 +9,7 @@
* @subpackage testing
*/
class SearchFilterApplyRelationTest extends SapphireTest{
static $fixture_file = 'SearchFilterApplyRelationTest.yml';
protected static $fixture_file = 'SearchFilterApplyRelationTest.yml';
protected $extraDataObjects = array(
'SearchFilterApplyRelationTest_DO',
@ -110,21 +110,21 @@ class SearchFilterApplyRelationTest extends SapphireTest{
}
class SearchFilterApplyRelationTest_DO extends DataObject implements TestOnly {
static $has_one = array(
private static $has_one = array(
'SearchFilterApplyRelationTest_HasOneGrantChild' => 'SearchFilterApplyRelationTest_HasOneGrantChild'
);
static $has_many = array(
private static $has_many = array(
'SearchFilterApplyRelationTest_HasManyGrantChildren' => 'SearchFilterApplyRelationTest_HasManyGrantChild'
);
static $many_many = array(
private static $many_many = array(
'ManyManyGrantChildren' => 'SearchFilterApplyRelationTest_ManyManyGrantChild'
);
}
class SearchFilterApplyRelationTest_HasOneParent extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Title" => "Varchar"
);
}
@ -132,7 +132,7 @@ class SearchFilterApplyRelationTest_HasOneParent extends DataObject implements T
class SearchFilterApplyRelationTest_HasOneChild extends SearchFilterApplyRelationTest_HasOneParent
implements TestOnly {
// This is to create an seperate Table only.
static $db = array(
private static $db = array(
"ChildField" => "Varchar"
);
}
@ -140,16 +140,16 @@ class SearchFilterApplyRelationTest_HasOneChild extends SearchFilterApplyRelatio
class SearchFilterApplyRelationTest_HasOneGrantChild extends SearchFilterApplyRelationTest_HasOneChild
implements TestOnly {
// This is to create an seperate Table only.
static $db = array(
private static $db = array(
"GrantChildField" => "Varchar"
);
static $has_many = array(
private static $has_many = array(
"SearchFilterApplyRelationTest_DOs" => "SearchFilterApplyRelationTest_DO"
);
}
class SearchFilterApplyRelationTest_HasManyParent extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Title" => "Varchar"
);
}
@ -157,19 +157,19 @@ class SearchFilterApplyRelationTest_HasManyParent extends DataObject implements
class SearchFilterApplyRelationTest_HasManyChild extends SearchFilterApplyRelationTest_HasManyParent
implements TestOnly {
// This is to create an separate Table only.
static $db = array(
private static $db = array(
"ChildField" => "Varchar"
);
}
class SearchFilterApplyRelationTest_HasManyGrantChild extends SearchFilterApplyRelationTest_HasManyChild{
static $has_one = array(
private static $has_one = array(
"SearchFilterApplyRelationTest_DO" => "SearchFilterApplyRelationTest_DO"
);
}
class SearchFilterApplyRelationTest_ManyManyParent extends DataObject implements TestOnly{
static $db = array(
private static $db = array(
"Title" => "Varchar"
);
}
@ -177,7 +177,7 @@ class SearchFilterApplyRelationTest_ManyManyParent extends DataObject implements
class SearchFilterApplyRelationTest_ManyManyChild extends SearchFilterApplyRelationTest_ManyManyParent
implements TestOnly {
// This is to create an seperate Table only.
static $db = array(
private static $db = array(
"ChildField" => "Varchar"
);
}
@ -185,10 +185,10 @@ class SearchFilterApplyRelationTest_ManyManyChild extends SearchFilterApplyRelat
class SearchFilterApplyRelationTest_ManyManyGrantChild extends SearchFilterApplyRelationTest_ManyManyChild
implements TestOnly {
// This is to create an seperate Table only.
static $db = array(
private static $db = array(
"GrantChildField" => "Varchar"
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
"DOs" => "SearchFilterApplyRelationTest_DO"
);
}

View File

@ -8,21 +8,21 @@ class BasicAuthTest extends FunctionalTest {
static $original_unique_identifier_field;
static $fixture_file = 'BasicAuthTest.yml';
protected static $fixture_file = 'BasicAuthTest.yml';
public function setUp() {
parent::setUp();
// Fixtures assume Email is the field used to identify the log in identity
self::$original_unique_identifier_field = Member::get_unique_identifier_field();
Member::set_unique_identifier_field('Email');
self::$original_unique_identifier_field = Member::config()->unique_identifier_field;
Member::config()->unique_identifier_field = 'Email';
}
public function tearDown() {
parent::tearDown();
BasicAuth::protect_entire_site(false);
Member::set_unique_identifier_field(self::$original_unique_identifier_field);
Member::config()->unique_identifier_field = self::$original_unique_identifier_field;
}
public function testBasicAuthEnabledWithoutLogin() {

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class GroupCsvBulkLoaderTest extends SapphireTest {
static $fixture_file = 'GroupCsvBulkLoaderTest.yml';
protected static $fixture_file = 'GroupCsvBulkLoaderTest.yml';
public function testNewImport() {
$loader = new GroupCsvBulkLoader();

View File

@ -5,7 +5,7 @@
*/
class GroupTest extends FunctionalTest {
static $fixture_file = 'GroupTest.yml';
protected static $fixture_file = 'GroupTest.yml';
public function testGroupCodeDefaultsToTitle() {
$g1 = new Group();

View File

@ -10,7 +10,7 @@ class MemberAuthenticatorTest extends SapphireTest {
public function testLegacyPasswordHashMigrationUponLogin() {
$member = new Member();
$field=Member::get_unique_identifier_field();
$field=Member::config()->unique_identifier_field;
$member->$field = 'test1@test.com';
$member->PasswordEncryption = "sha1";
@ -32,7 +32,7 @@ class MemberAuthenticatorTest extends SapphireTest {
public function testNoLegacyPasswordHashMigrationOnIncompatibleAlgorithm() {
Config::inst()->update('PasswordEncryptor', 'encryptors',
array('crc32'=>array('PasswordEncryptor_PHPHash'=>'crc32')));
$field=Member::get_unique_identifier_field();
$field=Member::config()->unique_identifier_field;
$member = new Member();
$member->$field = 'test2@test.com';
@ -54,13 +54,13 @@ class MemberAuthenticatorTest extends SapphireTest {
public function testCustomIdentifierField(){
$origField = Member::get_unique_identifier_field();
Member::set_unique_identifier_field('Username');
$origField = Member::config()->unique_identifier_field;
Member::config()->unique_identifier_field = 'Username';
$label=singleton('Member')->fieldLabel(Member::get_unique_identifier_field());
$label=singleton('Member')->fieldLabel(Member::config()->unique_identifier_field);
$this->assertEquals($label, 'Username');
Member::set_unique_identifier_field($origField);
Member::config()->unique_identifier_field = $origField;
}
}

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class MemberCsvBulkLoaderTest extends SapphireTest {
static $fixture_file = 'MemberCsvBulkLoaderTest.yml';
protected static $fixture_file = 'MemberCsvBulkLoaderTest.yml';
public function testNewImport() {
$loader = new MemberCsvBulkLoader();
@ -70,7 +70,7 @@ class MemberCsvBulkLoaderTest extends SapphireTest {
$member = DataObject::get_by_id('Member', $memberID);
// TODO Direct getter doesn't work, wtf!
$this->assertEquals(Security::get_password_encryption_algorithm(), $member->getField('PasswordEncryption'));
$this->assertEquals(Security::config()->password_encryption_algorithm, $member->getField('PasswordEncryption'));
$result = $member->checkPassword('mypassword');
$this->assertTrue($result->valid());
}

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class MemberTest extends FunctionalTest {
static $fixture_file = 'MemberTest.yml';
protected static $fixture_file = 'MemberTest.yml';
protected $orig = array();
protected $local = null;
@ -35,13 +35,13 @@ class MemberTest extends FunctionalTest {
public function setUp() {
parent::setUp();
$this->orig['Member_unique_identifier_field'] = Member::get_unique_identifier_field();
Member::set_unique_identifier_field('Email');
$this->orig['Member_unique_identifier_field'] = Member::config()->unique_identifier_field;
Member::config()->unique_identifier_field = 'Email';
Member::set_password_validator(null);
}
public function tearDown() {
Member::set_unique_identifier_field($this->orig['Member_unique_identifier_field']);
Member::config()->unique_identifier_field = $this->orig['Member_unique_identifier_field'];
parent::tearDown();
}
@ -81,7 +81,7 @@ class MemberTest extends FunctionalTest {
$memberWithPassword->write();
$this->assertEquals(
$memberWithPassword->PasswordEncryption,
Security::get_password_encryption_algorithm(),
Security::config()->password_encryption_algorithm,
'Password encryption is set for new member records on first write (with setting "Password")'
);
@ -99,8 +99,8 @@ class MemberTest extends FunctionalTest {
$member->PasswordEncryption = 'sha1_v2.4';
$member->write();
$origAlgo = Security::get_password_encryption_algorithm();
Security::set_password_encryption_algorithm('none');
$origAlgo = Security::config()->password_encryption_algorithm;
Security::config()->password_encryption_algorithm = 'none';
$member->Password = 'mynewpassword';
$member->write();
@ -112,7 +112,7 @@ class MemberTest extends FunctionalTest {
$result = $member->checkPassword('mynewpassword');
$this->assertTrue($result->valid());
Security::set_password_encryption_algorithm($origAlgo);
Security::config()->password_encryption_algorithm = $origAlgo;
}
public function testKeepsEncryptionOnEmptyPasswords() {
@ -278,7 +278,7 @@ class MemberTest extends FunctionalTest {
* Test that the PasswordExpiry date is set when passwords are changed
*/
public function testPasswordExpirySetting() {
Member::set_password_expiry(90);
Member::config()->password_expiry_days = 90;
$member = $this->objFromFixture('Member', 'test');
$this->assertNotNull($member);
@ -288,7 +288,7 @@ class MemberTest extends FunctionalTest {
$expiryDate = date('Y-m-d', time() + 90*86400);
$this->assertEquals($expiryDate, $member->PasswordExpiry);
Member::set_password_expiry(null);
Member::config()->password_expiry_days = null;
$valid = $member->changePassword("Xx?1234235");
$this->assertTrue($valid->valid());

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class PermissionCheckboxSetFieldTest extends SapphireTest {
static $fixture_file = 'PermissionCheckboxSetFieldTest.yml';
protected static $fixture_file = 'PermissionCheckboxSetFieldTest.yml';
public function testHiddenPermissions() {
$f = new PermissionCheckboxSetField(

View File

@ -4,7 +4,7 @@
* @subpackage tests
*/
class PermissionRoleTest extends FunctionalTest {
static $fixture_file = 'PermissionRoleTest.yml';
protected static $fixture_file = 'PermissionRoleTest.yml';
public function testDelete() {
$role = $this->objFromFixture('PermissionRole', 'role');

View File

@ -6,7 +6,7 @@
*/
class PermissionTest extends SapphireTest {
static $fixture_file = 'PermissionTest.yml';
protected static $fixture_file = 'PermissionTest.yml';
public function testGetCodesGrouped() {
$codes = Permission::get_codes();
@ -92,11 +92,11 @@ class PermissionTest extends SapphireTest {
$permissionCheckboxSet = new PermissionCheckboxSetField('Permissions','Permissions','Permission','GroupID');
$this->assertContains('CMS_ACCESS_LeftAndMain', $permissionCheckboxSet->Field());
Permission::add_to_hidden_permissions('CMS_ACCESS_LeftAndMain');
Config::inst()->update('Permission', 'hidden_permissions', array('CMS_ACCESS_LeftAndMain'));
$this->assertNotContains('CMS_ACCESS_LeftAndMain', $permissionCheckboxSet->Field());
Permission::remove_from_hidden_permissions('CMS_ACCESS_LeftAndMain');
Config::inst()->remove('Permission', 'hidden_permissions');
$this->assertContains('CMS_ACCESS_LeftAndMain', $permissionCheckboxSet->Field());
}
}

View File

@ -6,7 +6,7 @@
* @subpackage tests
*/
class SecurityTest extends FunctionalTest {
static $fixture_file = 'MemberTest.yml';
protected static $fixture_file = 'MemberTest.yml';
protected $autoFollowRedirection = false;
@ -28,8 +28,8 @@ class SecurityTest extends FunctionalTest {
Authenticator::set_default_authenticator('MemberAuthenticator');
// And that the unique identified field is 'Email'
$this->priorUniqueIdentifierField = Member::get_unique_identifier_field();
Member::set_unique_identifier_field('Email');
$this->priorUniqueIdentifierField = Member::config()->unique_identifier_field;
Member::config()->unique_identifier_field = 'Email';
parent::setUp();
}
@ -47,7 +47,7 @@ class SecurityTest extends FunctionalTest {
Authenticator::set_default_authenticator($this->priorDefaultAuthenticator);
// Restore unique identifier field
Member::set_unique_identifier_field($this->priorUniqueIdentifierField);
Member::config()->unique_identifier_field = $this->priorUniqueIdentifierField;
parent::tearDown();
}
@ -249,7 +249,7 @@ class SecurityTest extends FunctionalTest {
$local = i18n::get_locale();
i18n::set_locale('en_US');
Member::lock_out_after_incorrect_logins(5);
Member::config()->lock_out_after_incorrect_logins = 5;
/* LOG IN WITH A BAD PASSWORD 7 TIMES */
@ -310,7 +310,7 @@ class SecurityTest extends FunctionalTest {
}
public function testAlternatingRepeatedLoginAttempts() {
Member::lock_out_after_incorrect_logins(3);
Member::config()->lock_out_after_incorrect_logins = 3;
// ATTEMPTING LOG-IN TWICE WITH ONE ACCOUNT AND TWICE WITH ANOTHER SHOULDN'T LOCK ANYBODY OUT
@ -339,7 +339,7 @@ class SecurityTest extends FunctionalTest {
}
public function testUnsuccessfulLoginAttempts() {
Security::set_login_recording(true);
Security::config()->login_recording = true;
/* UNSUCCESSFUL ATTEMPTS WITH WRONG PASSWORD FOR EXISTING USER ARE LOGGED */
$this->doTestLoginForm('sam@silverstripe.com', 'wrongpassword');
@ -362,7 +362,7 @@ class SecurityTest extends FunctionalTest {
}
public function testSuccessfulLoginAttempts() {
Security::set_login_recording(true);
Security::config()->login_recording = true;
/* SUCCESSFUL ATTEMPTS ARE LOGGED */
$this->doTestLoginForm('sam@silverstripe.com', '1nitialPassword');

View File

@ -75,19 +75,19 @@ class YamlFixtureTest extends SapphireTest {
}
class YamlFixtureTest_DataObject extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar"
);
static $many_many = array(
private static $many_many = array(
"ManyMany" => "YamlFixtureTest_DataObjectRelation"
);
}
class YamlFixtureTest_DataObjectRelation extends DataObject implements TestOnly {
static $db = array(
private static $db = array(
"Name" => "Varchar"
);
static $belongs_many_many = array(
private static $belongs_many_many = array(
"TestParent" => "YamlFixtureTest_DataObject"
);
}

View File

@ -10,10 +10,4 @@ require_once('conf/ConfigureFromEnv.php');
global $databaseConfig;
$databaseConfig['memory'] = true;
$databaseConfig['path'] = dirname(dirname(__FILE__)) .'/assets/';
MySQLDatabase::set_connection_charset('utf8');
// Set the current theme. More themes can be downloaded from
// http://www.silverstripe.org/themes/
SSViewer::set_theme('simple');
$databaseConfig['path'] = dirname(dirname(__FILE__)) .'/assets/';

View File

@ -3,18 +3,18 @@
class SSViewerTest extends SapphireTest {
public function setUp() {
parent::setUp();
SSViewer::set_source_file_comments(false);
Config::inst()->update('SSViewer', 'source_file_comments', false);
}
/**
* Tests for {@link SSViewer::current_theme()} for different behaviour
* Tests for {@link Config::inst()->get('SSViewer', 'theme')} for different behaviour
* of user defined themes via {@link SiteConfig} and default theme
* when no user themes are defined.
*/
public function testCurrentTheme() {
//TODO: SiteConfig moved to CMS
SSViewer::set_theme('mytheme');
$this->assertEquals('mytheme', SSViewer::current_theme(),
Config::inst()->update('SSViewer', 'theme', 'mytheme');
$this->assertEquals('mytheme', Config::inst()->get('SSViewer', 'theme'),
'Current theme is the default - user has not defined one');
}
@ -52,7 +52,6 @@ class SSViewerTest extends SapphireTest {
$template = $this->render("<% require javascript($jsFile) %>
<% require css($cssFile) %>");
$this->assertFalse((bool)trim($template), "Should be no content in this return.");
}
@ -906,8 +905,8 @@ after')
SS_TemplateLoader::instance()->pushManifest($manifest);
$origTheme = SSViewer::current_theme();
SSViewer::set_theme($theme);
$origTheme = Config::inst()->get('SSViewer', 'theme');
Config::inst()->update('SSViewer', 'theme', $theme);
$e = null;
@ -916,7 +915,7 @@ after')
// Remove all the test themes we created
SS_TemplateLoader::instance()->popManifest();
SSViewer::set_theme($origTheme);
Config::inst()->update('SSViewer', 'theme', $origTheme);
if ($e) throw $e;
}
@ -966,8 +965,8 @@ after')
}
public function testRewriteHashlinks() {
$oldRewriteHashLinks = SSViewer::getOption('rewriteHashlinks');
SSViewer::setOption('rewriteHashlinks', true);
$orig = Config::inst()->get('SSViewer', 'rewrite_hash_links');
Config::inst()->update('SSViewer', 'rewrite_hash_links', true);
// Emulate SSViewer::process()
$base = Convert::raw2att($_SERVER['REQUEST_URI']);
@ -997,13 +996,13 @@ after')
);
unlink($tmplFile);
SSViewer::setOption('rewriteHashlinks', $oldRewriteHashLinks);
Config::inst()->update('SSViewer', 'rewrite_hash_links', $orig);
}
public function testRewriteHashlinksInPhpMode() {
$oldRewriteHashLinks = SSViewer::getOption('rewriteHashlinks');
SSViewer::setOption('rewriteHashlinks', 'php');
$orig = Config::inst()->get('SSViewer', 'rewrite_hash_links');
Config::inst()->update('SSViewer', 'rewrite_hash_links', 'php');
$tmplFile = TEMP_FOLDER . '/SSViewerTest_testRewriteHashlinksInPhpMode_' . sha1(rand()) . '.ss';
@ -1031,14 +1030,14 @@ after')
// );
unlink($tmplFile);
SSViewer::setOption('rewriteHashlinks', $oldRewriteHashLinks);
Config::inst()->update('SSViewer', 'rewrite_hash_links', $orig);
}
public function testRenderWithSourceFileComments() {
$origType = Director::get_environment_type();
Director::set_environment_type('dev');
SSViewer::set_source_file_comments(true);
$origEnv = Config::inst()->get('Director', 'environment_type');
Config::inst()->update('Director', 'environment_type', 'dev');
Config::inst()->update('SSViewer', 'source_file_comments', true);
$view = new SSViewer(array('SSViewerTestCommentsFullSource'));
$data = new ArrayData(array());
@ -1072,9 +1071,9 @@ after')
. '<!-- end include \'SSViewerTestCommentsInclude\' --></div><!-- end template ' . FRAMEWORK_PATH
. '/tests/templates/SSViewerTestCommentsWithInclude.ss -->';
$this->assertEquals($result, $expected);
SSViewer::set_source_file_comments(false);
Director::set_environment_type($origType);
Config::inst()->update('SSViewer', 'source_file_comments', false);
Config::inst()->update('Director', 'environment_type', $origEnv);
}
public function testLoopIteratorIterator() {
@ -1173,7 +1172,7 @@ class SSViewerTestFixture extends ViewableData {
class SSViewerTest_ViewableData extends ViewableData implements TestOnly {
public static $casting = array(
private static $casting = array(
'TextValue' => 'Text',
'HTMLValue' => 'HTMLText'
);

View File

@ -128,9 +128,9 @@ class ViewableDataTest extends SapphireTest {
*/
class ViewableDataTest_Castable extends ViewableData {
public static $default_cast = 'ViewableData_Caster';
private static $default_cast = 'ViewableData_Caster';
public static $casting = array (
private static $casting = array (
'alwaysCasted' => 'ViewableDataTest_RequiresCasting',
'castedUnsafeXML' => 'ViewableData_UnescaptedCaster'
);
@ -205,7 +205,7 @@ class ViewableDataTest_Container extends ViewableData {
}
class ViewableDataTest_CastingClass extends ViewableData {
public static $casting = array(
private static $casting = array(
'Field' => 'CastingType',
'Argument' => 'ArgumentType(Argument)',
'ArrayArgument' => 'ArrayArgumentType(array(foo, bar))'

View File

@ -758,7 +758,7 @@ class Requirements_Backend {
*/
public function add_i18n_javascript($langDir, $return = false, $langOnly = false) {
$files = array();
if(i18n::get_js_i18n()) {
if(i18n::config()->js_i18n) {
// Include i18n.js even if no languages are found. The fact that
// add_i18n_javascript() was called indicates that the methods in
// here are needed.

View File

@ -4468,7 +4468,7 @@ class SSTemplateParser extends Parser {
// non-dynamically calculated
$text = preg_replace(
'/href\s*\=\s*\"\#/',
'href="\' . (SSViewer::$options[\'rewriteHashlinks\'] ? strip_tags( $_SERVER[\'REQUEST_URI\'] ) : "") .
'href="\' . (Config::inst()->get(\'SSViewer\', \'rewrite_hash_links\') ? strip_tags( $_SERVER[\'REQUEST_URI\'] ) : "") .
\'#',
$text
);

View File

@ -533,25 +533,30 @@ class SSViewer_DataPresenter extends SSViewer_Scope {
class SSViewer {
/**
* @config
* @var boolean $source_file_comments
*/
protected static $source_file_comments = false;
private static $source_file_comments = false;
/**
* Set whether HTML comments indicating the source .SS file used to render this page should be
* included in the output. This is enabled by default
*
* @deprecated 3.2 Use the "SSViewer.source_file_comments" config setting instead
* @param boolean $val
*/
public static function set_source_file_comments($val) {
self::$source_file_comments = $val;
Deprecation::notice('3.2', 'Use the "SSViewer.source_file_comments" config setting instead');
Config::inst()->update('SSViewer', 'source_file_comments', $val);
}
/**
* @deprecated 3.2 Use the "SSViewer.source_file_comments" config setting instead
* @return boolean
*/
public static function get_source_file_comments() {
return self::$source_file_comments;
Deprecation::notice('3.2', 'Use the "SSViewer.source_file_comments" config setting instead');
return Config::inst()->get('SSViewer', 'source_file_comments');
}
/**
@ -566,14 +571,16 @@ class SSViewer {
protected $rewriteHashlinks = true;
/**
* @config
* @var string
*/
protected static $current_theme = null;
private static $current_theme = null;
/**
* @config
* @var string
*/
protected static $current_custom_theme = null;
private static $current_custom_theme = null;
/**
* @var boolean
@ -590,20 +597,24 @@ class SSViewer {
}
/**
* @deprecated 3.2 Use the "SSViewer.theme" config setting instead
* @param string $theme The "base theme" name (without underscores).
*/
public static function set_theme($theme) {
self::$current_theme = $theme;
Deprecation::notice('3.2', 'Use the "SSViewer.theme" config setting instead');
Config::inst()->update('SSViewer', 'theme', $theme);
//Static publishing needs to have a theme set, otherwise it defaults to the content controller theme
if(!is_null($theme))
self::$current_custom_theme=$theme;
Config::inst()->update('SSViewer', 'custom_theme', $theme);
}
/**
* @deprecated 3.2 Use the "SSViewer.theme" config setting instead
* @return string
*/
public static function current_theme() {
return self::$current_theme;
Deprecation::notice('3.2', 'Use the "SSViewer.theme" config setting instead');
return Config::inst()->get('SSViewer', 'theme');
}
/**
@ -612,7 +623,8 @@ class SSViewer {
* @return string
*/
public static function get_theme_folder() {
return self::current_theme() ? THEMES_DIR . "/" . self::current_theme() : project();
$theme = Config::inst()->get('SSViewer', 'theme');
return $theme ? THEMES_DIR . "/" . $theme : project();
}
/**
@ -643,7 +655,8 @@ class SSViewer {
* @return string
*/
public static function current_custom_theme(){
return self::$current_custom_theme;
Deprecation::notice('3.2', 'Use the "SSViewer.theme" config setting instead');
return Config::inst()->get('SSViewer', 'custom_theme');
}
/**
@ -671,15 +684,19 @@ class SSViewer {
$this->chosenTemplates['main'] = $templateList;
} else {
$this->chosenTemplates = SS_TemplateLoader::instance()->findTemplates(
$templateList, self::current_theme()
$templateList, Config::inst()->get('SSViewer', 'theme')
);
}
if(!$this->chosenTemplates) {
$templateList = (is_array($templateList)) ? $templateList : array($templateList);
user_error("None of these templates can be found in theme '"
. self::current_theme() . "': ". implode(".ss, ", $templateList) . ".ss", E_USER_WARNING);
user_error(
"None of these templates can be found in theme '"
. Config::inst()->get('SSViewer', 'theme') . "': "
. implode(".ss, ", $templateList) . ".ss",
E_USER_WARNING
);
}
}
@ -710,25 +727,40 @@ class SSViewer {
* links: "<?php echo $_SERVER['REQUEST_URI']; ?>". This is useful if you're generating a
* page that will be saved to a .php file and may be accessed from different URLs.
*
* @deprecated 3.2 Use the "SSViewer.rewrite_hash_links" config setting instead
* @param string $optionName
* @param mixed $optionVal
*/
public static function setOption($optionName, $optionVal) {
SSViewer::$options[$optionName] = $optionVal;
if($optionName == 'rewriteHashlinks') {
Deprecation::notice('3.2', 'Use the "SSViewer.rewrite_hash_links" config setting instead');
Config::inst()->update('SSViewer', 'rewrite_hash_links', $optionVal);
} else {
Deprecation::notice('3.2', 'Use the "SSViewer.' . $optionName . '" config setting instead');
Config::inst()->update('SSViewer', $optionName, $optionVal);
}
}
/**
* @deprecated 3.2 Use the "SSViewer.rewrite_hash_links" config setting instead
* @param string
*
* @return mixed
*/
public static function getOption($optionName) {
return SSViewer::$options[$optionName];
if($optionName == 'rewriteHashlinks') {
Deprecation::notice('3.2', 'Use the "SSViewer.rewrite_hash_links" config setting instead');
return Config::inst()->get('SSViewer', 'rewrite_hash_links');
} else {
Deprecation::notice('3.2', 'Use the "SSViewer.' . $optionName . '" config setting instead');
return Config::inst()->get('SSViewer', $optionName);
}
}
protected static $options = array(
'rewriteHashlinks' => true,
);
/**
* @config
* @var boolean
*/
private static $rewrite_hash_links = true;
protected static $topLevel = array();
@ -744,7 +776,7 @@ class SSViewer {
*/
public function dontRewriteHashlinks() {
$this->rewriteHashlinks = false;
self::$options['rewriteHashlinks'] = false;
Config::inst()->update('SSViewer', 'rewrite_hash_links', false);
return $this;
}
@ -760,7 +792,7 @@ class SSViewer {
*/
public static function getTemplateFileByType($identifier, $type) {
$loader = SS_TemplateLoader::instance();
$found = $loader->findTemplates("$type/$identifier", self::current_theme());
$found = $loader->findTemplates("$type/$identifier", Config::inst()->get('SSViewer', 'theme'));
if ($found) {
return $found['main'];
@ -922,9 +954,11 @@ class SSViewer {
array_pop(SSViewer::$topLevel);
// If we have our crazy base tag, then fix # links referencing the current page.
if($this->rewriteHashlinks && self::$options['rewriteHashlinks']) {
$rewrite = Config::inst()->get('SSViewer', 'rewrite_hash_links');
if($this->rewriteHashlinks && $rewrite) {
if(strpos($output, '<base') !== false) {
if(SSViewer::$options['rewriteHashlinks'] === 'php') {
if($rewrite === 'php') {
$thisURLRelativeToBase = "<?php echo strip_tags(\$_SERVER['REQUEST_URI']); ?>";
} else {
$thisURLRelativeToBase = strip_tags($_SERVER['REQUEST_URI']);
@ -949,7 +983,11 @@ class SSViewer {
}
public static function parseTemplateContent($content, $template="") {
return SSTemplateParser::compileString($content, $template, Director::isDev() && self::$source_file_comments);
return SSTemplateParser::compileString(
$content,
$template,
Director::isDev() && Config::inst()->get('SSViewer', 'source_file_comments')
);
}
/**

View File

@ -21,8 +21,9 @@ class ViewableData extends Object implements IteratorAggregate {
* </code>
*
* @var array
* @config
*/
public static $casting = array(
private static $casting = array(
'CSSClasses' => 'Varchar'
);
@ -31,8 +32,9 @@ class ViewableData extends Object implements IteratorAggregate {
* is required.
*
* @var string
* @config
*/
public static $default_cast = 'Text';
private static $default_cast = 'Text';
/**
* @var array
@ -330,7 +332,6 @@ class ViewableData extends Object implements IteratorAggregate {
if($customFields instanceof ViewableData) {
$data = $data->customise($customFields);
}
if($template instanceof SSViewer) {
return $template->process($data, is_array($customFields) ? $customFields : null);
}
@ -521,7 +522,7 @@ class ViewableData extends Object implements IteratorAggregate {
* @return string
*/
public function ThemeDir($subtheme = false) {
if($theme = SSViewer::current_theme()) {
if($theme = Config::inst()->get('SSViewer', 'theme')) {
return THEMES_DIR . "/$theme" . ($subtheme ? "_$subtheme" : null);
}