Merge pull request #6160 from SteveAzz/update-documentation

Update yml formating for extra javascript & css
This commit is contained in:
Stevie Mayhew 2016-10-07 12:26:29 +13:00 committed by GitHub
commit 0d173f231c

View File

@ -66,1990 +66,1990 @@ use SilverStripe\SiteConfig\SiteConfig;
*/ */
class LeftAndMain extends Controller implements PermissionProvider { class LeftAndMain extends Controller implements PermissionProvider {
/** /**
* Enable front-end debugging (increases verbosity) in dev mode. * Enable front-end debugging (increases verbosity) in dev mode.
* Will be ignored in live environments. * Will be ignored in live environments.
* *
* @var bool * @var bool
*/ */
private static $client_debugging = true; private static $client_debugging = true;
/** /**
* The current url segment attached to the LeftAndMain instance * The current url segment attached to the LeftAndMain instance
* *
* @config * @config
* @var string * @var string
*/ */
private static $url_segment; private static $url_segment;
/** /**
* @config * @config
* @var string * @var string
*/ */
private static $url_rule = '/$Action/$ID/$OtherID'; private static $url_rule = '/$Action/$ID/$OtherID';
/** /**
* @config * @config
* @var string * @var string
*/ */
private static $menu_title; private static $menu_title;
/** /**
* @config * @config
* @var string * @var string
*/ */
private static $menu_icon; private static $menu_icon;
/** /**
* @config * @config
* @var int * @var int
*/ */
private static $menu_priority = 0; private static $menu_priority = 0;
/** /**
* @config * @config
* @var int * @var int
*/ */
private static $url_priority = 50; private static $url_priority = 50;
/** /**
* A subclass of {@link DataObject}. * A subclass of {@link DataObject}.
* *
* Determines what is managed in this interface, through * Determines what is managed in this interface, through
* {@link getEditForm()} and other logic. * {@link getEditForm()} and other logic.
* *
* @config * @config
* @var string * @var string
*/ */
private static $tree_class = null; private static $tree_class = null;
/** /**
* The url used for the link in the Help tab in the backend * The url used for the link in the Help tab in the backend
* *
* @config * @config
* @var string * @var string
*/ */
private static $help_link = '//userhelp.silverstripe.org/framework/en/3.3'; private static $help_link = '//userhelp.silverstripe.org/framework/en/3.3';
/** /**
* @var array * @var array
*/ */
private static $allowed_actions = [ private static $allowed_actions = [
'index', 'index',
'save', 'save',
'savetreenode', 'savetreenode',
'getsubtree', 'getsubtree',
'updatetreenodes', 'updatetreenodes',
'printable', 'printable',
'show', 'show',
'EditorToolbar', 'EditorToolbar',
'EditForm', 'EditForm',
'AddForm', 'AddForm',
'batchactions', 'batchactions',
'BatchActionsForm', 'BatchActionsForm',
'schema', 'schema',
]; ];
private static $url_handlers = [ private static $url_handlers = [
'GET schema/$FormName/$ItemID' => 'schema' 'GET schema/$FormName/$ItemID' => 'schema'
]; ];
private static $dependencies = [ private static $dependencies = [
'schema' => '%$FormSchema' 'schema' => '%$FormSchema'
]; ];
/** /**
* Assign themes to use for cms * Assign themes to use for cms
* *
* @config * @config
* @var array * @var array
*/ */
private static $admin_themes = [ private static $admin_themes = [
'silverstripe/framework:/admin/themes/cms-forms', 'silverstripe/framework:/admin/themes/cms-forms',
SSViewer::DEFAULT_THEME, SSViewer::DEFAULT_THEME,
]; ];
/** /**
* Codes which are required from the current user to view this controller. * Codes which are required from the current user to view this controller.
* If multiple codes are provided, all of them are required. * If multiple codes are provided, all of them are required.
* All CMS controllers require "CMS_ACCESS_LeftAndMain" as a baseline check, * All CMS controllers require "CMS_ACCESS_LeftAndMain" as a baseline check,
* and fall back to "CMS_ACCESS_<class>" if no permissions are defined here. * and fall back to "CMS_ACCESS_<class>" if no permissions are defined here.
* See {@link canView()} for more details on permission checks. * See {@link canView()} for more details on permission checks.
* *
* @config * @config
* @var array * @var array
*/ */
private static $required_permission_codes; private static $required_permission_codes;
/** /**
* @config * @config
* @var String Namespace for session info, e.g. current record. * @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 * Defaults to the current class name, but can be amended to share a namespace in case
* controllers are logically bundled together, and mainly separated * controllers are logically bundled together, and mainly separated
* to achieve more flexible templating. * to achieve more flexible templating.
*/ */
private static $session_namespace; private static $session_namespace;
/** /**
* Register additional requirements through the {@link Requirements} class. * Register additional requirements through the {@link Requirements} class.
* Used mainly to work around the missing "lazy loading" functionality * Used mainly to work around the missing "lazy loading" functionality
* for getting css/javascript required after an ajax-call (e.g. loading the editform). * for getting css/javascript required after an ajax-call (e.g. loading the editform).
* *
* YAML configuration example: * YAML configuration example:
* <code> * <code>
* LeftAndMain: * LeftAndMain:
* extra_requirements_javascript: * extra_requirements_javascript:
* mysite/javascript/myscript.js: * - mysite/javascript/myscript.js
* </code> * </code>
* *
* @config * @config
* @var array * @var array
*/ */
private static $extra_requirements_javascript = array(); private static $extra_requirements_javascript = array();
/** /**
* YAML configuration example: * YAML configuration example:
* <code> * <code>
* LeftAndMain: * LeftAndMain:
* extra_requirements_css: * extra_requirements_css:
* mysite/css/mystyle.css: * - mysite/css/mystyle.css:
* media: screen * media: screen
* </code> * </code>
* *
* @config * @config
* @var array See {@link extra_requirements_javascript} * @var array See {@link extra_requirements_javascript}
*/ */
private static $extra_requirements_css = array(); private static $extra_requirements_css = array();
/** /**
* @config * @config
* @var array See {@link extra_requirements_javascript} * @var array See {@link extra_requirements_javascript}
*/ */
private static $extra_requirements_themedCss = array(); private static $extra_requirements_themedCss = array();
/** /**
* If true, call a keepalive ping every 5 minutes from the CMS interface, * If true, call a keepalive ping every 5 minutes from the CMS interface,
* to ensure that the session never dies. * to ensure that the session never dies.
* *
* @config * @config
* @var boolean * @var boolean
*/ */
private static $session_keepalive_ping = true; private static $session_keepalive_ping = true;
/** /**
* Value of X-Frame-Options header * Value of X-Frame-Options header
* *
* @config * @config
* @var string * @var string
*/ */
private static $frame_options = 'SAMEORIGIN'; private static $frame_options = 'SAMEORIGIN';
/** /**
* @var PjaxResponseNegotiator * @var PjaxResponseNegotiator
*/ */
protected $responseNegotiator; protected $responseNegotiator;
/** /**
* Gets the combined configuration of all LeafAndMain subclasses required by the client app. * Gets the combined configuration of all LeafAndMain subclasses required by the client app.
* *
* @return array * @return array
* *
* WARNING: Experimental API * WARNING: Experimental API
*/ */
public function getCombinedClientConfig() { public function getCombinedClientConfig() {
$combinedClientConfig = ['sections' => []]; $combinedClientConfig = ['sections' => []];
$cmsClassNames = CMSMenu::get_cms_classes('SilverStripe\\Admin\\LeftAndMain', true, CMSMenu::URL_PRIORITY); $cmsClassNames = CMSMenu::get_cms_classes('SilverStripe\\Admin\\LeftAndMain', true, CMSMenu::URL_PRIORITY);
foreach ($cmsClassNames as $className) { foreach ($cmsClassNames as $className) {
$combinedClientConfig['sections'][$className] = Injector::inst()->get($className)->getClientConfig(); $combinedClientConfig['sections'][$className] = Injector::inst()->get($className)->getClientConfig();
} }
// Pass in base url (absolute and relative) // Pass in base url (absolute and relative)
$combinedClientConfig['baseUrl'] = Director::baseURL(); $combinedClientConfig['baseUrl'] = Director::baseURL();
$combinedClientConfig['absoluteBaseUrl'] = Director::absoluteBaseURL(); $combinedClientConfig['absoluteBaseUrl'] = Director::absoluteBaseURL();
$combinedClientConfig['adminUrl'] = AdminRootController::admin_url(); $combinedClientConfig['adminUrl'] = AdminRootController::admin_url();
// Get "global" CSRF token for use in JavaScript // Get "global" CSRF token for use in JavaScript
$token = SecurityToken::inst(); $token = SecurityToken::inst();
$combinedClientConfig[$token->getName()] = $token->getValue(); $combinedClientConfig[$token->getName()] = $token->getValue();
// Set env // Set env
$combinedClientConfig['environment'] = Director::get_environment_type(); $combinedClientConfig['environment'] = Director::get_environment_type();
$combinedClientConfig['debugging'] = $this->config()->client_debugging; $combinedClientConfig['debugging'] = $this->config()->client_debugging;
return Convert::raw2json($combinedClientConfig); return Convert::raw2json($combinedClientConfig);
} }
/** /**
* Returns configuration required by the client app. * Returns configuration required by the client app.
* *
* @return array * @return array
* *
* WARNING: Experimental API * WARNING: Experimental API
*/
public function getClientConfig() {
return [
// Trim leading/trailing slash to make it easier to concatenate URL
// and use in routing definitions.
'url' => trim($this->Link(), '/'),
];
}
/**
* Gets a JSON schema representing the current edit form.
*
* WARNING: Experimental API.
*
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function schema($request) {
$response = $this->getResponse();
$formName = $request->param('FormName');
$itemID = $request->param('ItemID');
if (!$formName) {
return (new HTTPResponse('Missing request params', 400));
}
if(!$this->hasMethod("get{$formName}")) {
return (new HTTPResponse('Form not found', 404));
}
if(!$this->hasAction($formName)) {
return (new HTTPResponse('Form not accessible', 401));
}
$form = $this->{"get{$formName}"}($itemID);
$response->addHeader('Content-Type', 'application/json');
$response->setBody(Convert::raw2json($this->getSchemaForForm($form)));
return $response;
}
/**
* Given a form, generate a response containing the requested form
* schema if X-Formschema-Request header is set.
*
* @param Form $form
* @return HTTPResponse
*/
protected function getSchemaResponse($form) {
$request = $this->getRequest();
if($request->getHeader('X-Formschema-Request')) {
$data = $this->getSchemaForForm($form);
$response = new HTTPResponse(Convert::raw2json($data));
$response->addHeader('Content-Type', 'application/json');
return $response;
}
return null;
}
/**
* Returns a representation of the provided {@link Form} as structured data,
* based on the request data.
*
* @param Form $form
* @return array
*/
protected function getSchemaForForm(Form $form) {
$request = $this->getRequest();
$return = null;
// Valid values for the "X-Formschema-Request" header are "schema" and "state".
// If either of these values are set they will be stored in the $schemaParst array
// and used to construct the response body.
if ($schemaHeader = $request->getHeader('X-Formschema-Request')) {
$schemaParts = array_filter(explode(',', $schemaHeader), function($value) {
$validHeaderValues = ['schema', 'state'];
return in_array(trim($value), $validHeaderValues);
});
} else {
$schemaParts = ['schema'];
}
$return = ['id' => $form->FormName()];
if (in_array('schema', $schemaParts)) {
$return['schema'] = $this->schema->getSchema($form);
}
if (in_array('state', $schemaParts)) {
$return['state'] = $this->schema->getState($form);
}
return $return;
}
/**
* @param Member $member
* @return boolean
*/
public function canView($member = null) {
if(!$member && $member !== FALSE) $member = Member::currentUser();
// cms menus only for logged-in members
if(!$member) return false;
// alternative extended checks
if($this->hasMethod('alternateAccessCheck')) {
$alternateAllowed = $this->alternateAccessCheck();
if($alternateAllowed === false) {
return false;
}
}
// Check for "CMS admin" permission
if(Permission::checkMember($member, "CMS_ACCESS_LeftAndMain")) {
return true;
}
// Check for LeftAndMain sub-class permissions
$codes = $this->getRequiredPermissions();
if($codes === false) { // allow explicit FALSE to disable subclass check
return true;
}
foreach((array)$codes as $code) {
if(!Permission::checkMember($member, $code)) {
return false;
}
}
return true;
}
/**
* Get list of required permissions
*
* @return array|string|bool Code, array of codes, or false if no permission required
*/
public static function getRequiredPermissions() {
$class = get_called_class();
$code = Config::inst()->get($class, 'required_permission_codes', Config::FIRST_SET);
if ($code === false) {
return false;
}
if ($code) {
return $code;
}
return "CMS_ACCESS_" . $class;
}
/**
* @uses LeftAndMainExtension->init()
* @uses LeftAndMainExtension->accessedCMS()
* @uses CMSMenu
*/
protected function init() {
parent::init();
SSViewer::config()->update('rewrite_hash_links', false);
ContentNegotiator::config()->update('enabled', false);
// set language
$member = Member::currentUser();
if(!empty($member->Locale)) {
i18n::set_locale($member->Locale);
}
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(
'Help',
_t('LeftAndMain.HELP', 'Help', 'Menu title'),
$this->config()->help_link,
-2,
array(
'target' => '_blank'
)
);
// Allow customisation of the access check by a extension
// Also all the canView() check to execute Controller::redirect()
if(!$this->canView() && !$this->getResponse()->isFinished()) {
// When access /admin/, we should try a redirect to another part of the admin rather than be locked out
$menu = $this->MainMenu();
foreach($menu as $candidate) {
if(
$candidate->Link &&
$candidate->Link != $this->Link()
&& $candidate->MenuItem->controller
&& singleton($candidate->MenuItem->controller)->canView()
) {
$this->redirect($candidate->Link);
return;
}
}
if(Member::currentUser()) {
Session::set("BackURL", null);
}
// if no alternate menu items have matched, return a permission error
$messageSet = array(
'default' => _t(
'LeftAndMain.PERMDEFAULT',
"You must be logged in to access the administration area; please enter your credentials below."
),
'alreadyLoggedIn' => _t(
'LeftAndMain.PERMALREADY',
"I'm sorry, but you can't access that part of the CMS. If you want to log in as someone else, do"
. " so below."
),
'logInAgain' => _t(
'LeftAndMain.PERMAGAIN',
"You have been logged out of the CMS. If you would like to log in again, enter a username and"
. " password below."
),
);
Security::permissionFailure($this, $messageSet);
return;
}
// Don't continue if there's already been a redirection request.
if($this->redirectedTo()) {
return;
}
// Audit logging hook
if(empty($_REQUEST['executeForm']) && !$this->getRequest()->isAjax()) $this->extend('accessedCMS');
// Set the members html editor config
if(Member::currentUser()) {
HTMLEditorConfig::set_active_identifier(Member::currentUser()->getHtmlEditorConfigForCMS());
}
// Set default values in the config if missing. These things can't be defined in the config
// file because insufficient information exists when that is being processed
$htmlEditorConfig = HTMLEditorConfig::get_active();
$htmlEditorConfig->setOption('language', i18n::get_tinymce_lang());
Requirements::customScript("
window.ss = window.ss || {};
window.ss.config = " . $this->getCombinedClientConfig() . ";
");
Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/vendor.js');
Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/bundle.js');
Requirements::css(ltrim(FRAMEWORK_ADMIN_DIR . '/client/dist/styles/bundle.css', '/'));
Requirements::add_i18n_javascript(ltrim(FRAMEWORK_DIR . '/client/lang', '/'), false, true);
Requirements::add_i18n_javascript(FRAMEWORK_ADMIN_DIR . '/client/lang', false, true);
if ($this->config()->session_keepalive_ping) {
Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/LeftAndMain.Ping.js');
}
if (Director::isDev()) {
// TODO Confuses jQuery.ondemand through document.write()
Requirements::javascript(ADMIN_THIRDPARTY_DIR . '/jquery-entwine/src/jquery.entwine.inspector.js');
Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/leaktools.js');
}
// Custom requirements
$extraJs = $this->stat('extra_requirements_javascript');
if($extraJs) {
foreach($extraJs as $file => $config) {
if(is_numeric($file)) {
$file = $config;
}
Requirements::javascript($file);
}
}
$extraCss = $this->stat('extra_requirements_css');
if($extraCss) {
foreach($extraCss as $file => $config) {
if(is_numeric($file)) {
$file = $config;
$config = array();
}
Requirements::css($file, isset($config['media']) ? $config['media'] : null);
}
}
$extraThemedCss = $this->stat('extra_requirements_themedCss');
if($extraThemedCss) {
foreach ($extraThemedCss as $file => $config) {
if(is_numeric($file)) {
$file = $config;
$config = array();
}
Requirements::themedCSS($file, isset($config['media']) ? $config['media'] : null);
}
}
$dummy = null;
$this->extend('init', $dummy);
// Assign default cms theme and replace user-specified themes
SSViewer::set_themes($this->config()->admin_themes);
//set the reading mode for the admin to stage
Versioned::set_stage(Versioned::DRAFT);
}
public function handleRequest(HTTPRequest $request, DataModel $model = null) {
try {
$response = parent::handleRequest($request, $model);
} catch(ValidationException $e) {
// Nicer presentation of model-level validation errors
$msgs = _t('LeftAndMain.ValidationError', 'Validation error') . ': '
. $e->getMessage();
$e = new HTTPResponse_Exception($msgs, 403);
$errorResponse = $e->getResponse();
$errorResponse->addHeader('Content-Type', 'text/plain');
$errorResponse->addHeader('X-Status', rawurlencode($msgs));
$e->setResponse($errorResponse);
throw $e;
}
$title = $this->Title();
if(!$response->getHeader('X-Controller')) $response->addHeader('X-Controller', $this->class);
if(!$response->getHeader('X-Title')) $response->addHeader('X-Title', urlencode($title));
// Prevent clickjacking, see https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
$originalResponse = $this->getResponse();
$originalResponse->addHeader('X-Frame-Options', $this->config()->frame_options);
$originalResponse->addHeader('Vary', 'X-Requested-With');
return $response;
}
/**
* Overloaded redirection logic to trigger a fake redirect on ajax requests.
* While this violates HTTP principles, its the only way to work around the
* fact that browsers handle HTTP redirects opaquely, no intervention via JS is possible.
* In isolation, that's not a problem - but combined with history.pushState()
* it means we would request the same redirection URL twice if we want to update the URL as well.
* See LeftAndMain.js for the required jQuery ajaxComplete handlers.
*
* @param string $url
* @param int $code
* @return HTTPResponse|string
*/
public function redirect($url, $code=302) {
if($this->getRequest()->isAjax()) {
$response = $this->getResponse();
$response->addHeader('X-ControllerURL', $url);
if($this->getRequest()->getHeader('X-Pjax') && !$response->getHeader('X-Pjax')) {
$response->addHeader('X-Pjax', $this->getRequest()->getHeader('X-Pjax'));
}
$newResponse = new LeftAndMain_HTTPResponse(
$response->getBody(),
$response->getStatusCode(),
$response->getStatusDescription()
);
foreach($response->getHeaders() as $k => $v) {
$newResponse->addHeader($k, $v);
}
$newResponse->setIsFinished(true);
$this->setResponse($newResponse);
return ''; // Actual response will be re-requested by client
} else {
parent::redirect($url, $code);
}
}
/**
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function index($request) {
return $this->getResponseNegotiator()->respond($request);
}
/**
* If this is set to true, the "switchView" context in the
* template is shown, with links to the staging and publish site.
*
* @return boolean
*/
public function ShowSwitchView() {
return false;
}
//------------------------------------------------------------------------------------------//
// Main controllers
/**
* You should implement a Link() function in your subclass of LeftAndMain,
* to point to the URL of that particular controller.
*
* @param string $action
* @return string
*/
public function Link($action = null) {
// Handle missing url_segments
if($this->config()->url_segment) {
$segment = $this->config()->get('url_segment', Config::FIRST_SET);
} else {
$segment = $this->class;
};
$link = Controller::join_links(
AdminRootController::admin_url(),
$segment,
'/', // trailing slash needed if $action is null!
"$action"
);
$this->extend('updateLink', $link);
return $link;
}
/**
* @deprecated 5.0
*/
public static function menu_title_for_class($class) {
Deprecation::notice('5.0', 'Use menu_title() instead');
return static::menu_title($class, false);
}
/**
* Get menu title for this section (translated)
*
* @param string $class Optional class name if called on LeftAndMain directly
* @param bool $localise Determine if menu title should be localised via i18n.
* @return string Menu title for the given class
*/
public static function menu_title($class = null, $localise = true) {
if($class && is_subclass_of($class, __CLASS__)) {
// Respect oveloading of menu_title() in subclasses
return $class::menu_title(null, $localise);
}
if(!$class) {
$class = get_called_class();
}
// Get default class title
$title = Config::inst()->get($class, 'menu_title', Config::FIRST_SET);
if(!$title) {
$title = preg_replace('/Admin$/', '', $class);
}
// Check localisation
if(!$localise) {
return $title;
}
return i18n::_t("{$class}.MENUTITLE", $title);
}
/**
* Return styling for the menu icon, if a custom icon is set for this class
*
* Example: static $menu-icon = '/path/to/image/';
* @param string $class
* @return string
*/
public static function menu_icon_for_class($class) {
$icon = Config::inst()->get($class, 'menu_icon', Config::FIRST_SET);
if (!empty($icon)) {
$class = strtolower(Convert::raw2htmlname(str_replace('\\', '-', $class)));
return ".icon.icon-16.icon-{$class} { background-image: url('{$icon}'); } ";
}
return '';
}
/**
* @param HTTPRequest $request
* @return HTTPResponse
* @throws HTTPResponse_Exception
*/ */
public function show($request) { public function getClientConfig() {
// TODO Necessary for TableListField URLs to work properly return [
if($request->param('ID')) $this->setCurrentPageID($request->param('ID')); // Trim leading/trailing slash to make it easier to concatenate URL
return $this->getResponseNegotiator()->respond($request); // and use in routing definitions.
} 'url' => trim($this->Link(), '/'),
];
/** }
* Caution: Volatile API.
* /**
* @return PjaxResponseNegotiator * Gets a JSON schema representing the current edit form.
*/ *
public function getResponseNegotiator() { * WARNING: Experimental API.
if(!$this->responseNegotiator) { *
$controller = $this; * @param HTTPRequest $request
$this->responseNegotiator = new PjaxResponseNegotiator( * @return HTTPResponse
array( */
'CurrentForm' => function() use(&$controller) { public function schema($request) {
return $controller->getEditForm()->forTemplate(); $response = $this->getResponse();
}, $formName = $request->param('FormName');
'Content' => function() use(&$controller) { $itemID = $request->param('ItemID');
return $controller->renderWith($controller->getTemplatesWithSuffix('_Content'));
}, if (!$formName) {
'Breadcrumbs' => function() use (&$controller) { return (new HTTPResponse('Missing request params', 400));
return $controller->renderWith([ }
'type' => 'Includes',
'SilverStripe\\Admin\\CMSBreadcrumbs' if(!$this->hasMethod("get{$formName}")) {
]); return (new HTTPResponse('Form not found', 404));
}, }
'default' => function() use(&$controller) {
return $controller->renderWith($controller->getViewer('show')); if(!$this->hasAction($formName)) {
} return (new HTTPResponse('Form not accessible', 401));
), }
$this->getResponse()
); $form = $this->{"get{$formName}"}($itemID);
}
return $this->responseNegotiator; $response->addHeader('Content-Type', 'application/json');
} $response->setBody(Convert::raw2json($this->getSchemaForForm($form)));
//------------------------------------------------------------------------------------------// return $response;
// Main UI components }
/** /**
* Returns the main menu of the CMS. This is also used by init() * Given a form, generate a response containing the requested form
* to work out which sections the user has access to. * schema if X-Formschema-Request header is set.
* *
* @param bool $cached * @param Form $form
* @return SS_List * @return HTTPResponse
*/ */
public function MainMenu($cached = true) { protected function getSchemaResponse($form) {
if(!isset($this->_cache_MainMenu) || !$cached) { $request = $this->getRequest();
// Don't accidentally return a menu if you're not logged in - it's used to determine access. if($request->getHeader('X-Formschema-Request')) {
if(!Member::currentUser()) return new ArrayList(); $data = $this->getSchemaForForm($form);
$response = new HTTPResponse(Convert::raw2json($data));
// Encode into DO set $response->addHeader('Content-Type', 'application/json');
$menu = new ArrayList(); return $response;
$menuItems = CMSMenu::get_viewable_menu_items(); }
return null;
// extra styling for custom menu-icons }
$menuIconStyling = '';
/**
if($menuItems) { * Returns a representation of the provided {@link Form} as structured data,
/** @var CMSMenuItem $menuItem */ * based on the request data.
foreach($menuItems as $code => $menuItem) { *
// alternate permission checks (in addition to LeftAndMain->canView()) * @param Form $form
if( * @return array
isset($menuItem->controller) */
&& $this->hasMethod('alternateMenuDisplayCheck') protected function getSchemaForForm(Form $form) {
&& !$this->alternateMenuDisplayCheck($menuItem->controller) $request = $this->getRequest();
) { $return = null;
continue;
} // Valid values for the "X-Formschema-Request" header are "schema" and "state".
// If either of these values are set they will be stored in the $schemaParst array
$linkingmode = "link"; // and used to construct the response body.
if ($schemaHeader = $request->getHeader('X-Formschema-Request')) {
if($menuItem->controller && get_class($this) == $menuItem->controller) { $schemaParts = array_filter(explode(',', $schemaHeader), function($value) {
$linkingmode = "current"; $validHeaderValues = ['schema', 'state'];
} else if(strpos($this->Link(), $menuItem->url) !== false) { return in_array(trim($value), $validHeaderValues);
if($this->Link() == $menuItem->url) { });
$linkingmode = "current"; } else {
$schemaParts = ['schema'];
// default menu is the one with a blank {@link url_segment} }
} else if(singleton($menuItem->controller)->stat('url_segment') == '') {
if($this->Link() == AdminRootController::admin_url()) { $return = ['id' => $form->FormName()];
$linkingmode = "current";
} if (in_array('schema', $schemaParts)) {
$return['schema'] = $this->schema->getSchema($form);
} else { }
$linkingmode = "current";
} if (in_array('state', $schemaParts)) {
} $return['state'] = $this->schema->getState($form);
}
// already set in CMSMenu::populate_menu(), but from a static pre-controller
// context, so doesn't respect the current user locale in _t() calls - as a workaround, return $return;
// we simply call LeftAndMain::menu_title() again }
// if we're dealing with a controller
if($menuItem->controller) { /**
$title = LeftAndMain::menu_title($menuItem->controller); * @param Member $member
} else { * @return boolean
$title = $menuItem->title; */
} public function canView($member = null) {
if(!$member && $member !== FALSE) $member = Member::currentUser();
// Provide styling for custom $menu-icon. Done here instead of in
// CMSMenu::populate_menu(), because the icon is part of // cms menus only for logged-in members
// the CMS right pane for the specified class as well... if(!$member) return false;
if($menuItem->controller) {
$menuIcon = LeftAndMain::menu_icon_for_class($menuItem->controller); // alternative extended checks
if (!empty($menuIcon)) { if($this->hasMethod('alternateAccessCheck')) {
$menuIconStyling .= $menuIcon; $alternateAllowed = $this->alternateAccessCheck();
} if($alternateAllowed === false) {
} return false;
}
$menu->push(new ArrayData(array( }
"MenuItem" => $menuItem,
"AttributesHTML" => $menuItem->getAttributesHTML(), // Check for "CMS admin" permission
"Title" => Convert::raw2xml($title), if(Permission::checkMember($member, "CMS_ACCESS_LeftAndMain")) {
"Code" => $code, return true;
"Icon" => strtolower($code), }
"Link" => $menuItem->url,
"LinkingMode" => $linkingmode // Check for LeftAndMain sub-class permissions
))); $codes = $this->getRequiredPermissions();
} if($codes === false) { // allow explicit FALSE to disable subclass check
} return true;
if ($menuIconStyling) Requirements::customCSS($menuIconStyling); }
foreach((array)$codes as $code) {
$this->_cache_MainMenu = $menu; if(!Permission::checkMember($member, $code)) {
} return false;
}
return $this->_cache_MainMenu; }
}
return true;
public function Menu() { }
return $this->renderWith($this->getTemplatesWithSuffix('_Menu'));
} /**
* Get list of required permissions
/** *
* @todo Wrap in CMSMenu instance accessor * @return array|string|bool Code, array of codes, or false if no permission required
* @return ArrayData A single menu entry (see {@link MainMenu}) */
*/ public static function getRequiredPermissions() {
public function MenuCurrentItem() { $class = get_called_class();
$items = $this->MainMenu(); $code = Config::inst()->get($class, 'required_permission_codes', Config::FIRST_SET);
return $items->find('LinkingMode', 'current'); if ($code === false) {
} return false;
}
/** if ($code) {
* Return a list of appropriate templates for this class, with the given suffix using return $code;
* {@link SSViewer::get_templates_by_class()} }
* return "CMS_ACCESS_" . $class;
* @param string $suffix }
* @return array
*/ /**
public function getTemplatesWithSuffix($suffix) { * @uses LeftAndMainExtension->init()
$templates = SSViewer::get_templates_by_class(get_class($this), $suffix, __CLASS__); * @uses LeftAndMainExtension->accessedCMS()
return SSViewer::chooseTemplate($templates); * @uses CMSMenu
} */
protected function init() {
public function Content() { parent::init();
return $this->renderWith($this->getTemplatesWithSuffix('_Content'));
} SSViewer::config()->update('rewrite_hash_links', false);
ContentNegotiator::config()->update('enabled', false);
/**
* Render $PreviewPanel content // set language
* $member = Member::currentUser();
* @return DBHTMLText if(!empty($member->Locale)) {
*/ i18n::set_locale($member->Locale);
public function PreviewPanel() { }
$template = $this->getTemplatesWithSuffix('_PreviewPanel'); if(!empty($member->DateFormat)) {
// Only render sections with preview panel i18n::config()->date_format = $member->DateFormat;
if ($template) { }
return $this->renderWith($template); if(!empty($member->TimeFormat)) {
} i18n::config()->time_format = $member->TimeFormat;
} }
public function getRecord($id) { // can't be done in cms/_config.php as locale is not set yet
$className = $this->stat('tree_class'); CMSMenu::add_link(
if($className && $id instanceof $className) { 'Help',
return $id; _t('LeftAndMain.HELP', 'Help', 'Menu title'),
} else if($className && $id == 'root') { $this->config()->help_link,
return singleton($className); -2,
} else if($className && is_numeric($id)) { array(
return DataObject::get_by_id($className, $id); 'target' => '_blank'
} else { )
return false; );
}
} // Allow customisation of the access check by a extension
// Also all the canView() check to execute Controller::redirect()
/** if(!$this->canView() && !$this->getResponse()->isFinished()) {
* @param bool $unlinked // When access /admin/, we should try a redirect to another part of the admin rather than be locked out
* @return ArrayList $menu = $this->MainMenu();
*/ foreach($menu as $candidate) {
public function Breadcrumbs($unlinked = false) { if(
$items = new ArrayList(array( $candidate->Link &&
new ArrayData(array( $candidate->Link != $this->Link()
'Title' => $this->menu_title(), && $candidate->MenuItem->controller
'Link' => ($unlinked) ? false : $this->Link() && singleton($candidate->MenuItem->controller)->canView()
)) ) {
)); $this->redirect($candidate->Link);
$record = $this->currentPage(); return;
if($record && $record->exists()) { }
if($record->hasExtension('SilverStripe\\ORM\\Hierarchy\\Hierarchy')) { }
$ancestors = $record->getAncestors();
$ancestors = new ArrayList(array_reverse($ancestors->toArray())); if(Member::currentUser()) {
$ancestors->push($record); Session::set("BackURL", null);
foreach($ancestors as $ancestor) { }
$items->push(new ArrayData(array(
'Title' => ($ancestor->MenuTitle) ? $ancestor->MenuTitle : $ancestor->Title, // if no alternate menu items have matched, return a permission error
'Link' => ($unlinked) ? false : Controller::join_links($this->Link('show'), $ancestor->ID) $messageSet = array(
))); 'default' => _t(
} 'LeftAndMain.PERMDEFAULT',
} else { "You must be logged in to access the administration area; please enter your credentials below."
$items->push(new ArrayData(array( ),
'Title' => ($record->MenuTitle) ? $record->MenuTitle : $record->Title, 'alreadyLoggedIn' => _t(
'Link' => ($unlinked) ? false : Controller::join_links($this->Link('show'), $record->ID) 'LeftAndMain.PERMALREADY',
))); "I'm sorry, but you can't access that part of the CMS. If you want to log in as someone else, do"
} . " so below."
} ),
'logInAgain' => _t(
return $items; 'LeftAndMain.PERMAGAIN',
} "You have been logged out of the CMS. If you would like to log in again, enter a username and"
. " password below."
/** ),
* @return String HTML );
*/
public function SiteTreeAsUL() { Security::permissionFailure($this, $messageSet);
$html = $this->getSiteTreeFor($this->stat('tree_class')); return;
$this->extend('updateSiteTreeAsUL', $html); }
return $html;
} // Don't continue if there's already been a redirection request.
if($this->redirectedTo()) {
/** return;
* Gets the current search filter for this request, if available }
*
* @throws InvalidArgumentException // Audit logging hook
* @return LeftAndMain_SearchFilter if(empty($_REQUEST['executeForm']) && !$this->getRequest()->isAjax()) $this->extend('accessedCMS');
*/
protected function getSearchFilter() { // Set the members html editor config
// Check for given FilterClass if(Member::currentUser()) {
$params = $this->getRequest()->getVar('q'); HTMLEditorConfig::set_active_identifier(Member::currentUser()->getHtmlEditorConfigForCMS());
if(empty($params['FilterClass'])) { }
return null;
} // Set default values in the config if missing. These things can't be defined in the config
// file because insufficient information exists when that is being processed
// Validate classname $htmlEditorConfig = HTMLEditorConfig::get_active();
$filterClass = $params['FilterClass']; $htmlEditorConfig->setOption('language', i18n::get_tinymce_lang());
$filterInfo = new ReflectionClass($filterClass);
if(!$filterInfo->implementsInterface('SilverStripe\\Admin\\LeftAndMain_SearchFilter')) { Requirements::customScript("
throw new InvalidArgumentException(sprintf('Invalid filter class passed: %s', $filterClass)); window.ss = window.ss || {};
} window.ss.config = " . $this->getCombinedClientConfig() . ";
");
return Injector::inst()->createWithArgs($filterClass, array($params));
} Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/vendor.js');
Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/bundle.js');
/** Requirements::css(ltrim(FRAMEWORK_ADMIN_DIR . '/client/dist/styles/bundle.css', '/'));
* Get a site tree HTML listing which displays the nodes under the given criteria.
* Requirements::add_i18n_javascript(ltrim(FRAMEWORK_DIR . '/client/lang', '/'), false, true);
* @param string $className The class of the root object Requirements::add_i18n_javascript(FRAMEWORK_ADMIN_DIR . '/client/lang', false, true);
* @param string $rootID The ID of the root object. If this is null then a complete tree will be
* shown if ($this->config()->session_keepalive_ping) {
* @param string $childrenMethod The method to call to get the children of the tree. For example, Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/LeftAndMain.Ping.js');
* Children, AllChildrenIncludingDeleted, or AllHistoricalChildren }
* @param string $numChildrenMethod
* @param callable $filterFunction if (Director::isDev()) {
* @param int $nodeCountThreshold // TODO Confuses jQuery.ondemand through document.write()
* @return string Nested unordered list with links to each page Requirements::javascript(ADMIN_THIRDPARTY_DIR . '/jquery-entwine/src/jquery.entwine.inspector.js');
*/ Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/client/dist/js/leaktools.js');
public function getSiteTreeFor($className, $rootID = null, $childrenMethod = null, $numChildrenMethod = null, }
$filterFunction = null, $nodeCountThreshold = 30) {
// Custom requirements
// Filter criteria $extraJs = $this->stat('extra_requirements_javascript');
$filter = $this->getSearchFilter();
if($extraJs) {
// Default childrenMethod and numChildrenMethod foreach($extraJs as $file => $config) {
if(!$childrenMethod) $childrenMethod = ($filter && $filter->getChildrenMethod()) if(is_numeric($file)) {
? $filter->getChildrenMethod() $file = $config;
: 'AllChildrenIncludingDeleted'; }
if(!$numChildrenMethod) { Requirements::javascript($file);
$numChildrenMethod = 'numChildren'; }
if($filter && $filter->getNumChildrenMethod()) { }
$numChildrenMethod = $filter->getNumChildrenMethod();
} $extraCss = $this->stat('extra_requirements_css');
}
if(!$filterFunction && $filter) { if($extraCss) {
$filterFunction = function($node) use($filter) { foreach($extraCss as $file => $config) {
return $filter->isPageIncluded($node); if(is_numeric($file)) {
}; $file = $config;
} $config = array();
}
// Get the tree root
$record = ($rootID) ? $this->getRecord($rootID) : null; Requirements::css($file, isset($config['media']) ? $config['media'] : null);
$obj = $record ? $record : singleton($className); }
}
// Get the current page
// NOTE: This *must* be fetched before markPartialTree() is called, as this $extraThemedCss = $this->stat('extra_requirements_themedCss');
// causes the Hierarchy::$marked cache to be flushed (@see CMSMain::getRecord)
// which means that deleted pages stored in the marked tree would be removed if($extraThemedCss) {
$currentPage = $this->currentPage(); foreach ($extraThemedCss as $file => $config) {
if(is_numeric($file)) {
// Mark the nodes of the tree to return $file = $config;
if ($filterFunction) $obj->setMarkingFilterFunction($filterFunction); $config = array();
}
$obj->markPartialTree($nodeCountThreshold, $this, $childrenMethod, $numChildrenMethod);
Requirements::themedCSS($file, isset($config['media']) ? $config['media'] : null);
// Ensure current page is exposed }
if($currentPage) $obj->markToExpose($currentPage); }
// NOTE: SiteTree/CMSMain coupling :-( $dummy = null;
if(class_exists('SilverStripe\\CMS\\Model\\SiteTree')) { $this->extend('init', $dummy);
SiteTree::prepopulate_permission_cache(
'CanEditType', // Assign default cms theme and replace user-specified themes
$obj->markedNodeIDs(), SSViewer::set_themes($this->config()->admin_themes);
'SilverStripe\\CMS\\Model\\SiteTree::can_edit_multiple'
); //set the reading mode for the admin to stage
} Versioned::set_stage(Versioned::DRAFT);
}
// getChildrenAsUL is a flexible and complex way of traversing the tree
$controller = $this; public function handleRequest(HTTPRequest $request, DataModel $model = null) {
$recordController = ($this->stat('tree_class') == 'SilverStripe\\CMS\\Model\\SiteTree') try {
? CMSPageEditController::singleton() $response = parent::handleRequest($request, $model);
: $this; } catch(ValidationException $e) {
$titleFn = function(&$child, $numChildrenMethod) use(&$controller, &$recordController, $filter) { // Nicer presentation of model-level validation errors
$link = Controller::join_links($recordController->Link("show"), $child->ID); $msgs = _t('LeftAndMain.ValidationError', 'Validation error') . ': '
$node = LeftAndMain_TreeNode::create($child, $link, $controller->isCurrentPage($child), $numChildrenMethod, $filter); . $e->getMessage();
return $node->forTemplate(); $e = new HTTPResponse_Exception($msgs, 403);
}; $errorResponse = $e->getResponse();
$errorResponse->addHeader('Content-Type', 'text/plain');
// Limit the amount of nodes shown for performance reasons. $errorResponse->addHeader('X-Status', rawurlencode($msgs));
// Skip the check if we're filtering the tree, since its not clear how many children will $e->setResponse($errorResponse);
// match the filter criteria until they're queried (and matched up with previously marked nodes). throw $e;
$nodeThresholdLeaf = Config::inst()->get('SilverStripe\\ORM\\Hierarchy\\Hierarchy', 'node_threshold_leaf'); }
if($nodeThresholdLeaf && !$filterFunction) {
$nodeCountCallback = function($parent, $numChildren) use(&$controller, $className, $nodeThresholdLeaf) { $title = $this->Title();
if ($className !== 'SilverStripe\\CMS\\Model\\SiteTree' if(!$response->getHeader('X-Controller')) $response->addHeader('X-Controller', $this->class);
|| !$parent->ID if(!$response->getHeader('X-Title')) $response->addHeader('X-Title', urlencode($title));
|| $numChildren >= $nodeThresholdLeaf
) { // Prevent clickjacking, see https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
return null; $originalResponse = $this->getResponse();
} $originalResponse->addHeader('X-Frame-Options', $this->config()->frame_options);
return sprintf( $originalResponse->addHeader('Vary', 'X-Requested-With');
'<ul><li class="readonly"><span class="item">'
. '%s (<a href="%s" class="cms-panel-link" data-pjax-target="Content">%s</a>)' return $response;
. '</span></li></ul>', }
_t('LeftAndMain.TooManyPages', 'Too many pages'),
Controller::join_links( /**
$controller->LinkWithSearch($controller->Link()), ' * Overloaded redirection logic to trigger a fake redirect on ajax requests.
?view=list&ParentID=' . $parent->ID * While this violates HTTP principles, its the only way to work around the
), * fact that browsers handle HTTP redirects opaquely, no intervention via JS is possible.
_t( * In isolation, that's not a problem - but combined with history.pushState()
'LeftAndMain.ShowAsList', * it means we would request the same redirection URL twice if we want to update the URL as well.
'show as list', * See LeftAndMain.js for the required jQuery ajaxComplete handlers.
'Show large amount of pages in list instead of tree view' *
) * @param string $url
); * @param int $code
}; * @return HTTPResponse|string
} else { */
$nodeCountCallback = null; public function redirect($url, $code=302) {
} if($this->getRequest()->isAjax()) {
$response = $this->getResponse();
// If the amount of pages exceeds the node thresholds set, use the callback $response->addHeader('X-ControllerURL', $url);
$html = null; if($this->getRequest()->getHeader('X-Pjax') && !$response->getHeader('X-Pjax')) {
if($obj->ParentID && $nodeCountCallback) { $response->addHeader('X-Pjax', $this->getRequest()->getHeader('X-Pjax'));
$html = $nodeCountCallback($obj, $obj->$numChildrenMethod()); }
} $newResponse = new LeftAndMain_HTTPResponse(
$response->getBody(),
// Otherwise return the actual tree (which might still filter leaf thresholds on children) $response->getStatusCode(),
if(!$html) { $response->getStatusDescription()
$html = $obj->getChildrenAsUL( );
"", foreach($response->getHeaders() as $k => $v) {
$titleFn, $newResponse->addHeader($k, $v);
CMSPagesController::singleton(), }
true, $newResponse->setIsFinished(true);
$childrenMethod, $this->setResponse($newResponse);
$numChildrenMethod, return ''; // Actual response will be re-requested by client
$nodeCountThreshold, } else {
$nodeCountCallback parent::redirect($url, $code);
); }
} }
// Wrap the root if needs be. /**
if(!$rootID) { * @param HTTPRequest $request
$rootLink = $this->Link('show') . '/root'; * @return HTTPResponse
*/
// This lets us override the tree title with an extension public function index($request) {
if($this->hasMethod('getCMSTreeTitle') && $customTreeTitle = $this->getCMSTreeTitle()) { return $this->getResponseNegotiator()->respond($request);
$treeTitle = $customTreeTitle; }
} elseif(class_exists('SilverStripe\\SiteConfig\\SiteConfig')) {
$siteConfig = SiteConfig::current_site_config(); /**
$treeTitle = Convert::raw2xml($siteConfig->Title); * If this is set to true, the "switchView" context in the
} else { * template is shown, with links to the staging and publish site.
$treeTitle = '...'; *
} * @return boolean
*/
$html = "<ul><li id=\"record-0\" data-id=\"0\" class=\"Root nodelete\"><strong>$treeTitle</strong>" public function ShowSwitchView() {
. $html . "</li></ul>"; return false;
} }
return $html;
} //------------------------------------------------------------------------------------------//
// Main controllers
/**
* Get a subtree underneath the request param 'ID'. /**
* If ID = 0, then get the whole tree. * You should implement a Link() function in your subclass of LeftAndMain,
* * to point to the URL of that particular controller.
* @param HTTPRequest $request *
* @return string * @param string $action
*/ * @return string
public function getsubtree($request) { */
$html = $this->getSiteTreeFor( public function Link($action = null) {
$this->stat('tree_class'), // Handle missing url_segments
$request->getVar('ID'), if($this->config()->url_segment) {
null, $segment = $this->config()->get('url_segment', Config::FIRST_SET);
null, } else {
null, $segment = $this->class;
$request->getVar('minNodeCount') };
);
$link = Controller::join_links(
// Trim off the outer tag AdminRootController::admin_url(),
$html = preg_replace('/^[\s\t\r\n]*<ul[^>]*>/','', $html); $segment,
$html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/','', $html); '/', // trailing slash needed if $action is null!
"$action"
return $html; );
} $this->extend('updateLink', $link);
return $link;
/** }
* Allows requesting a view update on specific tree nodes.
* Similar to {@link getsubtree()}, but doesn't enforce loading /**
* all children with the node. Useful to refresh views after * @deprecated 5.0
* state modifications, e.g. saving a form. */
* public static function menu_title_for_class($class) {
* @param HTTPRequest $request Deprecation::notice('5.0', 'Use menu_title() instead');
* @return string JSON return static::menu_title($class, false);
*/ }
public function updatetreenodes($request) {
$data = array(); /**
$ids = explode(',', $request->getVar('ids')); * Get menu title for this section (translated)
foreach($ids as $id) { *
if($id === "") continue; // $id may be a blank string, which is invalid and should be skipped over * @param string $class Optional class name if called on LeftAndMain directly
* @param bool $localise Determine if menu title should be localised via i18n.
$record = $this->getRecord($id); * @return string Menu title for the given class
if(!$record) continue; // In case a page is no longer available */
$recordController = ($this->stat('tree_class') == 'SilverStripe\\CMS\\Model\\SiteTree') public static function menu_title($class = null, $localise = true) {
? CMSPageEditController::singleton() if($class && is_subclass_of($class, __CLASS__)) {
: $this; // Respect oveloading of menu_title() in subclasses
return $class::menu_title(null, $localise);
// Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset) }
// TODO: These methods should really be in hierarchy - for a start it assumes Sort exists if(!$class) {
$next = $prev = null; $class = get_called_class();
}
$className = $this->stat('tree_class');
$next = DataObject::get($className) // Get default class title
->filter('ParentID', $record->ParentID) $title = Config::inst()->get($class, 'menu_title', Config::FIRST_SET);
->filter('Sort:GreaterThan', $record->Sort) if(!$title) {
->first(); $title = preg_replace('/Admin$/', '', $class);
}
if (!$next) {
$prev = DataObject::get($className) // Check localisation
->filter('ParentID', $record->ParentID) if(!$localise) {
->filter('Sort:LessThan', $record->Sort) return $title;
->reverse() }
->first(); return i18n::_t("{$class}.MENUTITLE", $title);
} }
$link = Controller::join_links($recordController->Link("show"), $record->ID); /**
$html = LeftAndMain_TreeNode::create($record, $link, $this->isCurrentPage($record)) * Return styling for the menu icon, if a custom icon is set for this class
->forTemplate() . '</li>'; *
* Example: static $menu-icon = '/path/to/image/';
$data[$id] = array( * @param string $class
'html' => $html, * @return string
'ParentID' => $record->ParentID, */
'NextID' => $next ? $next->ID : null, public static function menu_icon_for_class($class) {
'PrevID' => $prev ? $prev->ID : null $icon = Config::inst()->get($class, 'menu_icon', Config::FIRST_SET);
); if (!empty($icon)) {
} $class = strtolower(Convert::raw2htmlname(str_replace('\\', '-', $class)));
$this->getResponse()->addHeader('Content-Type', 'text/json'); return ".icon.icon-16.icon-{$class} { background-image: url('{$icon}'); } ";
return Convert::raw2json($data); }
} return '';
}
/**
* Save handler /**
* * @param HTTPRequest $request
* @param array $data * @return HTTPResponse
* @param Form $form * @throws HTTPResponse_Exception
* @return HTTPResponse */
*/ public function show($request) {
public function save($data, $form) { // TODO Necessary for TableListField URLs to work properly
$request = $this->getRequest(); if($request->param('ID')) $this->setCurrentPageID($request->param('ID'));
$className = $this->stat('tree_class'); return $this->getResponseNegotiator()->respond($request);
}
// Existing or new record?
$id = $data['ID']; /**
if(is_numeric($id) && $id > 0) { * Caution: Volatile API.
$record = DataObject::get_by_id($className, $id); *
if($record && !$record->canEdit()) { * @return PjaxResponseNegotiator
return Security::permissionFailure($this); */
} public function getResponseNegotiator() {
if(!$record || !$record->ID) { if(!$this->responseNegotiator) {
$this->httpError(404, "Bad record ID #" . (int)$id); $controller = $this;
} $this->responseNegotiator = new PjaxResponseNegotiator(
} else { array(
if(!singleton($this->stat('tree_class'))->canCreate()) { 'CurrentForm' => function() use(&$controller) {
return Security::permissionFailure($this); return $controller->getEditForm()->forTemplate();
} },
$record = $this->getNewItem($id, false); 'Content' => function() use(&$controller) {
} return $controller->renderWith($controller->getTemplatesWithSuffix('_Content'));
},
// save form data into record 'Breadcrumbs' => function() use (&$controller) {
$form->saveInto($record, true); return $controller->renderWith([
$record->write(); 'type' => 'Includes',
$this->extend('onAfterSave', $record); 'SilverStripe\\Admin\\CMSBreadcrumbs'
$this->setCurrentPageID($record->ID); ]);
},
$message = _t('LeftAndMain.SAVEDUP', 'Saved.'); 'default' => function() use(&$controller) {
if($request->getHeader('X-Formschema-Request')) { return $controller->renderWith($controller->getViewer('show'));
// Ensure that newly created records have all their data loaded back into the form. }
$form->loadDataFrom($record); ),
$form->setMessage($message, 'good'); $this->getResponse()
$data = $this->getSchemaForForm($form); );
$response = new HTTPResponse(Convert::raw2json($data)); }
$response->addHeader('Content-Type', 'application/json'); return $this->responseNegotiator;
} else { }
$response = $this->getResponseNegotiator()->respond($request);
} //------------------------------------------------------------------------------------------//
// Main UI components
$response->addHeader('X-Status', rawurlencode($message));
return $response; /**
} * Returns the main menu of the CMS. This is also used by init()
* to work out which sections the user has access to.
/** *
* Create new item. * @param bool $cached
* * @return SS_List
* @param string|int $id */
* @param bool $setID public function MainMenu($cached = true) {
* @return DataObject if(!isset($this->_cache_MainMenu) || !$cached) {
*/ // Don't accidentally return a menu if you're not logged in - it's used to determine access.
public function getNewItem($id, $setID = true) { if(!Member::currentUser()) return new ArrayList();
$class = $this->stat('tree_class');
$object = Injector::inst()->create($class); // Encode into DO set
if($setID) { $menu = new ArrayList();
$object->ID = $id; $menuItems = CMSMenu::get_viewable_menu_items();
}
return $object; // extra styling for custom menu-icons
} $menuIconStyling = '';
public function delete($data, $form) { if($menuItems) {
$className = $this->stat('tree_class'); /** @var CMSMenuItem $menuItem */
foreach($menuItems as $code => $menuItem) {
$id = $data['ID']; // alternate permission checks (in addition to LeftAndMain->canView())
$record = DataObject::get_by_id($className, $id); if(
if($record && !$record->canDelete()) return Security::permissionFailure(); isset($menuItem->controller)
if(!$record || !$record->ID) $this->httpError(404, "Bad record ID #" . (int)$id); && $this->hasMethod('alternateMenuDisplayCheck')
&& !$this->alternateMenuDisplayCheck($menuItem->controller)
$record->delete(); ) {
continue;
$this->getResponse()->addHeader('X-Status', rawurlencode(_t('LeftAndMain.DELETED', 'Deleted.'))); }
return $this->getResponseNegotiator()->respond(
$this->getRequest(), $linkingmode = "link";
array('currentform' => array($this, 'EmptyForm'))
); if($menuItem->controller && get_class($this) == $menuItem->controller) {
} $linkingmode = "current";
} else if(strpos($this->Link(), $menuItem->url) !== false) {
/** if($this->Link() == $menuItem->url) {
* Update the position and parent of a tree node. $linkingmode = "current";
* Only saves the node if changes were made.
* // default menu is the one with a blank {@link url_segment}
* Required data: } else if(singleton($menuItem->controller)->stat('url_segment') == '') {
* - 'ID': The moved node if($this->Link() == AdminRootController::admin_url()) {
* - 'ParentID': New parent relation of the moved node (0 for root) $linkingmode = "current";
* - 'SiblingIDs': Array of all sibling nodes to the moved node (incl. the node itself). }
* In case of a 'ParentID' change, relates to the new siblings under the new parent.
* } else {
* @param HTTPRequest $request $linkingmode = "current";
* @return HTTPResponse JSON string with a }
* @throws HTTPResponse_Exception }
*/
public function savetreenode($request) { // already set in CMSMenu::populate_menu(), but from a static pre-controller
if (!SecurityToken::inst()->checkRequest($request)) { // context, so doesn't respect the current user locale in _t() calls - as a workaround,
return $this->httpError(400); // we simply call LeftAndMain::menu_title() again
} // if we're dealing with a controller
if (!Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN')) { if($menuItem->controller) {
$this->getResponse()->setStatusCode( $title = LeftAndMain::menu_title($menuItem->controller);
403, } else {
_t('LeftAndMain.CANT_REORGANISE', $title = $menuItem->title;
"You do not have permission to rearange the site tree. Your change was not saved.") }
);
return; // Provide styling for custom $menu-icon. Done here instead of in
} // CMSMenu::populate_menu(), because the icon is part of
// the CMS right pane for the specified class as well...
$className = $this->stat('tree_class'); if($menuItem->controller) {
$statusUpdates = array('modified'=>array()); $menuIcon = LeftAndMain::menu_icon_for_class($menuItem->controller);
$id = $request->requestVar('ID'); if (!empty($menuIcon)) {
$parentID = $request->requestVar('ParentID'); $menuIconStyling .= $menuIcon;
}
if($className == 'SilverStripe\\CMS\\Model\\SiteTree' && $page = DataObject::get_by_id('Page', $id)){ }
$root = $page->getParentType();
if(($parentID == '0' || $root == 'root') && !SiteConfig::current_site_config()->canCreateTopLevel()){ $menu->push(new ArrayData(array(
$this->getResponse()->setStatusCode( "MenuItem" => $menuItem,
403, "AttributesHTML" => $menuItem->getAttributesHTML(),
_t('LeftAndMain.CANT_REORGANISE', "Title" => Convert::raw2xml($title),
"You do not have permission to alter Top level pages. Your change was not saved.") "Code" => $code,
); "Icon" => strtolower($code),
return; "Link" => $menuItem->url,
} "LinkingMode" => $linkingmode
} )));
}
$siblingIDs = $request->requestVar('SiblingIDs'); }
$statusUpdates = array('modified'=>array()); if ($menuIconStyling) Requirements::customCSS($menuIconStyling);
if(!is_numeric($id) || !is_numeric($parentID)) throw new InvalidArgumentException();
$this->_cache_MainMenu = $menu;
$node = DataObject::get_by_id($className, $id); }
if($node && !$node->canEdit()) return Security::permissionFailure($this);
return $this->_cache_MainMenu;
if(!$node) { }
$this->getResponse()->setStatusCode(
500, public function Menu() {
_t('LeftAndMain.PLEASESAVE', return $this->renderWith($this->getTemplatesWithSuffix('_Menu'));
"Please Save Page: This page could not be updated because it hasn't been saved yet." }
)
); /**
return; * @todo Wrap in CMSMenu instance accessor
} * @return ArrayData A single menu entry (see {@link MainMenu})
*/
// Update hierarchy (only if ParentID changed) public function MenuCurrentItem() {
if($node->ParentID != $parentID) { $items = $this->MainMenu();
$node->ParentID = (int)$parentID; return $items->find('LinkingMode', 'current');
$node->write(); }
$statusUpdates['modified'][$node->ID] = array( /**
'TreeTitle'=>$node->TreeTitle * Return a list of appropriate templates for this class, with the given suffix using
); * {@link SSViewer::get_templates_by_class()}
*
// Update all dependent pages * @param string $suffix
if(class_exists('SilverStripe\\CMS\\Model\\VirtualPage')) { * @return array
$virtualPages = VirtualPage::get()->filter("CopyContentFromID", $node->ID); */
foreach($virtualPages as $virtualPage) { public function getTemplatesWithSuffix($suffix) {
$statusUpdates['modified'][$virtualPage->ID] = array( $templates = SSViewer::get_templates_by_class(get_class($this), $suffix, __CLASS__);
'TreeTitle' => $virtualPage->TreeTitle() return SSViewer::chooseTemplate($templates);
); }
}
} public function Content() {
return $this->renderWith($this->getTemplatesWithSuffix('_Content'));
$this->getResponse()->addHeader('X-Status', }
rawurlencode(_t('LeftAndMain.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.')));
} /**
* Render $PreviewPanel content
// Update sorting *
if(is_array($siblingIDs)) { * @return DBHTMLText
$counter = 0; */
foreach($siblingIDs as $id) { public function PreviewPanel() {
if($id == $node->ID) { $template = $this->getTemplatesWithSuffix('_PreviewPanel');
$node->Sort = ++$counter; // Only render sections with preview panel
$node->write(); if ($template) {
$statusUpdates['modified'][$node->ID] = array( return $this->renderWith($template);
'TreeTitle' => $node->TreeTitle }
); }
} else if(is_numeric($id)) {
// Nodes that weren't "actually moved" shouldn't be registered as public function getRecord($id) {
// having been edited; do a direct SQL update instead $className = $this->stat('tree_class');
++$counter; if($className && $id instanceof $className) {
DB::prepared_query( return $id;
"UPDATE \"$className\" SET \"Sort\" = ? WHERE \"ID\" = ?", } else if($className && $id == 'root') {
array($counter, $id) return singleton($className);
); } else if($className && is_numeric($id)) {
} return DataObject::get_by_id($className, $id);
} } else {
return false;
$this->getResponse()->addHeader('X-Status', }
rawurlencode(_t('LeftAndMain.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.'))); }
}
/**
return Convert::raw2json($statusUpdates); * @param bool $unlinked
} * @return ArrayList
*/
public function CanOrganiseSitetree() { public function Breadcrumbs($unlinked = false) {
return !Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN') ? false : true; $items = new ArrayList(array(
} new ArrayData(array(
'Title' => $this->menu_title(),
/** 'Link' => ($unlinked) ? false : $this->Link()
* Retrieves an edit form, either for display, or to process submitted data. ))
* Also used in the template rendered through {@link Right()} in the $EditForm placeholder. ));
* $record = $this->currentPage();
* This is a "pseudo-abstract" methoed, usually connected to a {@link getEditForm()} if($record && $record->exists()) {
* method in an entwine subclass. This method can accept a record identifier, if($record->hasExtension('SilverStripe\\ORM\\Hierarchy\\Hierarchy')) {
* selected either in custom logic, or through {@link currentPageID()}. $ancestors = $record->getAncestors();
* The form usually construct itself from {@link DataObject->getCMSFields()} $ancestors = new ArrayList(array_reverse($ancestors->toArray()));
* for the specific managed subclass defined in {@link LeftAndMain::$tree_class}. $ancestors->push($record);
* foreach($ancestors as $ancestor) {
* @param HTTPRequest $request Optionally contains an identifier for the $items->push(new ArrayData(array(
* record to load into the form. 'Title' => ($ancestor->MenuTitle) ? $ancestor->MenuTitle : $ancestor->Title,
* @return Form Should return a form regardless wether a record has been found. 'Link' => ($unlinked) ? false : Controller::join_links($this->Link('show'), $ancestor->ID)
* Form might be readonly if the current user doesn't have the permission to edit )));
* the record. }
*/ } else {
/** $items->push(new ArrayData(array(
* @return Form 'Title' => ($record->MenuTitle) ? $record->MenuTitle : $record->Title,
*/ 'Link' => ($unlinked) ? false : Controller::join_links($this->Link('show'), $record->ID)
public function EditForm($request = null) { )));
return $this->getEditForm(); }
} }
/** return $items;
* Calls {@link SiteTree->getCMSFields()} }
*
* @param Int $id /**
* @param FieldList $fields * @return String HTML
* @return Form */
*/ public function SiteTreeAsUL() {
public function getEditForm($id = null, $fields = null) { $html = $this->getSiteTreeFor($this->stat('tree_class'));
if(!$id) $id = $this->currentPageID(); $this->extend('updateSiteTreeAsUL', $html);
return $html;
if(is_object($id)) { }
$record = $id;
} else { /**
$record = $this->getRecord($id); * Gets the current search filter for this request, if available
if($record && !$record->canView()) return Security::permissionFailure($this); *
} * @throws InvalidArgumentException
* @return LeftAndMain_SearchFilter
if($record) { */
$fields = ($fields) ? $fields : $record->getCMSFields(); protected function getSearchFilter() {
if ($fields == null) { // Check for given FilterClass
user_error( $params = $this->getRequest()->getVar('q');
"getCMSFields() returned null - it should return a FieldList object. if(empty($params['FilterClass'])) {
Perhaps you forgot to put a return statement at the end of your method?", return null;
E_USER_ERROR }
);
} // Validate classname
$filterClass = $params['FilterClass'];
// Add hidden fields which are required for saving the record $filterInfo = new ReflectionClass($filterClass);
// and loading the UI state if(!$filterInfo->implementsInterface('SilverStripe\\Admin\\LeftAndMain_SearchFilter')) {
if(!$fields->dataFieldByName('ClassName')) { throw new InvalidArgumentException(sprintf('Invalid filter class passed: %s', $filterClass));
$fields->push(new HiddenField('ClassName')); }
}
return Injector::inst()->createWithArgs($filterClass, array($params));
$tree_class = $this->stat('tree_class'); }
if(
$tree_class::has_extension('SilverStripe\\ORM\\Hierarchy\\Hierarchy') /**
&& !$fields->dataFieldByName('ParentID') * Get a site tree HTML listing which displays the nodes under the given criteria.
) { *
$fields->push(new HiddenField('ParentID')); * @param string $className The class of the root object
} * @param string $rootID The ID of the root object. If this is null then a complete tree will be
* shown
// Added in-line to the form, but plucked into different view by frontend scripts. * @param string $childrenMethod The method to call to get the children of the tree. For example,
if ($record instanceof CMSPreviewable) { * Children, AllChildrenIncludingDeleted, or AllHistoricalChildren
/** @skipUpgrade */ * @param string $numChildrenMethod
$navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator()); * @param callable $filterFunction
$navField->setAllowHTML(true); * @param int $nodeCountThreshold
$fields->push($navField); * @return string Nested unordered list with links to each page
} */
public function getSiteTreeFor($className, $rootID = null, $childrenMethod = null, $numChildrenMethod = null,
if($record->hasMethod('getAllCMSActions')) { $filterFunction = null, $nodeCountThreshold = 30) {
$actions = $record->getAllCMSActions();
} else { // Filter criteria
$actions = $record->getCMSActions(); $filter = $this->getSearchFilter();
// add default actions if none are defined
if(!$actions || !$actions->count()) { // Default childrenMethod and numChildrenMethod
if($record->hasMethod('canEdit') && $record->canEdit()) { if(!$childrenMethod) $childrenMethod = ($filter && $filter->getChildrenMethod())
$actions->push( ? $filter->getChildrenMethod()
FormAction::create('save',_t('CMSMain.SAVE','Save')) : 'AllChildrenIncludingDeleted';
->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
); if(!$numChildrenMethod) {
} $numChildrenMethod = 'numChildren';
if($record->hasMethod('canDelete') && $record->canDelete()) { if($filter && $filter->getNumChildrenMethod()) {
$actions->push( $numChildrenMethod = $filter->getNumChildrenMethod();
FormAction::create('delete',_t('ModelAdmin.DELETE','Delete')) }
->addExtraClass('ss-ui-action-destructive') }
); if(!$filterFunction && $filter) {
} $filterFunction = function($node) use($filter) {
} return $filter->isPageIncluded($node);
} };
}
// Use <button> to allow full jQuery UI styling
$actionsFlattened = $actions->dataFields(); // Get the tree root
if($actionsFlattened) { $record = ($rootID) ? $this->getRecord($rootID) : null;
/** @var FormAction $action */ $obj = $record ? $record : singleton($className);
foreach($actionsFlattened as $action) {
$action->setUseButtonTag(true); // Get the current page
} // NOTE: This *must* be fetched before markPartialTree() is called, as this
} // causes the Hierarchy::$marked cache to be flushed (@see CMSMain::getRecord)
// which means that deleted pages stored in the marked tree would be removed
$negotiator = $this->getResponseNegotiator(); $currentPage = $this->currentPage();
$form = Form::create(
$this, "EditForm", $fields, $actions // Mark the nodes of the tree to return
)->setHTMLID('Form_EditForm'); if ($filterFunction) $obj->setMarkingFilterFunction($filterFunction);
$form->addExtraClass('cms-edit-form');
$form->loadDataFrom($record); $obj->markPartialTree($nodeCountThreshold, $this, $childrenMethod, $numChildrenMethod);
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$form->setAttribute('data-pjax-fragment', 'CurrentForm'); // Ensure current page is exposed
$form->setValidationResponseCallback(function() use ($negotiator, $form) { if($currentPage) $obj->markToExpose($currentPage);
$request = $this->getRequest();
if($request->isAjax() && $negotiator) { // NOTE: SiteTree/CMSMain coupling :-(
$form->setupFormErrors(); if(class_exists('SilverStripe\\CMS\\Model\\SiteTree')) {
$result = $form->forTemplate(); SiteTree::prepopulate_permission_cache(
'CanEditType',
return $negotiator->respond($request, array( $obj->markedNodeIDs(),
'CurrentForm' => function() use($result) { 'SilverStripe\\CMS\\Model\\SiteTree::can_edit_multiple'
return $result; );
} }
));
} // getChildrenAsUL is a flexible and complex way of traversing the tree
}); $controller = $this;
$recordController = ($this->stat('tree_class') == 'SilverStripe\\CMS\\Model\\SiteTree')
// Announce the capability so the frontend can decide whether to allow preview or not. ? CMSPageEditController::singleton()
if ($record instanceof CMSPreviewable) { : $this;
$form->addExtraClass('cms-previewable'); $titleFn = function(&$child, $numChildrenMethod) use(&$controller, &$recordController, $filter) {
} $link = Controller::join_links($recordController->Link("show"), $child->ID);
$node = LeftAndMain_TreeNode::create($child, $link, $controller->isCurrentPage($child), $numChildrenMethod, $filter);
// Set this if you want to split up tabs into a separate header row return $node->forTemplate();
// if($form->Fields()->hasTabset()) { };
// $form->Fields()->findOrMakeTab('Root')->setTemplate('SilverStripe\\Forms\\CMSTabSet');
// } // Limit the amount of nodes shown for performance reasons.
// Skip the check if we're filtering the tree, since its not clear how many children will
// Add a default or custom validator. // match the filter criteria until they're queried (and matched up with previously marked nodes).
// @todo Currently the default Validator.js implementation $nodeThresholdLeaf = Config::inst()->get('SilverStripe\\ORM\\Hierarchy\\Hierarchy', 'node_threshold_leaf');
// adds javascript to the document body, meaning it won't if($nodeThresholdLeaf && !$filterFunction) {
// be included properly if the associated fields are loaded $nodeCountCallback = function($parent, $numChildren) use(&$controller, $className, $nodeThresholdLeaf) {
// through ajax. This means only serverside validation if ($className !== 'SilverStripe\\CMS\\Model\\SiteTree'
// will kick in for pages+validation loaded through ajax. || !$parent->ID
// This will be solved by using less obtrusive javascript validation || $numChildren >= $nodeThresholdLeaf
// in the future, see http://open.silverstripe.com/ticket/2915 and ) {
// http://open.silverstripe.com/ticket/3386 return null;
if($record->hasMethod('getCMSValidator')) { }
$validator = $record->getCMSValidator(); return sprintf(
// The clientside (mainly LeftAndMain*.js) rely on ajax responses '<ul><li class="readonly"><span class="item">'
// which can be evaluated as javascript, hence we need . '%s (<a href="%s" class="cms-panel-link" data-pjax-target="Content">%s</a>)'
// to override any global changes to the validation handler. . '</span></li></ul>',
if($validator != NULL){ _t('LeftAndMain.TooManyPages', 'Too many pages'),
$form->setValidator($validator); Controller::join_links(
} $controller->LinkWithSearch($controller->Link()), '
} else { ?view=list&ParentID=' . $parent->ID
$form->unsetValidator(); ),
} _t(
'LeftAndMain.ShowAsList',
if($record->hasMethod('canEdit') && !$record->canEdit()) { 'show as list',
$readonlyFields = $form->Fields()->makeReadonly(); 'Show large amount of pages in list instead of tree view'
$form->setFields($readonlyFields); )
} );
} else { };
$form = $this->EmptyForm(); } else {
} $nodeCountCallback = null;
}
return $form;
} // If the amount of pages exceeds the node thresholds set, use the callback
$html = null;
/** if($obj->ParentID && $nodeCountCallback) {
* Returns a placeholder form, used by {@link getEditForm()} if no record is selected. $html = $nodeCountCallback($obj, $obj->$numChildrenMethod());
* Our javascript logic always requires a form to be present in the CMS interface. }
*
* @return Form // Otherwise return the actual tree (which might still filter leaf thresholds on children)
*/ if(!$html) {
public function EmptyForm() { $html = $obj->getChildrenAsUL(
$form = Form::create( "",
$this, $titleFn,
"EditForm", CMSPagesController::singleton(),
new FieldList( true,
// new HeaderField( $childrenMethod,
// 'WelcomeHeader', $numChildrenMethod,
// $this->getApplicationName() $nodeCountThreshold,
// ), $nodeCountCallback
// new LiteralField( );
// 'WelcomeText', }
// sprintf('<p id="WelcomeMessage">%s %s. %s</p>',
// _t('LeftAndMain_right_ss.WELCOMETO','Welcome to'), // Wrap the root if needs be.
// $this->getApplicationName(), if(!$rootID) {
// _t('CHOOSEPAGE','Please choose an item from the left.') $rootLink = $this->Link('show') . '/root';
// )
// ) // This lets us override the tree title with an extension
), if($this->hasMethod('getCMSTreeTitle') && $customTreeTitle = $this->getCMSTreeTitle()) {
new FieldList() $treeTitle = $customTreeTitle;
)->setHTMLID('Form_EditForm'); } elseif(class_exists('SilverStripe\\SiteConfig\\SiteConfig')) {
$form->unsetValidator(); $siteConfig = SiteConfig::current_site_config();
$form->addExtraClass('cms-edit-form'); $treeTitle = Convert::raw2xml($siteConfig->Title);
$form->addExtraClass('root-form'); } else {
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); $treeTitle = '...';
$form->setAttribute('data-pjax-fragment', 'CurrentForm'); }
return $form; $html = "<ul><li id=\"record-0\" data-id=\"0\" class=\"Root nodelete\"><strong>$treeTitle</strong>"
} . $html . "</li></ul>";
}
/**
* Return the CMS's HTML-editor toolbar return $html;
*/ }
public function EditorToolbar() {
return HTMLEditorField_Toolbar::create($this, "EditorToolbar"); /**
} * Get a subtree underneath the request param 'ID'.
* If ID = 0, then get the whole tree.
/** *
* Renders a panel containing tools which apply to all displayed * @param HTTPRequest $request
* "content" (mostly through {@link EditForm()}), for example a tree navigation or a filter panel. * @return string
* Auto-detects applicable templates by naming convention: "<controller classname>_Tools.ss", */
* and takes the most specific template (see {@link getTemplatesWithSuffix()}). public function getsubtree($request) {
* To explicitly disable the panel in the subclass, simply create a more specific, empty template. $html = $this->getSiteTreeFor(
* $this->stat('tree_class'),
* @return String HTML $request->getVar('ID'),
*/ null,
public function Tools() { null,
$templates = $this->getTemplatesWithSuffix('_Tools'); null,
if($templates) { $request->getVar('minNodeCount')
$viewer = new SSViewer($templates); );
return $viewer->process($this);
} else { // Trim off the outer tag
return false; $html = preg_replace('/^[\s\t\r\n]*<ul[^>]*>/','', $html);
} $html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/','', $html);
}
return $html;
/** }
* Renders a panel containing tools which apply to the currently displayed edit form.
* The main difference to {@link Tools()} is that the panel is displayed within /**
* the element structure of the form panel (rendered through {@link EditForm}). * Allows requesting a view update on specific tree nodes.
* This means the panel will be loaded alongside new forms, and refreshed upon save, * Similar to {@link getsubtree()}, but doesn't enforce loading
* which can mean a performance hit, depending on how complex your panel logic gets. * all children with the node. Useful to refresh views after
* Any form fields contained in the returned markup will also be submitted with the main form, * state modifications, e.g. saving a form.
* which might be desired depending on the implementation details. *
* * @param HTTPRequest $request
* @return String HTML * @return string JSON
*/ */
public function EditFormTools() { public function updatetreenodes($request) {
$templates = $this->getTemplatesWithSuffix('_EditFormTools'); $data = array();
if($templates) { $ids = explode(',', $request->getVar('ids'));
$viewer = new SSViewer($templates); foreach($ids as $id) {
return $viewer->process($this); if($id === "") continue; // $id may be a blank string, which is invalid and should be skipped over
} else {
return false; $record = $this->getRecord($id);
} if(!$record) continue; // In case a page is no longer available
} $recordController = ($this->stat('tree_class') == 'SilverStripe\\CMS\\Model\\SiteTree')
? CMSPageEditController::singleton()
/** : $this;
* Batch Actions Handler
*/ // Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset)
public function batchactions() { // TODO: These methods should really be in hierarchy - for a start it assumes Sort exists
return new CMSBatchActionHandler($this, 'batchactions', $this->stat('tree_class')); $next = $prev = null;
}
$className = $this->stat('tree_class');
/** $next = DataObject::get($className)
* @return Form ->filter('ParentID', $record->ParentID)
*/ ->filter('Sort:GreaterThan', $record->Sort)
public function BatchActionsForm() { ->first();
$actions = $this->batchactions()->batchActionList();
$actionsMap = array('-1' => _t('LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...')); // Placeholder action if (!$next) {
foreach($actions as $action) { $prev = DataObject::get($className)
$actionsMap[$action->Link] = $action->Title; ->filter('ParentID', $record->ParentID)
} ->filter('Sort:LessThan', $record->Sort)
->reverse()
$form = new Form( ->first();
$this, }
'BatchActionsForm',
new FieldList( $link = Controller::join_links($recordController->Link("show"), $record->ID);
new HiddenField('csvIDs'), $html = LeftAndMain_TreeNode::create($record, $link, $this->isCurrentPage($record))
DropdownField::create( ->forTemplate() . '</li>';
'Action',
false, $data[$id] = array(
$actionsMap 'html' => $html,
) 'ParentID' => $record->ParentID,
->setAttribute('autocomplete', 'off') 'NextID' => $next ? $next->ID : null,
->setAttribute('data-placeholder', _t('LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...')) 'PrevID' => $prev ? $prev->ID : null
), );
new FieldList( }
// TODO i18n $this->getResponse()->addHeader('Content-Type', 'text/json');
new FormAction('submit', _t('Form.SubmitBtnLabel', "Go")) return Convert::raw2json($data);
) }
);
$form->addExtraClass('cms-batch-actions form--no-dividers'); /**
$form->unsetValidator(); * Save handler
*
$this->extend('updateBatchActionsForm', $form); * @param array $data
return $form; * @param Form $form
} * @return HTTPResponse
*/
public function printable() { public function save($data, $form) {
$form = $this->getEditForm($this->currentPageID()); $request = $this->getRequest();
if(!$form) return false; $className = $this->stat('tree_class');
$form->transform(new PrintableTransformation()); // Existing or new record?
$form->setActions(null); $id = $data['ID'];
if(is_numeric($id) && $id > 0) {
Requirements::clear(); $record = DataObject::get_by_id($className, $id);
Requirements::css(FRAMEWORK_ADMIN_DIR . '/dist/css/LeftAndMain_printable.css'); if($record && !$record->canEdit()) {
return array( return Security::permissionFailure($this);
"PrintForm" => $form }
); if(!$record || !$record->ID) {
} $this->httpError(404, "Bad record ID #" . (int)$id);
}
/** } else {
* Used for preview controls, mainly links which switch between different states of the page. if(!singleton($this->stat('tree_class'))->canCreate()) {
* return Security::permissionFailure($this);
* @return DBHTMLText }
*/ $record = $this->getNewItem($id, false);
public function getSilverStripeNavigator() { }
$page = $this->currentPage();
if ($page instanceof CMSPreviewable) { // save form data into record
$navigator = new SilverStripeNavigator($page); $form->saveInto($record, true);
return $navigator->renderWith($this->getTemplatesWithSuffix('_SilverStripeNavigator')); $record->write();
} $this->extend('onAfterSave', $record);
return null; $this->setCurrentPageID($record->ID);
}
$message = _t('LeftAndMain.SAVEDUP', 'Saved.');
/** if($request->getHeader('X-Formschema-Request')) {
* Identifier for the currently shown record, // Ensure that newly created records have all their data loaded back into the form.
* in most cases a database ID. Inspects the following $form->loadDataFrom($record);
* sources (in this order): $form->setMessage($message, 'good');
* - GET/POST parameter named 'ID' $data = $this->getSchemaForForm($form);
* - URL parameter named 'ID' $response = new HTTPResponse(Convert::raw2json($data));
* - Session value namespaced by classname, e.g. "CMSMain.currentPage" $response->addHeader('Content-Type', 'application/json');
* } else {
* @return int $response = $this->getResponseNegotiator()->respond($request);
*/ }
public function currentPageID() {
if($this->getRequest()->requestVar('ID') && is_numeric($this->getRequest()->requestVar('ID'))) { $response->addHeader('X-Status', rawurlencode($message));
return $this->getRequest()->requestVar('ID'); return $response;
} elseif ($this->getRequest()->requestVar('CMSMainCurrentPageID') && is_numeric($this->getRequest()->requestVar('CMSMainCurrentPageID'))) { }
// see GridFieldDetailForm::ItemEditForm
return $this->getRequest()->requestVar('CMSMainCurrentPageID'); /**
} elseif (isset($this->urlParams['ID']) && is_numeric($this->urlParams['ID'])) { * Create new item.
return $this->urlParams['ID']; *
} elseif(Session::get($this->sessionNamespace() . ".currentPage")) { * @param string|int $id
return Session::get($this->sessionNamespace() . ".currentPage"); * @param bool $setID
} else { * @return DataObject
return null; */
} public function getNewItem($id, $setID = true) {
} $class = $this->stat('tree_class');
$object = Injector::inst()->create($class);
/** if($setID) {
* Forces the current page to be set in session, $object->ID = $id;
* which can be retrieved later through {@link currentPageID()}. }
* Keep in mind that setting an ID through GET/POST or return $object;
* as a URL parameter will overrule this value. }
*
* @param int $id public function delete($data, $form) {
*/ $className = $this->stat('tree_class');
public function setCurrentPageID($id) {
$id = (int)$id; $id = $data['ID'];
Session::set($this->sessionNamespace() . ".currentPage", $id); $record = DataObject::get_by_id($className, $id);
} if($record && !$record->canDelete()) return Security::permissionFailure();
if(!$record || !$record->ID) $this->httpError(404, "Bad record ID #" . (int)$id);
/**
* Uses {@link getRecord()} and {@link currentPageID()} $record->delete();
* to get the currently selected record.
* $this->getResponse()->addHeader('X-Status', rawurlencode(_t('LeftAndMain.DELETED', 'Deleted.')));
* @return DataObject return $this->getResponseNegotiator()->respond(
*/ $this->getRequest(),
public function currentPage() { array('currentform' => array($this, 'EmptyForm'))
return $this->getRecord($this->currentPageID()); );
} }
/** /**
* Compares a given record to the currently selected one (if any). * Update the position and parent of a tree node.
* Used for marking the current tree node. * Only saves the node if changes were made.
* *
* @param DataObject $record * Required data:
* @return bool * - 'ID': The moved node
*/ * - 'ParentID': New parent relation of the moved node (0 for root)
public function isCurrentPage(DataObject $record) { * - 'SiblingIDs': Array of all sibling nodes to the moved node (incl. the node itself).
return ($record->ID == $this->currentPageID()); * In case of a 'ParentID' change, relates to the new siblings under the new parent.
} *
* @param HTTPRequest $request
/** * @return HTTPResponse JSON string with a
* @return String * @throws HTTPResponse_Exception
*/ */
protected function sessionNamespace() { public function savetreenode($request) {
$override = $this->stat('session_namespace'); if (!SecurityToken::inst()->checkRequest($request)) {
return $override ? $override : $this->class; return $this->httpError(400);
} }
if (!Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN')) {
/** $this->getResponse()->setStatusCode(
* URL to a previewable record which is shown through this controller. 403,
* The controller might not have any previewable content, in which case _t('LeftAndMain.CANT_REORGANISE',
* this method returns FALSE. "You do not have permission to rearange the site tree. Your change was not saved.")
* );
* @return String|boolean return;
*/ }
public function LinkPreview() {
return false; $className = $this->stat('tree_class');
} $statusUpdates = array('modified'=>array());
$id = $request->requestVar('ID');
/** $parentID = $request->requestVar('ParentID');
* Return the version number of this application.
* Uses the number in <mymodule>/silverstripe_version if($className == 'SilverStripe\\CMS\\Model\\SiteTree' && $page = DataObject::get_by_id('Page', $id)){
* (automatically replaced by build scripts). $root = $page->getParentType();
* If silverstripe_version is empty, if(($parentID == '0' || $root == 'root') && !SiteConfig::current_site_config()->canCreateTopLevel()){
* then attempts to get it from composer.lock $this->getResponse()->setStatusCode(
* 403,
* @return string _t('LeftAndMain.CANT_REORGANISE',
*/ "You do not have permission to alter Top level pages. Your change was not saved.")
public function CMSVersion() { );
$versions = array(); return;
$modules = array( }
'silverstripe/framework' => array( }
'title' => 'Framework',
'versionFile' => FRAMEWORK_PATH . '/silverstripe_version', $siblingIDs = $request->requestVar('SiblingIDs');
) $statusUpdates = array('modified'=>array());
); if(!is_numeric($id) || !is_numeric($parentID)) throw new InvalidArgumentException();
if(defined('CMS_PATH')) {
$modules['silverstripe/cms'] = array( $node = DataObject::get_by_id($className, $id);
'title' => 'CMS', if($node && !$node->canEdit()) return Security::permissionFailure($this);
'versionFile' => CMS_PATH . '/silverstripe_version',
); if(!$node) {
} $this->getResponse()->setStatusCode(
500,
// Tries to obtain version number from composer.lock if it exists _t('LeftAndMain.PLEASESAVE',
$composerLockPath = BASE_PATH . '/composer.lock'; "Please Save Page: This page could not be updated because it hasn't been saved yet."
if (file_exists($composerLockPath)) { )
$cache = Cache::factory('LeftAndMain_CMSVersion'); );
$cacheKey = filemtime($composerLockPath); return;
$versions = $cache->load($cacheKey); }
if($versions) {
$versions = json_decode($versions, true); // Update hierarchy (only if ParentID changed)
} else { if($node->ParentID != $parentID) {
$versions = array(); $node->ParentID = (int)$parentID;
} $node->write();
if(!$versions && $jsonData = file_get_contents($composerLockPath)) {
$lockData = json_decode($jsonData); $statusUpdates['modified'][$node->ID] = array(
if($lockData && isset($lockData->packages)) { 'TreeTitle'=>$node->TreeTitle
foreach ($lockData->packages as $package) { );
if(
array_key_exists($package->name, $modules) // Update all dependent pages
&& isset($package->version) if(class_exists('SilverStripe\\CMS\\Model\\VirtualPage')) {
) { $virtualPages = VirtualPage::get()->filter("CopyContentFromID", $node->ID);
$versions[$package->name] = $package->version; foreach($virtualPages as $virtualPage) {
} $statusUpdates['modified'][$virtualPage->ID] = array(
} 'TreeTitle' => $virtualPage->TreeTitle()
$cache->save(json_encode($versions), $cacheKey); );
} }
} }
}
$this->getResponse()->addHeader('X-Status',
// Fall back to static version file rawurlencode(_t('LeftAndMain.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.')));
foreach($modules as $moduleName => $moduleSpec) { }
if(!isset($versions[$moduleName])) {
if($staticVersion = file_get_contents($moduleSpec['versionFile'])) { // Update sorting
$versions[$moduleName] = $staticVersion; if(is_array($siblingIDs)) {
} else { $counter = 0;
$versions[$moduleName] = _t('LeftAndMain.VersionUnknown', 'Unknown'); foreach($siblingIDs as $id) {
} if($id == $node->ID) {
} $node->Sort = ++$counter;
} $node->write();
$statusUpdates['modified'][$node->ID] = array(
$out = array(); 'TreeTitle' => $node->TreeTitle
foreach($modules as $moduleName => $moduleSpec) { );
$out[] = $modules[$moduleName]['title'] . ': ' . $versions[$moduleName]; } else if(is_numeric($id)) {
} // Nodes that weren't "actually moved" shouldn't be registered as
return implode(', ', $out); // having been edited; do a direct SQL update instead
} ++$counter;
DB::prepared_query(
/** "UPDATE \"$className\" SET \"Sort\" = ? WHERE \"ID\" = ?",
* @return array array($counter, $id)
*/ );
public function SwitchView() { }
if($page = $this->currentPage()) { }
$nav = SilverStripeNavigator::get_for_record($page);
return $nav['items']; $this->getResponse()->addHeader('X-Status',
} rawurlencode(_t('LeftAndMain.REORGANISATIONSUCCESSFUL', 'Reorganised the site tree successfully.')));
} }
/** return Convert::raw2json($statusUpdates);
* @return SiteConfig }
*/
public function SiteConfig() { public function CanOrganiseSitetree() {
return (class_exists('SilverStripe\\SiteConfig\\SiteConfig')) ? SiteConfig::current_site_config() : null; return !Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN') ? false : true;
} }
/** /**
* The href for the anchor on the Silverstripe logo. * Retrieves an edit form, either for display, or to process submitted data.
* Set by calling LeftAndMain::set_application_link() * Also used in the template rendered through {@link Right()} in the $EditForm placeholder.
* *
* @config * This is a "pseudo-abstract" methoed, usually connected to a {@link getEditForm()}
* @var String * method in an entwine subclass. This method can accept a record identifier,
*/ * selected either in custom logic, or through {@link currentPageID()}.
private static $application_link = '//www.silverstripe.org/'; * The form usually construct itself from {@link DataObject->getCMSFields()}
* for the specific managed subclass defined in {@link LeftAndMain::$tree_class}.
/** *
* @return String * @param HTTPRequest $request Optionally contains an identifier for the
*/ * record to load into the form.
public function ApplicationLink() { * @return Form Should return a form regardless wether a record has been found.
return $this->stat('application_link'); * Form might be readonly if the current user doesn't have the permission to edit
} * the record.
*/
/** /**
* The application name. Customisable by calling * @return Form
* LeftAndMain::setApplicationName() - the first parameter. */
* public function EditForm($request = null) {
* @config return $this->getEditForm();
* @var String }
*/
private static $application_name = 'SilverStripe'; /**
* Calls {@link SiteTree->getCMSFields()}
/** *
* Get the application name. * @param Int $id
* * @param FieldList $fields
* @return string * @return Form
*/ */
public function getApplicationName() { public function getEditForm($id = null, $fields = null) {
return $this->stat('application_name'); if(!$id) $id = $this->currentPageID();
}
if(is_object($id)) {
/** $record = $id;
* @return string } else {
*/ $record = $this->getRecord($id);
public function Title() { if($record && !$record->canView()) return Security::permissionFailure($this);
$app = $this->getApplicationName(); }
return ($section = $this->SectionTitle()) ? sprintf('%s - %s', $app, $section) : $app; if($record) {
} $fields = ($fields) ? $fields : $record->getCMSFields();
if ($fields == null) {
/** user_error(
* Return the title of the current section. Either this is pulled from "getCMSFields() returned null - it should return a FieldList object.
* the current panel's menu_title or from the first active menu Perhaps you forgot to put a return statement at the end of your method?",
* E_USER_ERROR
* @return string );
*/ }
public function SectionTitle() {
$title = $this->menu_title(); // Add hidden fields which are required for saving the record
if($title) { // and loading the UI state
return $title; if(!$fields->dataFieldByName('ClassName')) {
} $fields->push(new HiddenField('ClassName'));
}
foreach($this->MainMenu() as $menuItem) {
if($menuItem->LinkingMode != 'link') { $tree_class = $this->stat('tree_class');
return $menuItem->Title; if(
} $tree_class::has_extension('SilverStripe\\ORM\\Hierarchy\\Hierarchy')
} && !$fields->dataFieldByName('ParentID')
} ) {
$fields->push(new HiddenField('ParentID'));
/** }
* Same as {@link ViewableData->CSSClasses()}, but with a changed name
* to avoid problems when using {@link ViewableData->customise()} // Added in-line to the form, but plucked into different view by frontend scripts.
* (which always returns "ArrayData" from the $original object). if ($record instanceof CMSPreviewable) {
* /** @skipUpgrade */
* @return String $navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator());
*/ $navField->setAllowHTML(true);
public function BaseCSSClasses() { $fields->push($navField);
return $this->CSSClasses('SilverStripe\\Control\\Controller'); }
}
if($record->hasMethod('getAllCMSActions')) {
/** $actions = $record->getAllCMSActions();
* @return String } else {
*/ $actions = $record->getCMSActions();
public function Locale() { // add default actions if none are defined
return DBField::create_field('Locale', i18n::get_locale()); if(!$actions || !$actions->count()) {
} if($record->hasMethod('canEdit') && $record->canEdit()) {
$actions->push(
public function providePermissions() { FormAction::create('save',_t('CMSMain.SAVE','Save'))
$perms = array( ->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')
"CMS_ACCESS_LeftAndMain" => array( );
'name' => _t('CMSMain.ACCESSALLINTERFACES', 'Access to all CMS sections'), }
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'), if($record->hasMethod('canDelete') && $record->canDelete()) {
'help' => _t('CMSMain.ACCESSALLINTERFACESHELP', 'Overrules more specific access settings.'), $actions->push(
'sort' => -100 FormAction::create('delete',_t('ModelAdmin.DELETE','Delete'))
) ->addExtraClass('ss-ui-action-destructive')
); );
}
// Add any custom ModelAdmin subclasses. Can't put this on ModelAdmin itself }
// since its marked abstract, and needs to be singleton instanciated. }
foreach(ClassInfo::subclassesFor('SilverStripe\\Admin\\ModelAdmin') as $i => $class) {
if ($class == 'SilverStripe\\Admin\\ModelAdmin') { // Use <button> to allow full jQuery UI styling
continue; $actionsFlattened = $actions->dataFields();
} if($actionsFlattened) {
if (ClassInfo::classImplements($class, 'SilverStripe\\Dev\\TestOnly')) { /** @var FormAction $action */
continue; foreach($actionsFlattened as $action) {
} $action->setUseButtonTag(true);
}
// Check if modeladmin has explicit required_permission_codes option. }
// If a modeladmin is namespaced you can apply this config to override
// the default permission generation based on fully qualified class name. $negotiator = $this->getResponseNegotiator();
$code = $this->getRequiredPermissions(); $form = Form::create(
if (!$code) { $this, "EditForm", $fields, $actions
continue; )->setHTMLID('Form_EditForm');
} $form->addExtraClass('cms-edit-form');
// Get first permission if multiple specified $form->loadDataFrom($record);
if (is_array($code)) { $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$code = reset($code); $form->setAttribute('data-pjax-fragment', 'CurrentForm');
} $form->setValidationResponseCallback(function() use ($negotiator, $form) {
$title = LeftAndMain::menu_title($class); $request = $this->getRequest();
$perms[$code] = array( if($request->isAjax() && $negotiator) {
'name' => _t( $form->setupFormErrors();
'CMSMain.ACCESS', $result = $form->forTemplate();
"Access to '{title}' section",
"Item in permission selection identifying the admin section. Example: Access to 'Files & Images'", return $negotiator->respond($request, array(
array('title' => $title) 'CurrentForm' => function() use($result) {
), return $result;
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access') }
); ));
} }
});
return $perms;
} // Announce the capability so the frontend can decide whether to allow preview or not.
if ($record instanceof CMSPreviewable) {
$form->addExtraClass('cms-previewable');
}
// Set this if you want to split up tabs into a separate header row
// if($form->Fields()->hasTabset()) {
// $form->Fields()->findOrMakeTab('Root')->setTemplate('SilverStripe\\Forms\\CMSTabSet');
// }
// Add a default or custom validator.
// @todo Currently the default Validator.js implementation
// adds javascript to the document body, meaning it won't
// be included properly if the associated fields are loaded
// through ajax. This means only serverside validation
// will kick in for pages+validation loaded through ajax.
// This will be solved by using less obtrusive javascript validation
// in the future, see http://open.silverstripe.com/ticket/2915 and
// http://open.silverstripe.com/ticket/3386
if($record->hasMethod('getCMSValidator')) {
$validator = $record->getCMSValidator();
// The clientside (mainly LeftAndMain*.js) rely on ajax responses
// which can be evaluated as javascript, hence we need
// to override any global changes to the validation handler.
if($validator != NULL){
$form->setValidator($validator);
}
} else {
$form->unsetValidator();
}
if($record->hasMethod('canEdit') && !$record->canEdit()) {
$readonlyFields = $form->Fields()->makeReadonly();
$form->setFields($readonlyFields);
}
} else {
$form = $this->EmptyForm();
}
return $form;
}
/**
* Returns a placeholder form, used by {@link getEditForm()} if no record is selected.
* Our javascript logic always requires a form to be present in the CMS interface.
*
* @return Form
*/
public function EmptyForm() {
$form = Form::create(
$this,
"EditForm",
new FieldList(
// new HeaderField(
// 'WelcomeHeader',
// $this->getApplicationName()
// ),
// new LiteralField(
// 'WelcomeText',
// sprintf('<p id="WelcomeMessage">%s %s. %s</p>',
// _t('LeftAndMain_right_ss.WELCOMETO','Welcome to'),
// $this->getApplicationName(),
// _t('CHOOSEPAGE','Please choose an item from the left.')
// )
// )
),
new FieldList()
)->setHTMLID('Form_EditForm');
$form->unsetValidator();
$form->addExtraClass('cms-edit-form');
$form->addExtraClass('root-form');
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$form->setAttribute('data-pjax-fragment', 'CurrentForm');
return $form;
}
/**
* Return the CMS's HTML-editor toolbar
*/
public function EditorToolbar() {
return HTMLEditorField_Toolbar::create($this, "EditorToolbar");
}
/**
* Renders a panel containing tools which apply to all displayed
* "content" (mostly through {@link EditForm()}), for example a tree navigation or a filter panel.
* Auto-detects applicable templates by naming convention: "<controller classname>_Tools.ss",
* and takes the most specific template (see {@link getTemplatesWithSuffix()}).
* To explicitly disable the panel in the subclass, simply create a more specific, empty template.
*
* @return String HTML
*/
public function Tools() {
$templates = $this->getTemplatesWithSuffix('_Tools');
if($templates) {
$viewer = new SSViewer($templates);
return $viewer->process($this);
} else {
return false;
}
}
/**
* Renders a panel containing tools which apply to the currently displayed edit form.
* The main difference to {@link Tools()} is that the panel is displayed within
* the element structure of the form panel (rendered through {@link EditForm}).
* This means the panel will be loaded alongside new forms, and refreshed upon save,
* which can mean a performance hit, depending on how complex your panel logic gets.
* Any form fields contained in the returned markup will also be submitted with the main form,
* which might be desired depending on the implementation details.
*
* @return String HTML
*/
public function EditFormTools() {
$templates = $this->getTemplatesWithSuffix('_EditFormTools');
if($templates) {
$viewer = new SSViewer($templates);
return $viewer->process($this);
} else {
return false;
}
}
/**
* Batch Actions Handler
*/
public function batchactions() {
return new CMSBatchActionHandler($this, 'batchactions', $this->stat('tree_class'));
}
/**
* @return Form
*/
public function BatchActionsForm() {
$actions = $this->batchactions()->batchActionList();
$actionsMap = array('-1' => _t('LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...')); // Placeholder action
foreach($actions as $action) {
$actionsMap[$action->Link] = $action->Title;
}
$form = new Form(
$this,
'BatchActionsForm',
new FieldList(
new HiddenField('csvIDs'),
DropdownField::create(
'Action',
false,
$actionsMap
)
->setAttribute('autocomplete', 'off')
->setAttribute('data-placeholder', _t('LeftAndMain.DropdownBatchActionsDefault', 'Choose an action...'))
),
new FieldList(
// TODO i18n
new FormAction('submit', _t('Form.SubmitBtnLabel', "Go"))
)
);
$form->addExtraClass('cms-batch-actions form--no-dividers');
$form->unsetValidator();
$this->extend('updateBatchActionsForm', $form);
return $form;
}
public function printable() {
$form = $this->getEditForm($this->currentPageID());
if(!$form) return false;
$form->transform(new PrintableTransformation());
$form->setActions(null);
Requirements::clear();
Requirements::css(FRAMEWORK_ADMIN_DIR . '/dist/css/LeftAndMain_printable.css');
return array(
"PrintForm" => $form
);
}
/**
* Used for preview controls, mainly links which switch between different states of the page.
*
* @return DBHTMLText
*/
public function getSilverStripeNavigator() {
$page = $this->currentPage();
if ($page instanceof CMSPreviewable) {
$navigator = new SilverStripeNavigator($page);
return $navigator->renderWith($this->getTemplatesWithSuffix('_SilverStripeNavigator'));
}
return null;
}
/**
* Identifier for the currently shown record,
* in most cases a database ID. Inspects the following
* sources (in this order):
* - GET/POST parameter named 'ID'
* - URL parameter named 'ID'
* - Session value namespaced by classname, e.g. "CMSMain.currentPage"
*
* @return int
*/
public function currentPageID() {
if($this->getRequest()->requestVar('ID') && is_numeric($this->getRequest()->requestVar('ID'))) {
return $this->getRequest()->requestVar('ID');
} elseif ($this->getRequest()->requestVar('CMSMainCurrentPageID') && is_numeric($this->getRequest()->requestVar('CMSMainCurrentPageID'))) {
// see GridFieldDetailForm::ItemEditForm
return $this->getRequest()->requestVar('CMSMainCurrentPageID');
} elseif (isset($this->urlParams['ID']) && is_numeric($this->urlParams['ID'])) {
return $this->urlParams['ID'];
} elseif(Session::get($this->sessionNamespace() . ".currentPage")) {
return Session::get($this->sessionNamespace() . ".currentPage");
} else {
return null;
}
}
/**
* Forces the current page to be set in session,
* which can be retrieved later through {@link currentPageID()}.
* Keep in mind that setting an ID through GET/POST or
* as a URL parameter will overrule this value.
*
* @param int $id
*/
public function setCurrentPageID($id) {
$id = (int)$id;
Session::set($this->sessionNamespace() . ".currentPage", $id);
}
/**
* Uses {@link getRecord()} and {@link currentPageID()}
* to get the currently selected record.
*
* @return DataObject
*/
public function currentPage() {
return $this->getRecord($this->currentPageID());
}
/**
* Compares a given record to the currently selected one (if any).
* Used for marking the current tree node.
*
* @param DataObject $record
* @return bool
*/
public function isCurrentPage(DataObject $record) {
return ($record->ID == $this->currentPageID());
}
/**
* @return String
*/
protected function sessionNamespace() {
$override = $this->stat('session_namespace');
return $override ? $override : $this->class;
}
/**
* URL to a previewable record which is shown through this controller.
* The controller might not have any previewable content, in which case
* this method returns FALSE.
*
* @return String|boolean
*/
public function LinkPreview() {
return false;
}
/**
* Return the version number of this application.
* Uses the number in <mymodule>/silverstripe_version
* (automatically replaced by build scripts).
* If silverstripe_version is empty,
* then attempts to get it from composer.lock
*
* @return string
*/
public function CMSVersion() {
$versions = array();
$modules = array(
'silverstripe/framework' => array(
'title' => 'Framework',
'versionFile' => FRAMEWORK_PATH . '/silverstripe_version',
)
);
if(defined('CMS_PATH')) {
$modules['silverstripe/cms'] = array(
'title' => 'CMS',
'versionFile' => CMS_PATH . '/silverstripe_version',
);
}
// Tries to obtain version number from composer.lock if it exists
$composerLockPath = BASE_PATH . '/composer.lock';
if (file_exists($composerLockPath)) {
$cache = Cache::factory('LeftAndMain_CMSVersion');
$cacheKey = filemtime($composerLockPath);
$versions = $cache->load($cacheKey);
if($versions) {
$versions = json_decode($versions, true);
} else {
$versions = array();
}
if(!$versions && $jsonData = file_get_contents($composerLockPath)) {
$lockData = json_decode($jsonData);
if($lockData && isset($lockData->packages)) {
foreach ($lockData->packages as $package) {
if(
array_key_exists($package->name, $modules)
&& isset($package->version)
) {
$versions[$package->name] = $package->version;
}
}
$cache->save(json_encode($versions), $cacheKey);
}
}
}
// Fall back to static version file
foreach($modules as $moduleName => $moduleSpec) {
if(!isset($versions[$moduleName])) {
if($staticVersion = file_get_contents($moduleSpec['versionFile'])) {
$versions[$moduleName] = $staticVersion;
} else {
$versions[$moduleName] = _t('LeftAndMain.VersionUnknown', 'Unknown');
}
}
}
$out = array();
foreach($modules as $moduleName => $moduleSpec) {
$out[] = $modules[$moduleName]['title'] . ': ' . $versions[$moduleName];
}
return implode(', ', $out);
}
/**
* @return array
*/
public function SwitchView() {
if($page = $this->currentPage()) {
$nav = SilverStripeNavigator::get_for_record($page);
return $nav['items'];
}
}
/**
* @return SiteConfig
*/
public function SiteConfig() {
return (class_exists('SilverStripe\\SiteConfig\\SiteConfig')) ? SiteConfig::current_site_config() : null;
}
/**
* The href for the anchor on the Silverstripe logo.
* Set by calling LeftAndMain::set_application_link()
*
* @config
* @var String
*/
private static $application_link = '//www.silverstripe.org/';
/**
* @return String
*/
public function ApplicationLink() {
return $this->stat('application_link');
}
/**
* The application name. Customisable by calling
* LeftAndMain::setApplicationName() - the first parameter.
*
* @config
* @var String
*/
private static $application_name = 'SilverStripe';
/**
* Get the application name.
*
* @return string
*/
public function getApplicationName() {
return $this->stat('application_name');
}
/**
* @return string
*/
public function Title() {
$app = $this->getApplicationName();
return ($section = $this->SectionTitle()) ? sprintf('%s - %s', $app, $section) : $app;
}
/**
* Return the title of the current section. Either this is pulled from
* the current panel's menu_title or from the first active menu
*
* @return string
*/
public function SectionTitle() {
$title = $this->menu_title();
if($title) {
return $title;
}
foreach($this->MainMenu() as $menuItem) {
if($menuItem->LinkingMode != 'link') {
return $menuItem->Title;
}
}
}
/**
* Same as {@link ViewableData->CSSClasses()}, but with a changed name
* to avoid problems when using {@link ViewableData->customise()}
* (which always returns "ArrayData" from the $original object).
*
* @return String
*/
public function BaseCSSClasses() {
return $this->CSSClasses('SilverStripe\\Control\\Controller');
}
/**
* @return String
*/
public function Locale() {
return DBField::create_field('Locale', i18n::get_locale());
}
public function providePermissions() {
$perms = array(
"CMS_ACCESS_LeftAndMain" => array(
'name' => _t('CMSMain.ACCESSALLINTERFACES', 'Access to all CMS sections'),
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'),
'help' => _t('CMSMain.ACCESSALLINTERFACESHELP', 'Overrules more specific access settings.'),
'sort' => -100
)
);
// Add any custom ModelAdmin subclasses. Can't put this on ModelAdmin itself
// since its marked abstract, and needs to be singleton instanciated.
foreach(ClassInfo::subclassesFor('SilverStripe\\Admin\\ModelAdmin') as $i => $class) {
if ($class == 'SilverStripe\\Admin\\ModelAdmin') {
continue;
}
if (ClassInfo::classImplements($class, 'SilverStripe\\Dev\\TestOnly')) {
continue;
}
// Check if modeladmin has explicit required_permission_codes option.
// If a modeladmin is namespaced you can apply this config to override
// the default permission generation based on fully qualified class name.
$code = $this->getRequiredPermissions();
if (!$code) {
continue;
}
// Get first permission if multiple specified
if (is_array($code)) {
$code = reset($code);
}
$title = LeftAndMain::menu_title($class);
$perms[$code] = array(
'name' => _t(
'CMSMain.ACCESS',
"Access to '{title}' section",
"Item in permission selection identifying the admin section. Example: Access to 'Files & Images'",
array('title' => $title)
),
'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access')
);
}
return $perms;
}
} }