diff --git a/_config.php b/_config.php
index 7a7f03db..a44c8e70 100644
--- a/_config.php
+++ b/_config.php
@@ -6,8 +6,7 @@
* @package cms
*/
Director::addRules(50, array(
- 'processes//$Action/$ID/$Batch' => 'BatchProcess_Controller',
- 'admin/help//$Action/$ID' => 'CMSHelp',
+ '' => 'RootURLController',
'admin/bulkload//$Action/$ID/$OtherID' => 'BulkLoaderAdmin',
'admin/cms//$Action/$ID/$OtherID' => 'CMSMain',
'dev/buildcache/$Action' => 'RebuildStaticCacheTask',
@@ -17,36 +16,6 @@ Director::addRules(1, array(
'$URLSegment//$Action/$ID/$OtherID' => 'ModelAsController',
));
-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');
-
// Register default side reports
SS_Report::register("SideReport", "SideReport_EmptyPages");
SS_Report::register("SideReport", "SideReport_RecentlyEdited");
diff --git a/code/CMSMenu.php b/code/CMSMenu.php
deleted file mode 100644
index e13e7eff..00000000
--- a/code/CMSMenu.php
+++ /dev/null
@@ -1,325 +0,0 @@
- '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;
- }
-}
-?>
\ No newline at end of file
diff --git a/code/CMSMenuItem.php b/code/CMSMenuItem.php
deleted file mode 100644
index 4a6cd654..00000000
--- a/code/CMSMenuItem.php
+++ /dev/null
@@ -1,50 +0,0 @@
-title = $title;
- $this->url = $url;
- $this->controller = $controller;
- $this->priority = $priority;
- parent::__construct();
- }
-
-}
-?>
\ No newline at end of file
diff --git a/code/GroupImportForm.php b/code/GroupImportForm.php
deleted file mode 100644
index 3cab0c7d..00000000
--- a/code/GroupImportForm.php
+++ /dev/null
@@ -1,90 +0,0 @@
-Import one or more groups in CSV format (comma-separated values). Show advanced usage
Existing groups are matched by their unique Code value, and updated with any new values from the imported file
-
Group hierarchies can be created by using a ParentCode column.
-
Permission codes can be assigned by the PermissionCode column. Existing permission codes are not cleared.
-
-
');
-
- $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 (Allowed extensions: *.csv)'
- )
- )
- );
- $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();
- }
-
-}
-?>
\ No newline at end of file
diff --git a/code/LeftAndMain.php b/code/LeftAndMain.php
deleted file mode 100644
index aac218e2..00000000
--- a/code/LeftAndMain.php
+++ /dev/null
@@ -1,1325 +0,0 @@
- 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(class_exists('Translatable') && 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 . '/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/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/thirdparty/jstree/jquery.jstree.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 .= '
' . $this->SwitchView() . '
';
- }
-
- 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 = '
- "
";
- }
-
- 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]*
]*>/','', $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('
%s %s. %s
',
- _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('
%s
',
- _t(
- 'CMSMain_left.ss.SELECTPAGESACTIONS',
- 'Select the pages that you want to change & 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' => $form
- ))->renderWith('BlankPage');
- }
-
- public function Member_ProfileForm() {
- return new Member_ProfileForm($this, 'Member_ProfileForm', Member::currentUser());
- }
-
- public function printable() {
- $form = $this->getEditForm($this->currentPageID());
- if(!$form) return false;
-
- $form->transform(new PrintableTransformation());
- $form->setActions(null);
-
- Requirements::clear();
- Requirements::css(CMS_DIR . '/css/LeftAndMain_printable.css');
- return array(
- "PrintForm" => $form
- );
- }
-
- /**
- * 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->request->requestVar('ID')) {
- return $this->request->requestVar('ID');
- } elseif ($this->request->param('ID') && is_numeric($this->request->param('ID'))) {
- return $this->request->param('ID');
- } elseif(Session::get("{$this->class}.currentPage")) {
- return Session::get("{$this->class}.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) {
- Session::set("{$this->class}.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.
- *
- * @return boolean
- */
- public function isCurrentPage(DataObject $record) {
- return ($record->ID == $this->currentPageID());
- }
-
- /**
- * Get the staus of a certain page and version.
- *
- * This function is used for concurrent editing, and providing alerts
- * when multiple users are editing a single page. It echoes a json
- * encoded string to the UA.
- */
-
- /**
- * Return the CMS's HTML-editor toolbar
- */
- public function EditorToolbar() {
- return Object::create('HtmlEditorField_Toolbar', $this, "EditorToolbar");
- }
-
- /**
- * Return the version number of this application.
- * Uses the subversion path information in /silverstripe_version
- * (automacially replaced $URL$ placeholder).
- *
- * @return string
- */
- public function CMSVersion() {
- $sapphireVersionFile = file_get_contents(BASE_PATH . '/sapphire/silverstripe_version');
- $cmsVersionFile = file_get_contents(BASE_PATH . '/cms/silverstripe_version');
-
- $sapphireVersion = $this->versionFromVersionFile($sapphireVersionFile);
- $cmsVersion = $this->versionFromVersionFile($cmsVersionFile);
-
- return "cms: $cmsVersion, sapphire: $sapphireVersion";
- }
-
- /**
- * Return the version from the content of a silverstripe_version file
- */
- public function versionFromVersionFile($fileContent) {
- if(preg_match('/\/trunk\/silverstripe_version/', $fileContent)) {
- return "trunk";
- } else {
- preg_match("/\/(?:branches|tags\/rc|tags\/beta|tags\/alpha|tags)\/([A-Za-z0-9._-]+)\/silverstripe_version/", $fileContent, $matches);
- return ($matches) ? $matches[1] : null;
- }
- }
-
- /**
- * @return array
- */
- function SwitchView() {
- if($page = $this->currentPage()) {
- $nav = SilverStripeNavigator::get_for_record($page);
- return $nav['items'];
- }
- }
-
- /**
- * The application name. Customisable by calling
- * LeftAndMain::setApplicationName() - the first parameter.
- *
- * @var String
- */
- static $application_name = 'SilverStripe CMS';
-
- /**
- * The application logo text. Customisable by calling
- * LeftAndMain::setApplicationName() - the second parameter.
- *
- * @var String
- */
- static $application_logo_text = 'SilverStripe';
-
- /**
- * Set the application name, and the logo text.
- *
- * @param String $name The application name
- * @param String $logoText The logo text
- */
- static $application_link = "http://www.silverstripe.org/";
-
- /**
- * @param String $name
- * @param String $logoText
- * @param String $link (Optional)
- */
- static function setApplicationName($name, $logoText = null, $link = null) {
- self::$application_name = $name;
- self::$application_logo_text = $logoText ? $logoText : $name;
- if($link) self::$application_link = $link;
- }
-
- /**
- * Get the application name.
- * @return String
- */
- function getApplicationName() {
- return self::$application_name;
- }
-
- /**
- * Get the application logo text.
- * @return String
- */
- function getApplicationLogoText() {
- return self::$application_logo_text;
- }
-
- /**
- * @return String
- */
- function ApplicationLink() {
- return self::$application_link;
- }
-
- /**
- * Return the title of the current section, as shown on the main menu
- */
- function SectionTitle() {
- // Get menu - use obj() to cache it in the same place as the template engine
- $menu = $this->obj('MainMenu');
-
- foreach($menu as $menuItem) {
- if($menuItem->LinkingMode == 'current') return $menuItem->Title;
- }
- }
-
- /**
- * The application logo path. Customisable by calling
- * LeftAndMain::setLogo() - the first parameter.
- *
- * @var unknown_type
- */
- static $application_logo = 'cms/images/mainmenu/logo.gif';
-
- /**
- * The application logo style. Customisable by calling
- * LeftAndMain::setLogo() - the second parameter.
- *
- * @var String
- */
- static $application_logo_style = '';
-
- /**
- * Set the CMS application logo.
- *
- * @param String $logo Relative path to the logo
- * @param String $logoStyle Custom CSS styles for the logo
- * e.g. "border: 1px solid red; padding: 5px;"
- */
- static function setLogo($logo, $logoStyle) {
- self::$application_logo = $logo;
- self::$application_logo_style = $logoStyle;
- self::$application_logo_text = '';
- }
-
- /**
- * The height of the image should be around 164px to avoid the overlaping between the image and loading animation graphic.
- * If the given image's height is significantly larger or smaller, adjust the loading animation's top offset in
- * positionLoadingSpinner() in LeftAndMain.js
- */
- protected static $loading_image = 'cms/images/logo.gif';
-
- /**
- * Set the image shown when the CMS is loading.
- */
- static function set_loading_image($loadingImage) {
- self::$loading_image = $loadingImage;
- }
-
- function LoadingImage() {
- return self::$loading_image;
- }
-
- /**
- * Combines an optional background image and additional CSS styles,
- * set through {@link setLogo()}.
- *
- * @return String CSS attribute
- */
- function LogoStyle() {
- $attr = self::$application_logo_style;
- if(self::$application_logo) $attr .= "background: url(" . self::$application_logo . ") no-repeat; ";
- return $attr;
- }
-
- /**
- * Return the base directory of the tiny_mce codebase
- */
- function MceRoot() {
- return MCE_ROOT;
- }
-
- /**
- * Register the given javascript file as required in the CMS.
- * Filenames should be relative to the base, eg, SAPPHIRE_DIR . '/javascript/loader.js'
- */
- public static function require_javascript($file) {
- self::$extra_requirements['javascript'][] = array($file);
- }
-
- /**
- * Register the given stylesheet file as required.
- *
- * @param $file String Filenames should be relative to the base, eg, THIRDPARTY_DIR . '/tree/tree.css'
- * @param $media String Comma-separated list of media-types (e.g. "screen,projector")
- * @see http://www.w3.org/TR/REC-CSS2/media.html
- */
- public static function require_css($file, $media = null) {
- self::$extra_requirements['css'][] = array($file, $media);
- }
-
- /**
- * Register the given "themeable stylesheet" as required.
- * Themeable stylesheets have globally unique names, just like templates and PHP files.
- * Because of this, they can be replaced by similarly named CSS files in the theme directory.
- *
- * @param $name String The identifier of the file. For example, css/MyFile.css would have the identifier "MyFile"
- * @param $media String Comma-separated list of media-types (e.g. "screen,projector")
- */
- static function require_themed_css($name, $media = null) {
- self::$extra_requirements['themedcss'][] = array($name, $media);
- }
-
-}
-
-/**
- * @package cms
- * @subpackage core
- */
-class LeftAndMainMarkingFilter {
-
- /**
- * @var array Request params (unsanitized)
- */
- protected $params = array();
-
- /**
- * @param array $params Request params (unsanitized)
- */
- function __construct($params = null) {
- $this->ids = array();
- $this->expanded = array();
- $parents = array();
-
- $q = $this->getQuery($params);
- $res = $q->execute();
- if (!$res) return;
-
- // And keep a record of parents we don't need to get parents
- // of themselves, as well as IDs to mark
- foreach($res as $row) {
- if ($row['ParentID']) $parents[$row['ParentID']] = true;
- $this->ids[$row['ID']] = true;
- }
-
- // We need to recurse up the tree,
- // finding ParentIDs for each ID until we run out of parents
- while (!empty($parents)) {
- $res = DB::query('SELECT "ParentID", "ID" FROM "SiteTree" WHERE "ID" in ('.implode(',',array_keys($parents)).')');
- $parents = array();
-
- foreach($res as $row) {
- if ($row['ParentID']) $parents[$row['ParentID']] = true;
- $this->ids[$row['ID']] = true;
- $this->expanded[$row['ID']] = true;
- }
- }
- }
-
- protected function getQuery($params) {
- $where = array();
-
- $SQL_params = Convert::raw2sql($params);
- if(isset($SQL_params['ID'])) unset($SQL_params['ID']);
- foreach($SQL_params as $name => $val) {
- switch($name) {
- default:
- // Partial string match against a variety of fields
- if(!empty($val) && singleton("SiteTree")->hasDatabaseField($name)) {
- $where[] = "\"$name\" LIKE '%$val%'";
- }
- }
- }
-
- return new SQLQuery(
- array("ParentID", "ID"),
- 'SiteTree',
- $where
- );
- }
-
- function mark($node) {
- $id = $node->ID;
- if(array_key_exists((int) $id, $this->expanded)) $node->markOpened();
- return array_key_exists((int) $id, $this->ids) ? $this->ids[$id] : false;
- }
-}
-?>
\ No newline at end of file
diff --git a/code/LeftAndMainDecorator.php b/code/LeftAndMainDecorator.php
deleted file mode 100644
index 7e6970e0..00000000
--- a/code/LeftAndMainDecorator.php
+++ /dev/null
@@ -1,21 +0,0 @@
-
\ No newline at end of file
diff --git a/code/MemberImportForm.php b/code/MemberImportForm.php
deleted file mode 100644
index a2423ef6..00000000
--- a/code/MemberImportForm.php
+++ /dev/null
@@ -1,108 +0,0 @@
-Import members in CSV format (comma-separated values). Show advanced usage'
- );
- $helpHtml .= _t(
- 'MemberImportForm.Help2',
-'
-
Advanced usage
-
-
Allowed columns: %s
-
Existing members are matched by their unique Code property, and updated with any new values from the imported file.
-
Groups can be assigned by the Groups column. Groups are identified by their Code property, multiple groups can be separated by comma. Existing group memberships are not cleared.
-
-
');
-
- $importer = new MemberCsvBulkLoader();
- $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 (Allowed extensions: *.csv)'
- )
- )
- );
- $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);
-
- Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-entwine/dist/jquery.entwine-dist.js');
- Requirements::javascript(CMS_DIR . '/javascript/MemberImportForm.js');
- $this->addExtraClass('import-form');
- }
-
- function doImport($data, $form) {
- $loader = new MemberCsvBulkLoader();
-
- // optionally set group relation
- if($this->group) $loader->setGroups(array($this->group));
-
- // load file
- $result = $loader->load($data['CsvFile']['tmp_name']);
-
- // result message
- $msgArr = array();
- if($result->CreatedCount()) $msgArr[] = sprintf(
- _t('MemberImportForm.ResultCreated', 'Created %d members'),
- $result->CreatedCount()
- );
- if($result->UpdatedCount()) $msgArr[] = sprintf(
- _t('MemberImportForm.ResultUpdated', 'Updated %d members'),
- $result->UpdatedCount()
- );
- if($result->DeletedCount()) $msgArr[] = sprintf(
- _t('MemberImportForm.ResultDeleted', 'Deleted %d members'),
- $result->DeletedCount()
- );
- $msg = ($msgArr) ? implode(',', $msgArr) : _t('MemberImportForm.ResultNone', 'No changes');
-
- $this->sessionMessage($msg, 'good');
-
- $this->controller->redirectBack();
- }
-
- /**
- * @param $group Group
- */
- function setGroup($group) {
- $this->group = $group;
- }
-
- /**
- * @return Group
- */
- function getGroup($group) {
- return $this->group;
- }
-}
-?>
\ No newline at end of file
diff --git a/code/MemberTableField.php b/code/MemberTableField.php
deleted file mode 100755
index 806d18da..00000000
--- a/code/MemberTableField.php
+++ /dev/null
@@ -1,553 +0,0 @@
-summaryFields();
- $memberDbFields = $SNG_member->db();
- $csvFieldList = array();
-
- foreach($memberDbFields as $field => $dbFieldType) {
- $csvFieldList[$field] = $field;
- }
-
- if($group) {
- if(is_object($group)) {
- $this->group = $group;
- } elseif(is_numeric($group)) {
- $this->group = DataObject::get_by_id('Group', $group);
- }
- } else if(isset($_REQUEST['ctf'][$this->Name()]["ID"]) && is_numeric($_REQUEST['ctf'][$this->Name()]["ID"])) {
- $this->group = DataObject::get_by_id('Group', $_REQUEST['ctf'][$this->Name()]["ID"]);
- }
-
- if(!$hidePassword) {
- $fieldList["SetPassword"] = "Password";
- }
-
- $this->hidePassword = $hidePassword;
-
- // @todo shouldn't this use $this->group? It's unclear exactly
- // what group it should be customising the custom Member set with.
- if($members && $group) {
- $this->setCustomSourceItems($this->memberListWithGroupID($members, $group));
- }
-
- parent::__construct($controller, $name, $sourceClass, $fieldList);
-
- $SQL_search = isset($_REQUEST['MemberSearch']) ? Convert::raw2sql($_REQUEST['MemberSearch']) : null;
- if(!empty($_REQUEST['MemberSearch'])) {
- $searchFilters = array();
- foreach($SNG_member->searchableFields() as $fieldName => $fieldSpec) {
- if(strpos($fieldName, '.') === false) $searchFilters[] = "\"$fieldName\" LIKE '%{$SQL_search}%'";
- }
- $this->sourceFilter[] = '(' . implode(' OR ', $searchFilters) . ')';
- }
-
- if($this->group) {
- $groupIDs = array($this->group->ID);
- if($this->group->AllChildren()) $groupIDs = array_merge($groupIDs, $this->group->AllChildren()->column('ID'));
- $this->sourceFilter[] = sprintf(
- '"Group_Members"."GroupID" IN (%s)',
- implode(',', $groupIDs)
- );
- }
-
- $this->sourceJoin = " INNER JOIN \"Group_Members\" ON \"MemberID\"=\"Member\".\"ID\"";
- $this->setFieldListCsv($csvFieldList);
- $this->setPageSize($this->stat('page_size'));
- }
-
- function FieldHolder() {
- $ret = parent::FieldHolder();
-
- Requirements::javascript(SAPPHIRE_DIR . "/thirdparty/scriptaculous/controls.js");
- Requirements::javascript(CMS_DIR . '/javascript/MemberTableField.js');
- Requirements::javascript(CMS_DIR . "/javascript/MemberTableField_popup.js");
-
- return $ret;
- }
-
- function sourceID() {
- return ($this->group) ? $this->group->ID : 0;
- }
-
- function AddLink() {
- return Controller::join_links($this->Link(), 'add');
- }
-
- function SearchForm() {
- $groupID = (isset($this->group)) ? $this->group->ID : 0;
- $query = isset($_GET['MemberSearch']) ? $_GET['MemberSearch'] : null;
-
- $searchFields = new FieldGroup(
- new TextField('MemberSearch', _t('MemberTableField.SEARCH', 'Search'), $query),
- new HiddenField("ctf[ID]", '', $groupID),
- new HiddenField('MemberFieldName', '', $this->name),
- new HiddenField('MemberDontShowPassword', '', $this->hidePassword)
- );
-
- $actionFields = new LiteralField('MemberFilterButton','');
-
- $fieldContainer = new FieldGroup(
- $searchFields,
- $actionFields
- );
-
- return $fieldContainer->FieldHolder();
- }
-
- /**
- * Add existing member to group rather than creating a new member
- */
- function addtogroup() {
- // Protect against CSRF on destructive action
- $token = $this->getForm()->getSecurityToken();
- if(!$token->checkRequest($this->controller->getRequest())) return $this->httpError(400);
-
- $data = $_REQUEST;
- $groupID = (isset($data['ctf']['ID'])) ? $data['ctf']['ID'] : null;
-
- if(!is_numeric($groupID)) {
- FormResponse::status_messsage(_t('MemberTableField.ADDINGFIELD', 'Adding failed'), 'bad');
- return;
- }
-
- // Get existing record either by ID or unique identifier.
- $identifierField = Member::get_unique_identifier_field();
- $className = self::$data_class;
- $record = null;
- if(isset($data[$identifierField])) {
- $record = DataObject::get_one(
- $className,
- sprintf('"%s" = \'%s\'', $identifierField, $data[$identifierField])
- );
-
- if($record && !$record->canEdit()) return $this->httpError('401');
- }
-
- // Fall back to creating a new record
- if(!$record) $record = new $className();
-
- // Update an existing record, or populate a new one.
- // If values on an existing (autocompleted) record have been changed,
- // they will overwrite current data. We need to unset 'ID'
- // record as it points to the group rather than the member record, and would
- // cause the member to be written to a potentially existing record.
- unset($data['ID']);
- $record->update($data);
-
- // Validate record, mainly password restrictions.
- // Note: Doesn't use Member_Validator
- $valid = $record->validate();
- if($valid->valid()) {
- $record->write();
- $record->Groups()->add($groupID);
-
- $this->sourceItems();
-
- // TODO add javascript to highlight added row (problem: might not show up due to sorting/filtering)
- FormResponse::update_dom_id($this->id(), $this->renderWith($this->template), true);
- FormResponse::status_message(
- _t(
- 'MemberTableField.ADDEDTOGROUP','Added member to group'
- ),
- 'good'
- );
-
- } else {
- $message = sprintf(
- _t(
- 'MemberTableField.ERRORADDINGUSER',
- 'There was an error adding the user to the group: %s'
- ),
- Convert::raw2xml($valid->starredList())
- );
-
- FormResponse::status_message($message, 'bad');
- }
-
- return FormResponse::respond();
- }
-
- /**
- * Custom delete implementation:
- * Remove member from group rather than from the database
- */
- function delete() {
- // Protect against CSRF on destructive action
- $token = $this->getForm()->getSecurityToken();
- // TODO Not sure how this is called, using $_REQUEST to be on the safe side
- if(!$token->check($_REQUEST['SecurityID'])) return $this->httpError(400);
-
- $groupID = Convert::raw2sql($_REQUEST['ctf']['ID']);
- $memberID = Convert::raw2sql($_REQUEST['ctf']['childID']);
- if(is_numeric($groupID) && is_numeric($memberID)) {
- $member = DataObject::get_by_id('Member', $memberID);
- $member->Groups()->remove($groupID);
- } else {
- user_error("MemberTableField::delete: Bad parameters: Group=$groupID, Member=$memberID", E_USER_ERROR);
- }
-
- return FormResponse::respond();
-
- }
-
- /**
- * #################################
- * Utility Functions
- * #################################
- */
- function getParentClass() {
- return 'Group';
- }
-
- function getParentIdName($childClass, $parentClass) {
- return 'GroupID';
- }
-
- /**
- * #################################
- * Custom Functions
- * #################################
- */
-
- /**
- * Customise an existing DataObjectSet of Member
- * objects with a GroupID.
- *
- * @param DataObjectSet $members Set of Member objects to customise
- * @param Group $group Group object to customise with
- * @return DataObjectSet Customised set of Member objects
- */
- function memberListWithGroupID($members, $group) {
- $newMembers = new DataObjectSet();
- foreach($members as $member) {
- $newMembers->push($member->customise(array('GroupID' => $group->ID)));
- }
- return $newMembers;
- }
-
- function setGroup($group) {
- $this->group = $group;
- }
-
- /**
- * @return Group
- */
- function getGroup() {
- return $this->group;
- }
-
- function setController($controller) {
- $this->controller = $controller;
- }
-
- function GetControllerName() {
- return $this->controller->class;
- }
-
- /**
- * Add existing member to group by name (with JS-autocompletion)
- */
- function AddRecordForm() {
- $fields = new FieldSet();
- foreach($this->FieldList() as $fieldName => $fieldTitle) {
- // If we're adding the set password field, we want to hide the text from any peeping eyes
- if($fieldName == 'SetPassword') {
- $fields->push(new PasswordField($fieldName));
- } else {
- $fields->push(new TextField($fieldName));
- }
- }
- if($this->group) {
- $fields->push(new HiddenField('ctf[ID]', null, $this->group->ID));
- }
- $actions = new FieldSet(
- new FormAction('addtogroup', _t('MemberTableField.ADD','Add'))
- );
-
- return new TabularStyle(
- new NestedForm(
- new Form(
- $this,
- 'AddRecordForm',
- $fields,
- $actions
- )
- )
- );
- }
-
- function AddForm() {
- $form = parent::AddForm();
-
- // Set default groups - also implemented in MemberTableField_Popup::__construct()
- if($this->group) {
- $groupsField = $form->Fields()->dataFieldByName('Groups');
- // TODO Needs to be a string value (not int) because of TreeMultiselectField->getItems(),
- // see http://open.silverstripe.org/ticket/5836
- if($groupsField) $groupsField->setValue((string)$this->group->ID);
- }
-
- return $form;
- }
-
- /**
- * Same behaviour as parent class, but adds the
- * member to the passed GroupID.
- *
- * @return string
- */
- function saveComplexTableField($data, $form, $params) {
- $className = $this->sourceClass();
- $childData = new $className();
-
- // Needs to write before saveInto() to ensure the 'Groups' TreeMultiselectField saves
- $childData->write();
-
- try {
- $form->saveInto($childData);
- $childData->write();
- } catch(ValidationException $e) {
- $form->sessionMessage($e->getResult()->message(), 'bad');
- return Director::redirectBack();
- }
-
- $closeLink = sprintf(
- '(%s)',
- _t('ComplexTableField.CLOSEPOPUP', 'Close Popup')
- );
- $message = sprintf(
- _t('ComplexTableField.SUCCESSADD', 'Added %s %s %s'),
- $childData->singular_name(),
- '' . htmlspecialchars($childData->Title, ENT_QUOTES, 'UTF-8') . '',
- $closeLink
- );
- $form->sessionMessage($message, 'good');
-
- $this->controller->redirectBack();
- }
-
- /**
- * Cached version for getting the appropraite members for this particular group.
- *
- * This includes getting inherited groups, such as groups under groups.
- */
- function sourceItems() {
- // Caching.
- if($this->sourceItems) {
- return $this->sourceItems;
- }
-
- // Setup limits
- $limitClause = '';
- if(isset($_REQUEST['ctf'][$this->Name()]['start']) && is_numeric($_REQUEST['ctf'][$this->Name()]['start'])) {
- $limitClause = ($_REQUEST['ctf'][$this->Name()]['start']) . ", {$this->pageSize}";
- } else {
- $limitClause = "0, {$this->pageSize}";
- }
-
- // We use the group to get the members, as they already have the bulk of the look up functions
- $start = isset($_REQUEST['ctf'][$this->Name()]['start']) ? $_REQUEST['ctf'][$this->Name()]['start'] : 0;
-
- $this->sourceItems = false;
-
- if($this->group) {
- $this->sourceItems = $this->group->Members(
- $this->pageSize, // limit
- $start, // offset
- $this->sourceFilter,
- $this->sourceSort
- );
- } else {
- $this->sourceItems = DataObject::get(self::$data_class,
- $this->sourceFilter,
- $this->sourceSort,
- null,
- array('limit' => $this->pageSize, 'start' => $start)
- );
- }
- // Because we are not used $this->upagedSourceItems any more, and the DataObjectSet is usually the source
- // that a large member set runs out of memory. we disable it here.
- //$this->unpagedSourceItems = $this->group->Members('', '', $this->sourceFilter, $this->sourceSort);
- $this->totalCount = ($this->sourceItems) ? $this->sourceItems->TotalItems() : 0;
-
- return $this->sourceItems;
- }
-
- function TotalCount() {
- $this->sourceItems(); // Called for its side-effect of setting total count
- return $this->totalCount;
- }
-
- /**
- * Handles item requests
- * MemberTableField needs its own item request class so that it can overload the delete method
- */
- function handleItem($request) {
- return new MemberTableField_ItemRequest($this, $request->param('ID'));
- }
-}
-
-/**
- * Popup window for {@link MemberTableField}.
- * @package cms
- * @subpackage security
- */
-class MemberTableField_Popup extends ComplexTableField_Popup {
-
- function __construct($controller, $name, $fields, $validator, $readonly, $dataObject) {
- $group = ($controller instanceof MemberTableField) ? $controller->getGroup() : $controller->getParent()->getGroup();
- // Set default groups - also implemented in AddForm()
- if($group) {
- $groupsField = $fields->dataFieldByName('Groups');
- if($groupsField) $groupsField->setValue($group->ID);
- }
-
- parent::__construct($controller, $name, $fields, $validator, $readonly, $dataObject);
- }
-
- function forTemplate() {
- $ret = parent::forTemplate();
-
- Requirements::css(CMS_DIR . '/css/SecurityAdmin.css');
- Requirements::javascript(CMS_DIR . '/javascript/MemberTableField.js');
- Requirements::javascript(CMS_DIR . '/javascript/MemberTableField_popup.js');
-
- return $ret;
- }
-
-}
-
-/**
-* @package cms
-* @subpackage security
-*/
-class MemberTableField_Item extends ComplexTableField_Item {
-
- function Actions() {
- $actions = parent::Actions();
-
- foreach($actions as $action) {
- if($action->Name == 'delete') {
- if($this->parent->getGroup()) {
- $action->TitleText = _t('MemberTableField.DeleteTitleText',
- 'Delete from this group',
- PR_MEDIUM,
- 'Delete button hover text'
- );
- } else {
- $action->TitleText = _t('MemberTableField.DeleteTitleTextDatabase',
- 'Delete from database and all groups',
- PR_MEDIUM,
- 'Delete button hover text'
- );
- }
- }
- }
-
- return $actions;
- }
-}
-
-/**
-* @package cms
-* @subpackage security
-*/
-
-class MemberTableField_ItemRequest extends ComplexTableField_ItemRequest {
-
- /**
- * Deleting an item from a member table field should just remove that member from the group
- */
- function delete($request) {
- // Protect against CSRF on destructive action
- $token = $this->ctf->getForm()->getSecurityToken();
- if(!$token->checkRequest($request)) return $this->httpError('400');
-
- if($this->ctf->Can('delete') !== true) {
- return false;
- }
-
- // if a group limitation is set on the table, remove relation.
- // otherwise remove the record from the database
- if($this->ctf->getGroup()) {
- $groupID = $this->ctf->sourceID();
- $group = DataObject::get_by_id('Group', $groupID);
-
- // Remove from group and all child groups
- foreach($group->getAllChildren() as $subGroup) {
- $this->dataObj()->Groups()->remove($subGroup);
- }
- $this->dataObj()->Groups()->remove($groupID);
- } else {
- $this->dataObj()->delete();
- }
- }
-
- function getParent() {
- return $this->ctf;
- }
-}
-
-?>
\ No newline at end of file
diff --git a/code/ModelAdmin.php b/code/ModelAdmin.php
deleted file mode 100755
index 5127242f..00000000
--- a/code/ModelAdmin.php
+++ /dev/null
@@ -1,1055 +0,0 @@
-
- * Director::addRules(50, array('admin/mymodel/$Class/$Action/$ID' => 'MyModelAdmin'));
- *
- *
- * @todo saving logic (should mostly use Form->saveInto() and iterate over relations)
- * @todo ajax form loading and saving
- * @todo ajax result display
- * @todo relation formfield scaffolding (one tab per relation) - relations don't have DBField sublclasses, we do
- * we define the scaffold defaults. can be ComplexTableField instances for a start.
- * @todo has_many/many_many relation autocomplete field (HasManyComplexTableField doesn't work well with larger datasets)
- *
- * Long term TODOs:
- * @todo Hook into RESTful interface on DataObjects (yet to be developed)
- * @todo Permission control via datamodel and Form class
- *
- * @uses SearchContext
- *
- * @package cms
- * @subpackage core
- */
-abstract class ModelAdmin extends LeftAndMain {
-
- static $url_rule = '/$Action';
-
- /**
- * List of all managed {@link DataObject}s in this interface.
- *
- * Simple notation with class names only:
- *
- * array('MyObjectClass','MyOtherObjectClass')
- *
- *
- * Extended notation with options (e.g. custom titles):
- *
- * array(
- * 'MyObjectClass' => array('title' => "Custom title")
- * )
- *
- *
- * Available options:
- * - 'title': Set custom titles for the tabs or dropdown names
- * - 'collection_controller': Set a custom class to use as a collection controller for this model
- * - 'record_controller': Set a custom class to use as a record controller for this model
- *
- * @var array|string
- */
- public static $managed_models = null;
-
- /**
- * More actions are dynamically added in {@link defineMethods()} below.
- */
- public static $allowed_actions = array(
- 'add',
- 'edit',
- 'delete',
- 'import',
- 'renderimportform',
- 'handleList',
- 'handleItem',
- 'ImportForm'
- );
-
- /**
- * @param string $collection_controller_class Override for controller class
- */
- public static $collection_controller_class = "ModelAdmin_CollectionController";
-
- /**
- * @param string $collection_controller_class Override for controller class
- */
- public static $record_controller_class = "ModelAdmin_RecordController";
-
- /**
- * Forward control to the default action handler
- */
- public static $url_handlers = array(
- '$Action' => 'handleAction'
- );
-
- /**
- * Model object currently in manipulation queue. Used for updating Link to point
- * to the correct generic data object in generated URLs.
- *
- * @var string
- */
- private $currentModel = false;
-
- /**
- * Change this variable if you don't want the Import from CSV form to appear.
- * This variable can be a boolean or an array.
- * If array, you can list className you want the form to appear on. i.e. array('myClassOne','myClasstwo')
- */
- public $showImportForm = true;
-
- /**
- * List of all {@link DataObject}s which can be imported through
- * a subclass of {@link BulkLoader} (mostly CSV data).
- * By default {@link CsvBulkLoader} is used, assuming a standard mapping
- * of column names to {@link DataObject} properties/relations.
- *
- * e.g. "BlogEntry" => "BlogEntryCsvBulkLoader"
- *
- * @var array
- */
- public static $model_importers = null;
-
- /**
- * Amount of results showing on a single page.
- *
- * @var int
- */
- public static $page_length = 30;
-
- /**
- * Class name of the form field used for the results list. Overloading this in subclasses
- * can let you customise the results table field.
- */
- protected $resultsTableClassName = 'TableListField';
-
- /**
- * Return {@link $this->resultsTableClassName}
- */
- public function resultsTableClassName() {
- return $this->resultsTableClassName;
- }
-
- /**
- * Initialize the model admin interface. Sets up embedded jquery libraries and requisite plugins.
- *
- * @todo remove reliance on urlParams
- */
- public function init() {
- parent::init();
-
- // security check for valid models
- if(isset($this->urlParams['Action']) && !in_array($this->urlParams['Action'], $this->getManagedModels())) {
- //user_error('ModelAdmin::init(): Invalid Model class', E_USER_ERROR);
- }
-
- Requirements::css(CMS_DIR . '/css/ModelAdmin.css'); // standard layout formatting for management UI
- Requirements::css(CMS_DIR . '/css/silverstripe.tabs.css'); // follows the jQuery UI theme conventions
-
- Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery/jquery.js');
- Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-livequery/jquery.livequery.js');
- Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-ui/jquery-ui.js');
- Requirements::javascript(SAPPHIRE_DIR . '/javascript/jquery/jquery_improvements.js');
- Requirements::javascript(CMS_DIR . '/javascript/ModelAdmin.js');
- Requirements::javascript(CMS_DIR . '/javascript/ModelAdmin.History.js');
- }
-
- /**
- * overwrite the static page_length of the admin panel,
- * should be called in the project _config file.
- */
- static function set_page_length($length){
- self::$page_length = $length;
- }
-
- /**
- * Return the static page_length of the admin, default as 30
- */
- static function get_page_length(){
- return self::$page_length;
- }
-
- /**
- * Return the class name of the collection controller
- *
- * @param string $model model name to get the controller for
- * @return string the collection controller class
- */
- function getCollectionControllerClass($model) {
- $models = $this->getManagedModels();
-
- if(isset($models[$model]['collection_controller'])) {
- $class = $models[$model]['collection_controller'];
- } else {
- $class = $this->stat('collection_controller_class');
- }
-
- return $class;
- }
-
- /**
- * Return the class name of the record controller
- *
- * @param string $model model name to get the controller for
- * @return string the record controller class
- */
- function getRecordControllerClass($model) {
- $models = $this->getManagedModels();
-
- if(isset($models[$model]['record_controller'])) {
- $class = $models[$model]['record_controller'];
- } else {
- $class = $this->stat('record_controller_class');
- }
-
- return $class;
- }
-
- /**
- * Add mappings for generic form constructors to automatically delegate to a scaffolded form object.
- */
- function defineMethods() {
- parent::defineMethods();
- foreach($this->getManagedModels() as $class => $options) {
- if(is_numeric($class)) $class = $options;
- $this->addWrapperMethod($class, 'bindModelController');
- self::$allowed_actions[] = $class;
- }
- }
-
- /**
- * Base scaffolding method for returning a generic model instance.
- */
- public function bindModelController($model, $request = null) {
- $class = $this->getCollectionControllerClass($model);
- return new $class($this, $model);
- }
-
- /**
- * This method can be overloaded to specify the UI by which the search class is chosen.
- *
- * It can create a tab strip or a dropdown. The dropdown is useful when there are a large number of classes.
- * By default, it will show a tabs for 1-3 classes, and a dropdown for 4 or more classes.
- *
- * @return String: 'tabs' or 'dropdown'
- */
- public function SearchClassSelector() {
- return sizeof($this->getManagedModels()) > 3 ? 'dropdown' : 'tabs';
- }
-
- /**
- * Returns managed models' create, search, and import forms
- * @uses SearchContext
- * @uses SearchFilter
- * @return DataObjectSet of forms
- */
- protected function getModelForms() {
- $models = $this->getManagedModels();
- $forms = new DataObjectSet();
-
- foreach($models as $class => $options) {
- if(is_numeric($class)) $class = $options;
- $forms->push(new ArrayData(array (
- 'Title' => (is_array($options) && isset($options['title'])) ? $options['title'] : singleton($class)->i18n_singular_name(),
- 'ClassName' => $class,
- 'Content' => $this->$class()->getModelSidebar()
- )));
- }
-
- return $forms;
- }
-
- /**
- * @return array
- */
- function getManagedModels() {
- $models = $this->stat('managed_models');
- if(is_string($models)) {
- $models = array($models);
- }
- if(!count($models)) {
- user_error(
- 'ModelAdmin::getManagedModels():
- You need to specify at least one DataObject subclass in public static $managed_models.
- Make sure that this property is defined, and that its visibility is set to "public"',
- E_USER_ERROR
- );
- }
-
- return $models;
- }
-
- /**
- * Returns all importers defined in {@link self::$model_importers}.
- * If none are defined, we fall back to {@link self::managed_models}
- * with a default {@link CsvBulkLoader} class. In this case the column names of the first row
- * in the CSV file are assumed to have direct mappings to properties on the object.
- *
- * @return array
- */
- function getModelImporters() {
- $importers = $this->stat('model_importers');
-
- // fallback to all defined models if not explicitly defined
- if(is_null($importers)) {
- $models = $this->getManagedModels();
- foreach($models as $modelName => $options) {
- if(is_numeric($modelName)) $modelName = $options;
- $importers[$modelName] = 'CsvBulkLoader';
- }
- }
-
- return $importers;
- }
-
-}
-
-/**
- * Handles a managed model class and provides default collection filtering behavior.
- *
- * @package cms
- * @subpackage core
- */
-class ModelAdmin_CollectionController extends Controller {
- public $parentController;
- protected $modelClass;
-
- public $showImportForm = null;
-
- static $url_handlers = array(
- '$Action' => 'handleActionOrID'
- );
-
- function __construct($parent, $model) {
- $this->parentController = $parent;
- $this->modelClass = $model;
-
- parent::__construct();
- }
-
- /**
- * Appends the model class to the URL.
- *
- * @param string $action
- * @return string
- */
- function Link($action = null) {
- return $this->parentController->Link(Controller::join_links($this->modelClass, $action));
- }
-
- /**
- * Return the class name of the model being managed.
- *
- * @return unknown
- */
- function getModelClass() {
- return $this->modelClass;
- }
-
- /**
- * Delegate to different control flow, depending on whether the
- * URL parameter is a number (record id) or string (action).
- *
- * @param unknown_type $request
- * @return unknown
- */
- function handleActionOrID($request) {
- if (is_numeric($request->param('Action'))) {
- return $this->handleID($request);
- } else {
- return $this->handleAction($request);
- }
- }
-
- /**
- * Delegate to the RecordController if a valid numeric ID appears in the URL
- * segment.
- *
- * @param SS_HTTPRequest $request
- * @return RecordController
- */
- public function handleID($request) {
- $class = $this->parentController->getRecordControllerClass($this->getModelClass());
- return new $class($this, $request);
- }
-
- // -----------------------------------------------------------------------------------------------------------------
-
- /**
- * Get a combination of the Search, Import and Create forms that can be inserted into a {@link ModelAdmin} sidebar.
- *
- * @return string
- */
- public function getModelSidebar() {
- return $this->renderWith('ModelSidebar');
- }
-
- /**
- * Get a search form for a single {@link DataObject} subclass.
- *
- * @return Form
- */
- public function SearchForm() {
- $context = singleton($this->modelClass)->getDefaultSearchContext();
- $fields = $context->getSearchFields();
- $columnSelectionField = $this->ColumnSelectionField();
- $fields->push($columnSelectionField);
- $validator = new RequiredFields();
- $validator->setJavascriptValidationHandler('none');
-
- $form = new Form($this, "SearchForm",
- $fields,
- new FieldSet(
- new FormAction('search', _t('MemberTableField.SEARCH', 'Search')),
- $clearAction = new ResetFormAction('clearsearch', _t('ModelAdmin.CLEAR_SEARCH','Clear Search'))
- ),
- $validator
- );
- //$form->setFormAction(Controller::join_links($this->Link(), "search"));
- $form->setFormMethod('get');
- $form->setHTMLID("Form_SearchForm_" . $this->modelClass);
- $form->disableSecurityToken();
- $clearAction->useButtonTag = true;
- $clearAction->addExtraClass('minorAction');
-
- return $form;
- }
-
- /**
- * Create a form that consists of one button
- * that directs to a give model's Add form
- */
- public function CreateForm() {
- $modelName = $this->modelClass;
-
- if($this->hasMethod('alternatePermissionCheck')) {
- if(!$this->alternatePermissionCheck()) return false;
- } else {
- if(!singleton($modelName)->canCreate(Member::currentUser())) return false;
- }
-
- $buttonLabel = sprintf(_t('ModelAdmin.CREATEBUTTON', "Create '%s'", PR_MEDIUM, "Create a new instance from a model class"), singleton($modelName)->i18n_singular_name());
-
- $form = new Form($this, "CreateForm",
- new FieldSet(),
- new FieldSet($createButton = new FormAction('add', $buttonLabel)),
- $validator = new RequiredFields()
- );
-
- $createButton->dontEscape = true;
- $validator->setJavascriptValidationHandler('none');
- $form->setHTMLID("Form_CreateForm_" . $this->modelClass);
- return $form;
- }
-
- /**
- * Checks if a CSV import form should be generated by a className criteria or in general for ModelAdmin.
- */
- function showImportForm() {
- if($this->showImportForm === null) return $this->parentController->showImportForm;
- else return $this->showImportForm;
- }
-
- /**
- * Generate a CSV import form for a single {@link DataObject} subclass.
- *
- * @return Form
- */
- public function ImportForm() {
- $modelName = $this->modelClass;
- // check if a import form should be generated
- if(!$this->showImportForm() || (is_array($this->showImportForm()) && !in_array($modelName,$this->showImportForm()))) return false;
- $importers = $this->parentController->getModelImporters();
- if(!$importers || !isset($importers[$modelName])) return false;
-
- if(!singleton($modelName)->canCreate(Member::currentUser())) return false;
-
- $fields = new FieldSet(
- new HiddenField('ClassName', _t('ModelAdmin.CLASSTYPE'), $modelName),
- new FileField('_CsvFile', false)
- );
-
- // get HTML specification for each import (column names etc.)
- $importerClass = $importers[$modelName];
- $importer = new $importerClass($modelName);
- $spec = $importer->getImportSpec();
- $specFields = new DataObjectSet();
- foreach($spec['fields'] as $name => $desc) {
- $specFields->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
- }
- $specRelations = new DataObjectSet();
- foreach($spec['relations'] as $name => $desc) {
- $specRelations->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
- }
- $specHTML = $this->customise(array(
- 'ModelName' => Convert::raw2att($modelName),
- 'Fields' => $specFields,
- 'Relations' => $specRelations,
- ))->renderWith('ModelAdmin_ImportSpec');
-
- $fields->push(new LiteralField("SpecFor{$modelName}", $specHTML));
- $fields->push(new CheckboxField('EmptyBeforeImport', 'Clear Database before import', false));
-
- $actions = new FieldSet(
- new FormAction('import', _t('ModelAdmin.IMPORT', 'Import from CSV'))
- );
-
- $validator = new RequiredFields();
- $validator->setJavascriptValidationHandler('none');
-
- $form = new Form(
- $this,
- "ImportForm",
- $fields,
- $actions,
- $validator
- );
- $form->setHTMLID("Form_ImportForm_" . $this->modelClass);
- return $form;
- }
-
- /**
- * Imports the submitted CSV file based on specifications given in
- * {@link self::model_importers}.
- * Redirects back with a success/failure message.
- *
- * @todo Figure out ajax submission of files via jQuery.form plugin
- *
- * @param array $data
- * @param Form $form
- * @param SS_HTTPRequest $request
- */
- function import($data, $form, $request) {
-
- $modelName = $data['ClassName'];
-
- if(!$this->showImportForm() || (is_array($this->showImportForm()) && !in_array($modelName,$this->showImportForm()))) return false;
- $importers = $this->parentController->getModelImporters();
- $importerClass = $importers[$modelName];
-
- $loader = new $importerClass($data['ClassName']);
-
- // File wasn't properly uploaded, show a reminder to the user
- if(
- empty($_FILES['_CsvFile']['tmp_name']) ||
- file_get_contents($_FILES['_CsvFile']['tmp_name']) == ''
- ) {
- $form->sessionMessage(_t('ModelAdmin.NOCSVFILE', 'Please browse for a CSV file to import'), 'good');
- $this->redirectBack();
- return false;
- }
-
- if (!empty($data['EmptyBeforeImport']) && $data['EmptyBeforeImport']) { //clear database before import
- $loader->deleteExistingRecords = true;
- }
- $results = $loader->load($_FILES['_CsvFile']['tmp_name']);
-
- $message = '';
- if($results->CreatedCount()) $message .= sprintf(
- _t('ModelAdmin.IMPORTEDRECORDS', "Imported %s records."),
- $results->CreatedCount()
- );
- if($results->UpdatedCount()) $message .= sprintf(
- _t('ModelAdmin.UPDATEDRECORDS', "Updated %s records."),
- $results->UpdatedCount()
- );
- if($results->DeletedCount()) $message .= sprintf(
- _t('ModelAdmin.DELETEDRECORDS', "Deleted %s records."),
- $results->DeletedCount()
- );
- if(!$results->CreatedCount() && !$results->UpdatedCount()) $message .= _t('ModelAdmin.NOIMPORT', "Nothing to import");
-
- $form->sessionMessage($message, 'good');
- $this->redirectBack();
- }
-
-
- /**
- * Return the columns available in the column selection field.
- * Overload this to make other columns available
- */
- public function columnsAvailable() {
- return singleton($this->modelClass)->summaryFields();
- }
-
- /**
- * Return the columns selected by default in the column selection field.
- * Overload this to make other columns selected by default
- */
- public function columnsSelectedByDefault() {
- return array_keys(singleton($this->modelClass)->summaryFields());
- }
-
- /**
- * Give the flexibilility to show variouse combination of columns in the search result table
- */
- public function ColumnSelectionField() {
- $model = singleton($this->modelClass);
- $source = $this->columnsAvailable();
-
- // select all fields by default
- $value = $this->columnsSelectedByDefault();
-
- // Reorder the source so that you read items down the column and then across
- $columnisedSource = array();
- $keys = array_keys($source);
- $midPoint = ceil(sizeof($source)/2);
- for($i=0;$i<$midPoint;$i++) {
- $key1 = $keys[$i];
- $columnisedSource[$key1] = $model->fieldLabel($source[$key1]);
- // If there are an odd number of items, the last item will be unset
- if(isset($keys[$i+$midPoint])) {
- $key2 = $keys[$i+$midPoint];
- $columnisedSource[$key2] = $model->fieldLabel($source[$key2]);
- }
- }
-
- $checkboxes = new CheckboxSetField("ResultAssembly", false, $columnisedSource, $value);
-
- $field = new CompositeField(
- new LiteralField(
- "ToggleResultAssemblyLink",
- sprintf("%s",
- _t('ModelAdmin.CHOOSE_COLUMNS', 'Select result columns...')
- )
- ),
- $checkboxesBlock = new CompositeField(
- $checkboxes,
- new LiteralField("ClearDiv", ""),
- new LiteralField(
- "TickAllAssemblyLink",
- sprintf(
- "%s",
- _t('ModelAdmin.SELECTALL', 'select all')
- )
- ),
- new LiteralField(
- "UntickAllAssemblyLink",
- sprintf(
- "%s",
- _t('ModelAdmin.SELECTNONE', 'select none')
- )
- )
- )
- );
-
- $field->addExtraClass("ResultAssemblyBlock");
- $checkboxesBlock->addExtraClass("hidden");
- return $field;
- }
-
- /**
- * Action to render a data object collection, using the model context to provide filters
- * and paging.
- *
- * @return string
- */
- function search($request, $form) {
- // Get the results form to be rendered
- $resultsForm = $this->ResultsForm(array_merge($form->getData(), $request));
- // Before rendering, let's get the total number of results returned
- $tableField = $resultsForm->Fields()->dataFieldByName($this->modelClass);
- $tableField->addExtraClass('resultsTable');
- $numResults = $tableField->TotalCount();
-
- if($numResults) {
- $msg = sprintf(
- _t('ModelAdmin.FOUNDRESULTS',"Your search found %s matching items"),
- $numResults
- );
- } else {
- $msg = _t('ModelAdmin.NORESULTS',"Your search didn't return any matching items");
- }
- return new SS_HTTPResponse(
- $resultsForm->formHtmlContent(),
- 200,
- $msg
- );
- }
-
- /**
- * Gets the search query generated on the SearchContext from
- * {@link DataObject::getDefaultSearchContext()},
- * and the current GET parameters on the request.
- *
- * @return SQLQuery
- */
- function getSearchQuery($searchCriteria) {
- $context = singleton($this->modelClass)->getDefaultSearchContext();
- return $context->getQuery($searchCriteria);
- }
-
- /**
- * Returns all columns used for tabular search results display.
- * Defaults to all fields specified in {@link DataObject->summaryFields()}.
- *
- * @param array $searchCriteria Limit fields by populating the 'ResultsAssembly' key
- * @param boolean $selectedOnly Limit by 'ResultsAssempty
- */
- function getResultColumns($searchCriteria, $selectedOnly = true) {
- $model = singleton($this->modelClass);
-
- $summaryFields = $this->columnsAvailable();
-
- if($selectedOnly && isset($searchCriteria['ResultAssembly'])) {
- $resultAssembly = $searchCriteria['ResultAssembly'];
- if(!is_array($resultAssembly)) {
- $explodedAssembly = split(' *, *', $resultAssembly);
- $resultAssembly = array();
- foreach($explodedAssembly as $item) $resultAssembly[$item] = true;
- }
- return array_intersect_key($summaryFields, $resultAssembly);
- } else {
- return $summaryFields;
- }
- }
-
- /**
- * Creates and returns the result table field for resultsForm.
- * Uses {@link resultsTableClassName()} to initialise the formfield.
- * Method is called from {@link ResultsForm}.
- *
- * @param array $searchCriteria passed through from ResultsForm
- *
- * @return TableListField
- */
- function getResultsTable($searchCriteria) {
-
- $summaryFields = $this->getResultColumns($searchCriteria);
-
- $className = $this->parentController->resultsTableClassName();
- $tf = new $className(
- $this->modelClass,
- $this->modelClass,
- $summaryFields
- );
-
- $tf->setCustomQuery($this->getSearchQuery($searchCriteria));
- $tf->setPageSize($this->parentController->stat('page_length'));
- $tf->setShowPagination(true);
- // @todo Remove records that can't be viewed by the current user
- $tf->setPermissions(array_merge(array('view','export'), TableListField::permissions_for_object($this->modelClass)));
-
- // csv export settings (select all columns regardless of user checkbox settings in 'ResultsAssembly')
- $exportFields = $this->getResultColumns($searchCriteria, false);
- $tf->setFieldListCsv($exportFields);
-
- $url = 'Link() . '/$ID/edit\">$value';
- if(count($summaryFields)) {
- $tf->setFieldFormatting(array_combine(
- array_keys($summaryFields),
- array_fill(0,count($summaryFields), $url)
- ));
- }
-
- return $tf;
- }
-
- /**
- * Shows results from the "search" action in a TableListField.
- *
- * @uses getResultsTable()
- *
- * @return Form
- */
- function ResultsForm($searchCriteria) {
-
- if($searchCriteria instanceof SS_HTTPRequest) $searchCriteria = $searchCriteria->getVars();
-
- $tf = $this->getResultsTable($searchCriteria);
-
- // implemented as a form to enable further actions on the resultset
- // (serverside sorting, export as CSV, etc)
- $form = new Form(
- $this,
- 'ResultsForm',
- new FieldSet(
- new TabSet('Root',
- new Tab('SearchResults',
- _t('ModelAdmin.SEARCHRESULTS','Search Results'),
- $tf
- )
- )
- ),
- new FieldSet()
- );
-
- // Include the search criteria on the results form URL, but not dodgy variables like those below
- $filteredCriteria = $searchCriteria;
- unset($filteredCriteria['ctf']);
- unset($filteredCriteria['url']);
- unset($filteredCriteria['action_search']);
-
- $form->setFormAction($this->Link() . '/ResultsForm?' . http_build_query($filteredCriteria));
- return $form;
- }
-
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Create a new model record.
- *
- * @param unknown_type $request
- * @return unknown
- */
- function add($request) {
- return new SS_HTTPResponse(
- $this->AddForm()->formHtmlContent(),
- 200,
- sprintf(
- _t('ModelAdmin.ADDFORM', "Fill out this form to add a %s to the database."),
- $this->modelClass
- )
- );
- }
-
- /**
- * Returns a form suitable for adding a new model, falling back on the default edit form.
- *
- * Caution: The add-form shows a DataObject's {@link DataObject->getCMSFields()} method on a record
- * that doesn't exist in the database yet, hence has no ID. This means the {@link DataObject->getCMSFields()}
- * implementation has to ensure that no fields are added which would rely on a
- * record ID being present, e.g. {@link HasManyComplexTableField}.
- *
- * Example:
- *
- * function getCMSFields() {
- * $fields = parent::getCMSFields();
- * if($this->exists()) {
- * $ctf = new HasManyComplexTableField($this, 'MyRelations', 'MyRelation');
- * $fields->addFieldToTab('Root.Main', $ctf);
- * }
- * return $fields;
- * }
- *
- *
- * @return Form
- */
- public function AddForm() {
- $newRecord = new $this->modelClass();
-
- if($newRecord->canCreate()){
- if($newRecord->hasMethod('getCMSAddFormFields')) {
- $fields = $newRecord->getCMSAddFormFields();
- } else {
- $fields = $newRecord->getCMSFields();
- }
-
- $validator = ($newRecord->hasMethod('getCMSValidator')) ? $newRecord->getCMSValidator() : null;
- if(!$validator) $validator = new RequiredFields();
- $validator->setJavascriptValidationHandler('none');
-
- $actions = new FieldSet (
- new FormAction("doCreate", _t('ModelAdmin.ADDBUTTON', "Add"))
- );
-
- $form = new Form($this, "AddForm", $fields, $actions, $validator);
- $form->loadDataFrom($newRecord);
-
- return $form;
- }
- }
-
- function doCreate($data, $form, $request) {
- $className = $this->getModelClass();
- $model = new $className();
- // We write before saveInto, since this will let us save has-many and many-many relationships :-)
- $model->write();
- $form->saveInto($model);
- $model->write();
-
- if($this->isAjax()) {
- $class = $this->parentController->getRecordControllerClass($this->getModelClass());
- $recordController = new $class($this, $request, $model->ID);
- return new SS_HTTPResponse(
- $recordController->EditForm()->formHtmlContent(),
- 200,
- sprintf(
- _t('ModelAdmin.LOADEDFOREDITING', "Loaded '%s' for editing."),
- $model->Title
- )
- );
- } else {
- Director::redirect(Controller::join_links($this->Link(), $model->ID , 'edit'));
- }
- }
-}
-
-/**
- * Handles operations on a single record from a managed model.
- *
- * @package cms
- * @subpackage core
- * @todo change the parent controller varname to indicate the model scaffolding functionality in ModelAdmin
- */
-class ModelAdmin_RecordController extends Controller {
- protected $parentController;
- protected $currentRecord;
-
- static $allowed_actions = array('edit', 'view', 'EditForm', 'ViewForm');
-
- function __construct($parentController, $request, $recordID = null) {
- $this->parentController = $parentController;
- $modelName = $parentController->getModelClass();
- $recordID = ($recordID) ? $recordID : $request->param('Action');
- $this->currentRecord = DataObject::get_by_id($modelName, $recordID);
-
- parent::__construct();
- }
-
- /**
- * Link fragment - appends the current record ID to the URL.
- */
- public function Link($action = null) {
- return $this->parentController->Link(Controller::join_links($this->currentRecord->ID, $action));
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Edit action - shows a form for editing this record
- */
- function edit($request) {
- if ($this->currentRecord) {
- if($this->isAjax()) {
- $this->response->setBody($this->EditForm()->formHtmlContent());
- $this->response->setStatusCode(
- 200,
- sprintf(
- _t('ModelAdmin.LOADEDFOREDITING', "Loaded '%s' for editing."),
- $this->currentRecord->Title
- )
- );
- return $this->response;
- } else {
- // This is really quite ugly; to fix will require a change in the way that customise() works. :-(
- return $this->parentController->parentController->customise(array(
- 'Right' => $this->parentController->parentController->customise(array(
- 'EditForm' => $this->EditForm()
- ))->renderWith(array("{$this->class}_right",'LeftAndMain_right'))
- ))->renderWith(array('ModelAdmin','LeftAndMain'));
- }
- } else {
- return _t('ModelAdmin.ITEMNOTFOUND', "I can't find that item");
- }
- }
-
- /**
- * Returns a form for editing the attached model
- */
- public function EditForm() {
- $fields = $this->currentRecord->getCMSFields();
- $fields->push(new HiddenField("ID"));
-
- $validator = ($this->currentRecord->hasMethod('getCMSValidator')) ? $this->currentRecord->getCMSValidator() : new RequiredFields();
- $validator->setJavascriptValidationHandler('none');
-
- $actions = $this->currentRecord->getCMSActions();
- if($this->currentRecord->canEdit(Member::currentUser())){
- if(!$actions->fieldByName('action_doSave') && !$actions->fieldByName('action_save')) {
- $actions->push(new FormAction("doSave", _t('ModelAdmin.SAVE', "Save")));
- }
- }else{
- $fields = $fields->makeReadonly();
- }
-
- if($this->currentRecord->canDelete(Member::currentUser())) {
- if(!$actions->fieldByName('action_doDelete')) {
- $actions->insertFirst($deleteAction = new FormAction('doDelete', _t('ModelAdmin.DELETE', 'Delete')));
- }
- $deleteAction->addExtraClass('delete');
- }
-
- $form = new Form($this, "EditForm", $fields, $actions, $validator);
- $form->loadDataFrom($this->currentRecord);
-
- return $form;
- }
-
- /**
- * Postback action to save a record
- *
- * @param array $data
- * @param Form $form
- * @param SS_HTTPRequest $request
- * @return mixed
- */
- function doSave($data, $form, $request) {
- $form->saveInto($this->currentRecord);
-
- try {
- $this->currentRecord->write();
- } catch(ValidationException $e) {
- $form->sessionMessage($e->getResult()->message(), 'bad');
- }
-
-
- // Behaviour switched on .
- if($this->parentController->isAjax()) {
- return $this->edit($request);
- } else {
- $this->parentController->redirectBack();
- }
- }
-
- /**
- * Delete the current record
- */
- public function doDelete($data, $form, $request) {
- if($this->currentRecord->canDelete(Member::currentUser())) {
- $this->currentRecord->delete();
- Director::redirect($this->parentController->Link('SearchForm?action=search'));
- } else {
- $this->parentController->redirectBack();
- }
- return;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- /**
- * Renders the record view template.
- *
- * @param SS_HTTPRequest $request
- * @return mixed
- */
- function view($request) {
- if($this->currentRecord) {
- $form = $this->ViewForm();
- return $form->formHtmlContent();
- } else {
- return _t('ModelAdmin.ITEMNOTFOUND');
- }
- }
-
- /**
- * Returns a form for viewing the attached model
- *
- * @return Form
- */
- public function ViewForm() {
- $fields = $this->currentRecord->getCMSFields();
- $form = new Form($this, "EditForm", $fields, new FieldSet());
- $form->loadDataFrom($this->currentRecord);
- $form->makeReadonly();
- return $form;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- function index() {
- Director::redirect(Controller::join_links($this->Link(), 'edit'));
- }
-
- function getCurrentRecord(){
- return $this->currentRecord;
- }
-
-}
-
-?>
\ No newline at end of file
diff --git a/code/SecurityAdmin.php b/code/SecurityAdmin.php
deleted file mode 100644
index 25bf9ab7..00000000
--- a/code/SecurityAdmin.php
+++ /dev/null
@@ -1,372 +0,0 @@
-currentPageID();
- $form = parent::getEditForm($id);
-
- // TODO Duplicate record fetching (see parent implementation)
- $record = $this->getRecord($id);
- if($record && !$record->canView()) return Security::permissionFailure($this);
-
- if($id && is_numeric($id)) {
- $form = parent::getEditForm($id);
- if(!$form) return false;
-
- $fields = $form->Fields();
- if($fields->hasTabSet() && $record->canEdit()) {
- $fields->findOrMakeTab('Root.Import',_t('Group.IMPORTTABTITLE', 'Import'));
- $fields->addFieldToTab('Root.Import',
- new LiteralField(
- 'MemberImportFormIframe',
- sprintf(
- '',
- $this->Link('memberimport')
- )
- )
- );
- if(Permission::check('APPLY_ROLES')) {
- $fields->addFieldToTab(
- 'Root.Roles',
- new LiteralField(
- 'RolesAddEditLink',
- sprintf(
- '
',
- $this->Link('show/root'),
- // TODO This should include #Root_Roles to switch directly to the tab,
- // but tabstrip.js doesn't display tabs when directly adressed through a URL pragma
- _t('Group.RolesAddEditLink', 'Add/edit roles')
- )
- )
- );
- }
-
- $form->Actions()->insertBefore(
- $actionAddMember = new FormAction('addmember',_t('SecurityAdmin.ADDMEMBER','Add Member')),
- 'action_save'
- );
- $actionAddMember->setForm($form);
-
- // Filter permissions
- $permissionField = $form->Fields()->dataFieldByName('Permissions');
- if($permissionField) $permissionField->setHiddenPermissions(self::$hidden_permissions);
- }
-
- $this->extend('updateEditForm', $form);
- } else {
- $form = $this->RootForm();
- }
-
- return $form;
- }
-
- /**
- * @return FieldSet
- */
- function RootForm() {
- $memberList = new MemberTableField(
- $this,
- "Members"
- );
- // unset 'inlineadd' permission, we don't want inline addition
- $memberList->setPermissions(array('edit', 'delete', 'add'));
- $memberList->setRelationAutoSetting(false);
-
- $fields = new FieldSet(
- new TabSet(
- 'Root',
- new Tab('Members', singleton('Member')->i18n_plural_name(),
- $memberList,
- new LiteralField('MembersCautionText',
- sprintf('
%s
',
- _t(
- 'SecurityAdmin.MemberListCaution',
- 'Caution: Removing members from this list will remove them from all groups and the database'
- )
- )
- )
- ),
- new Tab('Import', _t('SecurityAdmin.TABIMPORT', 'Import'),
- new LiteralField(
- 'GroupImportFormIframe',
- sprintf(
- '',
- $this->Link('groupimport')
- )
- )
- )
- ),
- // necessary for tree node selection in LeftAndMain.EditForm.js
- new HiddenField('ID', false, 0)
- );
-
- // Add roles editing interface
- if(Permission::check('APPLY_ROLES')) {
- $rolesCTF = new ComplexTableField(
- $this,
- 'Roles',
- 'PermissionRole'
- );
- $rolesCTF->setPermissions(array('add', 'edit', 'delete'));
-
- $rolesTab = $fields->findOrMakeTab('Root.Roles', _t('SecurityAdmin.TABROLES', 'Roles'));
- $rolesTab->push(new LiteralField(
- 'RolesDescription',
- ''
- ));
- $rolesTab->push($rolesCTF);
- }
-
- $actions = new FieldSet(
- new FormAction('addmember',_t('SecurityAdmin.ADDMEMBER','Add Member'))
- );
-
- $this->extend('updateRootFormFields', $fields, $actions);
-
- $form = new Form(
- $this,
- 'EditForm',
- $fields,
- $actions
- );
-
- return $form;
- }
-
- public function memberimport() {
- Requirements::clear();
- Requirements::css(SAPPHIRE_DIR . '/css/Form.css');
- Requirements::css(CMS_DIR . '/css/typography.css');
- Requirements::css(CMS_DIR . '/css/cms_right.css');
- Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
- Requirements::css(CMS_DIR . '/css/MemberImportForm.css');
- Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-entwine/dist/jquery.entwine-dist.js');
- Requirements::javascript(CMS_DIR . '/javascript/MemberImportForm.js');
-
- return $this->renderWith('BlankPage', array(
- 'Form' => $this->MemberImportForm()
- ));
- }
-
- /**
- * @see SecurityAdmin_MemberImportForm
- *
- * @return Form
- */
- public function MemberImportForm() {
- $group = $this->currentPage();
- $form = new MemberImportForm(
- $this,
- 'MemberImportForm'
- );
- $form->setGroup($group);
-
- return $form;
- }
-
- public function groupimport() {
- Requirements::clear();
- Requirements::css(SAPPHIRE_DIR . '/css/Form.css');
- Requirements::css(CMS_DIR . '/css/typography.css');
- Requirements::css(CMS_DIR . '/css/cms_right.css');
- Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
- Requirements::css(CMS_DIR . '/css/MemberImportForm.css');
- Requirements::javascript(SAPPHIRE_DIR . '/thirdparty/jquery-entwine/dist/jquery.entwine-dist.js');
- Requirements::javascript(CMS_DIR . '/javascript/MemberImportForm.js');
-
- return $this->renderWith('BlankPage', array(
- 'Form' => $this->GroupImportForm()
- ));
- }
-
- /**
- * @see SecurityAdmin_MemberImportForm
- *
- * @return Form
- */
- public function GroupImportForm() {
- $form = new GroupImportForm(
- $this,
- 'GroupImportForm'
- );
-
- return $form;
- }
-
- public function AddRecordForm() {
- $m = Object::create('MemberTableField',
- $this,
- "Members",
- $this->currentPageID()
- );
- return $m->AddRecordForm();
- }
-
- /**
- * Ajax autocompletion
- */
- public function autocomplete() {
- $fieldName = $this->urlParams['ID'];
- $fieldVal = $_REQUEST[$fieldName];
- $result = '';
- $uidField = Member::get_unique_identifier_field();
-
- // Make sure we only autocomplete on keys that actually exist, and that we don't autocomplete on password
- if(!singleton($this->stat('subitem_class'))->hasDatabaseField($fieldName) || $fieldName == 'Password') return;
-
- $matches = DataObject::get($this->stat('subitem_class'),"\"$fieldName\" LIKE '" . Convert::raw2sql($fieldVal) . "%'");
- if($matches) {
- $result .= "
";
- foreach($matches as $match) {
- // If the current user doesnt have permissions on the target user,
- // he's not allowed to add it to a group either: Don't include it in the suggestions.
- if(!$match->canView() || !$match->canEdit()) continue;
-
- $data = array();
- foreach($match->summaryFields() as $k => $v) {
- $data[$k] = $match->$k;
- }
- $result .= sprintf(
- '