diff --git a/_config.php b/_config.php
index 5feb389..b3d9bbc 100644
--- a/_config.php
+++ b/_config.php
@@ -1,23 +1 @@
\ No newline at end of file
diff --git a/code/AssetManager.php b/code/AssetManager.php
deleted file mode 100644
index 9c5f605..0000000
--- a/code/AssetManager.php
+++ /dev/null
@@ -1,40 +0,0 @@
- 'Title',
- 'Filename' => 'Filename'
- );
- }
-
- $fields = singleton($sourceClass)->getCMSFields();
- $fields->removeByName("OwnerID");
- $fields->removeByName("Parent");
- $fields->removeByName("Filename");
- $fields->removeByName("SortOrder");
- $fields->removeByName("Sort");
- $fields->push(new ReadonlyField('Filename'));
- $fields->push(new SimpleTreeDropdownField('ParentID','Folder',"Folder"));
- $fields->push(new HiddenField('ID','',$controller->ID));
-
- parent::__construct($controller, $name, $sourceClass, null, $headings, $fields, "\"ClassName\" != 'Folder'");
- }
-
- function FieldHolder()
- {
- if(!$this->controller->ID)
- return "";
- return parent::FieldHolder();
- }
-
-
-}
-
-?>
\ No newline at end of file
diff --git a/code/AssetManagerFolder.php b/code/AssetManagerFolder.php
deleted file mode 100644
index a1a461a..0000000
--- a/code/AssetManagerFolder.php
+++ /dev/null
@@ -1,31 +0,0 @@
-removeFieldFromTab("Root.Files","Files");
- $fields->removeFieldFromTab("Root.Files","deletemarked");
- $fields->removeByName("Upload");
- $fields->addFieldToTab("Root.Files", $a = new AssetManager($this->owner,"Files"));
- $a->setUploadFolder($this->owner->Filename);
- $a->setColumnWidths(array(
- 'Title' => 30,
- 'Filename' => 70
- ));
- $folder_filter = "(\"ClassName\" != 'Folder' AND \"ParentID\" = ".$this->owner->ID.")";
- $filter = $a->sourceFilter ? "({$a->sourceFilter}) AND $folder_filter" : $folder_filter;
- $a->setSourceFilter($filter);
- $a->setParentClass("Folder");
- $a->setPermissions(self::$permissions);
- if($this->owner->Title)
- $a->setAddTitle(sprintf(_t('AssetManager.ADDFILESTO','files to "%s"'),$this->owner->Title));
- else
- $a->setAddTitle(_t('AssetManager.FILES','files'));
- return $fields;
- }
-}
-
-?>
\ No newline at end of file
diff --git a/code/DataObjectManager.php b/code/DataObjectManager.php
index c877d02..ebcc168 100644
--- a/code/DataObjectManager.php
+++ b/code/DataObjectManager.php
@@ -1,1184 +1,96 @@
array(
- 'label' => 'Edit',
- 'icon' => null,
- 'class' => 'popuplink editlink',
- ),
- 'delete' => array(
- 'label' => 'Delete',
- 'icon' => null,
- 'class' => 'deletelink',
- )
- );
+ protected $grid;
- static $url_handlers = array(
- 'duplicate/$ID' => 'handleDuplicate'
- );
-
-
- public $popupClass = "DataObjectManager_Popup";
- public $templatePopup = "DataObjectManager_popup";
-
- public static function allow_assets_override($bool)
- {
- if($bool) {
- DataObject::add_extension("Folder","AssetManagerFolder");
- SortableDataObject::add_sortable_class("File");
- }
- else
- DataObject::remove_extension("Folder","AssetManagerFolder");
- }
-
- public static function allow_css_override($bool)
- {
- self::$allow_css_override = $bool;
- }
-
- public static function set_popup_width($width)
- {
- self::$popup_width = $width;
- }
-
- public static function set_confirm_delete($bool)
- {
- self::$confirm_delete = $bool;
- }
+ protected $dataClass;
function __construct($controller, $name = null, $sourceClass = null, $fieldList = null, $detailFormFields = null, $sourceFilter = "", $sourceSort = null, $sourceJoin = "")
{
- if(!class_exists("ComplexTableField_ItemRequest"))
- die(""._t('DataObjectManager.ERROR','Error').": "._t('DataObjectManager.SILVERSTRIPEVERSION','DataObjectManager requires Silverstripe version 2.3 or higher.'));
-
- // If no name is given, search the has_many for the first relation.
- if($name === null && $sourceClass === null) {
- if($has_manys = $controller->stat('has_many')) {
- foreach($has_manys as $relation => $value) {
- $name = $relation;
- $sourceClass = $value;
- break;
- }
- }
- }
- $SNG = singleton($sourceClass);
-
-
- if($fieldList === null) {
- $diff = array_diff($SNG->summaryFields(),singleton('DataObject')->summaryFields());
- if(!empty($diff)) {
- $fieldList = $SNG->summaryFields();
- }
- else if($db = $SNG->db()) {
- $fieldList = array();
- foreach($db as $field => $type) {
- if($field != "SortOrder")
- $fieldList[$field] = DOMUtil::readable_class($field);
- }
- }
- }
- parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin);
- Requirements::css('dataobject_manager/css/dataobject_manager.css');
- Requirements::css('dataobject_manager/css/facebox.css');
- if(self::$allow_css_override)
- Requirements::css('dataobject_manager/css/dataobjectmanager_override.css');
- Requirements::javascript(THIRDPARTY_DIR.'/jquery-livequery/jquery.livequery.js');
- Requirements::javascript('dataobject_manager/javascript/facebox.js');
- Requirements::javascript('dataobject_manager/javascript/dom_jquery_ui.js');
- Requirements::javascript('dataobject_manager/javascript/tooltip.js');
- Requirements::javascript('dataobject_manager/javascript/dataobject_manager.js');
-
- $this->filter_empty_string = '-- '._t('DataObjectManager.NOFILTER','No filter').' --';
-
- if($this->sourceSort) {
- $parts = explode(" " , $this->sourceSort);
- if(is_array($parts) && sizeof($parts) == 2) {
- list($field,$dir) = $parts;
- $this->sort = trim($field);
- $this->sort_dir = trim($dir);
- }
- else {
- $this->sort = $this->sourceSort;
- $this->sort_dir = "ASC";
- }
- }
-
- if(isset($_REQUEST['ctf'][$this->Name()])) {
- $this->start = $_REQUEST['ctf'][$this->Name()]['start'];
- $this->per_page = $_REQUEST['ctf'][$this->Name()]['per_page'];
- $this->showAll = $_REQUEST['ctf'][$this->Name()]['showall'];
- $this->search = $_REQUEST['ctf'][$this->Name()]['search'];
- $this->filter = $_REQUEST['ctf'][$this->Name()]['filter'];
- $this->sort = $_REQUEST['ctf'][$this->Name()]['sort'];
- $this->sort_dir = $_REQUEST['ctf'][$this->Name()]['sort_dir'];
- }
-
-
- $this->setPageSize($this->per_page);
- $this->loadSort();
- $this->loadSourceFilter();
-
- $fields = $this->getRawDetailFields(singleton($this->sourceClass()));
- foreach($fields as $field) {
- if($field instanceof DataObjectManager && !($field->controller instanceof SiteTree)) {
- $this->hasNested = true;
- $this->setPopupWidth(850);
- }
- elseif(class_exists("KickAssetField") && $field instanceof KickAssetField) {
- $this->setPopupWidth(850);
- }
- }
-
- }
-
- public function setClickToToggle($bool) {
- $this->clickToToggle = $bool;
- }
-
- public function setSourceFilter($filter)
- {
- $this->sourceFilter = $filter;
- }
-
- public function setUseViewAll($bool)
- {
- $this->use_view_all = $bool;
- }
-
- public function setPerPageMap($values)
- {
- $this->per_page_map = $values;
- }
-
- public function setPluralTitle($title)
- {
- $this->pluralTitle = $title;
- }
-
- public function setWideMode($bool)
- {
- $this->hasNested = $bool;
- }
-
- public function PluralTitle()
- {
- return $this->pluralTitle ? $this->pluralTitle : $this->AddTitle()."s";
- }
-
-
- protected function loadSort()
- {
- if($this->ShowAll())
- $this->setPageSize(999);
-
- if($this->Sortable() && (!isset($_REQUEST['ctf'][$this->Name()]['sort']) || $_REQUEST['ctf'][$this->Name()]['sort'] == "SortOrder")) {
- $this->sort = "SortOrder";
- $this->sourceSort = "\"SortOrder\" ASC";
- }
- elseif(isset($_REQUEST['ctf'][$this->Name()]['sort']) && !empty($_REQUEST['ctf'][$this->Name()]['sort'])) {
- $this->sourceSort = "\"" . $_REQUEST['ctf'][$this->Name()]['sort'] . "\" " . $this->sort_dir;
- }
- elseif($sort = singleton($this->sourceClass())->stat('default_sort')) {
- $this->sourceSort = $sort;
- }
- else {
- $this->sourceSort = "Created DESC";
- }
-
- }
-
- protected function loadSourceFilter()
- {
- $filter_string = "";
- if(!empty($this->filter)) {
- $break = strpos($this->filter, "_");
- $field = substr($this->filter, 0, $break);
- $value = substr($this->filter, $break+1, strlen($this->filter) - strlen($field));
- $filter_string = $field . "='$value'";
- }
-
- $search_string = "";
- if(!empty($this->search)) {
- $search = array();
- $SNG = singleton($this->sourceClass);
- foreach(parent::Headings() as $field) {
- if($SNG->hasDatabaseField($field->Name))
- $search[] = "UPPER({$this->sourceClass}.$field->Name) LIKE '%".Convert::raw2sql(strtoupper($this->search))."%'";
- }
- if(!empty($search)) {
- $search_string = "(".implode(" OR ", $search).")";
+ $title = FormField::name_to_label($name);
+ parent::__construct($name, $title);
+ $this->grid = new GridField($name, $title, $controller->$name(), GridFieldConfig_RecordEditor::create());
+ $this->dataClass = $sourceClass;
+ if($fieldList) {
+ $this->grid->getConfig()->getComponentByType('GridFieldDataColumns')->setDisplayFields($fieldList);
+ }
+ elseif(!singleton($this->dataClass)->stat('summary_fields')) {
+ if($db = singleton($this->dataClass)->db()) {
+ $list = array ();
+ foreach($db as $name => $type) {
+ $list[$name] = FormField::name_to_label($name);
+ }
+ $this->grid->setDisplayFields($list);
}
}
- $and = (!empty($this->filter) && !empty($this->search)) ? " AND " : "";
- $source_filter = $filter_string.$and.$search_string;
- if(!$this->sourceFilter) $this->sourceFilter = $source_filter;
- else if($this->sourceFilter && !empty($source_filter)) $this->sourceFilter .= " AND " . $source_filter;
- }
-
- public function handleItem($request) {
- return new DataObjectManager_ItemRequest($this, $request->param('ID'));
}
- public function getQueryString($params = array())
- {
- $start = isset($params['start'])? $params['start'] : $this->start;
- $per_page = isset($params['per_page'])? $params['per_page'] : $this->per_page;
- $show_all = isset($params['show_all'])? $params['show_all'] : $this->showAll;
- $sort = isset($params['sort'])? $params['sort'] : $this->sort;
- $sort_dir = isset($params['sort_dir'])? $params['sort_dir'] : $this->sort_dir;
- $filter = isset($params['filter'])? $params['filter'] : $this->filter;
- $search = isset($params['search'])? $params['search'] : $this->search;
- return "ctf[{$this->Name()}][start]={$start}&ctf[{$this->Name()}][per_page]={$per_page}&ctf[{$this->Name()}][showall]={$show_all}&ctf[{$this->Name()}][sort]={$sort}&ctf[{$this->Name()}][sort_dir]={$sort_dir}&ctf[{$this->Name()}][search]={$search}&ctf[{$this->Name()}][filter]={$filter}";
- }
-
- public function getSetting($setting)
- {
- if($this->$setting) {
- return $this->$setting;
- }
- return Object::get_static($this->class,DOMUtil::to_underscore($setting));
- }
-
- function FieldHolder()
- {
- if(!$this->controller->ID && $this->isNested)
- return $this->renderWith('DataObjectManager_holder');
- return parent::FieldHolder();
- }
-
- public function HasSearch() {
- $SNG = singleton($this->sourceClass);
- foreach(parent::Headings() as $field) {
- if($SNG->hasDatabaseField($field->Name)) {
- return true;
- }
- }
- return false;
+ public function setForm($form) {
+ $this->grid->setForm($form);
}
-
- public function Headings()
- {
- $headings = array();
- foreach($this->fieldList as $fieldName => $fieldTitle) {
- if(isset($_REQUEST['ctf'][$this->Name()]['sort_dir']))
- $dir = $_REQUEST['ctf'][$this->Name()]['sort_dir'] == "ASC" ? "DESC" : "ASC";
- else
- $dir = "ASC";
- $headings[] = new ArrayData(array(
- "Name" => $fieldName,
- "Title" => ($this->sourceClass) ? singleton($this->sourceClass)->fieldLabel($fieldTitle) : $fieldTitle,
- "IsSortable" => singleton($this->sourceClass)->hasDatabaseField($fieldName),
- "SortLink" => $this->RelativeLink(array(
- 'sort_dir' => $dir,
- 'sort' => $fieldName
- )),
- "SortDirection" => $dir,
- "IsSorted" => (isset($_REQUEST['ctf'][$this->Name()]['sort'])) && ($_REQUEST['ctf'][$this->Name()]['sort'] == $fieldName),
- "ColumnWidthCSS" => !empty($this->column_widths) ? sprintf("style='width:%f%%;'",($this->column_widths[$fieldName] - 0.1)) : ""
- ));
- }
- return new DataObjectSet($headings);
- }
-
- function saveComplexTableField($data, $form, $params) {
- $className = $this->sourceClass();
- $childData = new $className();
- $form->saveInto($childData);
- try {
- $childData->write();
- }
- catch(ValidationException $e) {
- $form->sessionMessage($e->getResult()->message(), 'bad');
- return Director::redirectBack();
- }
- if($childData->many_many()) {
- $form->saveInto($childData);
- $childData->write();
- }
- $form->sessionMessage(sprintf(_t('DataObjectManager.ADDEDNEW','Added new %s successfully'),$this->SingleTitle()), 'good');
-
- if($form->getFileFields() || $form->getNestedDOMs()) {
- $form->clearMessage();
- Director::redirect(Controller::join_links($this->BaseLink(),'item', $childData->ID, 'edit'));
-
- }
- else Director::redirectBack();
- }
-
- function setSourceID($val) {
- if (is_numeric($val)) {
- $this->sourceID = $val;
- $this->hasCustomSourceID = true;
- }
- }
-
- function sourceID() {
- if ($this->hasCustomSourceID) {
- return $this->sourceID;
- }
-
- if($this->isNested)
- return $this->controller->ID;
- $idField = $this->form->dataFieldByName('ID');
- return ($idField && is_numeric($idField->Value())) ? $idField->Value() : (isset($_REQUEST['ctf']['ID']) ? $_REQUEST['ctf']['ID'] : null);
- }
-
-
- protected function getRawDetailFields($childData)
- {
- if(is_a($this->detailFormFields,"Fieldset"))
- $fields = $this->detailFormFields;
- else {
- if(!is_string($this->detailFormFields)) $this->detailFormFields = "getCMSFields";
- $functioncall = $this->detailFormFields;
- if(!$childData->hasMethod($functioncall)) $functioncall = "getCMSFields";
-
- $fields = $childData->{$functioncall}($this);
- }
- return $fields;
- }
-
- public function getCustomFieldsFor($childData) {
- $fields = $this->getRawDetailFields($childData);
- foreach($fields as $field) {
- if($field->class == "CalendarDateField")
- $fields->replaceField($field->Name(), new DatePickerField($field->Name(), $field->Title(), $field->attrValue()));
- }
- return $fields;
- }
-
- function AddForm($childID = null)
- {
- $form = parent::AddForm($childID);
- $actions = new FieldSet();
- $titles = array();
- if($files = $form->getFileFields()) {
- foreach($files as $field) $titles[] = DOMUtil::readable_class($field->Title());
- }
- if($doms = $form->getNestedDOMs())
- foreach($doms as $field) $titles[] = $field->PluralTitle();
- if(empty($titles))
- $text = _t('DataObjectManager.SAVE','Save');
- elseif(sizeof($titles) > 3) {
- $first_three = array_slice($titles,0,3);
- $remaining = sizeof(array_slice($titles, 4));
- $text = sprintf(_t('DataObjectManager.SAVEANDADD','Save and add %s'), implode(', ',$first_three));
- $text .= ", " . sprintf(_t('DataObjectManager.ANDOTHERCOMPONENTS','and %d other components'),$remaining);
- }
- else
- $text = sprintf(_t('DataObjectManager.SAVEANDADD','Save and add %s'), DOMUtil::readable_list($titles));
-
- $actions->push(
- $saveAction = new FormAction("saveComplexTableField", $text)
- );
- $saveAction->addExtraClass('save');
- $form->setActions($actions);
- $form->Fields()->insertFirst(new LiteralField('open','
'));
- $o = $form->Fields()->Last();
- $form->Fields()->insertAfter(new LiteralField('close','
'),$o->Name());
-
- return $form;
- }
-
- public function ClickToToggle() {
- return $this->clickToToggle;
- }
+ public function setClickToToggle($bool) { }
- public function Link($action = null)
- {
- return Controller::join_links(parent::Link($action),'?'.$this->getQueryString());
- }
-
- public function BaseLink()
- {
- return parent::Link();
- }
-
- public function CurrentLink()
- {
- return $this->Link();
- }
-
- public function RelativeLink($params = array())
- {
- return Controller::join_links(parent::Link(),'?'.$this->getQueryString($params));
- }
- public function FirstLink()
- {
- return parent::FirstLink() ? $this->RelativeLink(array('start' => '0')) : false;
- }
-
- public function PrevLink()
- {
- $start = ($this->start - $this->pageSize < 0) ? 0 : $this->start - $this->pageSize;
- return parent::PrevLink() ? $this->RelativeLink(array('start' => $start)) : false;
- }
-
- public function NextLink()
- {
- $currentStart = isset($_REQUEST['ctf'][$this->Name()]['start']) ? $_REQUEST['ctf'][$this->Name()]['start'] : 0;
- $start = ($currentStart + $this->pageSize < $this->TotalCount()) ? $currentStart + $this->pageSize : $this->TotalCount() % $this->pageSize > 0;
- return parent::NextLink() ? $this->RelativeLink(array('start' => $start)) : false;
- }
- public function LastLink()
- {
- $pageSize = ($this->TotalCount() % $this->pageSize > 0) ? $this->TotalCount() % $this->pageSize : $this->pageSize;
- $start = $this->TotalCount() - $pageSize;
- return parent::LastLink() ? $this->RelativeLink(array('start' => $start)) : false;
+ public function setSourceFilter($filter) {
+ $this->grid->getList()->where($filter);
}
- public function ShowAllLink()
- {
- return $this->RelativeLink(array('show_all' => '1'));
- }
- public function PaginatedLink()
- {
- return $this->RelativeLink(array('show_all' => '0'));
- }
-
- public function AddLink() {
- return Controller::join_links($this->BaseLink(), 'add');
- }
-
- public function ShowAll()
- {
- return $this->showAll == "1";
- }
+ public function setUseViewAll($bool) { }
- public function Paginated()
- {
- return $this->showAll == "0";
- }
-
- public function Sortable()
- {
- return DataObject::has_extension($this->sourceClass(), 'SortableDataObject');
- }
- public function setFilter($field, $label, $map, $default = null)
- {
- if(is_array($map)) {
- $this->filter_map = $map;
- $this->filtered_field = $field;
- $this->filter_label = $label;
- }
- if($default) {
- $this->filter = $this->filtered_field.'_'.$default;
- $this->loadSourceFilter();
- }
- }
+ public function setPerPageMap($values) { }
- public function HasFilter()
- {
- return !empty($this->filter_map);
- }
-
- public function FilterDropdown()
- {
- $map = $this->filter_empty_string ? array($this->RelativeLink(array('filter' => '')) => $this->filter_empty_string) : array();
- foreach($this->filter_map as $k => $v) {
- $map[$this->RelativeLink(array('filter' => $this->filtered_field.'_'.$k))] = $v;
- }
- $value = !empty($this->filter) ? $this->RelativeLink(array('filter' => $this->filter)) : null;
- $dropdown = new DropdownField('Filter',$this->filter_label . " ("._t('DataObjectManager.REFRESH','refresh').")", $map, $value);
- return $dropdown->FieldHolder();
- }
-
- public function PerPageDropdown()
- {
- $map = array();
- foreach($this->per_page_map as $num) $map[$this->RelativeLink(array('per_page' => $num))] = $num;
- if($this->use_view_all)
- $map[$this->RelativeLink(array('per_page' => '9999'))] = _t('DataObjectManager.ALL','All');
- $value = !empty($this->per_page) ? $this->RelativeLink(array('per_page' => $this->per_page)) : null;
- return new FieldGroup(
- new LabelField('show', _t('DataObjectManager.PERPAGESHOW','Show').' ',null,true),
- new DropdownField('PerPage','',$map, $value),
- new LabelField('results', ' '._t('DataObjectManager.PERPAGERESULTS','results per page'),null,true)
- );
- }
- public function SearchValue()
- {
- return !empty($this->search) ? $this->search : false;
- }
-
- public function AddTitle()
- {
- return $this->addTitle ? $this->addTitle : DOMUtil::readable_class($this->Title());
- }
-
- public function SingleTitle()
- {
- return $this->singleTitle ? $this->singleTitle : DOMUtil::readable_class($this->AddTitle());
- }
-
- public function setAddTitle($title)
- {
- $this->addTitle = $title;
- }
-
- public function setSingleTitle($title)
- {
- $this->singleTitle = $title;
+ public function setPluralTitle($title) {
+ $this->grid->setTitle($title);
}
- public function getColumnWidths()
- {
- return $this->column_widths;
- }
-
- public function setColumnWidths($widths)
- {
- if(is_array($widths)) {
- $total = 0;
- foreach($widths as $name => $value) $total += $value;
- if($total != 100)
- die('DataObjectManager::setColumnWidths():' . sprintf(_t('DataObjectManager.TOTALNOT100','Column widths must total 100 and not %s'), $total));
- else
- $this->column_widths = $widths;
- }
- }
-
- public function setFilterEmptyString($str)
- {
- $this->filter_empty_string = $str;
- }
-
- public function addPermission($perm)
- {
- if(!in_array($perm,$this->permissions))
- $this->permissions[] = $perm;
- }
-
- public function removePermission($perm)
- {
- $key = array_search($perm,$this->permissions);
- if($key !== false)
- unset($this->permissions[$key]);
- }
-
- public function NestedType()
- {
- if($this->hasNested)
- return "hasNested";
- else if($this->isNested)
- return "isNested";
- else
- return "";
- }
-
- public function handleDuplicate($request)
- {
- return new DataObjectManager_ItemRequest($this,$request->param('ID'));
- }
-
- public function setPopupWidth($val)
- {
- $this->popupWidth = $val;
- }
-
- public function setConfirmDelete($bool)
- {
- $this->confirmDelete = $bool;
- }
-
- public function PopupWidth()
- {
- return $this->popupWidth ? $this->popupWidth : self::$popup_width;
- }
-
- public function ConfirmDelete()
- {
- return $this->getSetting('confirmDelete');
- }
-
-
+ public function setWideMode($bool) { }
-}
-class DataObjectManager_Item extends ComplexTableField_Item {
- function __construct(DataObject $item, DataObjectManager $parent)
- {
- parent::__construct($item, $parent);
- }
- function Link() {
- return Controller::join_links($this->parent->BaseLink(), 'item', $this->item->ID);
- }
-
- function Fields() {
- $fields = parent::Fields();
- $widths = $this->parent->getColumnWidths();
- if(!empty($widths)) {
- foreach($fields as $field) {
- $field->ColumnWidthCSS = sprintf("style='width:%f%%;'",($widths[$field->Name] - 0.1));
- }
- }
- return $fields;
- }
-
- public function CanViewOrEdit()
- {
- return $this->parent->Can('view') || $this->parent->Can('edit');
- }
-
- public function ViewOrEdit()
- {
- if($this->CanViewOrEdit())
- return $this->parent->Can('edit') ? "edit" : "view";
- return false;
- }
-
- public function ViewOrEdit_i18n()
- {
- if($res = $this->ViewOrEdit()) {
- return ($res == "edit") ? _t('DataObjectManager.EDIT','Edit') : _t('DataObjectManager.VIEW','View');
- }
- return null;
- }
-
- public function EditLink()
- {
- return Controller::join_links($this->Link(), "edit","?".$this->parent->getQueryString());
- }
-
- public function DuplicateLink()
- {
- return Controller::join_links($this->Link(), "duplicate");
- }
+ public function setFilter($field, $label, $map, $default = null) { }
- public function CustomActions()
- {
- if($this->item->hasMethod('customDOMActions')) {
- return $this->item->customDOMActions();
- }
- return false;
- }
+ public function setSingleTitle($title) { }
- public function PopupWidth()
- {
- return $this->parent->PopupWidth();
- }
-
- public function Actions()
- {
- $actions = new DataObjectSet();
- foreach($this->parent->permissions as $perm) {
- $action = false;
- switch($perm) {
- case "edit":
- case "view":
- $actions->push(new DataObjectManagerAction(
- $this->ViewOrEdit_i18n(),
- $this->EditLink(),
- "popup",
- "dataobject_manager/images/page_white_{$this->ViewOrEdit()}.png",
- "editlink" ,
- $this->parent->PopupWidth()
- ));
- break;
-
- case "delete":
- $actions->push(new DataObjectManagerAction(
- _t('DataObjectManager.DELETE','Delete'),
- $this->DeleteLink(),
- "delete",
- "dataobject_manager/images/trash.gif",
- null,
- $this->parent->getSetting('confirmDelete') ? "confirm" : null
- ));
- break;
-
- case "duplicate":
- $actions->push(new DataObjectManagerAction(
- _t('DataObjectManager.DUPLICATE','Duplicate'),
- $this->DuplicateLink(),
- "popup",
- "dataobject_manager/images/page_copy.png",
- null,
- 400
- ));
- break;
- }
- }
- if($custom = $this->CustomActions()) {
- if($custom instanceof DataObjectSet)
- $actions->merge($custom);
- else
- $actions->push($custom);
- }
- return $actions;
- }
-}
-
-class DataObjectManager_Controller extends Controller
-{
- public function dosort()
- {
- if(!empty($_POST) && is_array($_POST) && isset($this->urlParams['ID'])) {
- $className = $this->urlParams['ID'];
- if(stristr($className,"-") !== false) {
- list($ownerClass, $className) = explode("-",$className);
- }
- $many_many = ((is_numeric($this->urlParams['OtherID'])) && SortableDataObject::is_sortable_many_many($className));
- foreach($_POST as $group => $map) {
- if(substr($group, 0, 7) == "record-") {
- if($many_many) {
- $controllerID = $this->urlParams['OtherID'];
- $candidates = singleton($ownerClass)->many_many();
- if(is_array($candidates)) {
- foreach($candidates as $name => $class)
- if($class == $className) {
- $relationName = $name;
- break;
- }
- }
- if(!isset($relationName)) return false;
- list($parentClass, $componentClass, $parentField, $componentField, $table) = singleton($ownerClass)->many_many($relationName);
- foreach($map as $sort => $id)
- DB::query("UPDATE \"$table\" SET \"SortOrder\" = $sort WHERE \"{$className}ID\" = $id AND \"{$ownerClass}ID\" = $controllerID");
- }
- else {
- foreach($map as $sort => $id) {
- $obj = DataObject::get_by_id($className, $id);
- $obj->SortOrder = $sort;
- $obj->write();
- }
- }
- break;
- }
- }
- }
- }
- public function i18n_js()
- {
- return Convert::array2json(array(
- 'delete_confirm' => _t('DataObjectManager.CONFIRMDELETE','Delete?')
- ));
- }
-}
+ public function getColumnWidths() { }
-
-class DataObjectManager_Popup extends Form {
- protected $sourceClass;
- protected $dataObject;
- public $NestedController = false;
-
- function __construct($controller, $name, $fields, $validator, $readonly, $dataObject) {
- $this->dataObject = $dataObject;
- Requirements::clear();
- Requirements::clear_combined_files();
- // added prototype.js to provide support for TreeDropdownField
- Requirements::javascript(THIRDPARTY_DIR.'/prototype/prototype.js');
- Requirements::javascript(THIRDPARTY_DIR.'/jquery/jquery.js');
- Requirements::javascript(THIRDPARTY_DIR.'/jquery-livequery/jquery.livequery.js');
- Requirements::block(THIRDPARTY_DIR.'/behaviour.js');
- Requirements::block(SAPPHIRE_DIR.'/javascript/Validator.js');
- Requirements::clear(THIRDPARTY_DIR.'/behavior.js');
- Requirements::block(THIRDPARTY_DIR.'/behavior.js');
- Requirements::block(SAPPHIRE_DIR.'/javascript/ComplexTableField.js');
- Requirements::block(SAPPHIRE_DIR.'/javascript/TableListField.js');
- Requirements::block(THIRDPARTY_DIR.'/greybox/greybox.js');
- Requirements::block(THIRDPARTY_DIR.'/greybox/AmiJS.js');
- Requirements::block(THIRDPARTY_DIR.'/greybox/greybox.css');
- Requirements::block(SAPPHIRE_DIR.'/css/TableListField.css');
- Requirements::block(SAPPHIRE_DIR.'/css/ComplexTableField.css');
- Requirements::block(ASSETS_DIR.'/leftandmain.js');
- Requirements::block(ASSETS_DIR.'/base.js');
- Requirements::block(SAPPHIRE_DIR.'/javascript/lang/en_US.js');
- Requirements::css(SAPPHIRE_DIR . '/css/Form.css');
- Requirements::css(CMS_DIR . '/css/typography.css');
- Requirements::css(CMS_DIR . '/css/cms_right.css');
- Requirements::css('dataobject_manager/css/dataobject_manager.css');
-
- if($this->dataObject->hasMethod('getRequirementsForPopup')) {
- $this->dataObject->getRequirementsForPopup();
- }
- Requirements::javascript('dataobject_manager/javascript/dataobjectmanager_popup.js');
-
-
- $actions = new FieldSet();
- if(!$readonly) {
- $actions->push(
- $saveAction = new FormAction("saveComplexTableField", _t('DataObjectManager.SAVE','Save'))
-
- );
- $saveAction->addExtraClass('save');
- }
-
- parent::__construct($controller, $name, $fields, $actions, $validator);
- if ($this->validator instanceof Validator) {
- $this->validator->setJavascriptValidationHandler('none');
- }
- else {
- $this->unsetValidator();
- }
-
-
- if($this->getNestedDOMs()) {
- Requirements::javascript(THIRDPARTY_DIR.'/jquery-livequery/jquery.livequery.js');
- Requirements::javascript('dataobject_manager/javascript/dom_jquery_ui.js');
- Requirements::javascript('dataobject_manager/javascript/tooltip.js');
- Requirements::javascript('dataobject_manager/javascript/dataobject_manager.js');
- }
- $this->NestedController = $this->controller->isNested;
- }
-
- function FieldHolder() {
- return $this->renderWith('ComplexTableField_Form');
- }
+ public function setColumnWidths($widths) { }
- public function getFileFields()
- {
- $file_fields = array();
- foreach($this->Fields() as $field) {
- if($field instanceof FileIFrameField || $field instanceof ImageField)
- $file_fields[] = $field;
- }
- return !empty($file_fields)? $file_fields : false;
- }
+ public function setFilterEmptyString($str) { }
- public function getNestedDOMs()
- {
- $dom_fields = array();
- foreach($this->Fields()->dataFields() as $field) {
- if($field instanceof DataObjectManager) {
- $field->isNested = true;
- $dom_fields[] = $field;
- }
- elseif($field instanceof CompositeField) {
- if($children = $field->children) {
- foreach($children as $child) {
- if($child instanceof DataObjectManager) {
- $child->isNested = true;
- $dom_fields[] = $child;
- }
- }
- }
- }
- }
- return !empty($dom_fields)? $dom_fields : false;
- }
+ public function addPermission($perm) { }
+ public function removePermission($perm) { }
+
+ public function setPopupWidth($val) { }
-}
-
-
-
-class DataObjectManager_ItemRequest extends ComplexTableField_ItemRequest
-{
- public $isNested = false;
- protected $itemList;
- protected $currentIndex;
+ public function setConfirmDelete($bool) { }
- function __construct($ctf, $itemID)
- {
- parent::__construct($ctf, $itemID);
- $this->isNested = $this->ctf->isNested;
- if($this->ctf->Items()) {
- $this->itemList = $this->ctf->Items()->column();
- $this->currentIndex = array_search($this->itemID,$this->itemList);
- }
+ public function Field($properties = array()) {
+ return $this->FieldHolder($properties);
}
- function Link()
- {
- return Controller::join_links($this->ctf->BaseLink() , 'item', $this->itemID);
- }
-
- function saveComplexTableField($data, $form, $request) {
- $dataObject = $this->dataObj();
- $form->saveInto($dataObject);
- try {
- $dataObject->write();
- }
- catch(ValidationException $e) {
- $form->sessionMessage($e->getResult()->message(), 'bad');
- return Director::redirectBack();
- }
-
- // Save the many many relationship if it's available
- if(isset($data['ctf']['manyManyRelation'])) {
- $parentRecord = DataObject::get_by_id($data['ctf']['parentClass'], (int) $data['ctf']['sourceID']);
- $relationName = $data['ctf']['manyManyRelation'];
- $componentSet = $parentRecord->getManyManyComponents($relationName);
- $componentSet->add($dataObject);
- }
-
- $form->sessionMessage(sprintf(_t('DataObjectManager.SAVED','Saved %s successfully'),$this->ctf->SingleTitle()), 'good');
- Director::redirectBack();
- }
-
- function DetailForm($childID = null)
- {
- $form = parent::DetailForm($childID);
- $form->Fields()->insertFirst(new LiteralField('open',''));
- $o = $form->Fields()->Last();
- $form->Fields()->insertAfter(new LiteralField('close','
'),$o->Name());
- if(!$this->ctf->Can('edit')) {
- $form->makeReadonly();
- $form->setActions(null);
- }
- return $form;
- }
-
- function edit() {
- if(!$this->ctf->Can('view') && !$this->ctf->Can('edit'))
- return false;
-
- $this->methodName = "edit";
+ public function FieldHolder($properties = array()) {
+ return $this->grid->FieldHolder($properties);
+ }
- echo $this->renderWith($this->ctf->templatePopup);
- }
-
- public function duplicate()
- {
- if(!$this->ctf->Can('duplicate'))
- return false;
- $this->methodName = "duplicate";
-
- echo $this->renderWith(array('DataObjectManager_duplicate'));
- }
-
- public function DuplicateForm()
- {
- return new Form(
- $this,
- "DuplicateForm",
- new FieldSet(
- new FieldGroup(
- new LabelField('copy',_t('DataObjectManager.CREATE','Create ')),
- new NumericField('Count','','1'),
- new LabelField('times',sprintf(_t('DataObjectManager.COPIESOFOBJECT',' copies of this %s'),$this->ctf->SingleTitle()))
- ),
- new CheckboxField('Relations',_t('DataObjectManager.INCLUDERELATIONS','Include related objects'))
- ),
- new FieldSet(
- new FormAction('doDuplicate',_t('DataObjectManager.DUPLICATE','Duplicate'))
- )
- );
- }
-
- public function doDuplicate($data,$form)
- {
- if($obj = $this->dataObj()) {
- for($i = 0;$i < $data['Count'];$i++) {
- $new = $obj->duplicate();
- if(isset($data['Relations']) && $data['Relations'] == "1") {
- if($has_manys = $obj->has_many()) {
- foreach($has_manys as $name => $class) {
- // get the owner relation name
- if($has_ones = singleton($class)->has_one()) {
- if($ownerRelation = array_search($this->ctf->SourceClass(),$has_ones)) {
- $ownerID = $ownerRelation."ID";
- if($related_objects = $obj->$name()) {
- foreach($related_objects as $related_obj) {
- $o = $related_obj->duplicate(false);
- $o->$ownerID = $new->ID;
- $o->write();
- }
- }
- }
- else
- die(sprintf(_t('DataObjectManager.COULDNOTFINDRELATION','Could not find owner relation for class %s'),$this->ctf->SourceClass()));
- }
- else
- die(sprintf(_t('DataObjectManager.COULDNOTFINDRELATION','Could not find owner relation for class %s'),$this->ctf->SourceClass()));
- }
- }
- if($many_manys = $obj->many_many()) {
- foreach($many_manys as $name => $class) {
- if($obj->$name()) {
- $new->$name()->setByIdList($obj->$name()->column());
- }
- }
- $new->write();
- }
- }
- }
- $ret = "$i " . _t('DataObjectManager.DUPLICATESCREATED','duplicate(s) created');
- if(isset($data['Relations']) && $data['Relations'] == "1") $ret .= ", " . _t('DataObjectManager.WITHRELATIONS','with relations included');
- $form->sessionMessage($ret,'good');
- }
- else
- $form->sessionMessage(_t('DataObjectManager.ERRORDUPLICATING','There was an error duplicating the object.'),'bad');
- Director::redirectBack();
- }
-
-
- protected function getPrevID()
- {
- return $this->itemList[$this->currentIndex - 1];
- }
-
- protected function getNextID()
- {
- return $this->itemList[$this->currentIndex + 1];
- }
- function NextRecordLink()
- {
- if(!$this->itemList || $this->currentIndex == sizeof($this->itemList)-1) return false;
- return Controller::join_links($this->ctf->BaseLink() , 'item/' . $this->getNextID().'/edit',"?".$this->ctf->getQueryString());
- }
-
- function PrevRecordLink()
- {
- if(!$this->itemList || $this->currentIndex == 0) return false;
- return Controller::join_links($this->ctf->BaseLink() , 'item/' . $this->getPrevID().'/edit',"?".$this->ctf->getQueryString());
- }
-
-
- function HasPagination()
- {
- return $this->NextRecordLink() || $this->PrevRecordLink();
- }
-
- function HasDuplicate()
- {
- return $this->ctf->Can('duplicate');
+ public function handleAction($actionName, $args, $data) {
+ return $this->grid->handleAction($actionName, $args, $data);
}
- function SingleTitle()
- {
- return $this->ctf->SingleTitle();
+ function handleRequest(SS_HTTPRequest $request, DataModel $model) {
+ return $this->grid->handleRequest($request, $model);
}
-
- function DuplicateLink()
- {
- return Controller::join_links($this->ctf->BaseLink(),'duplicate'.$this->itemID);
- }
-
- function HasRelated()
- {
- $has_many = singleton($this->ctf->SourceClass())->has_many();
- return is_array($has_many) && !empty($has_many);
- }
-
-}
-class DataObjectManagerAction extends ViewableData
-{
- static $behaviour_to_js = array (
- 'popup' => 'popup-button',
- 'delete' => 'delete-link',
- 'refresh' => 'refresh-button',
- 'window' => 'window-link'
- );
-
- public $Title;
- public $Behaviour;
- public $ActionClass;
- public $Link;
- public $IconURL;
-
- public function __construct($title, $link, $behaviour = "popup", $icon = null, $class = null, $rel = null) {
- parent::__construct();
- $this->Title = $title;
- $this->Link = $link;
- $this->Behaviour = self::$behaviour_to_js[$behaviour];
- $this->IconURL = $icon;
- $this->ActionClass = $class;
- $this->Rel = $rel;
- }
}
-class DOMUtil
-{
- public static function readable_list($array)
- {
- if(!is_array($array))
- return '';
- $and = _t('DataObjectManager.AND','and');
- switch(count($array))
- {
- case 0:
- return '';
- case 1:
- // This may not be a normal numerically-indexed array.
- return reset($array);
- case 2:
- return reset($array)." $and ".end($array);
- default:
- $last = array_pop($array);
- return implode(', ', $array).", $and $last";
- }
- }
-
- public static function readable_class($string)
- {
- return ucwords(trim(strtolower(ereg_replace('([A-Z])',' \\1',$string))));
- }
-
- /**
- * Translates a camel case string into a string with underscores (e.g. firstName -> first_name)
- * @param string $str String in camel case format
- * @return string $str Translated into underscore format
- */
- public static function to_underscore($str) {
- $str[0] = strtolower($str[0]);
- $func = create_function('$c', 'return "_" . strtolower($c[1]);');
- return preg_replace_callback('/([A-Z])/', $func, $str);
- }
-
- /**
- * Translates a string with underscores into camel case (e.g. first_name -> firstName)
- * @param string $str String in underscore format
- * @param bool $capitalise_first_char If true, capitalise the first char in $str
- * @return string $str translated into camel caps
- */
- public static function to_camel_case($str, $capitalise_first_char = false) {
- if($capitalise_first_char) {
- $str[0] = strtoupper($str[0]);
- }
- $func = create_function('$c', 'return strtoupper($c[1]);');
- return preg_replace_callback('/_([a-z])/', $func, $str);
- }
-
-}
-
-
diff --git a/code/DataObjectManager_nestedurls.php b/code/DataObjectManager_nestedurls.php
deleted file mode 100644
index 3ec5c40..0000000
--- a/code/DataObjectManager_nestedurls.php
+++ /dev/null
@@ -1,505 +0,0 @@
- array(
- 'label' => 'Edit',
- 'icon' => null,
- 'class' => 'popuplink editlink',
- ),
- 'delete' => array(
- 'label' => 'Delete',
- 'icon' => null,
- 'class' => 'deletelink',
- )
- );
-
- public $popupClass = "DataObjectManager_Popup";
- public $templatePopup = "DataObjectManager_popup";
-
-
- function __construct($controller, $name, $sourceClass, $fieldList = null, $detailFormFields = null, $sourceFilter = "", $sourceSort = "", $sourceJoin = "")
- {
- if(!class_exists("ComplexTableField_ItemRequest"))
- die(""._t('DataObjectManager.ERROR','Error').": "._t('DataObjectManager.SILVERSTRIPEVERSION','DataObjectManager requires Silverstripe version 2.3 or higher.'));
-
- parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin);
- Requirements::block(THIRDPARTY_DIR . "/greybox/AmiJS.js");
- Requirements::block(THIRDPARTY_DIR . "prototype.js");
- Requirements::block(THIRDPARTY_DIR . "/greybox/greybox.js");
- Requirements::block(SAPPHIRE_DIR . "/javascript/ComplexTableField.js");
- Requirements::block(SAPPHIRE_DIR . "/javascript/TableListField.js");
-
- Requirements::block(THIRDPARTY_DIR . "/greybox/greybox.css");
- Requirements::block(SAPPHIRE_DIR . "/css/ComplexTableField.css");
- Requirements::css('dataobject_manager/css/dataobject_manager.css');
- Requirements::css('dataobject_manager/css/facebox.css');
- Requirements::javascript('dataobject_manager/javascript/facebox.js');
- Requirements::javascript('dataobject_manager/javascript/jquery-ui.1.5.3.js');
- Requirements::javascript('dataobject_manager/javascript/dataobject_manager.js');
- Requirements::javascript('dataobject_manager/javascript/tooltip.js');
-
- $this->filter_empty_string = '-- '._t('DataObjectManager.NOFILTER','No filter').' --';
-
- if(isset($_REQUEST['ctf'][$this->Name()])) {
- $this->per_page = $_REQUEST['ctf'][$this->Name()]['per_page'];
- $this->showAll = $_REQUEST['ctf'][$this->Name()]['showall'];
- $this->search = $_REQUEST['ctf'][$this->Name()]['search'];
- $this->filter = $_REQUEST['ctf'][$this->Name()]['filter'];
- $this->sort = $_REQUEST['ctf'][$this->Name()]['sort'];
- $this->sort_dir = $_REQUEST['ctf'][$this->Name()]['sort_dir'];
- }
- $this->setPageSize($this->per_page);
- $this->loadSort();
- $this->loadSourceFilter();
- }
-
- protected function loadSort()
- {
- if($this->ShowAll())
- $this->setPageSize(999);
-
- if($this->Sortable() && (!isset($_REQUEST['ctf'][$this->Name()]['sort']) || $_REQUEST['ctf'][$this->Name()]['sort'] == "SortOrder")) {
- $this->sort = "SortOrder";
- $this->sourceSort = "SortOrder ASC";
- }
- elseif(isset($_REQUEST['ctf'][$this->Name()]['sort']))
- $this->sourceSort = $_REQUEST['ctf'][$this->Name()]['sort'] . " " . $this->sort_dir;
-
- }
-
- protected function loadSourceFilter()
- {
- $filter_string = "";
- if(!empty($this->filter)) {
- $break = strpos($this->filter, "_");
- $field = substr($this->filter, 0, $break);
- $value = substr($this->filter, $break+1, strlen($this->filter) - strlen($field));
- $filter_string = $field . "='$value'";
- }
-
- $search_string = "";
- if(!empty($this->search)) {
- $search = array();
- $SNG = singleton($this->sourceClass);
- foreach(parent::Headings() as $field) {
- if($SNG->hasField($field->Name))
- $search[] = "UPPER($field->Name) LIKE '%".strtoupper($this->search)."%'";
- }
- $search_string = "(".implode(" OR ", $search).")";
- }
- $and = (!empty($this->filter) && !empty($this->search)) ? " AND " : "";
- $source_filter = $filter_string.$and.$search_string;
- if(!$this->sourceFilter) $this->sourceFilter = $source_filter;
- else if($this->sourceFilter && !empty($source_filter)) $this->sourceFilter .= " AND " . $source_filter;
- }
-
- public function handleItem($request) {
- return new DataObjectManager_ItemRequest($this, $request->param('ID'));
- }
-
- protected function getQueryString($params = array())
- {
- $per_page = isset($params['per_page'])? $params['per_page'] : $this->per_page;
- $show_all = isset($params['show_all'])? $params['show_all'] : $this->showAll;
- $sort = isset($params['sort'])? $params['sort'] : $this->sort;
- $sort_dir = isset($params['sort_dir'])? $params['sort_dir'] : $this->sort_dir;
- $filter = isset($params['filter'])? $params['filter'] : $this->filter;
- $search = isset($params['search'])? $params['search'] : $this->search;
- return "ctf[{$this->Name()}][per_page]={$per_page}&ctf[{$this->Name()}][showall]={$show_all}&ctf[{$this->Name()}][sort]={$sort}&ctf[{$this->Name()}][sort_dir]={$sort_dir}&ctf[{$this->Name()}][search]={$search}&ctf[{$this->Name()}][filter]={$filter}";
- }
-
-
- public function Headings()
- {
- $headings = array();
- foreach($this->fieldList as $fieldName => $fieldTitle) {
- if(isset($_REQUEST['ctf'][$this->Name()]['sort_dir']))
- $dir = $_REQUEST['ctf'][$this->Name()]['sort_dir'] == "ASC" ? "DESC" : "ASC";
- else
- $dir = "ASC";
- $headings[] = new ArrayData(array(
- "Name" => $fieldName,
- "Title" => ($this->sourceClass) ? singleton($this->sourceClass)->fieldLabel($fieldTitle) : $fieldTitle,
- "IsSortable" => singleton($this->sourceClass)->hasField($fieldName),
- "SortLink" => $this->RelativeLink(array(
- 'sort_dir' => $dir,
- 'sort' => $fieldName
- )),
- "SortDirection" => $dir,
- "IsSorted" => (isset($_REQUEST['ctf'][$this->Name()]['sort'])) && ($_REQUEST['ctf'][$this->Name()]['sort'] == $fieldName),
- "ColumnWidthCSS" => !empty($this->column_widths) ? sprintf("style='width:%f%%;'",($this->column_widths[$fieldName] - 0.1)) : ""
- ));
- }
- return new DataObjectSet($headings);
- }
-
- function saveComplexTableField($data, $form, $params) {
- $className = $this->sourceClass();
- $childData = new $className();
- $form->saveInto($childData);
- $childData->write();
- $form->sessionMessage(sprintf(_t('DataObjectManager.ADDEDNEW','Added new %s successfully'),$this->SingleTitle()), 'good');
-
- if($form->getFileField()) {
- $form->clearMessage();
- Director::redirect($this->BaseLink().'/item/'.$childData->ID.'/edit');
- }
- else Director::redirectBack();
-
- }
-
-
- function getCustomFieldsFor($childData) {
- if(is_a($this->detailFormFields,"Fieldset"))
- $fields = $this->detailFormFields;
- else {
- if(!is_string($this->detailFormFields)) $this->detailFormFields = "getCMSFields";
- $functioncall = $this->detailFormFields;
- if(!$childData->hasMethod($functioncall)) $functioncall = "getCMSFields";
-
- $fields = $childData->$functioncall();
- }
-
- foreach($fields as $field) {
- if($field->class == "CalendarDateField")
- $fields->replaceField($field->Name(), new DatePickerField($field->Name(), $field->Title(), $field->attrValue()));
- }
- return $fields;
- }
-
- function AddForm($childID = null)
- {
- $form = parent::AddForm($childID);
- $actions = new FieldSet();
- $text = ($field = $form->getFileField()) ? sprintf(_t('DataObjectManager.SAVEANDADD','Save and add %s'), $field->Title()) : _t('DataObjectManager.SAVE','Save');
-
- $actions->push(
- $saveAction = new FormAction("saveComplexTableField", $text)
- );
- $saveAction->addExtraClass('save');
- $form->setActions($actions);
- return $form;
-
-
- }
-
- public function Link($action = null)
- {
- return parent::Link($action)."?".$this->getQueryString();
- }
-
- public function BaseLink($action = null)
- {
- return parent::Link($action);
- }
-
- public function CurrentLink($action = null)
- {
- return $this->Link($action);
- }
-
- public function RelativeLink($params = array(), $action = null)
- {
- return parent::Link($action)."?".$this->getQueryString($params);
- }
- public function FirstLink($action = null)
- {
- return parent::FirstLink($action) ? parent::FirstLink($action)."&".$this->getQueryString() : false;
- }
-
- public function PrevLink($action = null)
- {
- return parent::PrevLink($action) ? parent::PrevLink($action)."&".$this->getQueryString() : false;
- }
-
- public function NextLink($action = null)
- {
- return parent::NextLink($action) ? parent::NextLink($action)."&".$this->getQueryString() : false;
- }
-
- public function LastLink($action = null)
- {
- return parent::LastLink($action) ? parent::LastLink($action)."&".$this->getQueryString() : false;
- }
-
- public function ShowAllLink($action = null)
- {
- return $this->RelativeLink(array('show_all' => '1'),$action);
- }
-
- public function PaginatedLink($action = null)
- {
- return $this->RelativeLink(array('show_all' => '0'),$action);
- }
-
- public function AddLink($action = null) {
- return $this->BaseLink($action) . '/add';
- }
-
-
-
- public function ShowAll()
- {
- return $this->showAll == "1";
- }
-
- public function Paginated()
- {
- return $this->showAll == "0";
- }
-
- public function Sortable()
- {
- return SortableDataObject::is_sortable_class($this->sourceClass());
- }
-
- public function setFilter($field, $label, $map)
- {
- if(is_array($map)) {
- $this->filter_map = $map;
- $this->filtered_field = $field;
- $this->filter_label = $label;
- }
- }
-
- public function HasFilter()
- {
- return !empty($this->filter_map);
- }
-
- public function FilterDropdown()
- {
- $map = $this->filter_empty_string ? array($this->RelativeLink(array('filter' => '')) => $this->filter_empty_string) : array();
- foreach($this->filter_map as $k => $v) {
- $map[$this->RelativeLink(array('filter' => $this->filtered_field.'_'.$k))] = $v;
- }
- $value = !empty($this->filter) ? $this->RelativeLink(array('filter' => $this->filter)) : null;
- $dropdown = new DropdownField('Filter',$this->filter_label . " ("._t('DataObjectManager.REFRESH','refresh').")", $map, $value);
- return $dropdown->FieldHolder();
- }
-
- public function PerPageDropdown()
- {
- $map = array();
- for($i=10;$i<=50;$i+=10) $map[$this->RelativeLink(array('per_page' => $i))] = $i;
- $value = !empty($this->per_page) ? $this->RelativeLink(array('per_page' => $this->per_page)) : null;
- return new FieldGroup(
- new LabelField('show', _t('DataObjectManager.PERPAGESHOW','Show').' '),
- new DropdownField('PerPage','',$map, $value),
- new LabelField('results', ' '._t('DataObjectManager.PERPAGERESULTS','results per page'))
-
- );
- }
- public function SearchValue()
- {
- return !empty($this->search) ? $this->search : false;
- }
-
- public function AddTitle()
- {
- return $this->addTitle ? $this->addTitle : $this->Title();
- }
-
- public function SingleTitle()
- {
- return $this->singleTitle ? $this->singleTitle : $this->AddTitle();
- }
-
- public function setAddTitle($title)
- {
- $this->addTitle = $title;
- }
-
- public function setSingleTitle($title)
- {
- $this->singleTitle = $title;
- }
-
- public function getColumnWidths()
- {
- return $this->column_widths;
- }
-
- public function setColumnWidths($widths)
- {
- if(is_array($widths)) {
- $total = 0;
- foreach($widths as $name => $value) $total += $value;
- if($total != 100)
- die('DataObjectManager::setColumnWidths():' . sprintf(_t('DataObjectManager.TOTALNOT100','Column widths must total 100 and not %s'), $total));
- else
- $this->column_widths = $widths;
- }
- }
-
- public function setFilterEmptyString($str)
- {
- $this->filter_empty_string = $str;
- }
-
-}
-
-class DataObjectManager_Item extends ComplexTableField_Item {
- function __construct(DataObject $item, DataObjectManager $parent, $start)
- {
- parent::__construct($item, $parent, $start);
- }
-
- function Link($action = null) {
- return $this->parent->BaseLink(Controller::join_links('item', $this->item->ID, $action));
- }
-
- function Fields() {
- $fields = parent::Fields();
- $widths = $this->parent->getColumnWidths();
- if(!empty($widths)) {
- foreach($fields as $field) {
- $field->ColumnWidthCSS = sprintf("style='width:%f%%;'",($widths[$field->Name] - 0.1));
- }
- }
- return $fields;
- }
-
-}
-
-class DataObjectManager_Controller extends Controller
-{
- function dosort()
- {
- if(!empty($_POST) && is_array($_POST) && isset($this->urlParams['ID'])) {
- $className = $this->urlParams['ID'];
- foreach($_POST as $group => $map) {
- if(substr($group, 0, 7) == "record-") {
- foreach($map as $sort => $id) {
- $obj = DataObject::get_by_id($className, $id);
- $obj->SortOrder = $sort;
- $obj->write();
- }
- }
- }
- }
- }
-
-}
-
-
-class DataObjectManager_Popup extends Form {
- protected $sourceClass;
- protected $dataObject;
-
- function __construct($controller, $name, $fields, $validator, $readonly, $dataObject) {
- $this->dataObject = $dataObject;
- Requirements::clear();
- Requirements::block('/jsparty/behaviour.js');
- Requirements::block('sapphire/javascript/Validator.js');
- Requirements::block('jsparty/prototype.js');
- Requirements::block('jsparty/behavior.js');
- Requirements::block('jsparty/jquery/jquery.js');
- Requirements::clear('jsparty/behavior.js');
-
- Requirements::block('sapphire/javascript/i18n.js');
- Requirements::block('assets/base.js');
- Requirements::block('sapphire/javascript/lang/en_US.js');
- Requirements::css(SAPPHIRE_DIR . '/css/Form.css');
- Requirements::css(CMS_DIR . '/css/typography.css');
- Requirements::css(CMS_DIR . '/css/cms_right.css');
- Requirements::css('dataobject_manager/css/dataobject_manager.css');
- if($this->dataObject->hasMethod('getRequirementsForPopup')) {
- $this->dataObject->getRequirementsForPopup();
- }
-
- Requirements::javascript('dataobject_manager/javascript/jquery.1.3.js');
-
- // File iframe fields force horizontal scrollbars in the popup. Not cool.
- // Override the close popup method.
- Requirements::customScript("
- jQuery(function() {
- jQuery('iframe').css({'width':'433px'});
- });
- ");
-
- $actions = new FieldSet();
- if(!$readonly) {
- $actions->push(
- $saveAction = new FormAction("saveComplexTableField", _t('DataObjectManager.SAVE','Save'))
-
- );
- $saveAction->addExtraClass('save');
- }
-
- parent::__construct($controller, $name, $fields, $actions, $validator);
-
- $this->unsetValidator();
- }
-
- function FieldHolder() {
- return $this->renderWith('ComplexTableField_Form');
- }
-
- public function getFileField()
- {
- foreach($this->Fields() as $field) {
- if($field instanceof FileIFrameField || $field instanceof ImageField)
- return $field;
- }
-
- return false;
- }
-
-}
-
-
-
-class DataObjectManager_ItemRequest extends ComplexTableField_ItemRequest
-{
- function __construct($ctf, $itemID)
- {
- parent::__construct($ctf, $itemID);
- }
-
- function Link($action = null)
- {
- return $this->ctf->BaseLink(Controller::join_links('item', $this->itemID, $action));
- }
-
- function saveComplexTableField($data, $form, $request) {
- $form->saveInto($this->dataObj());
- $this->dataObj()->write();
- $form->sessionMessage(sprintf(_t('DataObjectManager.SAVED','Saved %s successfully'),$this->ctf->SingleTitle()), 'good');
-
- Director::redirectBack();
- }
-
-}
-
-
-
-
-*/
-?>
\ No newline at end of file
diff --git a/code/FileDataObjectManager.php b/code/FileDataObjectManager.php
index de1c08f..8f68c56 100644
--- a/code/FileDataObjectManager.php
+++ b/code/FileDataObjectManager.php
@@ -2,172 +2,14 @@
class FileDataObjectManager extends DataObjectManager
{
- static $url_handlers = array(
- 'import/$ID' => 'handleImport'
- );
-
- public static $upgrade_audio = true;
- public static $upgrade_video = true;
- public static $upgrade_image = true;
- public static $upload_limit = "40";
-
- public $view;
- public $default_view = "grid";
- protected $allowedFileTypes;
- protected $uploadOnSubmit = false;
- protected $limitFileTypes;
- protected $uploadLimit;
- protected $allowUploadFolderSelection = true;
- protected $enableUploadDebugging = false;
- public $hasDataObject = true;
- public $importClass = "File";
-
- protected $permissions = array(
- "add",
- "edit",
- "show",
- "delete",
- "upload",
- "import"
- );
- public $popupClass = "FileDataObjectManager_Popup";
- public $itemClass = "FileDataObjectManager_Item";
- public $template = "FileDataObjectManager";
- public $templatePopup = "DataObjectManager_popup";
-
- public $gridLabelField;
- public $pluralTitle;
- public $browseButtonText = "Upload files";
-
- public $uploadFolder = "Uploads";
-
- public $uploadifyField = "MultipleFileUploadField";
-
- public $copyOnImport = true;
-
public function __construct($controller, $name = null, $sourceClass = null, $fileFieldName = null, $fieldList = null, $detailFormFields = null, $sourceFilter = "", $sourceSort = "", $sourceJoin = "")
{
- if(!class_exists("SWFUploadField") && !class_exists("UploadifyField"))
- die(""._t('DataObjectManager.ERROR','Error').": "._t('FileDataObjectManager.SWFUPLOADUPLOADIFY','DataObjectManager requires the Uploadify or SWFUpload modules.'));
- parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin);
- // Intelligent constructor for fileFieldName
- $SNG = singleton($this->sourceClass());
- if($fileFieldName === null) {
- if($has_ones = $SNG->has_one()) {
- foreach($has_ones as $relation => $value) {
- if($value == "File" || is_subclass_of($value,"File")) {
- $fileFieldName = $relation;
- $fileClassName = $value;
- break;
- }
- }
- }
- }
-
- if(isset($_REQUEST['ctf'][$this->Name()])) {
- $this->view = $_REQUEST['ctf'][$this->Name()]['view'];
- }
- if($this->sourceClass() == "File" || is_subclass_of($this->sourceClass(), "File")) {
- $this->hasDataObject = false;
- $this->fileFieldName = $name;
- $this->fileClassName = $this->sourceClass();
- $this->dataObjectFieldName = null;
- }
- else {
- $this->dataObjectFieldName = $name;
- $this->fileFieldName = $fileFieldName;
- $this->fileClassName = $SNG->has_one($this->fileFieldName);
- if(!$this->fileClassName)
- die("FileDataObjectManager::__construct():"._t('FileDataObjectManager.FILERELATION','Could not determine file relationship'));
- }
-
- $this->controllerClassName = $controller->class;
- if($key = array_search($this->controllerClassName, $SNG->stat('has_one')))
- $this->controllerFieldName = $key;
- else
- $this->controllerFieldName = $this->controllerClassName;
- $this->controllerID = $controller->ID;
- // Check for allowed file types
- if($types = Object::get_static($this->fileClassName,'allowed_file_types'))
- $this->setAllowedFileTypes($types);
+ parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $souceFilter, $sourceSort, $sourceJoin);
}
- public function getQueryString($params = array())
- {
- $view = isset($params['view'])? $params['view'] : $this->view;
- return parent::getQueryString($params)."&ctf[{$this->Name()}][view]={$view}";
- }
- public function setGridLabelField($fieldName)
- {
- $this->gridLabelField = $fieldName;
- }
+ public function setGridLabelField($fieldName) { }
- public function GridLink()
- {
- return $this->RelativeLink(array('view' => 'grid'));
- }
-
- public function ListLink()
- {
- return $this->RelativeLink(array('view' => 'list'));
- }
-
- public function GridView()
- {
- return $this->ListStyle() == "grid";
- }
-
- public function ListView()
- {
- return $this->ListStyle() == "list";
- }
-
- public function ListStyle()
- {
- return $this->view ? $this->view : $this->default_view;
- }
-
-
- public function ImportDropdown()
- {
- return new HTMLDropdownField('ImportFolder','',$this->getImportFolderHierarchy(0),null, null, "-- "._t('DataObjectManager.SELECTFOLDER', 'Select a folder')." --");
- }
-
- protected function importLinkFor($file)
- {
- return Controller::join_links($this->BaseLink(), "import", $file->ID);
- }
-
- protected function getImportFolderHierarchy($parentID, $level = 0)
- {
- $options = array();
- if($children = DataObject::get("Folder", "\"ParentID\" = $parentID")) {
- foreach($children as $child) {
- $indent="";
- for($i=0;$i<$level;$i++) $indent .= " ";
- $files = DataObject::get($this->importClass, "\"ClassName\" != 'Folder' AND \"ParentID\" = $child->ID");
- $count = $files ? $files->Count() : "0";
- $options[$this->importLinkFor($child)] = $indent.$child->Title . " ($count files)";
- $options += $this->getImportFolderHierarchy($child->ID, $level+1);
- }
- }
- return $options;
- }
-
- protected function getUploadFolderHierarchy($parentID, $level = 0)
- {
- $options = array();
- if($children = DataObject::get("Folder", "\"ParentID\" = $parentID")) {
- foreach($children as $child) {
- $indent="";
- for($i=0;$i<$level;$i++) $indent .= " ";
- $options[$child->ID] = empty($child->Title) ? "$indent Untitled" : $indent.$child->Title;
- $options += $this->getUploadFolderHierarchy($child->ID, $level+1);
- }
- }
- return $options;
- }
public function setAllowedFileTypes($types = array())
@@ -180,676 +22,22 @@ public function setAllowedFileTypes($types = array())
$this->allowedFileTypes = $types;
}
- public function getAllowedFileTypes()
- {
- return $this->allowedFileTypes;
- }
-
- public function setUploadLimit($num)
- {
- $this->uploadLimit = $num;
- }
-
- public function getUploadLimit()
- {
- return $this->getSetting('uploadLimit');
- }
-
- public function setBrowseButtonText($text)
- {
- $this->browseButtonText = $text;
- }
-
- public function getBrowseButtonText()
- {
- return $this->browseButtonText;
- }
-
- public function ButtonAddTitle()
- {
- return $this->addTitle ? $this->addTitle : $this->PluralTitle();
- }
-
- public function allowUploadFolderSelection()
- {
- $this->allowUploadFolderSelection = true;
- }
-
- public function enableUploadDebugging()
- {
- $this->enableUploadDebugging = true;
- }
-
- public function setDefaultView($type)
- {
- $this->default_view = $type;
- }
-
- public function uploadOnSubmit()
- {
- $this->uploadOnSubmit = true;
- }
-
- public function upload()
- {
- if(!$this->can('add')) return;
- $form = class_exists('UploadifyField') ? $this->UploadifyForm() : $this->UploadForm();
- if(is_string($form))
- return $this->customise(array(
- 'String' => true,
- 'NestedController' => $this->isNested,
- 'DetailForm' => $this->UploadForm(),
- ))->renderWith($this->templatePopup);
- else {
- $form = class_exists('UploadifyField') ? $this->UploadifyForm() : $this->UploadForm();
- return $this->customise(array(
- 'String' => is_string($form),
- 'DetailForm' => $form
- ))->renderWith($this->templatePopup);
- }
- }
-
- public function UploadLink()
- {
- return Controller::join_links($this->BaseLink(),'upload');
- }
-
- protected function getUploadFields()
- {
-
- $fields = new FieldSet(
- new HeaderField($title = sprintf(_t('DataObjectManager.ADDITEM', 'Add %s'),$this->PluralTitle()), $headingLevel = 2),
- new HeaderField($title = _t('DataObjectManager.UPLOADFROMPC', 'Upload from my computer'), $headingLevel = 3),
- new SWFUploadField(
- "UploadForm",
- "Upload",
- "",
- array(
- 'file_upload_limit' => $this->getUploadLimit(), // how many files can be uploaded
- 'file_queue_limit' => $this->getUploadLimit(), // how many files can be in the queue at once
- 'browse_button_text' => $this->getBrowseButtonText(),
- 'upload_url' => Director::absoluteURL('FileDataObjectManager_Controller/handleswfupload'),
- 'required' => 'true'
- )
- )
- );
-
- if($this->allowUploadFolderSelection)
- $fields->insertBefore(new HTMLDropdownField('UploadFolder','',$this->getUploadFolderHierarchy(0),null, null, "-- Select a folder --"),"Upload");
- return $fields;
- }
-
- protected function getUploadifyFields()
- {
-
- $class = $this->uploadifyField;
- $fields = new FieldSet(
- new HeaderField($title = sprintf(_t('DataObjectManager.ADDITEM', 'Add %s'),$this->PluralTitle()), $headingLevel = 2),
- $uploader = new $class('UploadedFiles')
- );
-
- if(!$this->allowUploadFolderSelection) {
- $uploader->removeFolderSelection();
- }
- if($this->uploadFolder) {
- $uploader->setUploadFolder($this->uploadFolder);
- }
- $uploader->setVar('buttonText', $this->getBrowseButtonText());
- $uploader->setVar('queueSizeLimit', $this->getUploadLimit());
- if(is_subclass_of($this->fileClassName, "File")) {
- if(is_subclass_of($this->fileClassName, "Image")) {
- $uploader->setVar('image_class', $this->fileClassName);
- }
- else {
- $uploader->setVar('file_class', $this->fileClassName);
- }
- }
-
- if(!empty($this->allowedFileTypes)) {
- $uploader->setFileTypes($this->getAllowedFileTypes(), $this->PluralTitle() . '(' . implode(',',$this->allowedFileTypes) . ')');
- }
- $uploader->uploadFolder = $this->uploadFolder;
- if($this->uploadOnSubmit) {
- $uploader->uploadOnSubmit();
- }
- return $fields;
- }
-
- public function UploadifyForm() {
-
- Validator::set_javascript_validation_handler('none');
-
- $fields = $this->Can('upload') ? $this->getUploadifyFields() : new FieldSet(
- new HeaderField($title = sprintf(_t('DataObjectManager.ADD', 'Add %s'),$this->PluralTitle()), $headingLevel = 2)
- );
-
- $className = $this->sourceClass();
- $childData = new $className();
-
- $form = Object::create(
- $this->popupClass,
- $this,
- 'UploadifyForm',
- $fields,
- new RequiredFields('UploadedFiles'),
- false,
- $childData
- );
-
- $uploader = $form->Fields()->fieldByName('UploadedFiles');
- $action = $this->Can('upload') ? new FieldSet(new FormAction('saveUploadifyForm', 'Continue')) : new FieldSet();
- $form->setActions($action);
- return $form;
- }
-
- public function UploadForm()
- {
- // Sync up the DB
-// singleton('Folder')->syncChildren();
- $className = $this->sourceClass();
- $childData = new $className();
- $validator = $this->getValidatorFor($childData);
- if($this->Can('upload')) {
- SWFUploadConfig::addPostParams(array(
- 'dataObjectClassName' => $this->sourceClass(),
- 'dataObjectFieldName' => $this->dataObjectFieldName,
- 'fileFieldName' => $this->fileFieldName,
- 'fileClassName' => $this->fileClassName,
- 'parentIDName' => $this->getParentIdName( $this->getParentClass(), $this->sourceClass() ),
- 'controllerID' => $this->controllerID,
- 'OverrideUploadFolder' => $this->getUploadFolder(),
- 'hasDataObject' => $this->hasDataObject ? 1 : 0
- ));
-
- if($this->allowUploadFolderSelection)
- SWFUploadConfig::addDynamicPostParam('UploadFolder',$this->popupClass.'_UploadForm_UploadFolder');
-
- if($this->getAllowedFileTypes())
- SWFUploadConfig::addFileTypes($this->getAllowedFileTypes());
-
- if($this->enableUploadDebugging)
- SWFUploadConfig::set_var('debug','true');
- }
-
- $fields = $this->Can('upload') ? $this->getUploadFields() : new FieldSet(
- new HeaderField($title = sprintf(_t('DataObjectManager.ADD', 'Add %s'),$this->PluralTitle()), $headingLevel = 2)
- );
-
- $form = Object::create(
- $this->popupClass,
- $this,
- 'UploadForm',
- $fields,
- $validator,
- false,
- $childData
- );
- $action = $this->Can('upload') ? new FieldSet(new FormAction('saveUploadForm', 'Upload')) : new FieldSet();
- $form->setActions($action);
- if($this->Can('import')) {
- $header = new HeaderField($title = _t('DataObjectManager.IMPORTFROMFOLDER', 'Import from an existing folder'), $headingLevel = 3);
- $holder = new LiteralField("holder","");
- if(!isset($_POST['uploaded_files']))
- return $form->forTemplate() . $header->Field() . $this->ImportDropdown()->Field() . $holder->Field();
- else
- return $form;
- }
- return $form;
-
- }
-
- public function saveUploadForm()
- {
- if(isset($_POST['uploaded_files']) && is_array($_POST['uploaded_files'])) {
- $form = $this->EditUploadedForm();
- return $this->customise(array(
- 'String' => is_string($form),
- 'DetailForm' => $form
- ))->renderWith($this->templatePopup);
- }
- }
-
- public function updateDataObject(&$object) { }
-
- public function saveUploadifyForm($data, $form)
- {
- if(!isset($data['UploadedFiles']) || !is_array($data['UploadedFiles'])) {
- return Director::redirectBack();
- }
-
- $file_class = $this->fileClassName;
- $do_class = $this->sourceClass();
- $idxfield = $this->fileFieldName."ID";
- $fff = $this->fileFieldName;
- $dataobject_ids = array();
- if($this->hasDataObject) {
- foreach($data['UploadedFiles'] as $id) {
- if($file = DataObject::get_by_id("File", (int) $id)) {
- $upload_folder = $form->Fields()->fieldByName('UploadedFiles')->uploadFolder;
- $folder_id = Folder::findOrMake($upload_folder)->ID;
- if($this->copyOnImport && ($file->ParentID != $folder_id)) {
- $new_file_path = $upload_folder.'/'.$file->Name;
- copy($file->getFullPath(), BASE_PATH.'/'.ASSETS_DIR.'/'.$new_file_path);
- $clone = new $file_class();
- $clone->Filename = $new_file_path;
- $clone->ParentID = $folder_id;
- $clone->write();
- $id = $clone->ID;
- }
-
- $obj = new $do_class();
- $obj->$idxfield = $id;
- $ownerID = $this->getParentIdName($this->getParentClass(), $this->sourceClass());
- $obj->$ownerID = $this->controllerID;
- $this->updateDataObject($obj);
- $obj->write();
- $obj->$fff()->write();
- $dataobject_ids[] = $obj->ID;
- }
- }
- $_POST['uploaded_files'] = $dataobject_ids;
- foreach($_POST['uploaded_files'] as $id) {
- }
- }
- else {
- foreach($data['UploadedFiles'] as $id) {
- if($file = DataObject::get_by_id("File", (int) $id)) {
- $ownerID = $this->getParentIdName($this->getParentClass(), $this->sourceClass());
- $file->$ownerID = $this->controllerID;
- $file->write();
- }
- }
- }
-
- $form = $this->EditUploadedForm();
- return $this->customise(array(
- 'String' => is_string($form),
- 'DetailForm' => $form
- ))->renderWith($this->templatePopup);
- }
-
- protected function getChildDataObj()
- {
- $class = $this->sourceClass();
- return new $class();
- }
-
- public function getPreviewFieldFor($fileObject, $size = 150)
- {
- if($fileObject instanceof Image) {
- $URL = $fileObject->getHeight() > $size ? $fileObject->SetHeight($size)->URL : $fileObject->URL
- ;
- return new LiteralField("icon",
- "$fileObject->Filename
"
- );
- }
- else {
- $URL = $fileObject->Icon();
- return new LiteralField("icon",
- "$fileObject->Filename
"
- );
- }
- }
-
- protected function closePopup()
- {
- Requirements::clear();
- if($this->isNested)
- Requirements::customScript("parent.jQuery('#iframe_".$this->id()." a').click();");
- else {
- Requirements::customScript("
- var container = parent.jQuery('#".$this->id()."');
- parent.jQuery('#facebox').fadeOut(function() {
- parent.jQuery('#facebox .content').removeClass().addClass('content');
- parent.jQuery('#facebox_overlay').remove();
- parent.jQuery('#facebox .loading').remove();
- parent.refresh(container, container.attr('href'));
- });");
- }
- return $this->customise(array(
- 'String' => true,
- 'DetailForm' => 'Closing...'
- ))->renderWith($this->templatePopup);
- }
-
- public function EditUploadedForm()
- {
- if(!$this->hasDataObject)
- return $this->closePopup();
-
- $childData = $this->getChildDataObj();
- $validator = $this->getValidatorFor($childData);
- $fields = $this->getFieldsFor($childData);
- $fields->removeByName($this->fileFieldName);
- $total = isset($_POST['totalsize']) ? $_POST['totalsize'] : sizeof($_POST['uploaded_files']);
- $index = isset($_POST['index']) ? $_POST['index'] + 1 : 1;
- $fields->push(new HiddenField('totalsize','',$total));
- $fields->push(new HiddenField('index','',$index));
- if(isset($_POST['uploaded_files']) && is_array($_POST['uploaded_files'])) {
- $remaining_files = $_POST['uploaded_files'];
- $current = $remaining_files[0];
- $dataObject = DataObject::get_by_id($this->sourceClass(), $current);
- $fileObject = $dataObject->obj($this->fileFieldName);
- $fields->push(new HiddenField('current','',$current));
- unset($remaining_files[0]);
- if(!$fields->loaded) {
- foreach($remaining_files as $id)
- $fields->push(new LiteralField("u-$id",""));
- $first = $fields->First()->Name();
- $fields->insertBefore(new HeaderField("Header","Editing file $index of $total",2), $first);
- $fields->insertBefore($this->getPreviewFieldFor($fileObject), $first);
- }
- }
-
- $form = Object::create(
- $this->popupClass,
- $this,
- 'EditUploadedForm',
- $fields,
- $validator,
- false,
- $childData
- );
- $form->setActions(new FieldSet(new FormAction("saveEditUploadedForm", $index == $total ? "Finish" : "Next")));
- if(isset($dataObject) && $dataObject)
- $form->loadDataFrom($dataObject);
- $fields->loaded = true;
- return $form;
- }
-
- function saveEditUploadedForm($data, $form)
- {
- $obj = DataObject::get_by_id($this->sourceClass(), $data['current']);
- $form->saveInto($obj);
- $obj->write();
- if(isset($data['uploaded_files']) && is_array($data['uploaded_files'])) {
- $form = $this->EditUploadedForm();
- return $this->customise(array(
- 'String' => is_string($form),
- 'DetailForm' => $form
- ))->renderWith($this->templatePopup);
- }
- else {
- return $this->closePopup();
- }
- }
-
- public function handleImport($request)
- {
- $this->importFolderID = $request->param('ID');
- die($this->ImportForm($this->importFolderID)->forTemplate());
- }
-
- protected function getImportFields()
- {
- return new FieldSet(
- new HiddenField('dataObjectClassName','',$this->sourceClass()),
- new HiddenField('fileFieldName','', $this->fileFieldName),
- new HiddenField('parentIDName','', $this->getParentIdName( $this->getParentClass(), $this->sourceClass() )),
- new HiddenField('controllerID','',$this->controllerID)
- );
- }
+ public function getAllowedFileTypes() { }
- protected function ImportForm($folder_id = null)
- {
- $folder_id = isset($_POST['folder_id']) ? $_POST['folder_id'] : $this->importFolderID;;
- if($files = DataObject::get($this->importClass, "\"ClassName\" != 'Folder' AND \"ParentID\" = $folder_id"))
- $fields = $this->getImportFields();
- $fields->push(new HiddenField('folder_id','',$folder_id));
- $fields->push(new LiteralField('select',''));
- $fields->push(new LiteralField("ul",""));
- return new Form(
- $this,
- "ImportForm",
- $fields,
- new FieldSet(new FormAction('saveImportForm','Import'))
- );
- }
+ public function setUploadLimit($num) { }
- public function saveImportForm($data, $form)
- {
- if(isset($data['imported_files']) && is_array($data['imported_files'])) {
- $_POST['uploaded_files'] = array();
- // If the user has set a custom upload folder, cut a new copy of the file when importing
- $custom_folder = $this->getUploadFolder() != "Uploads" ? Folder::findOrMake($this->getCleanUploadFolder()) : false;
- foreach($data['imported_files'] as $file_id) {
- $file = DataObject::get_by_id("File",$file_id);
- if($custom_folder && $file->ParentID != $custom_folder->ID) {
- $new_path = Director::baseFolder().'/'.$custom_folder->Filename.$file->Name;
- copy($file->getFullPath(),$new_path);
- $file_class = $file->ClassName;
- $new_file = new $file_class();
- $new_file->setFilename($custom_folder->Filename.$file->Name);
- $new_file->setName($file->Name);
- $new_file->setParentID($custom_folder->ID);
- $new_file->write();
- $file = $new_file;
- $file_id = $new_file->ID;
- }
-
- // If something other than File has been specified as the linked file class,
- // we need to "upgrade" the imported file to the correct class.
- if($this->fileClassName != "File" && $file->ClassName != $this->fileClassName) {
- $file = $file->newClassInstance($this->fileClassName);
- $file->write();
- }
- $owner_id = $data['parentIDName'];
- if($this->hasDataObject) {
- $do_class = $data['dataObjectClassName'];
- $idxfield = $data['fileFieldName']."ID";
- $obj = new $do_class();
- $obj->$idxfield = $file_id;
- $obj->$owner_id = $data['controllerID'];
- $obj->write();
- $_POST['uploaded_files'][] = $obj->ID;
- }
- else {
- if($file = DataObject::get_by_id($this->fileClassName, $file_id)) {
- $id_field = $this->controllerFieldName."ID";
-
- if($file->hasField($owner_id)) {
- $file->$owner_id = $this->controllerID;
- $file->write();
- }
- }
- }
- }
- $form = $this->EditUploadedForm();
- return $this->customise(array(
- 'String' => is_string($form),
- 'DetailForm' => $form
- ))->renderWith($this->templatePopup);
-
- }
- }
- public function setUploadFolder($override)
- {
- $this->uploadFolder = $override;
- }
- public function getUploadFolder()
- {
- return $this->uploadFolder;
- }
+ public function getUploadLimit() { }
- public function getCleanUploadFolder()
- {
- $path = str_replace(ASSETS_DIR."/","",$this->getUploadFolder());
- if(substr($path,-1)=="/") $path = substr($path,0, -1);
- return $path;
- }
+ public function setBrowseButtonText($text){ }
-}
-
-class FileDataObjectManager_Controller extends Controller
-{
- public function handleswfupload()
- {
- if(!Permission::check("CMS_ACCESS_CMSMain"))
- return;
+ public function getBrowseButtonText() { }
- if(isset($_FILES['swfupload_file']) && !empty($_FILES['swfupload_file'])) {
- $do_class = $_POST['dataObjectClassName'];
- $hasDataObject = $_POST['hasDataObject'];
- $idxfield = $_POST['fileFieldName']."ID";
- $file_class = $_POST['fileClassName'];
- $file = new $file_class();
-
- if(isset($_POST['UploadFolder'])) {
- $folder = DataObject::get_by_id("Folder",$_POST['UploadFolder']);
- $path = str_replace(ASSETS_DIR."/","",$folder->Filename);
- if(substr($path,-1)=="/") $path = substr($path,0, -1);
- }
- else {
- $path = str_replace(ASSETS_DIR."/","",$_POST['OverrideUploadFolder']);
- if(substr($path,-1)=="/") $path = substr($path,0, -1);
- }
- if(class_exists("Upload")) {
- $u = new Upload();
- $u->loadIntoFile($_FILES['swfupload_file'], $file, $path);
- }
- else
- $file->loadUploaded($_FILES['swfupload_file'],$path);
-
- if(isset($_POST['UploadFolder']))
- $file->setField("ParentID",$folder->ID);
-
- // Provide an "upgrade" to File subclasses
- if($file->class == "File") {
- $ext = strtolower($file->Extension);
- if(in_array($ext, MP3::$allowed_file_types) && FileDataObjectManager::$upgrade_audio)
- $file = $file->newClassInstance("MP3");
- else if(in_array($ext, array('jpg','jpeg','gif','png')) && FileDataObjectManager::$upgrade_image)
- $file = $file->newClassInstance("Image");
- else if(in_array($ext, FLV::$allowed_file_types) && FileDataObjectManager::$upgrade_video)
- $file = $file->newClassInstance("FLV");
- }
- $file->OwnerID = Member::currentUserID();
- if($hasDataObject) {
- $file->write();
- $obj = new $do_class();
- $obj->$idxfield = $file->ID;
- $ownerID = $_POST['parentIDName'];
- $obj->$ownerID = $_POST['controllerID'];
- $obj->write();
- echo $obj->ID;
- }
- else {
- $ownerID = $_POST['parentIDName'];
- $file->$ownerID = $_POST['controllerID'];
- $file->write();
- echo $file->ID;
- }
- }
- else {
- echo ' ';
- }
-
+ public function allowUploadFolderSelection() { }
- }
-}
-
-class FileDataObjectManager_Item extends DataObjectManager_Item {
- function __construct(DataObject $item, ComplexTableField $parent)
- {
- parent::__construct($item, $parent);
- }
+ public function enableUploadDebugging() { }
- public function IsFile()
- {
- return $this instanceof File;
- }
+ public function setDefaultView($type) { }
- public function FileIcon()
- {
- if($this->parent->hasDataObject) {
- $field = $this->parent->fileFieldName."ID";
- $file = DataObject::get_by_id($this->parent->fileClassName, $this->item->$field);
- }
- else
- $file = $this->item;
-
- if($file && $file->ID) {
- if($file instanceof Image)
- $img = $file;
- else {
- $ext = $file->Extension;
- $imgExts = array('jpg','jpeg','gif');
- if(in_array($ext, $imgExts)) {
- $img = new Image_Cached($file->Filename);
- $img->ID = $file->ID; //image resize functions require an id
- }
- }
- if(isset($img)) {
- if($crop = $img->CroppedImage(50,50)) {
- return $crop->URL;
- }
- }
- return $file->Icon();
-
- }
- else return "{$this->item->$field}";
- }
-
- public function FileLabel()
- {
- $idField = $this->parent->fileFieldName."ID";
- if($this->parent->gridLabelField) {
- $field = $this->parent->gridLabelField;
- return $this->$field;
- }
- else if(!$this->parent->hasDataObject)
- $label = $this->item->Title;
- else if($file = DataObject::get_by_id($this->parent->fileClassName, $this->item->$idField))
- $label = $file->Title;
- else
- $label = "";
- return strlen($label) > 30 ? substr($label, 0, 30)."..." : $label;
- }
-
-}
-
-
-class FileDataObjectManager_Popup extends DataObjectManager_Popup
-{
- function __construct($controller, $name, $fields, $validator, $readonly, $dataObject) {
- parent::__construct($controller, $name, $fields, $validator, $readonly, $dataObject);
-
- // Hack!
- Requirements::block(THIRDPARTY_DIR.'/prototype.js');
- if($name == "UploadForm" && !isset($_POST['uploaded_files']) && $controller->Can('upload')) SWFUploadConfig::bootstrap();
-
- Requirements::javascript('dataobject_manager/javascript/filedataobjectmanager_popup.js');
- }
+ public function uploadOnSubmit() { }
-}
+}
\ No newline at end of file
diff --git a/code/HasManyDataObjectManager.php b/code/HasManyDataObjectManager.php
index a2dafbe..b864eb1 100644
--- a/code/HasManyDataObjectManager.php
+++ b/code/HasManyDataObjectManager.php
@@ -2,185 +2,18 @@
class HasManyDataObjectManager extends DataObjectManager
{
- public $joinField;
- public $addTitle;
- public $RelationType = "HasMany";
- protected $htmlListEndName = 'CheckedList';
- protected $htmlListField = 'selected';
- public $template = 'RelationDataObjectManager';
- public $itemClass = 'HasManyDataObjectManager_Item';
- protected $relationAutoSetting = false;
- protected $markingPermission;
- /**
- * Most of the code below was copied from HasManyComplexTableField.
- * Painful, but necessary, until PHP supports multiple inheritance.
- */
-
- function __construct($controller, $name, $sourceClass, $fieldList = null, $detailFormFields = null, $sourceFilter = "", $sourceSort = "", $sourceJoin = "")
- {
- parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin);
-
- $this->Markable = true;
- if($controllerClass = $this->controllerClass()) {
- $this->joinField = $this->getParentIdName($controllerClass, $this->sourceClass);
- } else {
- user_error("Can't figure out the data class of $controller", E_USER_WARNING);
- }
-
+ public function FieldHolder() {
+ $list = Object::create(
+ "ListboxField",
+ $this->grid->getName(),
+ sprintf(_t('DOM.Selected','Selected %s'),$this->grid->Title()),
+ DataList::create($this->dataClass)
+ ->map('ID', 'Title')
+ ->toArray()
+ )->setMultiple(true);
+ $this->grid->setList(DataList::create($this->dataClass));
+ return "{$list->FieldHolder()}
{$this->grid->FieldHolder()}";
}
-
- /**
- * Try to determine the DataObject that this field is built on top of
- */
- function controllerClass() {
- if($this->controller instanceof DataObject) return $this->controller->class;
- elseif($this->controller instanceof ContentController) return $this->controller->data()->class;
- }
-
- public function setMarkingPermission($perm)
- {
- $this->markingPermission = $perm;
- }
-
- public function hasMarkingPermission()
- {
- if(is_bool($this->markingPermission))
- return $this->markingPermission;
- elseif($this->markingPermission)
- return Permission::check($this->markingPermission);
- return true;
- }
-
- public function setParentClass($class)
- {
- parent::setParentClass($class);
- $this->joinField = $this->getParentIdName($class, $this->sourceClass);
- }
-
- function getQuery($limitClause = null) {
- if($this->customQuery) {
- $query = $this->customQuery;
- $query->select[] = "\"{$this->sourceClass}\".\"ID\" AS \"ID\"";
- $query->select[] = "\"{$this->sourceClass}\".\"ClassName\" AS \"ClassName\"";
- $query->select[] = "\"{$this->sourceClass}\".\"ClassName\" AS \"RecordClassName\"";
- }
- else {
- $query = singleton($this->sourceClass)->extendedSQL($this->sourceFilter, $this->sourceSort, $limitClause, $this->sourceJoin);
-
- // Add more selected fields if they are from joined table.
-
- $SNG = singleton($this->sourceClass);
- foreach($this->FieldList() as $k => $title) {
- if(! $SNG->hasField($k) && ! $SNG->hasMethod('get' . $k) && ! $SNG->has_one($k))
- $query->select[] = $k;
- }
- }
- return clone $query;
- }
-
- function sourceItems() {
- if($this->sourceItems)
- return $this->sourceItems;
-
- $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";
-
- $dataQuery = $this->getQuery($limitClause);
- $records = $dataQuery->execute();
- $items = new DataObjectSet();
- $class = $this->sourceClass;
- foreach($records as $record) {
- $items->push(new $class($record));
- }
-
- // changed to avoid using $this->unpagedSourceItems because it fails on large datasets
- $this->totalCount = $this->getQuery()->unlimitedRowCount();
-
- return $items;
- }
-
- function getControllerID() {
- return $this->controller->ID;
- }
-
- public function SortableClass()
- {
- return $this->sourceClass();
- }
-
- function saveInto(DataObject $record) {
- $fieldName = $this->name;
- $saveDest = $record->$fieldName();
-
- if(! $saveDest)
- user_error("HasManyDataObjectManager::saveInto() Field '$fieldName' not found on $record->class.$record->ID", E_USER_ERROR);
-
- $items = array();
-
- if($list = $this->value[ $this->htmlListField ]) {
- if($list != 'undefined')
- $items = explode(',', trim($list,","));
- }
-
- $saveDest->setByIDList($items);
- }
-
- function ExtraData() {
- $items = array();
- // changed to avoid having to use $this->unpagedSourceItems because it fails on large datasets
- $items = $this->getSelectedIDs();
- $list = implode(',', $items);
- $value = ",";
- $value .= !empty($list) ? $list."," : "";
- $inputId = $this->id() . '_' . $this->htmlListEndName;
- return <<