Permalink
Browse files

MINOR Moved LeftAndMain, SecurityAdmin, ModelAdmin and related functi…

…onality from 'cms' module to sapphire/admin
  • Loading branch information...
1 parent 29afbea commit a1fb071b2b97ce5b592e285535c62aabbd516456 @chillu chillu committed Mar 23, 2011
Showing with 41,561 additions and 1 deletion.
  1. +39 −0 admin/_config.php
  2. +273 −0 admin/code/CMSBatchAction.php
  3. +208 −0 admin/code/CMSBatchActionHandler.php
  4. +325 −0 admin/code/CMSMenu.php
  5. +50 −0 admin/code/CMSMenuItem.php
  6. +90 −0 admin/code/GroupImportForm.php
  7. +1,329 −0 admin/code/LeftAndMain.php
  8. +21 −0 admin/code/LeftAndMainDecorator.php
  9. +108 −0 admin/code/MemberImportForm.php
  10. +553 −0 admin/code/MemberTableField.php
  11. +1,055 −0 admin/code/ModelAdmin.php
  12. +391 −0 admin/code/SecurityAdmin.php
  13. +167 −0 admin/css/Image_iframe.css
  14. +36 −0 admin/css/LeftAndMain_printable.css
  15. +25 −0 admin/css/MemberImportForm.css
  16. +173 −0 admin/css/ModelAdmin.css
  17. +14 −0 admin/css/SecurityAdmin.css
  18. +414 −0 admin/css/cms_left.css
  19. +590 −0 admin/css/cms_right.css
  20. +20 −0 admin/css/editor.css
  21. +718 −0 admin/css/layout.css
  22. +31 −0 admin/css/silverstripe.tabs.css
  23. +34 −0 admin/css/typography.css
  24. +134 −0 admin/css/unjquery.css
  25. BIN admin/images/alert-bad.gif
  26. BIN admin/images/alert-good.gif
  27. BIN admin/images/logo.gif
  28. BIN admin/images/logout.gif
  29. BIN admin/images/mainmenu/content.png
  30. BIN admin/images/mainmenu/current.gif
  31. BIN admin/images/mainmenu/currentHover.gif
  32. BIN admin/images/mainmenu/help.gif
  33. BIN admin/images/mainmenu/help.png
  34. BIN admin/images/mainmenu/hover.gif
  35. BIN admin/images/mainmenu/logo.gif
  36. BIN admin/images/mainmenu/logo.png
  37. BIN admin/images/mainmenu/top-bg.gif
  38. BIN admin/images/network-save.gif
  39. BIN admin/images/spinner.gif
  40. BIN admin/images/textures/ToolBar.png
  41. BIN admin/images/textures/bottom.png
  42. BIN admin/images/textures/footerBg.gif
  43. BIN admin/images/textures/mce_editor.gif
  44. BIN admin/images/textures/obar-18.gif
  45. BIN admin/images/textures/obar-light.png
  46. BIN admin/images/textures/obar.gif
  47. BIN admin/images/textures/seperator.png
  48. BIN admin/javascript/.DS_Store
  49. +170 −0 admin/javascript/AssetTableField.js
  50. +163 −0 admin/javascript/LeftAndMain.AddForm.js
  51. +355 −0 admin/javascript/LeftAndMain.BatchActions.js
  52. +382 −0 admin/javascript/LeftAndMain.EditForm.js
  53. +302 −0 admin/javascript/LeftAndMain.Tree.js
  54. +457 −0 admin/javascript/LeftAndMain.js
  55. +32 −0 admin/javascript/MemberImportForm.js
  56. +357 −0 admin/javascript/MemberTableField.js
  57. +21 −0 admin/javascript/MemberTableField_popup.js
  58. +178 −0 admin/javascript/ModelAdmin.History.js
  59. +216 −0 admin/javascript/ModelAdmin.js
  60. +12 −0 admin/javascript/SecurityAdmin.Tree.js
  61. +73 −0 admin/javascript/SecurityAdmin.js
  62. +17 −0 admin/javascript/jquery-changetracker/README.md
  63. +103 −0 admin/javascript/jquery-changetracker/lib/jquery.changetracker.js
  64. +31 −0 admin/javascript/jquery-changetracker/spec/.tmp_spec.html.49538~
  65. +34 −0 admin/javascript/jquery-changetracker/spec/.tmp_spec.html.8678~
  66. +32 −0 admin/javascript/jquery-changetracker/spec/.tmp_spec.html.970~
  67. +31 −0 admin/javascript/jquery-changetracker/spec/.tmp_spec_selectors.html.13329~
  68. +105 −0 admin/javascript/jquery-changetracker/spec/.tmp_speed.html.70283~
  69. +128 −0 admin/javascript/jquery-changetracker/spec/spec.changetracker.basics.js
  70. +8 −0 admin/javascript/jquery-changetracker/spec/spec.core.js
  71. +24 −0 admin/javascript/jquery-changetracker/spec/spec.dom.html
  72. +9 −0 admin/javascript/jquery-changetracker/spec/spec.rhino.js
  73. +61 −0 admin/javascript/jquery-changetracker/vendor/TrivialReporter.js
  74. +24 −0 admin/javascript/jquery-changetracker/vendor/jasmine.css
  75. +900 −0 admin/javascript/jquery-changetracker/vendor/jasmine.js
  76. +4,376 −0 admin/javascript/jquery-changetracker/vendor/jquery-1.3.2.js
  77. +57 −0 admin/javascript/jquery-fitheighttoparent/jquery.fitheighttoparent.js
  78. +11 −0 admin/javascript/jquery-fitheighttoparent/test.html
  79. +150 −0 admin/javascript/jquery-fitheighttoparent/tests/unit.html
  80. +93 −0 admin/javascript/ssui.core.js
  81. +10 −0 admin/templates/Includes/CMSTopMenu.ss
  82. +35 −0 admin/templates/Includes/Editor_toolbar.ss
  83. +3 −0 admin/templates/Includes/LeftAndMain_right.ss
  84. 0 admin/templates/Includes/LeftAndMain_rightbottom.ss
  85. +62 −0 admin/templates/Includes/MemberTableField.ss
  86. 0 admin/templates/Includes/ModelAdmin.ss
  87. +21 −0 admin/templates/Includes/ModelAdmin_ImportSpec.ss
  88. +5 −0 admin/templates/Includes/ModelAdmin_Results.ss
  89. +26 −0 admin/templates/Includes/ModelAdmin_left.ss
  90. +45 −0 admin/templates/Includes/SecurityAdmin_left.ss
  91. +60 −0 admin/templates/LeftAndMain.ss
  92. +13 −0 admin/templates/LeftAndMain_printable.ss
  93. +12 −0 admin/templates/ModelSidebar.ss
  94. +79 −0 admin/tests/CMSMenuTest.php
  95. +176 −0 admin/tests/LeftAndMainTest.php
  96. +113 −0 admin/tests/LeftAndMainTest.yml
  97. +139 −0 admin/tests/MemberTableFieldTest.php
  98. +31 −0 admin/tests/MemberTableFieldTest.yml
  99. +32 −0 admin/tests/ModelAdminTest.php
  100. +19 −0 admin/tests/ModelAdminTest.yml
  101. +86 −0 admin/tests/SecurityAdminTest.php
  102. +1 −0 admin/thirdparty/jquery-layout/README.txt
  103. +60 −0 admin/thirdparty/jquery-layout/changelog.txt
  104. +23 −0 admin/thirdparty/jquery-layout/example.html
  105. +8,176 −0 admin/thirdparty/jquery-layout/jquery.js
  106. +4,332 −0 admin/thirdparty/jquery-layout/jquery.layout.js
  107. +142 −0 admin/thirdparty/jquery-layout/jquery.layout.min.js
  108. +140 −0 admin/thirdparty/jquery-layout/jquery.layout.state.js
  109. +11,545 −0 admin/thirdparty/jquery-layout/jquery.ui.all.js
  110. +150 −0 admin/thirdparty/jquery-layout/nested.html
  111. +197 −0 admin/thirdparty/jquery-layout/simple.html
  112. +8 −0 admin/thirdparty/jquery-notice/.piston.yml
  113. +36 −0 admin/thirdparty/jquery-notice/jquery.notice.css
  114. +73 −0 admin/thirdparty/jquery-notice/jquery.notice.js
  115. +1 −1 forms/TreeSelectorField.php
View
39 admin/_config.php
@@ -0,0 +1,39 @@
+<?php
+Director::addRules(50, array(
+ '' => 'RootURLController',
+ 'processes//$Action/$ID/$Batch' => 'BatchProcess_Controller',
+ 'admin/help//$Action/$ID' => 'CMSHelp',
+ 'admin/bulkload//$Action/$ID/$OtherID' => 'BulkLoaderAdmin',
+ 'admin/cms//$Action/$ID/$OtherID' => 'CMSMain',
+ 'dev/buildcache/$Action' => 'RebuildStaticCacheTask',
+));
+
+CMSMenu::add_director_rules();
+
+// Default CMS HTMLEditorConfig
+HtmlEditorConfig::get('cms')->setOptions(array(
+ 'friendly_name' => 'Default CMS',
+ 'priority' => '50',
+ 'mode' => 'none',
+
+ 'body_class' => 'typography',
+ 'document_base_url' => Director::absoluteBaseURL(),
+
+ 'urlconverter_callback' => "nullConverter",
+ 'setupcontent_callback' => "sapphiremce_setupcontent",
+ 'cleanup_callback' => "sapphiremce_cleanup",
+
+ 'use_native_selects' => true, // fancy selects are bug as of SS 2.3.0
+ 'valid_elements' => "@[id|class|style|title],#a[id|rel|rev|dir|tabindex|accesskey|type|name|href|target|title|class],-strong/-b[class],-em/-i[class],-strike[class],-u[class],#p[id|dir|class|align|style],-ol[class],-ul[class],-li[class],br,img[id|dir|longdesc|usemap|class|src|border|alt=|title|width|height|align],-sub[class],-sup[class],-blockquote[dir|class],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|dir|id|style],-tr[id|dir|class|rowspan|width|height|align|valign|bgcolor|background|bordercolor|style],tbody[id|class|style],thead[id|class|style],tfoot[id|class|style],#td[id|dir|class|colspan|rowspan|width|height|align|valign|scope|style],-th[id|dir|class|colspan|rowspan|width|height|align|valign|scope|style],caption[id|dir|class],-div[id|dir|class|align|style],-span[class|align|style],-pre[class|align],address[class|align],-h1[id|dir|class|align|style],-h2[id|dir|class|align|style],-h3[id|dir|class|align|style],-h4[id|dir|class|align|style],-h5[id|dir|class|align|style],-h6[id|dir|class|align|style],hr[class],dd[id|class|title|dir],dl[id|class|title|dir],dt[id|class|title|dir],@[id,style,class]",
+ 'extended_valid_elements' => "img[class|src|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|usemap],iframe[src|name|width|height|align|frameborder|marginwidth|marginheight|scrolling],object[width|height|data|type],param[name|value],map[class|name|id],area[shape|coords|href|target|alt]"
+));
+
+HtmlEditorConfig::get('cms')->enablePlugins('media', 'fullscreen');
+HtmlEditorConfig::get('cms')->enablePlugins(array('ssbuttons' => '../../../cms/javascript/tinymce_ssbuttons/editor_plugin_src.js'));
+
+HtmlEditorConfig::get('cms')->insertButtonsBefore('formatselect', 'styleselect');
+HtmlEditorConfig::get('cms')->insertButtonsBefore('advcode', 'ssimage', 'ssflash', 'sslink', 'unlink', 'anchor', 'separator' );
+HtmlEditorConfig::get('cms')->insertButtonsAfter ('advcode', 'fullscreen', 'separator');
+
+HtmlEditorConfig::get('cms')->removeButtons('tablecontrols');
+HtmlEditorConfig::get('cms')->addButtonsToLine(3, 'tablecontrols');
View
273 admin/code/CMSBatchAction.php
@@ -0,0 +1,273 @@
+<?php
+
+/**
+ * A class representing back actions.
+ * See cms/javascript/CMSMain.BatchActions.js on how to add custom javascript
+ * functionality.
+ *
+ * <code>
+ * CMSMain::register_batch_action('publishitems', new CMSBatchAction('doPublish',
+ * _t('CMSBatchActions.PUBLISHED_PAGES', 'published %d pages')));
+ * </code>
+ *
+ * @package cms
+ * @subpackage batchaction
+ */
+abstract class CMSBatchAction extends Object {
+ /**
+ * The the text to show in the dropdown for this action
+ */
+ abstract function getActionTitle();
+
+ /**
+ * Run this action for the given set of pages.
+ * Return a set of status-updated JavaScript to return to the CMS.
+ */
+ abstract function run(DataObjectSet $pages);
+
+ /**
+ * Helper method for processing batch actions.
+ * Returns a set of status-updating JavaScript to return to the CMS.
+ *
+ * @param $pages The DataObjectSet of SiteTree objects to perform this batch action
+ * on.
+ * @param $helperMethod The method to call on each of those objects.
+ * @return JSON encoded map in the following format:
+ * {
+ * 'modified': {
+ * 3: {'TreeTitle': 'Page3'},
+ * 5: {'TreeTitle': 'Page5'}
+ * },
+ * 'deleted': {
+ * // all deleted pages
+ * }
+ * }
+ */
+ public function batchaction(DataObjectSet $pages, $helperMethod, $successMessage, $arguments = array()) {
+ $status = array('modified' => array(), 'error' => array());
+
+ foreach($pages as $page) {
+
+ // Perform the action
+ if (!call_user_func_array(array($page, $helperMethod), $arguments)) {
+ $status['error'][$page->ID] = '';
+ }
+
+ // Now make sure the tree title is appropriately updated
+ $publishedRecord = DataObject::get_by_id('SiteTree', $page->ID);
+ if ($publishedRecord) {
+ $status['modified'][$publishedRecord->ID] = array(
+ 'TreeTitle' => $publishedRecord->TreeTitle,
+ );
+ }
+ $page->destroy();
+ unset($page);
+ }
+
+ $response = Controller::curr()->getResponse();
+ if($response) {
+ $response->setStatusCode(
+ 200,
+ sprintf($successMessage, $pages->Count(), count($status['error']))
+ );
+ }
+
+ return Convert::raw2json($status);
+ }
+
+
+
+ /**
+ * Helper method for applicablePages() methods. Acts as a skeleton implementation.
+ *
+ * @param $ids The IDs passed to applicablePages
+ * @param $methodName The canXXX() method to call on each page to check if the action is applicable
+ * @param $checkStagePages Set to true if you want to check stage pages
+ * @param $checkLivePages Set to true if you want to check live pages (e.g, for deleted-from-draft)
+ */
+ function applicablePagesHelper($ids, $methodName, $checkStagePages = true, $checkLivePages = true) {
+ if(!is_array($ids)) user_error("Bad \$ids passed to applicablePagesHelper()", E_USER_WARNING);
+ if(!is_string($methodName)) user_error("Bad \$methodName passed to applicablePagesHelper()", E_USER_WARNING);
+
+ $applicableIDs = array();
+
+ $SQL_ids = implode(', ', array_filter($ids, 'is_numeric'));
+ $draftPages = DataObject::get("SiteTree", "\"SiteTree\".\"ID\" IN ($SQL_ids)");
+
+ $onlyOnLive = array_fill_keys($ids, true);
+ if($checkStagePages) {
+ foreach($draftPages as $page) {
+ unset($onlyOnLive[$page->ID]);
+ if($page->$methodName()) $applicableIDs[] = $page->ID;
+ }
+ }
+
+ // Get the pages that only exist on live (deleted from stage)
+ if($checkLivePages && $onlyOnLive) {
+ $SQL_ids = implode(', ', array_keys($onlyOnLive));
+ $livePages = Versioned::get_by_stage("SiteTree", "Live", "\"SiteTree\".\"ID\" IN ($SQL_ids)");
+
+ if($livePages) foreach($livePages as $page) {
+ if($page->$methodName()) $applicableIDs[] = $page->ID;
+ }
+ }
+
+ return $applicableIDs;
+ }
+
+
+ // if your batchaction has parameters, return a fieldset here
+ function getParameterFields() {
+ return false;
+ }
+
+ /**
+ * If you wish to restrict the batch action to some users, overload this function.
+ */
+ function canView() {
+ return true;
+ }
+}
+
+/**
+ * Publish items batch action.
+ *
+ * @package cms
+ * @subpackage batchaction
+ */
+class CMSBatchAction_Publish extends CMSBatchAction {
+ function getActionTitle() {
+ return _t('CMSBatchActions.PUBLISH_PAGES', 'Publish');
+ }
+ function getDoingText() {
+ return _t('CMSBatchActions.PUBLISHING_PAGES', 'Publishing selected pages');
+ }
+
+ function run(DataObjectSet $pages) {
+ return $this->batchaction($pages, 'doPublish',
+ _t('CMSBatchActions.PUBLISHED_PAGES', 'Published %d pages, %d failures')
+ );
+ }
+
+ function applicablePages($ids) {
+ return $this->applicablePagesHelper($ids, 'canPublish', true, false);
+ }
+}
+
+/**
+ * Un-publish items batch action.
+ *
+ * @package cms
+ * @subpackage batchaction
+ */
+class CMSBatchAction_Unpublish extends CMSBatchAction {
+ function getActionTitle() {
+ return _t('CMSBatchActions.UNPUBLISH_PAGES', 'Un-publish');
+ }
+ function getDoingText() {
+ return _t('CMSBatchActions.UNPUBLISHING_PAGES', 'Un-publishing selected pages');
+ }
+
+ function run(DataObjectSet $pages) {
+ return $this->batchaction($pages, 'doUnpublish',
+ _t('CMSBatchActions.UNPUBLISHED_PAGES', 'Un-published %d pages')
+ );
+ }
+}
+
+/**
+ * Delete items batch action.
+ *
+ * @package cms
+ * @subpackage batchaction
+ */
+class CMSBatchAction_Delete extends CMSBatchAction {
+ function getActionTitle() {
+ return _t('CMSBatchActions.DELETE_DRAFT_PAGES', 'Delete from draft site');
+ }
+ function getDoingText() {
+ return _t('CMSBatchActions.DELETING_DRAFT_PAGES', 'Deleting selected pages from the draft site');
+ }
+
+ function run(DataObjectSet $pages) {
+ $status = array(
+ 'modified'=>array(),
+ 'deleted'=>array(),
+ 'error'=>array()
+ );
+
+ foreach($pages as $page) {
+ $id = $page->ID;
+
+ // Perform the action
+ if($page->canDelete()) $page->delete();
+ else $status['error'][$page->ID] = true;
+
+ // check to see if the record exists on the live site,
+ // if it doesn't remove the tree node
+ $liveRecord = Versioned::get_one_by_stage( 'SiteTree', 'Live', "\"SiteTree\".\"ID\"=$id");
+ if($liveRecord) {
+ $liveRecord->IsDeletedFromStage = true;
+ $status['modified'][$liveRecord->ID] = array(
+ 'TreeTitle' => $liveRecord->TreeTitle,
+ );
+ } else {
+ $status['deleted'][$id] = array();
+ }
+
+ }
+
+ return Convert::raw2json($status);
+ }
+
+ function applicablePages($ids) {
+ return $this->applicablePagesHelper($ids, 'canDelete', true, false);
+ }
+}
+
+/**
+ * Unpublish (delete from live site) items batch action.
+ *
+ * @package cms
+ * @subpackage batchaction
+ */
+class CMSBatchAction_DeleteFromLive extends CMSBatchAction {
+ function getActionTitle() {
+ return _t('CMSBatchActions.DELETE_PAGES', 'Delete from published site');
+ }
+ function getDoingText() {
+ return _t('CMSBatchActions.DELETING_PAGES', 'Deleting selected pages from the published site');
+ }
+
+ function run(DataObjectSet $pages) {
+ $status = array(
+ 'modified'=>array(),
+ 'deleted'=>array()
+ );
+
+ foreach($pages as $page) {
+ $id = $page->ID;
+
+ // Perform the action
+ if($page->canDelete()) $page->doDeleteFromLive();
+
+ // check to see if the record exists on the stage site, if it doesn't remove the tree node
+ $stageRecord = Versioned::get_one_by_stage( 'SiteTree', 'Stage', "\"SiteTree\".\"ID\"=$id");
+ if($stageRecord) {
+ $stageRecord->IsAddedToStage = true;
+ $status['modified'][$stageRecord->ID] = array(
+ 'TreeTitle' => $stageRecord->TreeTitle,
+ );
+ } else {
+ $status['deleted'][$id] = array();
+ }
+
+ }
+
+ return Convert::raw2json($status);
+ }
+
+ function applicablePages($ids) {
+ return $this->applicablePagesHelper($ids, 'canDelete', false, true);
+ }
+}
View
208 admin/code/CMSBatchActionHandler.php
@@ -0,0 +1,208 @@
+<?php
+
+/**
+ * Special request handler for admin/batchaction
+ *
+ * @package cms
+ * @subpackage batchaction
+ */
+class CMSBatchActionHandler extends RequestHandler {
+
+ static $batch_actions = array();
+
+ static $url_handlers = array(
+ '$BatchAction/applicablepages' => 'handleApplicablePages',
+ '$BatchAction/confirmation' => 'handleConfirmation',
+ '$BatchAction' => 'handleAction',
+ );
+
+ protected $parentController;
+
+ /**
+ * @var String
+ */
+ protected $urlSegment;
+
+ /**
+ * @var String $recordClass The classname that should be affected
+ * by any batch changes. Needs to be set in the actual {@link CMSBatchAction}
+ * implementations as well.
+ */
+ protected $recordClass = 'SiteTree';
+
+ /**
+ * Register a new batch action. Each batch action needs to be represented by a subclass
+ * of {@link CMSBatchAction}.
+ *
+ * @param $urlSegment The URL Segment of the batch action - the URL used to process this
+ * action will be admin/batchactions/(urlSegment)
+ * @param $batchActionClass The name of the CMSBatchAction subclass to register
+ */
+ static function register($urlSegment, $batchActionClass, $recordClass = 'SiteTree') {
+ if(is_subclass_of($batchActionClass, 'CMSBatchAction')) {
+ self::$batch_actions[$urlSegment] = array(
+ 'class' => $batchActionClass,
+ 'recordClass' => $recordClass
+ );
+ } else {
+ user_error("CMSBatchActionHandler::register() - Bad class '$batchActionClass'", E_USER_ERROR);
+ }
+ }
+
+ /**
+ * @param string $parentController
+ * @param string $urlSegment
+ * @param string $recordClass
+ */
+ function __construct($parentController, $urlSegment, $recordClass = null) {
+ $this->parentController = $parentController;
+ $this->urlSegment = $urlSegment;
+ if($recordClass) $this->recordClass = $recordClass;
+
+ parent::__construct();
+ }
+
+ function Link() {
+ return Controller::join_links($this->parentController->Link(), $this->urlSegment);
+ }
+
+ function handleAction($request) {
+ // This method can't be called without ajax.
+ if(!$this->parentController->isAjax()) {
+ $this->parentController->redirectBack();
+ return;
+ }
+
+ // Protect against CSRF on destructive action
+ if(!SecurityToken::inst()->checkRequest($request)) return $this->httpError(400);
+
+ $actions = $this->batchActions();
+ $actionClass = $actions[$request->param('BatchAction')]['class'];
+ $actionHandler = new $actionClass();
+
+ // Sanitise ID list and query the database for apges
+ $ids = split(' *, *', trim($request->requestVar('csvIDs')));
+ foreach($ids as $k => $v) if(!is_numeric($v)) unset($ids[$k]);
+
+ if($ids) {
+ if(class_exists('Translatable') && Object::has_extension('SiteTree','Translatable')) Translatable::disable_locale_filter();
+
+ $pages = DataObject::get(
+ $this->recordClass,
+ sprintf(
+ '"%s"."ID" IN (%s)',
+ ClassInfo::baseDataClass($this->recordClass),
+ implode(", ", $ids)
+ )
+ );
+
+ if(class_exists('Translatable') && Object::has_extension('SiteTree','Translatable')) Translatable::enable_locale_filter();
+
+ if(Object::has_extension($this->recordClass, 'Versioned')) {
+ // If we didn't query all the pages, then find the rest on the live site
+ if(!$pages || $pages->Count() < sizeof($ids)) {
+ foreach($ids as $id) $idsFromLive[$id] = true;
+ if($pages) foreach($pages as $page) unset($idsFromLive[$page->ID]);
+ $idsFromLive = array_keys($idsFromLive);
+
+ $sql = sprintf(
+ '"%s"."ID" IN (%s)',
+ $this->recordClass,
+ implode(", ", $idsFromLive)
+ );
+ $livePages = Versioned::get_by_stage($this->recordClass, 'Live', $sql);
+ if($pages) $pages->merge($livePages);
+ else $pages = $livePages;
+ }
+ }
+ } else {
+ $pages = new DataObjectSet();
+ }
+
+ return $actionHandler->run($pages);
+ }
+
+ function handleApplicablePages($request) {
+ // Find the action handler
+ $actions = Object::get_static($this->class, 'batch_actions');
+ $actionClass = $actions[$request->param('BatchAction')];
+ $actionHandler = new $actionClass['class']();
+
+ // Sanitise ID list and query the database for apges
+ $ids = split(' *, *', trim($request->requestVar('csvIDs')));
+ foreach($ids as $k => $id) $ids[$k] = (int)$id;
+ $ids = array_filter($ids);
+
+ if($actionHandler->hasMethod('applicablePages')) {
+ $applicableIDs = $actionHandler->applicablePages($ids);
+ } else {
+ $applicableIDs = $ids;
+ }
+
+ $response = new SS_HTTPResponse(json_encode($applicableIDs));
+ $response->addHeader("Content-type", "application/json");
+ return $response;
+ }
+
+ function handleConfirmation($request) {
+ // Find the action handler
+ $actions = Object::get_static($this->class, 'batch_actions');
+ $actionClass = $actions[$request->param('BatchAction')];
+ $actionHandler = new $actionClass();
+
+ // Sanitise ID list and query the database for apges
+ $ids = split(' *, *', trim($request->requestVar('csvIDs')));
+ foreach($ids as $k => $id) $ids[$k] = (int)$id;
+ $ids = array_filter($ids);
+
+ if($actionHandler->hasMethod('confirmationDialog')) {
+ $response = new SS_HTTPResponse(json_encode($actionHandler->confirmationDialog($ids)));
+ } else {
+ $response = new SS_HTTPResponse(json_encode(array('alert' => false)));
+ }
+
+ $response->addHeader("Content-type", "application/json");
+ return $response;
+ }
+
+ /**
+ * Return a DataObjectSet of ArrayData objects containing the following pieces of info
+ * about each batch action:
+ * - Link
+ * - Title
+ */
+ function batchActionList() {
+ $actions = $this->batchActions();
+ $actionList = new DataObjectSet();
+
+ foreach($actions as $urlSegment => $action) {
+ $actionClass = $action['class'];
+ $actionObj = new $actionClass();
+ if($actionObj->canView()) {
+ $actionDef = new ArrayData(array(
+ "Link" => Controller::join_links($this->Link(), $urlSegment),
+ "Title" => $actionObj->getActionTitle(),
+ ));
+ $actionList->push($actionDef);
+ }
+ }
+
+ return $actionList;
+ }
+
+ /**
+ * Get all registered actions through the static defaults set by {@link register()}.
+ * Filters for the currently set {@link recordClass}.
+ *
+ * @return array See {@link register()} for the returned format.
+ */
+ function batchActions() {
+ $actions = Object::get_static($this->class, 'batch_actions');
+ if($actions) foreach($actions as $action) {
+ if($action['recordClass'] != $this->recordClass) unset($action);
+ }
+
+ return $actions;
+ }
+
+}
View
325 admin/code/CMSMenu.php
@@ -0,0 +1,325 @@
+<?php
+/**
+ * The object manages the main CMS menu. See {@link LeftAndMain::init()} for example usage.
+ *
+ * The menu will be automatically populated with menu items for subclasses of {@link LeftAndMain}.
+ * That is, for each class in the CMS that creates an administration panel, a CMS menu item will be created.
+ * The default configuration will also include a 'help' link to the SilverStripe user documentation.
+ *
+ * @package cms
+ * @subpackage content
+ */
+class CMSMenu extends Object implements IteratorAggregate, i18nEntityProvider
+{
+
+ /**
+ * An array of changes to be made to the menu items, in the order that the changes should be
+ * applied. Each item is a map in one of the two forms:
+ * - array('type' => 'add', 'item' => new CMSMenuItem(...) )
+ * - array('type' => 'remove', 'code' => 'codename' )
+ */
+ protected static $menu_item_changes = array();
+
+ /**
+ * Set to true if clear_menu() is called, to indicate that the default menu shouldn't be
+ * included
+ */
+ protected static $menu_is_cleared = false;
+
+ /**
+ * Generate CMS main menu items by collecting valid
+ * subclasses of {@link LeftAndMain}
+ */
+ public static function populate_menu() {
+ self::$menu_is_cleared = false;
+ }
+
+ /**
+ * Add Director rules for all of the CMS controllers.
+ */
+ public static function add_director_rules() {
+ array_map(array('self','add_director_rule_for_controller'), self::get_cms_classes());
+ }
+
+ /**
+ * Add a LeftAndMain controller to the CMS menu.
+ *
+ * @param string $controllerClass The class name of the controller
+ * @return The result of the operation
+ * @todo A director rule is added when a controller link is added, but it won't be removed
+ * when the item is removed. Functionality needed in {@link Director}.
+ */
+ public static function add_controller($controllerClass) {
+ if($menuItem = self::menuitem_for_controller($controllerClass)) {
+ self::add_menu_item_obj($controllerClass, $menuItem);
+ }
+ }
+
+ /**
+ * Return a CMSMenuItem to add the given controller to the CMSMenu
+ */
+ protected static function menuitem_for_controller($controllerClass) {
+ $urlBase = Object::get_static($controllerClass, 'url_base');
+ $urlSegment = Object::get_static($controllerClass, 'url_segment');
+ $menuPriority = Object::get_static($controllerClass, 'menu_priority');
+
+ // Don't add menu items defined the old way
+ if($urlSegment === null && $controllerClass != "CMSMain") return;
+
+ $link = Controller::join_links($urlBase, $urlSegment) . '/';
+
+ // doesn't work if called outside of a controller context (e.g. in _config.php)
+ // as the locale won't be detected properly. Use {@link LeftAndMain->MainMenu()} to update
+ // titles for existing menu entries
+ $defaultTitle = LeftAndMain::menu_title_for_class($controllerClass);
+ $menuTitle = _t("{$controllerClass}.MENUTITLE", $defaultTitle);
+
+ return new CMSMenuItem($menuTitle, $link, $controllerClass, $menuPriority);
+ }
+
+ /**
+ * Add the appropriate Director rules for the given controller.
+ */
+ protected static function add_director_rule_for_controller($controllerClass) {
+ $urlBase = Object::get_static($controllerClass, 'url_base');
+ $urlSegment = Object::get_static($controllerClass, 'url_segment');
+ $urlRule = Object::get_static($controllerClass, 'url_rule');
+ $urlPriority = Object::get_static($controllerClass, 'url_priority');
+
+ if($urlSegment || $controllerClass == "CMSMain") {
+ $link = Controller::join_links($urlBase, $urlSegment) . '/';
+
+ // Make director rule
+ if($urlRule[0] == '/') $urlRule = substr($urlRule,1);
+ $rule = $link . '/' . $urlRule; // the / will combine with the / on the end of $link to make a //
+ Director::addRules($urlPriority, array(
+ $rule => $controllerClass
+ ));
+ }
+ }
+
+ /**
+ * Add an arbitrary URL to the CMS menu.
+ *
+ * @param string $code A unique identifier (used to create a CSS ID and as it's key in {@link $menu_items}
+ * @param string $menuTitle The link's title in the CMS menu
+ * @param string $url The url of the link
+ * @param integer $priority The menu priority (sorting order) of the menu item. Higher priorities will be further left.
+ * @return boolean The result of the operation.
+ */
+ public static function add_link($code, $menuTitle, $url, $priority = -1) {
+ return self::add_menu_item($code, $menuTitle, $url, null, $priority);
+ }
+
+ /**
+ * Add a navigation item to the main administration menu showing in the top bar.
+ *
+ * uses {@link CMSMenu::$menu_items}
+ *
+ * @param string $code Unique identifier for this menu item (e.g. used by {@link replace_menu_item()} and
+ * {@link remove_menu_item}. Also used as a CSS-class for icon customization.
+ * @param string $menuTitle Localized title showing in the menu bar
+ * @param string $url A relative URL that will be linked in the menu bar.
+ * @param string $controllerClass The controller class for this menu, used to check permisssions.
+ * If blank, it's assumed that this is public, and always shown to users who
+ * have the rights to access some other part of the admin area.
+ * @return boolean Success
+ */
+ public static function add_menu_item($code, $menuTitle, $url, $controllerClass = null, $priority = -1) {
+ // If a class is defined, then force the use of that as a code. This helps prevent menu item duplication
+ if($controllerClass) $code = $controllerClass;
+
+ return self::replace_menu_item($code, $menuTitle, $url, $controllerClass, $priority);
+ }
+
+ /**
+ * Get a single menu item by its code value.
+ *
+ * @param string $code
+ * @return array
+ */
+ public static function get_menu_item($code) {
+ $menuItems = self::get_menu_items();
+ return (isset($menuItems[$code])) ? $menuItems[$code] : false;
+ }
+
+ /**
+ * Get all menu entries.
+ *
+ * @return array
+ */
+ public static function get_menu_items() {
+ $menuItems = array();
+
+ // Set up default menu items
+ if(!self::$menu_is_cleared) {
+ $cmsClasses = self::get_cms_classes();
+ foreach($cmsClasses as $cmsClass) {
+ $menuItem = self::menuitem_for_controller($cmsClass);
+ if($menuItem) $menuItems[$cmsClass] = $menuItem;
+ }
+ }
+
+ // Apply changes
+ foreach(self::$menu_item_changes as $change) {
+ switch($change['type']) {
+ case 'add':
+ $menuItems[$change['code']] = $change['item'];
+ break;
+
+ case 'remove':
+ unset($menuItems[$change['code']]);
+ break;
+
+ default:
+ user_error("Bad menu item change type {$change[type]}", E_USER_WARNING);
+ }
+ }
+
+ // Sort menu items according to priority
+ $menuPriority = array();
+ $i = 0;
+ foreach($menuItems as $key => $menuItem) {
+ $i++;
+ // This funny litle formula ensures that the first item added with the same priority will be left-most.
+ $menuPriority[$key] = $menuItem->priority*100 - $i;
+ }
+ array_multisort($menuPriority, SORT_DESC, $menuItems);
+
+ return $menuItems;
+ }
+
+ /**
+ * Get all menu items that the passed member can view.
+ * Defaults to {@link Member::currentUser()}.
+ *
+ * @param Member $member
+ * @return array
+ */
+ public static function get_viewable_menu_items($member = null) {
+ if(!$member && $member !== FALSE) {
+ $member = Member::currentUser();
+ }
+
+ $viewableMenuItems = array();
+ $allMenuItems = self::get_menu_items();
+ if($allMenuItems) foreach($allMenuItems as $code => $menuItem) {
+ // exclude all items which have a controller to perform permission
+ // checks on
+ if($menuItem->controller) {
+ $controllerObj = singleton($menuItem->controller);
+ // Necessary for canView() to have request data available,
+ // e.g. to check permissions against LeftAndMain->currentPage()
+ $controllerObj->setRequest(Controller::curr()->getRequest());
+ if(!$controllerObj->canView($member)) continue;
+ }
+
+ $viewableMenuItems[$code] = $menuItem;
+ }
+
+ return $viewableMenuItems;
+ }
+
+ /**
+ * Removes an existing item from the menu.
+ *
+ * @param string $code Unique identifier for this menu item
+ */
+ public static function remove_menu_item($code) {
+ self::$menu_item_changes[] = array('type' => 'remove', 'code' => $code);
+ }
+
+ /**
+ * Clears the entire menu
+ */
+ public static function clear_menu() {
+ self::$menu_item_changes = array();
+ self::$menu_is_cleared = true;
+ }
+
+ /**
+ * Replace a navigation item to the main administration menu showing in the top bar.
+ *
+ * @param string $code Unique identifier for this menu item (e.g. used by {@link replace_menu_item()} and
+ * {@link remove_menu_item}. Also used as a CSS-class for icon customization.
+ * @param string $menuTitle Localized title showing in the menu bar
+ * @param string $url A relative URL that will be linked in the menu bar.
+ * Make sure to add a matching route via {@link Director::addRules()} to this url.
+ * @param string $controllerClass The controller class for this menu, used to check permisssions.
+ * If blank, it's assumed that this is public, and always shown to users who
+ * have the rights to access some other part of the admin area.
+ * @return boolean Success
+ */
+ public static function replace_menu_item($code, $menuTitle, $url, $controllerClass = null, $priority = -1) {
+ self::$menu_item_changes[] = array(
+ 'type' => 'add',
+ 'code' => $code,
+ 'item' => new CMSMenuItem($menuTitle, $url, $controllerClass, $priority),
+ );
+ }
+
+ /**
+ * Add a previously built menuitem object to the menu
+ */
+ protected static function add_menu_item_obj($code, $cmsMenuItem) {
+ self::$menu_item_changes[] = array(
+ 'type' => 'add',
+ 'code' => $code,
+ 'item' => $cmsMenuItem,
+ );
+ }
+
+ /**
+ * A utility funciton to retrieve subclasses of a given class that
+ * are instantiable (ie, not abstract) and have a valid menu title.
+ *
+ * @todo A variation of this function could probably be moved to {@link ClassInfo}
+ * @param string $root The root class to begin finding subclasses
+ * @param boolean $recursive Look for subclasses recursively?
+ * @return array Valid, unique subclasses
+ */
+ public static function get_cms_classes($root = 'LeftAndMain', $recursive = true) {
+ $subClasses = array_values(ClassInfo::subclassesFor($root));
+ foreach($subClasses as $className) {
+ if($recursive && $className != $root) {
+ $subClasses = array_merge($subClasses, array_values(ClassInfo::subclassesFor($className)));
+ }
+ }
+ $subClasses = array_unique($subClasses);
+ foreach($subClasses as $key => $className) {
+ // Remove abstract classes and LeftAndMain
+ $classReflection = new ReflectionClass($className);
+ if(
+ !$classReflection->isInstantiable()
+ || 'LeftAndMain' == $className
+ || ClassInfo::classImplements($className, 'TestOnly')
+ ) {
+ unset($subClasses[$key]);
+ }
+ }
+
+ return $subClasses;
+ }
+
+ /**
+ * IteratorAggregate Interface Method. Iterates over the menu items.
+ */
+ function getIterator() {
+ return new ArrayIterator(self::get_menu_items());
+ }
+
+ /**
+ * Provide menu titles to the i18n entity provider
+ */
+ function provideI18nEntities() {
+ $cmsClasses = self::get_cms_classes();
+ $entities = array();
+ foreach($cmsClasses as $cmsClass) {
+ $defaultTitle = LeftAndMain::menu_title_for_class($cmsClass);
+ $ownerModule = i18n::get_owner_module($cmsClass);
+ $entities["{$cmsClass}.MENUTITLE"] = array($defaultTitle, PR_HIGH, 'Menu title', $ownerModule);
+ }
+ return $entities;
+ }
+}
+?>
View
50 admin/code/CMSMenuItem.php
@@ -0,0 +1,50 @@
+<?php
+/**
+ * A simple CMS menu item
+ *
+ * @package cms
+ * @subpackage content
+ */
+class CMSMenuItem extends Object
+{
+ /**
+ * The (translated) menu title
+ * @var string $title
+ */
+ public $title;
+
+ /**
+ * Relative URL
+ * @var string $url
+ */
+ public $url;
+
+ /**
+ * Parent controller class name
+ * @var string $controller
+ */
+ public $controller;
+
+ /**
+ * Menu priority (sort order)
+ * @var integer $priority
+ */
+ public $priority;
+
+ /**
+ * Create a new CMS Menu Item
+ * @param string $title
+ * @param string $url
+ * @param string $controller Controller class name
+ * @param integer $priority The sort priority of the item
+ */
+ public function __construct($title, $url, $controller = null, $priority = -1) {
+ $this->title = $title;
+ $this->url = $url;
+ $this->controller = $controller;
+ $this->priority = $priority;
+ parent::__construct();
+ }
+
+}
+?>
View
90 admin/code/GroupImportForm.php
@@ -0,0 +1,90 @@
+<?php
+/**
+ * Imports {@link Group} records by CSV upload, as defined in
+ * {@link GroupCsvBulkLoader}.
+ *
+ * @package cms
+ * @subpackage batchactions
+ */
+class GroupImportForm extends Form {
+
+ /**
+ * @var Group Optional group relation
+ */
+ protected $group;
+
+ function __construct($controller, $name, $fields = null, $actions = null, $validator = null) {
+ if(!$fields) {
+ $helpHtml = _t(
+ 'GroupImportForm.Help1',
+ '<p>Import one or more groups in <em>CSV</em> format (comma-separated values). <small><a href="#" class="toggle-advanced">Show advanced usage</a></small></p>'
+ );
+ $helpHtml .= _t(
+ 'GroupImportForm.Help2',
+'<div class="advanced">
+ <h4>Advanced usage</h4>
+ <ul>
+ <li>Allowed columns: <em>%s</em></li>
+ <li>Existing groups are matched by their unique <em>Code</em> value, and updated with any new values from the imported file</li>
+ <li>Group hierarchies can be created by using a <em>ParentCode</em> column.</li>
+ <li>Permission codes can be assigned by the <em>PermissionCode</em> column. Existing permission codes are not cleared.</li>
+ </ul>
+</div>');
+
+ $importer = new GroupCsvBulkLoader();
+ $importSpec = $importer->getImportSpec();
+ $helpHtml = sprintf($helpHtml, implode(', ', array_keys($importSpec['fields'])));
+
+ $fields = new FieldSet(
+ new LiteralField('Help', $helpHtml),
+ $fileField = new FileField(
+ 'CsvFile',
+ _t(
+ 'SecurityAdmin_MemberImportForm.FileFieldLabel',
+ 'CSV File <small>(Allowed extensions: *.csv)</small>'
+ )
+ )
+ );
+ $fileField->getValidator()->setAllowedExtensions(array('csv'));
+ }
+
+ if(!$actions) $actions = new FieldSet(
+ new FormAction('doImport', _t('SecurityAdmin_MemberImportForm.BtnImport', 'Import'))
+ );
+
+ if(!$validator) $validator = new RequiredFields('CsvFile');
+
+ parent::__construct($controller, $name, $fields, $actions, $validator);
+
+ $this->addExtraClass('import-form');
+ }
+
+ function doImport($data, $form) {
+ $loader = new GroupCsvBulkLoader();
+
+ // load file
+ $result = $loader->load($data['CsvFile']['tmp_name']);
+
+ // result message
+ $msgArr = array();
+ if($result->CreatedCount()) $msgArr[] = sprintf(
+ _t('GroupImportForm.ResultCreated', 'Created %d groups'),
+ $result->CreatedCount()
+ );
+ if($result->UpdatedCount()) $msgArr[] = sprintf(
+ _t('GroupImportForm.ResultUpdated', 'Updated %d groups'),
+ $result->UpdatedCount()
+ );
+ if($result->DeletedCount()) $msgArr[] = sprintf(
+ _t('GroupImportForm.ResultDeleted', 'Deleted %d groups'),
+ $result->DeletedCount()
+ );
+ $msg = ($msgArr) ? implode(',', $msgArr) : _t('MemberImportForm.ResultNone', 'No changes');
+
+ $this->sessionMessage($msg, 'good');
+
+ $this->redirectBack();
+ }
+
+}
+?>
View
1,329 admin/code/LeftAndMain.php
@@ -0,0 +1,1329 @@
+<?php
+/**
+ * LeftAndMain is the parent class of all the two-pane views in the CMS.
+ * If you are wanting to add more areas to the CMS, you can do it by subclassing LeftAndMain.
+ *
+ * This is essentially an abstract class which should be subclassed.
+ * See {@link CMSMain} for a good example.
+ *
+ * @package cms
+ * @subpackage core
+ */
+class LeftAndMain extends Controller {
+
+ /**
+ * The 'base' url for CMS administration areas.
+ * Note that if this is changed, many javascript
+ * behaviours need to be updated with the correct url
+ *
+ * @var string $url_base
+ */
+ static $url_base = "admin";
+
+ static $url_segment;
+
+ static $url_rule = '/$Action/$ID/$OtherID';
+
+ static $menu_title;
+
+ static $menu_priority = 0;
+
+ static $url_priority = 50;
+
+ /**
+ * @var string A subclass of {@link DataObject}.
+ * Determines what is managed in this interface,
+ * through {@link getEditForm()} and other logic.
+ */
+ static $tree_class = null;
+
+ /**
+ * The url used for the link in the Help tab in the backend
+ * Value can be overwritten if required in _config.php
+ */
+ static $help_link = 'http://userhelp.silverstripe.org';
+
+ static $allowed_actions = array(
+ 'index',
+ 'savetreenode',
+ 'getitem',
+ 'getsubtree',
+ 'myprofile',
+ 'printable',
+ 'show',
+ 'Member_ProfileForm',
+ 'EditorToolbar',
+ 'EditForm',
+ 'RootForm',
+ 'AddForm',
+ 'batchactions',
+ 'BatchActionsForm',
+ 'Member_ProfileForm',
+ );
+
+ /**
+ * Register additional requirements through the {@link Requirements class}.
+ * Used mainly to work around the missing "lazy loading" functionality
+ * for getting css/javascript required after an ajax-call (e.g. loading the editform).
+ *
+ * @var array $extra_requirements
+ */
+ protected static $extra_requirements = array(
+ 'javascript' => array(),
+ 'css' => array(),
+ 'themedcss' => array(),
+ );
+
+ /**
+ * @param Member $member
+ * @return boolean
+ */
+ function canView($member = null) {
+ if(!$member && $member !== FALSE) {
+ $member = Member::currentUser();
+ }
+
+ // cms menus only for logged-in members
+ if(!$member) return false;
+
+ // alternative decorated checks
+ if($this->hasMethod('alternateAccessCheck')) {
+ $alternateAllowed = $this->alternateAccessCheck();
+ if($alternateAllowed === FALSE) return false;
+ }
+
+ // Default security check for LeftAndMain sub-class permissions
+ if(!Permission::checkMember($member, "CMS_ACCESS_$this->class") &&
+ !Permission::checkMember($member, "CMS_ACCESS_LeftAndMain")) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @uses LeftAndMainDecorator->init()
+ * @uses LeftAndMainDecorator->accessedCMS()
+ * @uses CMSMenu
+ */
+ function init() {
+ parent::init();
+
+ SSViewer::setOption('rewriteHashlinks', false);
+
+ // set language
+ $member = Member::currentUser();
+ if(!empty($member->Locale)) i18n::set_locale($member->Locale);
+ if(!empty($member->DateFormat)) i18n::set_date_format($member->DateFormat);
+ if(!empty($member->TimeFormat)) i18n::set_time_format($member->TimeFormat);
+
+ // can't be done in cms/_config.php as locale is not set yet
+ CMSMenu::add_link(
+ 'Help',
+ _t('LeftAndMain.HELP', 'Help', PR_HIGH, 'Menu title'),
+ self::$help_link
+ );
+
+ // set reading lang
+ if(Object::has_extension('SiteTree', 'Translatable') && !$this->isAjax()) {
+ Translatable::choose_site_locale(array_keys(Translatable::get_existing_content_languages('SiteTree')));
+ }
+
+ // Allow customisation of the access check by a decorator
+ // Also all the canView() check to execute Director::redirect()
+ if(!$this->canView() && !$this->response->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()
+ ) {
+ return Director::redirect($candidate->Link);
+ }
+ }
+
+ if(Member::currentUser()) {
+ Session::set("BackURL", null);
+ }
+
+ // if no alternate menu items have matched, return a permission error
+ $messageSet = array(
+ 'default' => _t('LeftAndMain.PERMDEFAULT',"Please choose an authentication method and enter your credentials to access the CMS."),
+ '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."),
+ );
+
+ return Security::permissionFailure($this, $messageSet);
+ }
+
+ // Don't continue if there's already been a redirection request.
+ if(Director::redirected_to()) return;
+
+ // Audit logging hook
+ if(empty($_REQUEST['executeForm']) && !$this->isAjax()) $this->extend('accessedCMS');
+
+ // Set the members html editor config
+ HtmlEditorConfig::set_active(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());
+ if(!$htmlEditorConfig->getOption('content_css')) {
+ $cssFiles = 'cms/css/editor.css';
+
+ // Use theme from the site config
+ if(($config = SiteConfig::current_site_config()) && $config->Theme) {
+ $theme = $config->Theme;
+ } elseif(SSViewer::current_theme()) {
+ $theme = SSViewer::current_theme();
+ } else {
+ $theme = false;
+ }
+
+ if($theme) $cssFiles .= ',' . THEMES_DIR . "/{$theme}/css/editor.css";
+ else if(project()) $cssFiles .= ',' . project() . '/css/editor.css';
+
+ $htmlEditorConfig->setOption('content_css', $cssFiles);
+ }
+
+
+ Requirements::css(CMS_DIR . '/css/typography.css');
+ Requirements::css(CMS_DIR . '/css/layout.css');
+ Requirements::css(CMS_DIR . '/css/cms_left.css');
+ Requirements::css(CMS_DIR . '/css/cms_right.css');
+ Requirements::css(SAPPHIRE_DIR . '/css/Form.css');
+
+ if(isset($_REQUEST['debug_firebug'])) {
+ // Firebug is a useful console for debugging javascript
+ // Its available as a Firefox extension or a javascript library
+ // for easy inclusion in other browsers (just append ?debug_firebug=1 to the URL)
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/firebug-lite/firebug.js');
+ }
+
+ Requirements::javascript(SAPPHIRE_DIR . '/javascript/prototypefix/intro.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/prototype/prototype.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/javascript/prototypefix/outro.js');
+
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery/jquery.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/javascript/jquery_improvements.js');
+
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-ui/jquery-ui.js'); //import all of jquery ui
+
+ Requirements::javascript(CMS_DIR . '/thirdparty/jquery-layout/jquery.layout.js');
+ Requirements::javascript(CMS_DIR . '/thirdparty/jquery-layout/jquery.layout.state.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/json-js/json2.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-metadata/jquery.metadata.js');
+ Requirements::javascript(CMS_DIR . '/javascript/jquery-fitheighttoparent/jquery.fitheighttoparent.js');
+
+ Requirements::javascript(CMS_DIR . '/javascript/ssui.core.js');
+ // @todo Load separately so the CSS files can be inlined
+ Requirements::css(SAPPHIRE_DIR . '/thirdparty/jquery-ui-themes/smoothness/jquery.ui.all.css');
+
+ // entwine
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-entwine/dist/jquery.entwine-dist.js');
+
+ // Required for TreeTools panel above tree
+ Requirements::javascript(SAPPHIRE_DIR . '/javascript/TabSet.js');
+
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/behaviour/behaviour.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-cookie/jquery.cookie.js');
+ Requirements::javascript(CMS_DIR . '/thirdparty/jquery-notice/jquery.notice.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/javascript/jquery-ondemand/jquery.ondemand.js');
+ Requirements::javascript(CMS_DIR . '/javascript/jquery-changetracker/lib/jquery.changetracker.js');
+ Requirements::add_i18n_javascript(SAPPHIRE_DIR . '/javascript/lang');
+ Requirements::add_i18n_javascript(CMS_DIR . '/javascript/lang');
+
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/scriptaculous/effects.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/scriptaculous/dragdrop.js');
+ Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/scriptaculous/controls.js');
+
+ Requirements::javascript(THIRDPARTY_DIR . '/tree/tree.js');
+ Requirements::css(THIRDPARTY_DIR . '/tree/tree.css');
+ Requirements::javascript(THIRDPARTY_DIR . '/jstree/jquery.jstree.js');
+ Requirements::css(THIRDPARTY_DIR . '/jstree/themes/apple/style.css');
+
+ Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.js');
+ Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.Tree.js');
+ Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.EditForm.js');
+ Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.AddForm.js');
+ Requirements::javascript(CMS_DIR . '/javascript/LeftAndMain.BatchActions.js');
+
+ // navigator
+ Requirements::css(CMS_DIR . '/css/SilverStripeNavigator.css');
+ Requirements::javascript(CMS_DIR . '/javascript/SilverStripeNavigator.js');
+
+ Requirements::themedCSS('typography');
+
+ foreach (self::$extra_requirements['javascript'] as $file) {
+ Requirements::javascript($file[0]);
+ }
+
+ foreach (self::$extra_requirements['css'] as $file) {
+ Requirements::css($file[0], $file[1]);
+ }
+
+ foreach (self::$extra_requirements['themedcss'] as $file) {
+ Requirements::themedCSS($file[0], $file[1]);
+ }
+
+ Requirements::css(CMS_DIR . '/css/unjquery.css');
+
+ // Javascript combined files
+ Requirements::combine_files(
+ 'base.js',
+ array(
+ 'sapphire/thirdparty/prototype/prototype.js',
+ 'sapphire/thirdparty/behaviour/behaviour.js',
+ 'sapphire/thirdparty/jquery/jquery.js',
+ 'sapphire/thirdparty/jquery-livequery/jquery.livequery.js',
+ 'sapphire/javascript/jquery-ondemand/jquery.ondemand.js',
+ 'sapphire/thirdparty/jquery-ui/jquery-ui.js',
+ 'sapphire/thirdparty/firebug-lite/firebug.js',
+ 'sapphire/thirdparty/firebug-lite/firebugx.js',
+ 'sapphire/javascript/i18n.js',
+ )
+ );
+
+ Requirements::combine_files(
+ 'leftandmain.js',
+ array(
+ 'sapphire/thirdparty/scriptaculous/effects.js',
+ 'sapphire/thirdparty/scriptaculous/dragdrop.js',
+ 'sapphire/thirdparty/scriptaculous/controls.js',
+ 'cms/javascript/LeftAndMain.js',
+ 'sapphire/javascript/tree/tree.js',
+ 'sapphire/javascript/TreeDropdownField.js',
+ 'cms/javascript/ThumbnailStripField.js',
+ )
+ );
+
+ $dummy = null;
+ $this->extend('init', $dummy);
+
+ // The user's theme shouldn't affect the CMS, if, for example, they have replaced
+ // TableListField.ss or Form.ss.
+ SSViewer::set_theme(null);
+ }
+
+
+ /**
+ * If this is set to true, the "switchView" context in the
+ * template is shown, with links to the staging and publish site.
+ *
+ * @return boolean
+ */
+ 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.
+ *
+ * @return string
+ */
+ public function Link($action = null) {
+ // Handle missing url_segments
+ if(!$this->stat('url_segment', true))
+ self::$url_segment = $this->class;
+ return Controller::join_links(
+ $this->stat('url_base', true),
+ $this->stat('url_segment', true),
+ '/', // trailing slash needed if $action is null!
+ "$action"
+ );
+ }
+
+ /**
+ * Returns the menu title for the given LeftAndMain subclass.
+ * Implemented static so that we can get this value without instantiating an object.
+ * Menu title is *not* internationalised.
+ */
+ static function menu_title_for_class($class) {
+ $title = eval("return $class::\$menu_title;");
+ if(!$title) $title = preg_replace('/Admin$/', '', $class);
+ return $title;
+ }
+
+ public function show($request) {
+ // TODO Necessary for TableListField URLs to work properly
+ if($request->param('ID')) $this->setCurrentPageID($request->param('ID'));
+
+ if($this->isAjax()) {
+ SSViewer::setOption('rewriteHashlinks', false);
+ $form = $this->getEditForm($request->param('ID'));
+ $content = $form->formHtmlContent();
+ } else {
+ // Rendering is handled by template, which will call EditForm() eventually
+ $content = $this->renderWith($this->getViewer('show'));
+ }
+
+ if($this->ShowSwitchView()) {
+ $content .= '<div id="AjaxSwitchView">' . $this->SwitchView() . '</div>';
+ }
+
+ return $content;
+ }
+
+ /**
+ * @deprecated 2.4 Please use show()
+ */
+ public function getitem($request) {
+ $form = $this->getEditForm($request->getVar('ID'));
+ return $form->formHtmlContent();
+ }
+
+ //------------------------------------------------------------------------------------------//
+ // Main UI components
+
+ /**
+ * Returns the main menu of the CMS. This is also used by init()
+ * to work out which sections the user has access to.
+ *
+ * @return DataObjectSet
+ */
+ public function MainMenu() {
+ // Don't accidentally return a menu if you're not logged in - it's used to determine access.
+ if(!Member::currentUser()) return new DataObjectSet();
+
+ // Encode into DO set
+ $menu = new DataObjectSet();
+ $menuItems = CMSMenu::get_viewable_menu_items();
+ if($menuItems) foreach($menuItems as $code => $menuItem) {
+ // alternate permission checks (in addition to LeftAndMain->canView())
+ if(
+ isset($menuItem->controller)
+ && $this->hasMethod('alternateMenuDisplayCheck')
+ && !$this->alternateMenuDisplayCheck($menuItem->controller)
+ ) {
+ continue;
+ }
+
+ $linkingmode = "";
+
+ if(strpos($this->Link(), $menuItem->url) !== false) {
+ if($this->Link() == $menuItem->url) {
+ $linkingmode = "current";
+
+ // default menu is the one with a blank {@link url_segment}
+ } else if(singleton($menuItem->controller)->stat('url_segment') == '') {
+ if($this->Link() == $this->stat('url_base').'/') $linkingmode = "current";
+
+ } else {
+ $linkingmode = "current";
+ }
+ }
+
+ // 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,
+ // we simply call LeftAndMain::menu_title_for_class() again
+ // if we're dealing with a controller
+ if($menuItem->controller) {
+ $defaultTitle = LeftAndMain::menu_title_for_class($menuItem->controller);
+ $title = _t("{$menuItem->controller}.MENUTITLE", $defaultTitle);
+ } else {
+ $title = $menuItem->title;
+ }
+
+ $menu->push(new ArrayData(array(
+ "MenuItem" => $menuItem,
+ "Title" => Convert::raw2xml($title),
+ "Code" => $code,
+ "Link" => $menuItem->url,
+ "LinkingMode" => $linkingmode
+ )));
+ }
+
+ // if no current item is found, assume that first item is shown
+ //if(!isset($foundCurrent))
+ return $menu;
+ }
+
+ public function CMSTopMenu() {
+ return $this->renderWith(array('CMSTopMenu_alternative','CMSTopMenu'));
+ }
+
+ /**
+ * Return a list of appropriate templates for this class, with the given suffix
+ */
+ protected function getTemplatesWithSuffix($suffix) {
+ $classes = array_reverse(ClassInfo::ancestry($this->class));
+ foreach($classes as $class) {
+ $templates[] = $class . $suffix;
+ if($class == 'LeftAndMain') break;
+ }
+ return $templates;
+ }
+
+ public function Left() {
+ return $this->renderWith($this->getTemplatesWithSuffix('_left'));
+ }
+
+ public function Right() {
+ return $this->renderWith($this->getTemplatesWithSuffix('_right'));
+ }
+
+ public function getRecord($id) {
+ $className = $this->stat('tree_class');
+ if($id instanceof $className) {
+ return $id;
+ } else if(is_numeric($id)) {
+ return DataObject::get_by_id($className, $id);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * @return String HTML
+ */
+ public function SiteTreeAsUL() {
+ return $this->getSiteTreeFor($this->stat('tree_class'));
+ }
+
+ /**
+ * Get a site tree HTML listing which displays the nodes under the given criteria.
+ *
+ * @param $className The class of the root object
+ * @param $rootID The ID of the root object. If this is null then a complete tree will be
+ * shown
+ * @param $childrenMethod The method to call to get the children of the tree. For example,
+ * Children, AllChildrenIncludingDeleted, or AllHistoricalChildren
+ * @return String Nested unordered list with links to each page
+ */
+ function getSiteTreeFor($className, $rootID = null, $childrenMethod = null, $numChildrenMethod = null, $filterFunction = null, $minNodeCount = 30) {
+ // Default childrenMethod and numChildrenMethod
+ if (!$childrenMethod) $childrenMethod = 'AllChildrenIncludingDeleted';
+ if (!$numChildrenMethod) $numChildrenMethod = 'numChildren';
+
+ // Get the tree root
+ $obj = $rootID ? $this->getRecord($rootID) : singleton($className);
+
+ // Mark the nodes of the tree to return
+ if ($filterFunction) $obj->setMarkingFilterFunction($filterFunction);
+
+ $obj->markPartialTree($minNodeCount, $this, $childrenMethod, $numChildrenMethod);
+
+ // Ensure current page is exposed
+ if($p = $this->currentPage()) $obj->markToExpose($p);
+
+ // NOTE: SiteTree/CMSMain coupling :-(
+ SiteTree::prepopuplate_permission_cache('CanEditType', $obj->markedNodeIDs(), 'SiteTree::can_edit_multiple');
+
+ // getChildrenAsUL is a flexible and complex way of traversing the tree
+ $titleEval = '
+ "<li id=\"record-$child->ID\" data-id=\"$child->ID\" class=\"" . $child->CMSTreeClasses($extraArg) . "\">" .
+ "<ins class=\"jstree-icon\">&nbsp;</ins>" .
+ "<a href=\"" . Controller::join_links(substr($extraArg->Link(),0,-1), "show", $child->ID) . "\" title=\"'
+ . _t('LeftAndMain.PAGETYPE','Page type: ')
+ . '".$child->class."\" ><ins class=\"jstree-icon\">&nbsp;</ins>" . ($child->TreeTitle) .
+ "</a>"
+ ';
+
+ $html = $obj->getChildrenAsUL(
+ "",
+ $titleEval,
+ $this,
+ true,
+ $childrenMethod,
+ $numChildrenMethod,
+ $minNodeCount
+ );
+
+ // Wrap the root if needs be.
+ if(!$rootID) {
+ $rootLink = $this->Link('show') . '/root';
+
+ // This lets us override the tree title with an extension
+ if($this->hasMethod('getCMSTreeTitle') && $customTreeTitle = $this->getCMSTreeTitle()) {
+ $treeTitle = $customTreeTitle;
+ } else {
+ $siteConfig = SiteConfig::current_site_config();
+ $treeTitle = $siteConfig->Title;
+ }
+
+ $html = "<ul id=\"sitetree\" class=\"tree unformatted\"><li id=\"record-0\" data-id=\"0\"class=\"Root nodelete\"><a href=\"$rootLink\"><strong>$treeTitle</strong></a>"
+ . $html . "</li></ul>";
+ }
+
+ return $html;
+ }
+
+ /**
+ * Get a subtree underneath the request param 'ID'.
+ * If ID = 0, then get the whole tree.
+ */
+ public function getsubtree($request) {
+ if($filterClass = $request->requestVar('FilterClass')) {
+ if(!is_subclass_of($filterClass, 'CMSSiteTreeFilter')) {
+ throw new Exception(sprintf('Invalid filter class passed: %s', $filterClass));
+ }
+
+ $filter = new $filterClass($request->requestVars());
+ } else {
+ $filter = null;
+ }
+
+ $html = $this->getSiteTreeFor(
+ $this->stat('tree_class'),
+ $request->getVar('ID'),
+ ($filter) ? $filter->getChildrenMethod() : null,
+ null,
+ ($filter) ? array($filter, 'isPageIncluded') : null,
+ $request->getVar('minNodeCount')
+ );
+
+ // Trim off the outer tag
+ $html = preg_replace('/^[\s\t\r\n]*<ul[^>]*>/','', $html);
+ $html = preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/','', $html);
+
+ return $html;
+ }
+
+ /**
+ * Save handler
+ */
+ public function save($data, $form) {
+ $className = $this->stat('tree_class');
+
+ // Existing or new record?
+ $SQL_id = Convert::raw2sql($data['ID']);
+ if(substr($SQL_id,0,3) != 'new') {
+ $record = DataObject::get_by_id($className, $SQL_id);
+ if($record && !$record->canEdit()) return Security::permissionFailure($this);
+ } else {
+ if(!singleton($this->stat('tree_class'))->canCreate()) return Security::permissionFailure($this);
+ $record = $this->getNewItem($SQL_id, false);
+ }
+
+ // save form data into record
+ $form->saveInto($record, true);
+ $record->write();
+ $this->extend('onAfterSave', $record);
+
+ $this->response->addHeader('X-Status', _t('LeftAndMain.SAVEDUP'));
+
+ // write process might've changed the record, so we reload before returning
+ $form = $this->getEditForm($record->ID);
+
+ return $form->formHtmlContent();
+ }
+
+ /**
+ * Update the position and parent of a tree node.
+ * Only saves the node if changes were made.
+ *
+ * Required data:
+ * - 'ID': The moved node
+ * - 'ParentID': New parent relation of the moved node (0 for root)
+ * - '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.
+ *
+ * @return SS_HTTPResponse JSON string with a
+ */
+ public function savetreenode($request) {
+ if (!Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN')) {
+ $this->response->setStatusCode(
+ 403,
+ _t('LeftAndMain.CANT_REORGANISE',"You do not have permission to rearange the site tree. Your change was not saved.")
+ );
+ return;
+ }
+
+ $className = $this->stat('tree_class');
+ $statusUpdates = array('modified'=>array());
+ $id = $request->requestVar('ID');
+ $parentID = $request->requestVar('ParentID');
+ $siblingIDs = $request->requestVar('SiblingIDs');
+ $statusUpdates = array('modified'=>array());
+ if(!is_numeric($id) || !is_numeric($parentID)) throw new InvalidArgumentException();
+
+ $node = DataObject::get_by_id($className, $id);
+ if($node && !$node->canEdit()) return Security::permissionFailure($this);
+
+ if(!$node) {
+ $this->response->setStatusCode(
+ 500,
+ _t(
+ 'LeftAndMain.PLEASESAVE',
+ "Please Save Page: This page could not be upated because it hasn't been saved yet."
+ )
+ );
+ return;
+ }
+
+ // Update hierarchy (only if ParentID changed)
+ if($node->ParentID != $parentID) {
+ $node->ParentID = (int)$parentID;
+ $node->write();
+
+ $statusUpdates['modified'][$node->ID] = array(
+ 'TreeTitle'=>$node->TreeTitle
+ );
+
+ // Update all dependent pages
+ if($virtualPages = DataObject::get("VirtualPage", "\"CopyContentFromID\" = $node->ID")) {
+ foreach($virtualPages as $virtualPage) {
+ $statusUpdates['modified'][$virtualPage->ID] = array(
+ 'TreeTitle' => $virtualPage->TreeTitle()
+ );
+ }
+ }
+
+ $this->response->addHeader('X-Status', _t('LeftAndMain.SAVED','saved'));
+ }
+
+ // Update sorting
+ if(is_array($siblingIDs)) {
+ $counter = 0;
+ foreach($siblingIDs as $id) {
+ if($id == $node->ID) {
+ $node->Sort = ++$counter;
+ $node->write();
+ $statusUpdates['modified'][$node->ID] = array(
+ 'TreeTitle' => $node->TreeTitle
+ );
+ } else if(is_numeric($id)) {
+ // Nodes that weren't "actually moved" shouldn't be registered as
+ // having been edited; do a direct SQL update instead
+ ++$counter;
+ DB::query(sprintf("UPDATE \"%s\" SET \"Sort\" = %d WHERE \"ID\" = '%d'", $className, $counter, $id));
+ }
+ }
+
+ $this->response->addHeader('X-Status', _t('LeftAndMain.SAVED','saved'));
+ }
+
+ return Convert::raw2json($statusUpdates);
+ }
+
+ public function CanOrganiseSitetree() {
+ return !Permission::check('SITETREE_REORGANISE') && !Permission::check('ADMIN') ? false : true;
+ }
+
+ /**
+ * 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.
+ *
+ * This is a "pseudo-abstract" methoed, usually connected to a {@link getEditForm()}
+ * method in an entwine subclass. This method can accept a record identifier,
+ * selected either in custom logic, or through {@link currentPageID()}.
+ * The form usually construct itself from {@link DataObject->getCMSFields()}
+ * for the specific managed subclass defined in {@link LeftAndMain::$tree_class}.
+ *
+ * @param HTTPRequest $request Optionally contains an identifier for the
+ * record to load into the form.
+ * @return Form Should return a form regardless wether a record has been found.
+ * Form might be readonly if the current user doesn't have the permission to edit
+ * the record.
+ */
+ /**
+ * @return Form
+ */
+ function EditForm($request = null) {
+ return $this->getEditForm();
+ }
+
+ public function getEditForm($id = null) {
+ if(!$id) $id = $this->currentPageID();
+
+ if(is_object($id)) {
+ $record = $id;
+ } else {
+ $record = ($id && $id != "root") ? $this->getRecord($id) : null;
+ if($record && !$record->canView()) return Security::permissionFailure($this);
+ }
+
+ if($record) {
+ $fields = $record->getCMSFields();
+ if ($fields == null) {
+ user_error(
+ "getCMSFields() returned null - it should return a FieldSet object.
+ Perhaps you forgot to put a return statement at the end of your method?",
+ E_USER_ERROR
+ );
+ }
+
+ // Add hidden fields which are required for saving the record
+ // and loading the UI state
+ if(!$fields->dataFieldByName('ClassName')) {
+ $fields->push(new HiddenField('ClassName'));
+ }
+ if(
+ Object::has_extension($this->stat('tree_class'), 'Hierarchy')
+ && !$fields->dataFieldByName('ParentID')
+ ) {
+ $fields->push(new HiddenField('ParentID'));
+ }
+
+ if($record->hasMethod('getAllCMSActions')) {
+ $actions = $record->getAllCMSActions();
+ } else {
+ $actions = $record->getCMSActions();
+ // add default actions if none are defined
+ if(!$actions || !$actions->Count()) {
+ if($record->canEdit()) {
+ $actions->push(new FormAction('save',_t('CMSMain.SAVE','Save')));
+ }
+ }
+ }
+
+ $form = new Form($this, "EditForm", $fields, $actions);
+ $form->loadDataFrom($record);
+
+ // 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.
+ $validator->setJavascriptValidationHandler('prototype');
+ $form->setValidator($validator);
+ } else {
+ $form->unsetValidator();
+ }
+
+ if(!$record->canEdit()) {
+ $readonlyFields = $form->Fields()->makeReadonly();
+ $form->setFields($readonlyFields);
+ }
+ } else {
+ $form = $this->RootForm();
+ }
+
+ return $form;
+ }
+
+ function RootForm() {
+ return $this->EmptyForm();
+ }
+
+ /**
+ * 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
+ */
+ function EmptyForm() {
+ $form = new Form(
+ $this,
+ "EditForm",
+ new FieldSet(
+ 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 FieldSet()
+ );
+ $form->unsetValidator();
+
+ return $form;
+ }
+
+ /**
+ * @return Form
+ */
+ function AddForm() {
+ $class = $this->stat('tree_class');
+
+ $typeMap = array($class => singleton($class)->i18n_singular_name());
+ $typeField = new DropdownField('Type', false, $typeMap, $class);
+ $form = new Form(
+ $this,
+ 'AddForm',
+ new FieldSet(
+ new HiddenField('ParentID'),
+ $typeField->performReadonlyTransformation()
+ ),
+ new FieldSet(
+ new FormAction('doAdd', _t('AssetAdmin_left.ss.GO','Go'))
+ )
+ );
+ $form->addExtraClass('actionparams');
+
+ return $form;
+ }
+
+ /**
+ * Add a new group and return its details suitable for ajax.
+ */
+ public function doAdd($data, $form) {
+ $class = $this->stat('tree_class');
+
+ // check create permissions
+ if(!singleton($class)->canCreate()) return Security::permissionFailure($this);
+
+ // check addchildren permissions
+ if(
+ singleton($class)->hasDatabaseField('Hierarchy')
+ && isset($data['ParentID'])
+ && is_numeric($data['ParentID'])
+ ) {
+ $parentRecord = DataObject::get_by_id($class, $data['ParentID']);
+ if(
+ $parentRecord->hasMethod('canAddChildren')
+ && !$parentRecord->canAddChildren()
+ ) return Security::permissionFailure($this);
+ }
+
+ $record = Object::create($class);
+ $form->saveInto($record);
+ $record->write();
+
+ // Used in TinyMCE inline folder creation
+ if(isset($data['returnID'])) {
+ return $record->ID;
+ } else if($this->isAjax()) {
+ $form = $this->getEditForm($record->ID);
+ return $form->formHtmlContent();
+ } else {
+ return $this->redirect(Controller::join_links($this->Link('show'), $record->ID));
+ }
+ }
+
+ /**
+ * Batch Actions Handler
+ */
+ function batchactions() {
+ return new CMSBatchActionHandler($this, 'batchactions', $this->stat('tree_class'));
+ }
+
+ /**
+ * @return Form
+ */
+ function BatchActionsForm() {
+ $actions = $this->batchactions()->batchActionList();
+ $actionsMap = array();
+ foreach($actions as $action) $actionsMap[$action->Link] = $action->Title;
+
+ $form = new Form(
+ $this,
+ 'BatchActionsForm',
+ new FieldSet(
+ new LiteralField(
+ 'Intro',
+ sprintf('<p><small>%s</small></p>',
+ _t(
+ 'CMSMain_left.ss.SELECTPAGESACTIONS',
+ 'Select the pages that you want to change &amp; then click an action:'
+ )
+ )
+ ),
+ new HiddenField('csvIDs'),
+ new DropdownField(
+ 'Action',
+ false,
+ $actionsMap
+ )
+ ),
+ new FieldSet(
+ // TODO i18n
+ new FormAction('submit', "Go")
+ )
+ );
+ $form->addExtraClass('actionparams');
+ $form->unsetValidator();
+
+ return $form;
+ }
+
+ public function myprofile() {
+ $form = $this->Member_ProfileForm();
+ return $this->customise(array(
+ 'Form'