Merge pull request #114 from spekulatius/moving-to-PSR-2

Converting to PSR-2
This commit is contained in:
Thierry François 2015-12-21 09:36:00 +01:00
commit ef0f9fbcb8
10 changed files with 1580 additions and 1654 deletions

View File

@ -1,9 +1,8 @@
<?php <?php
//define global path to Components' root folder //define global path to Components' root folder
if(!defined('BULKEDITTOOLS_PATH')) if (!defined('BULKEDITTOOLS_PATH')) {
{
$folder = rtrim(basename(dirname(__FILE__))); $folder = rtrim(basename(dirname(__FILE__)));
define('BULKEDITTOOLS_PATH', $folder); define('BULKEDITTOOLS_PATH', $folder);
define('BULKEDITTOOLS_UPLOAD_PATH', $folder . '/bulkUpload'); define('BULKEDITTOOLS_UPLOAD_PATH', $folder.'/bulkUpload');
define('BULKEDITTOOLS_MANAGER_PATH', $folder . '/bulkManager'); define('BULKEDITTOOLS_MANAGER_PATH', $folder.'/bulkManager');
} }

View File

@ -3,48 +3,47 @@
* Bulk action handler for deleting records. * Bulk action handler for deleting records.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkManager
*/ */
class GridFieldBulkActionDeleteHandler extends GridFieldBulkActionHandler class GridFieldBulkActionDeleteHandler extends GridFieldBulkActionHandler
{ {
/** /**
* RequestHandler allowed actions * RequestHandler allowed actions.
*
* @var array * @var array
*/ */
private static $allowed_actions = array('delete'); private static $allowed_actions = array('delete');
/** /**
* RequestHandler url => action map * RequestHandler url => action map.
*
* @var array * @var array
*/ */
private static $url_handlers = array( private static $url_handlers = array(
'delete' => 'delete' 'delete' => 'delete',
); );
/** /**
* Delete the selected records passed from the delete bulk action * Delete the selected records passed from the delete bulk action.
* *
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*
* @return SS_HTTPResponse List of deleted records ID * @return SS_HTTPResponse List of deleted records ID
*/ */
public function delete(SS_HTTPRequest $request) public function delete(SS_HTTPRequest $request)
{ {
$ids = array(); $ids = array();
foreach ( $this->getRecords() as $record ) foreach ($this->getRecords() as $record) {
{
array_push($ids, $record->ID); array_push($ids, $record->ID);
$record->delete(); $record->delete();
} }
$response = new SS_HTTPResponse(Convert::raw2json(array( $response = new SS_HTTPResponse(Convert::raw2json(array(
'done' => true, 'done' => true,
'records' => $ids 'records' => $ids,
))); )));
$response->addHeader('Content-Type', 'text/json'); $response->addHeader('Content-Type', 'text/json');
return $response; return $response;
} }
} }

View File

@ -3,36 +3,36 @@
* Bulk action handler for editing records. * Bulk action handler for editing records.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkManager
*/ */
class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
{ {
/** /**
* RequestHandler allowed actions * RequestHandler allowed actions.
*
* @var array * @var array
*/ */
private static $allowed_actions = array( private static $allowed_actions = array(
'index', 'index',
'bulkEditForm', 'bulkEditForm',
'recordEditForm' 'recordEditForm',
); );
/** /**
* RequestHandler url => action map * RequestHandler url => action map.
*
* @var array * @var array
*/ */
private static $url_handlers = array( private static $url_handlers = array(
'bulkEdit/bulkEditForm' => 'bulkEditForm', 'bulkEdit/bulkEditForm' => 'bulkEditForm',
'bulkEdit/recordEditForm' => 'recordEditForm', 'bulkEdit/recordEditForm' => 'recordEditForm',
'bulkEdit' => 'index' 'bulkEdit' => 'index',
); );
/** /**
* Return URL to this RequestHandler * Return URL to this RequestHandler.
*
* @param string $action Action to append to URL * @param string $action Action to append to URL
*
* @return string URL * @return string URL
*/ */
public function Link($action = null) public function Link($action = null)
@ -40,7 +40,6 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
return Controller::join_links(parent::Link(), 'bulkEdit', $action); return Controller::join_links(parent::Link(), 'bulkEdit', $action);
} }
/** /**
* Return a form for all the selected DataObjects * Return a form for all the selected DataObjects
* with their respective editable fields. * with their respective editable fields.
@ -50,9 +49,8 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
public function bulkEditForm() public function bulkEditForm()
{ {
$crumbs = $this->Breadcrumbs(); $crumbs = $this->Breadcrumbs();
if($crumbs && $crumbs->count()>=2) if ($crumbs && $crumbs->count() >= 2) {
{ $one_level_up = $crumbs->offsetGet($crumbs->count() - 2);
$one_level_up = $crumbs->offsetGet($crumbs->count()-2);
} }
$actions = new FieldList(); $actions = new FieldList();
@ -89,22 +87,20 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
'Editing {count} {class}', 'Editing {count} {class}',
array( array(
'count' => $editingCount, 'count' => $editingCount,
'class' => $titleModelClass 'class' => $titleModelClass,
) )
); );
$header = LiteralField::create( $header = LiteralField::create(
'bulkEditHeader', 'bulkEditHeader',
'<h1 id="bulkEditHeader">' . $headerText . '</h1>' '<h1 id="bulkEditHeader">'.$headerText.'</h1>'
); );
$recordsFieldList->push($header); $recordsFieldList->push($header);
$toggle = LiteralField::create('bulkEditToggle', '<span id="bulkEditToggle">' . _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.TOGGLE_ALL_LINK', 'Show/Hide all') . '</span>'); $toggle = LiteralField::create('bulkEditToggle', '<span id="bulkEditToggle">'._t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.TOGGLE_ALL_LINK', 'Show/Hide all').'</span>');
$recordsFieldList->push($toggle); $recordsFieldList->push($toggle);
//fetch fields for each record and push to fieldList //fetch fields for each record and push to fieldList
foreach ( $recordList as $id ) foreach ($recordList as $id) {
{
$record = DataObject::get_by_id($modelClass, $id); $record = DataObject::get_by_id($modelClass, $id);
$recordEditingFields = $this->getRecordEditingFields($record); $recordEditingFields = $this->getRecordEditingFields($record);
@ -127,7 +123,7 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
$actions $actions
); );
if($crumbs && $crumbs->count()>=2){ if ($crumbs && $crumbs->count() >= 2) {
$bulkEditForm->Backlink = $one_level_up->Link; $bulkEditForm->Backlink = $one_level_up->Link;
} }
@ -141,10 +137,9 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
return $bulkEditForm; return $bulkEditForm;
} }
/** /**
* Return's a form with only one record's fields * Return's a form with only one record's fields
* Used for bulkEditForm subForm requests via ajax * Used for bulkEditForm subForm requests via ajax.
* *
* @return Form Currently being edited form * @return Form Currently being edited form
*/ */
@ -155,24 +150,20 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
$recordInfo = $request->shift(); $recordInfo = $request->shift();
//shift request till we find the requested field //shift request till we find the requested field
while ($recordInfo) while ($recordInfo) {
{ if ($unescapedRecordInfo = $this->unEscapeFieldName($recordInfo)) {
if ( $unescapedRecordInfo = $this->unEscapeFieldName($recordInfo) )
{
$id = $unescapedRecordInfo['id']; $id = $unescapedRecordInfo['id'];
$fieldName = $unescapedRecordInfo['name']; $fieldName = $unescapedRecordInfo['name'];
$action = $request->shift(); $action = $request->shift();
break; break;
} } else {
else{
$recordInfo = $request->shift(); $recordInfo = $request->shift();
} }
} }
//generate a form with only that requested record's fields //generate a form with only that requested record's fields
if ( $id ) if ($id) {
{
$modelClass = $this->gridField->getModelClass(); $modelClass = $this->gridField->getModelClass();
$record = DataObject::get_by_id($modelClass, $id); $record = DataObject::get_by_id($modelClass, $id);
@ -188,20 +179,20 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
} }
} }
/** /**
* Returns a record's populated form fields * Returns a record's populated form fields
* with all filtering done ready to be included in the main form * with all filtering done ready to be included in the main form.
* *
* @uses DataObject::getCMSFields() * @uses DataObject::getCMSFields()
* *
* @param DataObject $record The record to get the fields from * @param DataObject $record The record to get the fields from
*
* @return array The record's editable fields * @return array The record's editable fields
*/ */
private function getRecordEditingFields(DataObject $record) private function getRecordEditingFields(DataObject $record)
{ {
$tempForm = Form::create( $tempForm = Form::create(
$this, "TempEditForm", $this, 'TempEditForm',
$record->getCMSFields(), $record->getCMSFields(),
FieldList::create() FieldList::create()
); );
@ -214,7 +205,6 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
return $fields; return $fields;
} }
/** /**
* Filters a records editable fields * Filters a records editable fields
* based on component's config * based on component's config
@ -223,7 +213,8 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
* See {@link GridFieldBulkManager} component for filtering config. * See {@link GridFieldBulkManager} component for filtering config.
* *
* @param FieldList $fields Record's CMS Fields * @param FieldList $fields Record's CMS Fields
* @param integer $id Record's ID, used fir unique name * @param int $id Record's ID, used fir unique name
*
* @return array Filtered record's fields * @return array Filtered record's fields
*/ */
private function filterRecordEditingFields(FieldList $fields, $id) private function filterRecordEditingFields(FieldList $fields, $id)
@ -232,22 +223,18 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
$editableFields = $config['editableFields']; $editableFields = $config['editableFields'];
// get all dataFields or just the ones allowed in config // get all dataFields or just the ones allowed in config
if ( $editableFields ) if ($editableFields) {
{
$dataFields = array(); $dataFields = array();
foreach ($editableFields as $fieldName) foreach ($editableFields as $fieldName) {
{
$dataFields[$fieldName] = $fields->dataFieldByName($fieldName); $dataFields[$fieldName] = $fields->dataFieldByName($fieldName);
} }
} } else {
else{
$dataFields = $fields->dataFields(); $dataFields = $fields->dataFields();
} }
// escape field names with unique prefix // escape field names with unique prefix
foreach ( $dataFields as $name => $field ) foreach ($dataFields as $name => $field) {
{
$field->Name = $this->escapeFieldName($id, $name); $field->Name = $this->escapeFieldName($id, $name);
$dataFields[$name] = $field; $dataFields[$name] = $field;
} }
@ -255,24 +242,24 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
return $dataFields; return $dataFields;
} }
/** /**
* Escape a fieldName with a unique prefix * Escape a fieldName with a unique prefix.
* *
* @param integer $recordID Record id from who the field belongs * @param int $recordID Record id from who the field belongs
* @param string $name Field name * @param string $name Field name
*
* @return string Escaped field name * @return string Escaped field name
*/ */
protected function escapeFieldName($recordID, $name) protected function escapeFieldName($recordID, $name)
{ {
return 'record_' . $recordID . '_' . $name; return 'record_'.$recordID.'_'.$name;
} }
/** /**
* Un-escape a previously escaped field name * Un-escape a previously escaped field name.
* *
* @param string $fieldName Escaped field name * @param string $fieldName Escaped field name
*
* @return array|false Fasle if the fieldName was not escaped. Or Array map with record 'id' and field 'name' * @return array|false Fasle if the fieldName was not escaped. Or Array map with record 'id' and field 'name'
*/ */
protected function unEscapeFieldName($fieldName) protected function unEscapeFieldName($fieldName)
@ -280,11 +267,9 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
$parts = array(); $parts = array();
$match = preg_match('/record_(\d+)_(\w+)/i', $fieldName, $parts); $match = preg_match('/record_(\d+)_(\w+)/i', $fieldName, $parts);
if ( !$match ) if (!$match) {
{
return false; return false;
} } else {
else{
return array( return array(
'id' => $parts[1], 'id' => $parts[1],
'name' => $parts[2], 'name' => $parts[2],
@ -292,9 +277,8 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
} }
} }
/** /**
* Creates and return the bulk editing interface * Creates and return the bulk editing interface.
* *
* @return string Form's HTML * @return string Form's HTML
*/ */
@ -305,30 +289,29 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
$form->addExtraClass('center cms-content'); $form->addExtraClass('center cms-content');
$form->setAttribute('data-pjax-fragment', 'CurrentForm Content'); $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
Requirements::javascript(BULKEDITTOOLS_MANAGER_PATH . '/javascript/GridFieldBulkEditingForm.js'); Requirements::javascript(BULKEDITTOOLS_MANAGER_PATH.'/javascript/GridFieldBulkEditingForm.js');
Requirements::css(BULKEDITTOOLS_MANAGER_PATH . '/css/GridFieldBulkEditingForm.css'); Requirements::css(BULKEDITTOOLS_MANAGER_PATH.'/css/GridFieldBulkEditingForm.css');
Requirements::add_i18n_javascript(BULKEDITTOOLS_PATH . '/lang/js'); Requirements::add_i18n_javascript(BULKEDITTOOLS_PATH.'/lang/js');
if($this->request->isAjax()) if ($this->request->isAjax()) {
{
$response = new SS_HTTPResponse( $response = new SS_HTTPResponse(
Convert::raw2json(array( 'Content' => $form->forAjaxTemplate()->getValue() )) Convert::raw2json(array('Content' => $form->forAjaxTemplate()->getValue()))
); );
$response->addHeader('X-Pjax', 'Content'); $response->addHeader('X-Pjax', 'Content');
$response->addHeader('Content-Type', 'text/json'); $response->addHeader('Content-Type', 'text/json');
$response->addHeader('X-Title', 'SilverStripe - Bulk '.$this->gridField->list->dataClass.' Editing'); $response->addHeader('X-Title', 'SilverStripe - Bulk '.$this->gridField->list->dataClass.' Editing');
return $response;
}
else {
$controller = $this->getToplevelController();
return $controller->customise(array( 'Content' => $form ));
}
}
return $response;
} else {
$controller = $this->getToplevelController();
return $controller->customise(array('Content' => $form));
}
}
/** /**
* Handles bulkEditForm submission * Handles bulkEditForm submission
* and parses and saves each records data * and parses and saves each records data.
* *
* @param array $data Sumitted form data * @param array $data Sumitted form data
* @param Form $form Form * @param Form $form Form
@ -343,12 +326,9 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
$done = 0; $done = 0;
//unescape and sort form data per record ID //unescape and sort form data per record ID
foreach ($data as $fieldName => $value) foreach ($data as $fieldName => $value) {
{ if ($fieldInfo = $this->unEscapeFieldName($fieldName)) {
if ( $fieldInfo = $this->unEscapeFieldName($fieldName) ) if (!isset($formsData[$fieldInfo['id']])) {
{
if ( !isset($formsData[$fieldInfo['id']]) )
{
$formsData[$fieldInfo['id']] = array(); $formsData[$fieldInfo['id']] = array();
} }
@ -357,11 +337,10 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
} }
//process each record's form data and save //process each record's form data and save
foreach ($formsData as $recordID => $recordData) foreach ($formsData as $recordID => $recordData) {
{
$record = DataObject::get_by_id($className, $recordID); $record = DataObject::get_by_id($className, $recordID);
$recordForm = Form::create( $recordForm = Form::create(
$this, "RecordForm", $this, 'RecordForm',
$record->getCMSFields(), $record->getCMSFields(),
FieldList::create() FieldList::create()
); );
@ -372,9 +351,8 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
array_push($ids, $record->ID); array_push($ids, $record->ID);
if ( $id ) if ($id) {
{ ++$done;
$done++;
} }
} }
@ -384,7 +362,7 @@ class GridFieldBulkActionEditHandler extends GridFieldBulkActionHandler
'{count} {class} saved successfully.', '{count} {class} saved successfully.',
array( array(
'count' => $done, 'count' => $done,
'class' => $messageModelClass 'class' => $messageModelClass,
) )
); );
$form->sessionMessage($message, 'good'); $form->sessionMessage($message, 'good');

View File

@ -2,37 +2,34 @@
/** /**
* Base class to extend for all custom bulk action handlers * Base class to extend for all custom bulk action handlers
* Gives access to the GridField, Component and Controller * Gives access to the GridField, Component and Controller
* and implements useful functions like {@link getRecordIDList()} and {@link getRecords()} * and implements useful functions like {@link getRecordIDList()} and {@link getRecords()}.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkManager
*/ */
class GridFieldBulkActionHandler extends RequestHandler class GridFieldBulkActionHandler extends RequestHandler
{ {
/** /**
* Related GridField instance * Related GridField instance.
*
* @var GridField * @var GridField
*/ */
protected $gridField; protected $gridField;
/** /**
* GridFieldBulkManager instance * GridFieldBulkManager instance.
*
* @var GridFieldBulkManager * @var GridFieldBulkManager
*/ */
protected $component; protected $component;
/** /**
* Current controller instance * Current controller instance.
*
* @var Controller * @var Controller
*/ */
protected $controller; protected $controller;
/** /**
*
* @param GridFIeld $gridField * @param GridFIeld $gridField
* @param GridField_URLHandler $component * @param GridField_URLHandler $component
* @param Controller $controller * @param Controller $controller
@ -45,13 +42,15 @@ class GridFieldBulkActionHandler extends RequestHandler
parent::__construct(); parent::__construct();
} }
/** /**
* Returns the URL for this RequestHandler * Returns the URL for this RequestHandler.
* *
* @author SilverStripe * @author SilverStripe
*
* @see GridFieldDetailForm_ItemRequest * @see GridFieldDetailForm_ItemRequest
*
* @param string $action * @param string $action
*
* @return string * @return string
*/ */
public function Link($action = null) public function Link($action = null)
@ -59,7 +58,6 @@ class GridFieldBulkActionHandler extends RequestHandler
return Controller::join_links($this->gridField->Link(), 'bulkAction', $action); return Controller::join_links($this->gridField->Link(), 'bulkAction', $action);
} }
/** /**
* Traverse up nested requests until we reach the first that's not a GridFieldDetailForm or GridFieldDetailForm_ItemRequest. * Traverse up nested requests until we reach the first that's not a GridFieldDetailForm or GridFieldDetailForm_ItemRequest.
* The opposite of {@link Controller::curr()}, required because * The opposite of {@link Controller::curr()}, required because
@ -70,53 +68,58 @@ class GridFieldBulkActionHandler extends RequestHandler
protected function getToplevelController() protected function getToplevelController()
{ {
$c = $this->controller; $c = $this->controller;
while($c && ($c instanceof GridFieldDetailForm_ItemRequest || $c instanceof GridFieldDetailForm)) { while ($c && ($c instanceof GridFieldDetailForm_ItemRequest || $c instanceof GridFieldDetailForm)) {
$c = $c->getController(); $c = $c->getController();
} }
return $c; return $c;
} }
/** /**
* Edited version of the GridFieldEditForm function * Edited version of the GridFieldEditForm function
* adds the 'Bulk Upload' at the end of the crums * adds the 'Bulk Upload' at the end of the crums.
* *
* CMS-specific functionality: Passes through navigation breadcrumbs * CMS-specific functionality: Passes through navigation breadcrumbs
* to the template, and includes the currently edited record (if any). * to the template, and includes the currently edited record (if any).
* see {@link LeftAndMain->Breadcrumbs()} for details. * see {@link LeftAndMain->Breadcrumbs()} for details.
* *
* @author SilverStripe original Breadcrumbs() method * @author SilverStripe original Breadcrumbs() method
*
* @see GridFieldDetailForm_ItemRequest * @see GridFieldDetailForm_ItemRequest
* @param boolean $unlinked *
* @param bool $unlinked
*
* @return ArrayData * @return ArrayData
*/ */
public function Breadcrumbs($unlinked = false) public function Breadcrumbs($unlinked = false)
{ {
if(!$this->controller->hasMethod('Breadcrumbs')) return; if (!$this->controller->hasMethod('Breadcrumbs')) {
return;
}
$items = $this->controller->Breadcrumbs($unlinked); $items = $this->controller->Breadcrumbs($unlinked);
$items->push(new ArrayData(array( $items->push(new ArrayData(array(
'Title' => 'Bulk Editing', 'Title' => 'Bulk Editing',
'Link' => false 'Link' => false,
))); )));
return $items; return $items;
} }
/** /**
* Returns the list of record IDs selected in the front-end * Returns the list of record IDs selected in the front-end.
* *
* @return array List of IDs * @return array List of IDs
*/ */
public function getRecordIDList() public function getRecordIDList()
{ {
$vars = $this->request->requestVars(); $vars = $this->request->requestVars();
return $vars['records']; return $vars['records'];
} }
/** /**
* Returns a DataList of the records selected in the front-end * Returns a DataList of the records selected in the front-end.
* *
* @return DataList List of records * @return DataList List of records
*/ */
@ -124,12 +127,11 @@ class GridFieldBulkActionHandler extends RequestHandler
{ {
$ids = $this->getRecordIDList(); $ids = $this->getRecordIDList();
if ( $ids ) if ($ids) {
{
$class = $this->gridField->list->dataClass; $class = $this->gridField->list->dataClass;
return DataList::create($class)->byIDs( $ids );
} return DataList::create($class)->byIDs($ids);
else{ } else {
return false; return false;
} }
} }

View File

@ -3,31 +3,30 @@
* Bulk action handler for unlinking records. * Bulk action handler for unlinking records.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkManager
*/ */
class GridFieldBulkActionUnLinkHandler extends GridFieldBulkActionHandler class GridFieldBulkActionUnlinkHandler extends GridFieldBulkActionHandler
{ {
/** /**
* RequestHandler allowed actions * RequestHandler allowed actions.
*
* @var array * @var array
*/ */
private static $allowed_actions = array('unLink'); private static $allowed_actions = array('unLink');
/** /**
* RequestHandler url => action map * RequestHandler url => action map.
*
* @var array * @var array
*/ */
private static $url_handlers = array( private static $url_handlers = array(
'unLink' => 'unLink' 'unLink' => 'unLink',
); );
/** /**
* Unlink the selected records passed from the unlink bulk action * Unlink the selected records passed from the unlink bulk action.
* *
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*
* @return SS_HTTPResponse List of affected records ID * @return SS_HTTPResponse List of affected records ID
*/ */
public function unLink(SS_HTTPRequest $request) public function unLink(SS_HTTPRequest $request)
@ -37,9 +36,10 @@ class GridFieldBulkActionUnLinkHandler extends GridFieldBulkActionHandler
$response = new SS_HTTPResponse(Convert::raw2json(array( $response = new SS_HTTPResponse(Convert::raw2json(array(
'done' => true, 'done' => true,
'records' => $ids 'records' => $ids,
))); )));
$response->addHeader('Content-Type', 'text/json'); $response->addHeader('Content-Type', 'text/json');
return $response; return $response;
} }
} }

View File

@ -1,15 +1,13 @@
<?php <?php
/** /**
* GridField component for editing attached models in bulk * GridField component for editing attached models in bulk.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkManager
*/ */
class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnProvider, GridField_URLHandler class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnProvider, GridField_URLHandler
{ {
/** /**
* component configuration * component configuration.
* *
* 'editableFields' => fields editable on the Model * 'editableFields' => fields editable on the Model
* 'actions' => maps of action name and configuration * 'actions' => maps of action name and configuration
@ -18,22 +16,22 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
*/ */
protected $config = array( protected $config = array(
'editableFields' => null, 'editableFields' => null,
'actions' => array() 'actions' => array(),
); );
/** /**
* GridFieldBulkManager component constructor * GridFieldBulkManager component constructor.
* *
* @param array $editableFields List of editable fields * @param array $editableFields List of editable fields
* @param boolean $defaultActions Use default actions list. False to start fresh. * @param bool $defaultActions Use default actions list. False to start fresh.
*/ */
public function __construct($editableFields = null, $defaultActions = true) public function __construct($editableFields = null, $defaultActions = true)
{ {
if ( $editableFields != null ) $this->setConfig ( 'editableFields', $editableFields ); if ($editableFields != null) {
$this->setConfig('editableFields', $editableFields);
}
if ( $defaultActions ) if ($defaultActions) {
{
$this->config['actions'] = array( $this->config['actions'] = array(
'bulkEdit' => array( 'bulkEdit' => array(
'label' => _t('GRIDFIELD_BULK_MANAGER.EDIT_SELECT_LABEL', 'Edit'), 'label' => _t('GRIDFIELD_BULK_MANAGER.EDIT_SELECT_LABEL', 'Edit'),
@ -41,8 +39,8 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
'config' => array( 'config' => array(
'isAjax' => false, 'isAjax' => false,
'icon' => 'pencil', 'icon' => 'pencil',
'isDestructive' => false 'isDestructive' => false,
) ),
), ),
'unLink' => array( 'unLink' => array(
'label' => _t('GRIDFIELD_BULK_MANAGER.UNLINK_SELECT_LABEL', 'UnLink'), 'label' => _t('GRIDFIELD_BULK_MANAGER.UNLINK_SELECT_LABEL', 'UnLink'),
@ -50,8 +48,8 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
'config' => array( 'config' => array(
'isAjax' => true, 'isAjax' => true,
'icon' => 'chain--minus', 'icon' => 'chain--minus',
'isDestructive' => false 'isDestructive' => false,
) ),
), ),
'delete' => array( 'delete' => array(
'label' => _t('GRIDFIELD_BULK_MANAGER.DELETE_SELECT_LABEL', 'Delete'), 'label' => _t('GRIDFIELD_BULK_MANAGER.DELETE_SELECT_LABEL', 'Delete'),
@ -59,39 +57,34 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
'config' => array( 'config' => array(
'isAjax' => true, 'isAjax' => true,
'icon' => 'decline', 'icon' => 'decline',
'isDestructive' => true 'isDestructive' => true,
) ),
) ),
); );
} }
} }
/* ********************************************************************** /* **********************************************************************
* Components settings and custom methodes * Components settings and custom methodes
* */ * */
/** /**
* Sets the component configuration parameter * Sets the component configuration parameter.
* *
* @param string $reference * @param string $reference
* @param mixed $value * @param mixed $value
*/ */
function setConfig($reference, $value) public function setConfig($reference, $value)
{
if (!array_key_exists($reference, $this->config) )
{ {
if (!array_key_exists($reference, $this->config)) {
user_error("Unknown option reference: $reference", E_USER_ERROR); user_error("Unknown option reference: $reference", E_USER_ERROR);
} }
if ( $reference == 'actions' ) if ($reference == 'actions') {
{ user_error('Bulk actions must be edited via addBulkAction() and removeBulkAction()', E_USER_ERROR);
user_error("Bulk actions must be edited via addBulkAction() and removeBulkAction()", E_USER_ERROR);
} }
if ( ($reference == 'editableFields') && !is_array($value) ) if (($reference == 'editableFields') && !is_array($value)) {
{
$value = array($value); $value = array($value);
} }
@ -100,22 +93,24 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
return $this; return $this;
} }
/** /**
* Returns one $config parameter of the full $config * Returns one $config parameter of the full $config.
* *
* @param string $reference $congif parameter to return * @param string $reference $congif parameter to return
*
* @return mixed * @return mixed
*/ */
function getConfig ( $reference = false ) public function getConfig($reference = false)
{ {
if ( $reference ) return $this->config[$reference]; if ($reference) {
else return $this->config; return $this->config[$reference];
} else {
return $this->config;
}
} }
/** /**
* Lets you add custom bulk actions to the bulk manager interface * Lets you add custom bulk actions to the bulk manager interface.
* *
* @todo add config options for front-end: isAjax, icon * @todo add config options for front-end: isAjax, icon
* *
@ -123,172 +118,163 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
* @param string $label Dropdown menu action's label. Default to ucfirst($name). * @param string $label Dropdown menu action's label. Default to ucfirst($name).
* @param string $handler RequestHandler class name for this action. Default to 'GridFieldBulkAction'.ucfirst($name).'Handler' * @param string $handler RequestHandler class name for this action. Default to 'GridFieldBulkAction'.ucfirst($name).'Handler'
* @param array $config Front-end configuration array( 'isAjax' => true, 'icon' => 'accept', 'isDestructive' => false ) * @param array $config Front-end configuration array( 'isAjax' => true, 'icon' => 'accept', 'isDestructive' => false )
*
* @return GridFieldBulkManager Current GridFieldBulkManager instance * @return GridFieldBulkManager Current GridFieldBulkManager instance
*/ */
function addBulkAction($name, $label = null, $handler = null, $config = null) public function addBulkAction($name, $label = null, $handler = null, $config = null)
{
if ( array_key_exists($name, $this->config['actions']) )
{ {
if (array_key_exists($name, $this->config['actions'])) {
user_error("Bulk action '$name' already exists.", E_USER_ERROR); user_error("Bulk action '$name' already exists.", E_USER_ERROR);
} }
if ( !$label ) if (!$label) {
{
$label = ucfirst($name); $label = ucfirst($name);
} }
if ( !$handler ) if (!$handler) {
{
$handler = 'GridFieldBulkAction'.ucfirst($name).'Handler'; $handler = 'GridFieldBulkAction'.ucfirst($name).'Handler';
} }
if ( !ClassInfo::exists( $handler ) ) if (!ClassInfo::exists($handler)) {
{
user_error("Bulk action handler for $name not found: $handler", E_USER_ERROR); user_error("Bulk action handler for $name not found: $handler", E_USER_ERROR);
} }
if ( $config && !is_array($config) ) if ($config && !is_array($config)) {
{ user_error('Bulk action front-end config should be an array of key => value pairs.', E_USER_ERROR);
user_error("Bulk action front-end config should be an array of key => value pairs.", E_USER_ERROR); } else {
}
else{
$config = array( $config = array(
'isAjax' => isset($config['isAjax']) ? $config['isAjax'] : true, 'isAjax' => isset($config['isAjax']) ? $config['isAjax'] : true,
'icon' => isset($config['icon']) ? $config['icon'] : 'accept', 'icon' => isset($config['icon']) ? $config['icon'] : 'accept',
'isDestructive' => isset($config['isDestructive']) ? $config['isDestructive'] : false 'isDestructive' => isset($config['isDestructive']) ? $config['isDestructive'] : false,
); );
} }
$this->config['actions'][$name] = array( $this->config['actions'][$name] = array(
'label' => $label, 'label' => $label,
'handler' => $handler, 'handler' => $handler,
'config' => $config 'config' => $config,
); );
return $this; return $this;
} }
/** /**
* Removes a bulk actions from the bulk manager interface * Removes a bulk actions from the bulk manager interface.
* *
* @param string $name Bulk action's name * @param string $name Bulk action's name
*
* @return GridFieldBulkManager Current GridFieldBulkManager instance * @return GridFieldBulkManager Current GridFieldBulkManager instance
*/ */
function removeBulkAction($name) public function removeBulkAction($name)
{
if ( !array_key_exists($name, $this->config['actions']) )
{ {
if (!array_key_exists($name, $this->config['actions'])) {
user_error("Bulk action '$name' doesn't exists.", E_USER_ERROR); user_error("Bulk action '$name' doesn't exists.", E_USER_ERROR);
} }
unset( $this->config['actions'][$name] ); unset($this->config['actions'][$name]);
return $this; return $this;
} }
/* ********************************************************************** /* **********************************************************************
* GridField_ColumnProvider * GridField_ColumnProvider
* */ * */
/** /**
* Add bulk select column * Add bulk select column.
* *
* @param GridField $gridField Current GridField instance * @param GridField $gridField Current GridField instance
* @param array $columns Columns list * @param array $columns Columns list
*/ */
function augmentColumns($gridField, &$columns) public function augmentColumns($gridField, &$columns)
{ {
if(!in_array('BulkSelect', $columns)) $columns[] = 'BulkSelect'; if (!in_array('BulkSelect', $columns)) {
$columns[] = 'BulkSelect';
}
} }
/** /**
* Which columns are handled by the component * Which columns are handled by the component.
* *
* @param GridField $gridField Current GridField instance * @param GridField $gridField Current GridField instance
*
* @return array List of handled column names * @return array List of handled column names
*/ */
function getColumnsHandled($gridField) public function getColumnsHandled($gridField)
{ {
return array('BulkSelect'); return array('BulkSelect');
} }
/** /**
* Sets the column's content * Sets the column's content.
* *
* @param GridField $gridField Current GridField instance * @param GridField $gridField Current GridField instance
* @param DataObject $record Record intance for this row * @param DataObject $record Record intance for this row
* @param string $columnName Column's name for which we need content * @param string $columnName Column's name for which we need content
*
* @return mixed Column's field content * @return mixed Column's field content
*/ */
function getColumnContent($gridField, $record, $columnName) public function getColumnContent($gridField, $record, $columnName)
{ {
$cb = CheckboxField::create('bulkSelect_'.$record->ID) $cb = CheckboxField::create('bulkSelect_'.$record->ID)
->addExtraClass('bulkSelect no-change-track') ->addExtraClass('bulkSelect no-change-track')
->setAttribute('data-record', $record->ID); ->setAttribute('data-record', $record->ID);
return $cb->Field(); return $cb->Field();
} }
/** /**
* Set the column's HTML attributes * Set the column's HTML attributes.
* *
* @param GridField $gridField Current GridField instance * @param GridField $gridField Current GridField instance
* @param DataObject $record Record intance for this row * @param DataObject $record Record intance for this row
* @param string $columnName Column's name for which we need attributes * @param string $columnName Column's name for which we need attributes
*
* @return array List of HTML attributes * @return array List of HTML attributes
*/ */
function getColumnAttributes($gridField, $record, $columnName) public function getColumnAttributes($gridField, $record, $columnName)
{ {
return array('class' => 'col-bulkSelect'); return array('class' => 'col-bulkSelect');
} }
/** /**
* Set the column's meta data * Set the column's meta data.
* *
* @param GridField $gridField Current GridField instance * @param GridField $gridField Current GridField instance
* @param string $columnName Column's name for which we need meta data * @param string $columnName Column's name for which we need meta data
*
* @return array List of meta data * @return array List of meta data
*/ */
function getColumnMetadata($gridField, $columnName) public function getColumnMetadata($gridField, $columnName)
{ {
if($columnName == 'BulkSelect') { if ($columnName == 'BulkSelect') {
return array('title' => 'Select'); return array('title' => 'Select');
} }
} }
/* ********************************************************************** /* **********************************************************************
* GridField_HTMLProvider * GridField_HTMLProvider
* */ * */
/** /**
*
* @param GridField $gridField * @param GridField $gridField
*
* @return array * @return array
*/ */
public function getHTMLFragments($gridField) public function getHTMLFragments($gridField)
{ {
Requirements::css(BULKEDITTOOLS_MANAGER_PATH . '/css/GridFieldBulkManager.css'); Requirements::css(BULKEDITTOOLS_MANAGER_PATH.'/css/GridFieldBulkManager.css');
Requirements::javascript(BULKEDITTOOLS_MANAGER_PATH . '/javascript/GridFieldBulkManager.js'); Requirements::javascript(BULKEDITTOOLS_MANAGER_PATH.'/javascript/GridFieldBulkManager.js');
Requirements::add_i18n_javascript(BULKEDITTOOLS_PATH . '/lang/js'); Requirements::add_i18n_javascript(BULKEDITTOOLS_PATH.'/lang/js');
if ( !count($this->config['actions']) ) if (!count($this->config['actions'])) {
{ user_error('Trying to use GridFieldBulkManager without any bulk action.', E_USER_ERROR);
user_error("Trying to use GridFieldBulkManager without any bulk action.", E_USER_ERROR);
} }
$actionsListSource = array(); $actionsListSource = array();
$actionsConfig = array(); $actionsConfig = array();
foreach ($this->config['actions'] as $action => $actionData) foreach ($this->config['actions'] as $action => $actionData) {
{
$actionsListSource[$action] = $actionData['label']; $actionsListSource[$action] = $actionData['label'];
$actionsConfig[$action] = $actionData['config']; $actionsConfig[$action] = $actionData['config'];
} }
@ -297,7 +283,7 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
$firstAction = key($this->config['actions']); $firstAction = key($this->config['actions']);
$dropDownActionsList = DropdownField::create('bulkActionName', '') $dropDownActionsList = DropdownField::create('bulkActionName', '')
->setSource( $actionsListSource ) ->setSource($actionsListSource)
->setAttribute('class', 'bulkActionName no-change-track') ->setAttribute('class', 'bulkActionName no-change-track')
->setAttribute('id', ''); ->setAttribute('id', '');
@ -307,40 +293,39 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
'Label' => _t('GRIDFIELD_BULK_MANAGER.ACTION_BTN_LABEL', 'Go'), 'Label' => _t('GRIDFIELD_BULK_MANAGER.ACTION_BTN_LABEL', 'Go'),
'DataURL' => $gridField->Link('bulkAction'), 'DataURL' => $gridField->Link('bulkAction'),
'Icon' => $this->config['actions'][$firstAction]['config']['icon'], 'Icon' => $this->config['actions'][$firstAction]['config']['icon'],
'DataConfig' => htmlspecialchars(json_encode($actionsConfig), ENT_QUOTES, 'UTF-8') 'DataConfig' => htmlspecialchars(json_encode($actionsConfig), ENT_QUOTES, 'UTF-8'),
), ),
'Select' => array( 'Select' => array(
'Label' => _t('GRIDFIELD_BULK_MANAGER.SELECT_ALL_LABEL', 'Select all') 'Label' => _t('GRIDFIELD_BULK_MANAGER.SELECT_ALL_LABEL', 'Select all'),
), ),
'Colspan' => (count($gridField->getColumns()) - 1) 'Colspan' => (count($gridField->getColumns()) - 1),
); );
$templateData = new ArrayData($templateData); $templateData = new ArrayData($templateData);
return array( return array(
'header' => $templateData->renderWith('BulkManagerButtons') 'header' => $templateData->renderWith('BulkManagerButtons'),
); );
} }
/* ********************************************************************** /* **********************************************************************
* GridField_URLHandler * GridField_URLHandler
* */ * */
/** /**
* Returns an action => handler list * Returns an action => handler list.
* *
* @param GridField $gridField * @param GridField $gridField
*
* @return array * @return array
*/ */
public function getURLHandlers($gridField) { public function getURLHandlers($gridField)
{
return array( return array(
'bulkAction' => 'handleBulkAction' 'bulkAction' => 'handleBulkAction',
); );
} }
/** /**
* Pass control over to the RequestHandler * Pass control over to the RequestHandler
* loop through the handlers provided in config['actions'] * loop through the handlers provided in config['actions']
@ -351,28 +336,29 @@ class GridFieldBulkManager implements GridField_HTMLProvider, GridField_ColumnPr
* *
* @param GridField $gridField * @param GridField $gridField
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*
* @return mixed * @return mixed
*/ */
public function handleBulkAction($gridField, $request) public function handleBulkAction($gridField, $request)
{ {
$controller = $gridField->getForm()->Controller(); $controller = $gridField->getForm()->Controller();
foreach ($this->config['actions'] as $name => $data) foreach ($this->config['actions'] as $name => $data) {
{
$handlerClass = $data['handler']; $handlerClass = $data['handler'];
$urlHandlers = Config::inst()->get($handlerClass, 'url_handlers', Config::UNINHERITED); $urlHandlers = Config::inst()->get($handlerClass, 'url_handlers', Config::UNINHERITED);
if($urlHandlers) foreach($urlHandlers as $rule => $action) if ($urlHandlers) {
{ foreach ($urlHandlers as $rule => $action) {
if($request->match($rule, false)) if ($request->match($rule, false)) {
{
//print_r('matched ' . $handlerClass . ' to ' . $rule); //print_r('matched ' . $handlerClass . ' to ' . $rule);
$handler = Injector::inst()->create($handlerClass, $gridField, $this, $controller); $handler = Injector::inst()->create($handlerClass, $gridField, $this, $controller);
return $handler->handleRequest($request, DataModel::inst()); return $handler->handleRequest($request, DataModel::inst());
} }
} }
} }
}
user_error("Unable to find matching bulk action handler for ".$request->remaining().'.', E_USER_ERROR); user_error('Unable to find matching bulk action handler for '.$request->remaining().'.', E_USER_ERROR);
} }
} }

View File

@ -1,17 +1,15 @@
<?php <?php
/** /**
* Legacy GridFieldBulkImageUpload component * Legacy GridFieldBulkImageUpload component.
* *
* @deprecated 2.0 "GridFieldBulkImageUpload" is deprecated, use {@link GridFieldBulkUpload} class instead. * @deprecated 2.0 "GridFieldBulkImageUpload" is deprecated, use {@link GridFieldBulkUpload} class instead.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkUpload
*/ */
class GridFieldBulkImageUpload extends GridFieldBulkUpload class GridFieldBulkImageUpload extends GridFieldBulkUpload
{ {
/** /**
* Component constructor * Component constructor.
* *
* @deprecated 2.0 "GridFieldBulkImageUpload" is deprecated, use {@link GridFieldBulkUpload} class instead. * @deprecated 2.0 "GridFieldBulkImageUpload" is deprecated, use {@link GridFieldBulkUpload} class instead.
* *
@ -20,6 +18,7 @@ class GridFieldBulkImageUpload extends GridFieldBulkUpload
public function __construct($fileRelationName = null) public function __construct($fileRelationName = null)
{ {
Deprecation::notice('2.0', '"GridFieldBulkImageUpload" is deprecated, use "GridFieldBulkUpload" class instead.'); Deprecation::notice('2.0', '"GridFieldBulkImageUpload" is deprecated, use "GridFieldBulkUpload" class instead.');
return new GridFieldBulkUpload($fileRelationName); return new GridFieldBulkUpload($fileRelationName);
} }
} }

View File

@ -1,28 +1,26 @@
<?php <?php
/** /**
* GridField component for uploading images in bulk * GridField component for uploading images in bulk.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkUpload
*/ */
class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandler class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandler
{ {
/** /**
* component configuration * component configuration.
* *
* 'fileRelationName' => field name of the $has_one File/Image relation * 'fileRelationName' => field name of the $has_one File/Image relation
*
* @var array * @var array
*/ */
protected $config = array( protected $config = array(
'fileRelationName' => null 'fileRelationName' => null,
); );
/** /**
* UploadField configuration. * UploadField configuration.
* These options are passed on directly to the UploadField * These options are passed on directly to the UploadField
* via {@link UploadField::setConfig()} api * via {@link UploadField::setConfig()} api.
* *
* Defaults are: * * Defaults are: *
* 'sequentialUploads' => false : process uploads 1 after the other rather than all at once * 'sequentialUploads' => false : process uploads 1 after the other rather than all at once
@ -34,13 +32,12 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
protected $ufConfig = array( protected $ufConfig = array(
'sequentialUploads' => false, 'sequentialUploads' => false,
'canAttachExisting' => true, 'canAttachExisting' => true,
'canPreviewFolder' => true 'canPreviewFolder' => true,
); );
/** /**
* UploadField setup function calls. * UploadField setup function calls.
* List of setup functions to call on {@link UploadField} with the value to pass * List of setup functions to call on {@link UploadField} with the value to pass.
* *
* e.g. array('setFolderName' => 'bulkUpload') will result in: * e.g. array('setFolderName' => 'bulkUpload') will result in:
* $uploadField->setFolderName('bulkUpload') * $uploadField->setFolderName('bulkUpload')
@ -48,13 +45,12 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
* @var array * @var array
*/ */
protected $ufSetup = array( protected $ufSetup = array(
'setFolderName' => 'bulkUpload' 'setFolderName' => 'bulkUpload',
); );
/** /**
* UploadField Validator setup function calls. * UploadField Validator setup function calls.
* List of setup functions to call on {@link Upload::validator} with the value to pass * List of setup functions to call on {@link Upload::validator} with the value to pass.
* *
* e.g. array('setAllowedMaxFileSize' => 10) will result in: * e.g. array('setAllowedMaxFileSize' => 10) will result in:
* $uploadField->getValidator()->setAllowedMaxFileSize(10) * $uploadField->getValidator()->setAllowedMaxFileSize(10)
@ -62,153 +58,158 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
* @var array * @var array
*/ */
protected $ufValidatorSetup = array( protected $ufValidatorSetup = array(
'setAllowedMaxFileSize' => null 'setAllowedMaxFileSize' => null,
); );
/** /**
* Component constructor * Component constructor.
* *
* @param string $fileRelationName * @param string $fileRelationName
*/ */
public function __construct($fileRelationName = null) public function __construct($fileRelationName = null)
{ {
if ( $fileRelationName != null ) $this->setConfig ( 'fileRelationName', $fileRelationName ); if ($fileRelationName != null) {
$this->setConfig('fileRelationName', $fileRelationName);
}
} }
/* ********************************************************************** /* **********************************************************************
* Components settings and custom methodes * Components settings and custom methodes
* */ * */
/** /**
* Set a component configuration parameter * Set a component configuration parameter.
* *
* @param string $reference * @param string $reference
* @param mixed $value * @param mixed $value
*/ */
function setConfig ( $reference, $value ) public function setConfig($reference, $value)
{
if ( in_array($reference, array('folderName', 'maxFileSize', 'sequentialUploads', 'canAttachExisting', 'canPreviewFolder')) )
{ {
if (in_array($reference, array('folderName', 'maxFileSize', 'sequentialUploads', 'canAttachExisting', 'canPreviewFolder'))) {
Deprecation::notice('2.1.0', "GridFieldBulkUpload 'setConfig()' doesn't support '$reference' anymore. Please use 'setUfConfig()', 'setUfSetup()' or 'setUfValidatorSetup()' instead."); Deprecation::notice('2.1.0', "GridFieldBulkUpload 'setConfig()' doesn't support '$reference' anymore. Please use 'setUfConfig()', 'setUfSetup()' or 'setUfValidatorSetup()' instead.");
if ( $reference === 'folderName' ) if ($reference === 'folderName') {
{
$this->setUfSetup('setFolderName', $value); $this->setUfSetup('setFolderName', $value);
} } elseif ($reference === 'maxFileSize') {
else if ( $reference === 'maxFileSize' )
{
$this->setUfValidatorSetup('setAllowedMaxFileSize', $value); $this->setUfValidatorSetup('setAllowedMaxFileSize', $value);
} } else {
else{
$this->setUfConfig($reference, $value); $this->setUfConfig($reference, $value);
} }
} } elseif (!array_key_exists($reference, $this->config)) {
else if (!array_key_exists($reference, $this->config) ) {
user_error("Unknown option reference: $reference", E_USER_ERROR); user_error("Unknown option reference: $reference", E_USER_ERROR);
} }
$this->config[$reference] = $value; $this->config[$reference] = $value;
return $this; return $this;
} }
/** /**
* Set an UploadField configuration parameter * Set an UploadField configuration parameter.
* *
* @param string $reference * @param string $reference
* @param mixed $value * @param mixed $value
*/ */
function setUfConfig ( $reference, $value ) public function setUfConfig($reference, $value)
{ {
$this->ufConfig[$reference] = $value; $this->ufConfig[$reference] = $value;
return $this; return $this;
} }
/** /**
* Set an UploadField setup function call * Set an UploadField setup function call.
* *
* @param string $function * @param string $function
* @param mixed $param * @param mixed $param
*/ */
function setUfSetup ( $function, $param ) public function setUfSetup($function, $param)
{ {
$this->ufSetup[$function] = $param; $this->ufSetup[$function] = $param;
return $this; return $this;
} }
/** /**
* Set an UploadField Validator setup function call * Set an UploadField Validator setup function call.
* *
* @param string $function * @param string $function
* @param mixed $param * @param mixed $param
*/ */
function setUfValidatorSetup ( $function, $param ) public function setUfValidatorSetup($function, $param)
{ {
$this->ufValidatorSetup[$function] = $param; $this->ufValidatorSetup[$function] = $param;
return $this; return $this;
} }
/** /**
* Returns one $config reference or the full $config * Returns one $config reference or the full $config.
* *
* @param string $reference $congif parameter to return * @param string $reference $congif parameter to return
*
* @return mixed * @return mixed
*/ */
function getConfig ( $reference = false ) public function getConfig($reference = false)
{ {
if ( $reference ) return $this->config[$reference]; if ($reference) {
else return $this->config; return $this->config[$reference];
} else {
return $this->config;
}
} }
/** /**
* Returns one $ufConfig reference or the full config. * Returns one $ufConfig reference or the full config.
* *
* @param string $reference $ufConfig parameter to return * @param string $reference $ufConfig parameter to return
*
* @return mixed * @return mixed
*/ */
function getUfConfig ( $reference = false ) public function getUfConfig($reference = false)
{ {
if ( $reference ) return $this->ufConfig[$reference]; if ($reference) {
else return $this->ufConfig; return $this->ufConfig[$reference];
} else {
return $this->ufConfig;
}
} }
/** /**
* Returns one $ufSetup reference or the full config. * Returns one $ufSetup reference or the full config.
* *
* @param string $reference $ufSetup parameter to return * @param string $reference $ufSetup parameter to return
*
* @return mixed * @return mixed
*/ */
function getUfSetup ( $reference = false ) public function getUfSetup($reference = false)
{ {
if ( $reference ) return $this->ufSetup[$reference]; if ($reference) {
else return $this->ufSetup; return $this->ufSetup[$reference];
} else {
return $this->ufSetup;
}
} }
/** /**
* Returns one $ufValidatorSetup reference or the full config. * Returns one $ufValidatorSetup reference or the full config.
* *
* @param string $reference $ufValidatorSetup parameter to return * @param string $reference $ufValidatorSetup parameter to return
*
* @return mixed * @return mixed
*/ */
function getUfValidatorSetup ( $reference = false ) public function getUfValidatorSetup($reference = false)
{ {
if ( $reference ) return $this->ufValidatorSetup[$reference]; if ($reference) {
else return $this->ufValidatorSetup; return $this->ufValidatorSetup[$reference];
} else {
return $this->ufValidatorSetup;
}
} }
/** /**
* Get the first has_one Image/File relation from the GridField managed DataObject * Get the first has_one Image/File relation from the GridField managed DataObject
* i.e. 'MyImage' => 'Image' will return 'MyImage' * i.e. 'MyImage' => 'Image' will return 'MyImage'.
* *
* @return string Name of the $has_one relation * @return string Name of the $has_one relation
*/ */
@ -218,10 +219,8 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
$hasOneFields = Config::inst()->get($recordClass, 'has_one', Config::INHERITED); $hasOneFields = Config::inst()->get($recordClass, 'has_one', Config::INHERITED);
$imageField = null; $imageField = null;
foreach( $hasOneFields as $field => $type ) foreach ($hasOneFields as $field => $type) {
{ if ($type === 'Image' || $type === 'File' || is_subclass_of($type, 'File')) {
if( $type === 'Image' || $type === 'File' || is_subclass_of($type, 'File') )
{
$imageField = $field; $imageField = $field;
break; break;
} }
@ -230,24 +229,23 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
return $imageField; return $imageField;
} }
/** /**
* Returns the name of the Image/File field name from the managed record * Returns the name of the Image/File field name from the managed record
* Either as set in the component config or the default one * Either as set in the component config or the default one.
* *
* @return string * @return string
*/ */
public function getFileRelationName($gridField) public function getFileRelationName($gridField)
{ {
$configFileRelationName = $this->getConfig('fileRelationName'); $configFileRelationName = $this->getConfig('fileRelationName');
return $configFileRelationName ? $configFileRelationName : $this->getDefaultFileRelationName($gridField); return $configFileRelationName ? $configFileRelationName : $this->getDefaultFileRelationName($gridField);
} }
/** /**
* Return the ClassName of the fileRelation * Return the ClassName of the fileRelation
* i.e. 'MyImage' => 'Image' will return 'Image' * i.e. 'MyImage' => 'Image' will return 'Image'
* i.e. 'MyImage' => 'File' will return 'File' * i.e. 'MyImage' => 'File' will return 'File'.
* *
* @return string file relation className * @return string file relation className
*/ */
@ -257,20 +255,19 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
$hasOneFields = Config::inst()->get($recordClass, 'has_one', Config::INHERITED); $hasOneFields = Config::inst()->get($recordClass, 'has_one', Config::INHERITED);
$fieldName = $this->getFileRelationName($gridField); $fieldName = $this->getFileRelationName($gridField);
if($fieldName) if ($fieldName) {
{
return $hasOneFields[$fieldName]; return $hasOneFields[$fieldName];
} } else {
else{
return 'File'; return 'File';
} }
} }
/** /**
* Returned a configured UploadField instance * Returned a configured UploadField instance
* embedded in the gridfield heard * embedded in the gridfield heard.
*
* @param GridField $gridField Current GridField * @param GridField $gridField Current GridField
*
* @return UploadField Configured UploadField instance * @return UploadField Configured UploadField instance
*/ */
public function bulkUploadField($gridField) public function bulkUploadField($gridField)
@ -295,43 +292,38 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
; ;
//set UploadField config //set UploadField config
foreach ($this->ufConfig as $key => $val) foreach ($this->ufConfig as $key => $val) {
{
$uploadField->setConfig($key, $val); $uploadField->setConfig($key, $val);
} }
//UploadField setup //UploadField setup
foreach ($this->ufSetup as $fn => $param) foreach ($this->ufSetup as $fn => $param) {
{
$uploadField->{$fn}($param); $uploadField->{$fn}($param);
} }
//UploadField Validator setup //UploadField Validator setup
foreach ($this->ufValidatorSetup as $fn => $param) foreach ($this->ufValidatorSetup as $fn => $param) {
{
$uploadField->getValidator()->{$fn}($param); $uploadField->getValidator()->{$fn}($param);
} }
return $uploadField; return $uploadField;
} }
/* ********************************************************************** /* **********************************************************************
* GridField_HTMLProvider * GridField_HTMLProvider
* */ * */
/** /**
* HTML to be embedded into the GridField * HTML to be embedded into the GridField.
* *
* @param GridField $gridField * @param GridField $gridField
*
* @return array * @return array
*/ */
public function getHTMLFragments($gridField) public function getHTMLFragments($gridField)
{ {
// permission check // permission check
if( !singleton($gridField->getModelClass())->canEdit() ) if (!singleton($gridField->getModelClass())->canEdit()) {
{
return array(); return array();
} }
@ -349,8 +341,7 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
->setAttribute('data-icon', 'arrow-circle-double') ->setAttribute('data-icon', 'arrow-circle-double')
->setUseButtonTag(true); ->setUseButtonTag(true);
if ( count($bulkManager) ) if (count($bulkManager)) {
{
$cancelButton = FormAction::create('Cancel', _t('GRIDFIELD_BULK_UPLOAD.CANCEL_BTN_LABEL', 'Cancel')) $cancelButton = FormAction::create('Cancel', _t('GRIDFIELD_BULK_UPLOAD.CANCEL_BTN_LABEL', 'Cancel'))
->addExtraClass('bulkUploadCancelButton ss-ui-action-destructive') ->addExtraClass('bulkUploadCancelButton ss-ui-action-destructive')
->setAttribute('data-icon', 'decline') ->setAttribute('data-icon', 'decline')
@ -359,17 +350,16 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
$bulkManager_config = $bulkManager->first()->getConfig(); $bulkManager_config = $bulkManager->first()->getConfig();
$bulkManager_actions = $bulkManager_config['actions']; $bulkManager_actions = $bulkManager_config['actions'];
if(array_key_exists('bulkedit' , $bulkManager_actions)){ if (array_key_exists('bulkedit', $bulkManager_actions)) {
$editAllButton = FormAction::create('EditAll', _t('GRIDFIELD_BULK_UPLOAD.EDIT_ALL_BTN_LABEL', 'Edit all')) $editAllButton = FormAction::create('EditAll', _t('GRIDFIELD_BULK_UPLOAD.EDIT_ALL_BTN_LABEL', 'Edit all'))
->addExtraClass('bulkUploadEditButton') ->addExtraClass('bulkUploadEditButton')
->setAttribute('data-icon', 'pencil') ->setAttribute('data-icon', 'pencil')
->setAttribute('data-url', $gridField->Link('bulkupload/edit')) ->setAttribute('data-url', $gridField->Link('bulkupload/edit'))
->setUseButtonTag(true); ->setUseButtonTag(true);
}else{ } else {
$editAllButton = ''; $editAllButton = '';
} }
} } else {
else{
$cancelButton = ''; $cancelButton = '';
$editAllButton = ''; $editAllButton = '';
} }
@ -383,43 +373,43 @@ class GridFieldBulkUpload implements GridField_HTMLProvider, GridField_URLHandle
$data = ArrayData::create(array( $data = ArrayData::create(array(
'Colspan' => count($gridField->getColumns()), 'Colspan' => count($gridField->getColumns()),
'UploadField' => $uploadField->Field() // call ->Field() to get requirements in right order 'UploadField' => $uploadField->Field(), // call ->Field() to get requirements in right order
)); ));
Requirements::css(BULKEDITTOOLS_UPLOAD_PATH . '/css/GridFieldBulkUpload.css'); Requirements::css(BULKEDITTOOLS_UPLOAD_PATH.'/css/GridFieldBulkUpload.css');
Requirements::javascript(BULKEDITTOOLS_UPLOAD_PATH . '/javascript/GridFieldBulkUpload.js'); Requirements::javascript(BULKEDITTOOLS_UPLOAD_PATH.'/javascript/GridFieldBulkUpload.js');
Requirements::javascript(BULKEDITTOOLS_UPLOAD_PATH . '/javascript/GridFieldBulkUpload_downloadtemplate.js'); Requirements::javascript(BULKEDITTOOLS_UPLOAD_PATH.'/javascript/GridFieldBulkUpload_downloadtemplate.js');
Requirements::add_i18n_javascript(BULKEDITTOOLS_PATH . '/lang/js'); Requirements::add_i18n_javascript(BULKEDITTOOLS_PATH.'/lang/js');
return array( return array(
'header' => $data->renderWith('GridFieldBulkUpload') 'header' => $data->renderWith('GridFieldBulkUpload'),
); );
} }
/* ********************************************************************** /* **********************************************************************
* GridField_URLHandler * GridField_URLHandler
* */ * */
/** /**
* Component URL handlers * Component URL handlers.
* *
* @param GridField $gridField * @param GridField $gridField
*
* @return array * @return array
*/ */
public function getURLHandlers($gridField) { public function getURLHandlers($gridField)
{
return array( return array(
'bulkupload' => 'handleBulkUpload' 'bulkupload' => 'handleBulkUpload',
); );
} }
/** /**
* Pass control over to the RequestHandler * Pass control over to the RequestHandler.
* *
* @param GridField $gridField * @param GridField $gridField
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*
* @return mixed * @return mixed
*/ */
public function handleBulkUpload($gridField, $request) public function handleBulkUpload($gridField, $request)

View File

@ -1,54 +1,52 @@
<?php <?php
/** /**
* Handles request from the GridFieldBulkUpload component * Handles request from the GridFieldBulkUpload component.
* *
* @author colymba * @author colymba
* @package GridFieldBulkEditingTools
* @subpackage BulkUpload
*/ */
class GridFieldBulkUpload_Request extends RequestHandler class GridFieldBulkUpload_Request extends RequestHandler
{ {
/** /**
* Gridfield instance * Gridfield instance.
*
* @var GridField * @var GridField
*/ */
protected $gridField; protected $gridField;
/** /**
* Bulk upload component * Bulk upload component.
*
* @var GridFieldBulkUpload * @var GridFieldBulkUpload
*/ */
protected $component; protected $component;
/** /**
* Gridfield Form controller * Gridfield Form controller.
*
* @var Controller * @var Controller
*/ */
protected $controller; protected $controller;
/** /**
* RequestHandler allowed actions * RequestHandler allowed actions.
*
* @var array * @var array
*/ */
private static $allowed_actions = array( private static $allowed_actions = array(
'upload', 'select', 'attach', 'fileexists' 'upload', 'select', 'attach', 'fileexists',
); );
/** /**
* RequestHandler url => action map * RequestHandler url => action map.
*
* @var array * @var array
*/ */
private static $url_handlers = array( private static $url_handlers = array(
'$Action!' => '$Action' '$Action!' => '$Action',
); );
/** /**
* Handler's constructor * Handler's constructor.
* *
* @param GridFIeld $gridField * @param GridFIeld $gridField
* @param GridField_URLHandler $component * @param GridField_URLHandler $component
@ -62,9 +60,8 @@ class GridFieldBulkUpload_Request extends RequestHandler
parent::__construct(); parent::__construct();
} }
/** /**
* Return the original component's UploadField * Return the original component's UploadField.
* *
* @return UploadField UploadField instance as defined in the component * @return UploadField UploadField instance as defined in the component
*/ */
@ -73,14 +70,14 @@ class GridFieldBulkUpload_Request extends RequestHandler
return $this->component->bulkUploadField($this->gridField); return $this->component->bulkUploadField($this->gridField);
} }
/** /**
* Process upload through UploadField, * Process upload through UploadField,
* creates new record and link newly uploaded file * creates new record and link newly uploaded file
* adds record to GrifField relation list * adds record to GrifField relation list
* and return image/file data and record edit form * and return image/file data and record edit form.
* *
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*
* @return string json * @return string json
*/ */
public function upload(SS_HTTPRequest $request) public function upload(SS_HTTPRequest $request)
@ -91,11 +88,10 @@ class GridFieldBulkUpload_Request extends RequestHandler
$record->write(); $record->write();
// passes the current gridfield-instance to a call-back method on the new object // passes the current gridfield-instance to a call-back method on the new object
$record->extend("onBulkUpload", $this->gridField); $record->extend('onBulkUpload', $this->gridField);
if ( $record->hasMethod('onBulkImageUpload') ) if ($record->hasMethod('onBulkImageUpload')) {
{
Deprecation::notice('2.0', '"onBulkImageUpload" callback is deprecated, use "onBulkUpload" instead.'); Deprecation::notice('2.0', '"onBulkImageUpload" callback is deprecated, use "onBulkUpload" instead.');
$record->extend("onBulkImageUpload", $this->gridField); $record->extend('onBulkImageUpload', $this->gridField);
} }
//get uploadField and process upload //get uploadField and process upload
@ -106,8 +102,8 @@ class GridFieldBulkUpload_Request extends RequestHandler
$uploadResponse = $uploadField->upload($request); $uploadResponse = $uploadField->upload($request);
//get uploaded File response datas //get uploaded File response datas
$uploadResponse = Convert::json2array( $uploadResponse->getBody() ); $uploadResponse = Convert::json2array($uploadResponse->getBody());
$uploadResponse = array_shift( $uploadResponse ); $uploadResponse = array_shift($uploadResponse);
// Attach the file to record. // Attach the file to record.
$record->{"{$fileRelationName}ID"} = $uploadResponse['id']; $record->{"{$fileRelationName}ID"} = $uploadResponse['id'];
@ -125,44 +121,38 @@ class GridFieldBulkUpload_Request extends RequestHandler
return $response; return $response;
} }
/** /**
* Updates the Upload/Attach response from the UploadField * Updates the Upload/Attach response from the UploadField
* with the new DataObject records for the JS template * with the new DataObject records for the JS template.
* *
* @param DataObject $record Newly create DataObject record * @param DataObject $record Newly create DataObject record
* @param array $uploadResponse Upload or Attach response from UploadField * @param array $uploadResponse Upload or Attach response from UploadField
*
* @return array Updated $uploadResponse with $record data * @return array Updated $uploadResponse with $record data
*/ */
protected function newRecordJSTemplateData(DataObject &$record, &$uploadResponse) protected function newRecordJSTemplateData(DataObject &$record, &$uploadResponse)
{ {
// fetch uploadedFile record and sort out previewURL // fetch uploadedFile record and sort out previewURL
// update $uploadResponse datas in case changes happened onAfterWrite() // update $uploadResponse datas in case changes happened onAfterWrite()
$uploadedFile = DataObject::get_by_id( $this->component->getFileRelationClassName($this->gridField), $uploadResponse['id'] ); $uploadedFile = DataObject::get_by_id($this->component->getFileRelationClassName($this->gridField), $uploadResponse['id']);
if ( $uploadedFile ) if ($uploadedFile) {
{
$uploadResponse['name'] = $uploadedFile->Name; $uploadResponse['name'] = $uploadedFile->Name;
$uploadResponse['url'] = $uploadedFile->getURL(); $uploadResponse['url'] = $uploadedFile->getURL();
if ( $uploadedFile instanceof Image ) if ($uploadedFile instanceof Image) {
{ $uploadResponse['thumbnail_url'] = $uploadedFile->CroppedImage(30, 30)->getURL();
$uploadResponse['thumbnail_url'] = $uploadedFile->CroppedImage(30,30)->getURL(); } else {
}
else{
$uploadResponse['thumbnail_url'] = $uploadedFile->Icon(); $uploadResponse['thumbnail_url'] = $uploadedFile->Icon();
} }
// check if our new record has a Title, if not create one automatically // check if our new record has a Title, if not create one automatically
$title = $record->getTitle(); $title = $record->getTitle();
if ( !$title || $title === $record->ID ) if (!$title || $title === $record->ID) {
{ if ($record->hasDatabaseField('Title')) {
if ( $record->hasDatabaseField('Title') )
{
$record->Title = $uploadedFile->Title; $record->Title = $uploadedFile->Title;
$record->write(); $record->write();
} } elseif ($record->hasDatabaseField('Name')) {
else if ($record->hasDatabaseField('Name')){
$record->Name = $uploadedFile->Title; $record->Name = $uploadedFile->Title;
$record->write(); $record->write();
} }
@ -172,16 +162,15 @@ class GridFieldBulkUpload_Request extends RequestHandler
// Collect all data for JS template // Collect all data for JS template
$return = array_merge($uploadResponse, array( $return = array_merge($uploadResponse, array(
'record' => array( 'record' => array(
'id' => $record->ID 'id' => $record->ID,
) ),
)); ));
return $return; return $return;
} }
/** /**
* Pass select request to UploadField * Pass select request to UploadField.
* *
* @link UploadField->select() * @link UploadField->select()
*/ */
@ -192,41 +181,42 @@ class GridFieldBulkUpload_Request extends RequestHandler
return $uploadField->handleSelect($request); return $uploadField->handleSelect($request);
*/ */
$uploadField = $this->getUploadField(); $uploadField = $this->getUploadField();
return UploadField_SelectHandler::create($this, $uploadField->getFolderName()); return UploadField_SelectHandler::create($this, $uploadField->getFolderName());
} }
/** /**
* Pass getRelationAutosetClass request to UploadField * Pass getRelationAutosetClass request to UploadField
* Used by select dialog * Used by select dialog.
* *
* @link UploadField->getRelationAutosetClass() * @link UploadField->getRelationAutosetClass()
*/ */
public function getRelationAutosetClass($default = 'File') public function getRelationAutosetClass($default = 'File')
{ {
$uploadField = $this->getUploadField(); $uploadField = $this->getUploadField();
return $uploadField->getRelationAutosetClass($default); return $uploadField->getRelationAutosetClass($default);
} }
/** /**
* Pass getAllowedMaxFileNumber request to UploadField * Pass getAllowedMaxFileNumber request to UploadField
* Used by select dialog * Used by select dialog.
* *
* @link UploadField->getAllowedMaxFileNumber() * @link UploadField->getAllowedMaxFileNumber()
*/ */
public function getAllowedMaxFileNumber() public function getAllowedMaxFileNumber()
{ {
$uploadField = $this->getUploadField(); $uploadField = $this->getUploadField();
return $uploadField->getAllowedMaxFileNumber(); return $uploadField->getAllowedMaxFileNumber();
} }
/** /**
* Retrieve Files to be attached * Retrieve Files to be attached
* and generated DataObjects for each one * and generated DataObjects for each one.
* *
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*
* @return SS_HTTPResponse * @return SS_HTTPResponse
*/ */
public function attach(SS_HTTPRequest $request) public function attach(SS_HTTPRequest $request)
@ -239,12 +229,11 @@ class GridFieldBulkUpload_Request extends RequestHandler
$recordClass = $this->gridField->list->dataClass; $recordClass = $this->gridField->list->dataClass;
$return = array(); $return = array();
foreach ($attachResponses as $attachResponse) foreach ($attachResponses as $attachResponse) {
{
// create record // create record
$record = Object::create($recordClass); $record = Object::create($recordClass);
$record->write(); $record->write();
$record->extend("onBulkUpload", $this->gridField); $record->extend('onBulkUpload', $this->gridField);
// attach file // attach file
$record->{"{$fileRelationName}ID"} = $attachResponse['id']; $record->{"{$fileRelationName}ID"} = $attachResponse['id'];
@ -266,39 +255,40 @@ class GridFieldBulkUpload_Request extends RequestHandler
return $response; return $response;
} }
/** /**
* Pass fileexists request to UploadField * Pass fileexists request to UploadField.
* *
* @link UploadField->fileexists() * @link UploadField->fileexists()
*/ */
public function fileexists(SS_HTTPRequest $request) public function fileexists(SS_HTTPRequest $request)
{ {
$uploadField = $this->getUploadField(); $uploadField = $this->getUploadField();
return $uploadField->fileexists($request); return $uploadField->fileexists($request);
} }
/** /**
* @param string $action * @param string $action
*
* @return string * @return string
*/ */
public function Link($action = null) { public function Link($action = null)
{
return Controller::join_links($this->gridField->Link(), '/bulkupload/', $action); return Controller::join_links($this->gridField->Link(), '/bulkupload/', $action);
} }
/** /**
* Sets response 'Content-Type' depending on browser capabilities * Sets response 'Content-Type' depending on browser capabilities
* e.g. IE needs text/plain for iframe transport * e.g. IE needs text/plain for iframe transport
* https://github.com/blueimp/jQuery-File-Upload/issues/1795 * https://github.com/blueimp/jQuery-File-Upload/issues/1795.
*
* @param SS_HTTPResponse $response HTTP Response to set content-type on * @param SS_HTTPResponse $response HTTP Response to set content-type on
*/ */
protected function contentTypeNegotiation(&$response) protected function contentTypeNegotiation(&$response)
{ {
if (isset($_SERVER['HTTP_ACCEPT']) && ((strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) || $_SERVER['HTTP_ACCEPT'] === '*/*' )) if (isset($_SERVER['HTTP_ACCEPT']) && ((strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) || $_SERVER['HTTP_ACCEPT'] === '*/*')) {
{
$response->addHeader('Content-Type', 'application/json'); $response->addHeader('Content-Type', 'application/json');
}else{ } else {
$response->addHeader('Content-Type', 'text/plain'); $response->addHeader('Content-Type', 'text/plain');
} }
} }

View File

@ -4,15 +4,16 @@
* from Transifex data. This tasks assumes that: * from Transifex data. This tasks assumes that:
* - Javascript translations are from the Transifex resource called 'js' * - Javascript translations are from the Transifex resource called 'js'
* - YML translations are from the Transifex resource called 'yml' * - YML translations are from the Transifex resource called 'yml'
* - Transifex AUTH credentials to be saved in $txAuthFile with content {"username": "user", "password": "pwd"} * - Transifex AUTH credentials to be saved in $txAuthFile with content {"username": "user", "password": "pwd"}.
* *
* This is inspired by SilverStripe build tools. Thanks * This is inspired by SilverStripe build tools. Thanks
*
* @see https://github.com/silverstripe/silverstripe-buildtools/blob/master/src/GenerateJavascriptI18nTask.php * @see https://github.com/silverstripe/silverstripe-buildtools/blob/master/src/GenerateJavascriptI18nTask.php
*/ */
include_once "phing/Task.php"; include_once 'phing/Task.php';
// Ignore this file if phing is not installed // Ignore this file if phing is not installed
if(!class_exists('Task')) { if (!class_exists('Task')) {
return; return;
} }
@ -38,32 +39,28 @@ class BuildTransifexTranslations extends Task
} }
/** /**
* Task init * Task init.
*/ */
public function init() public function init()
{ {
$root = realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); $root = realpath(__DIR__.DIRECTORY_SEPARATOR.'..');
$authFile = $root . DIRECTORY_SEPARATOR . $this->txAuthFile; $authFile = $root.DIRECTORY_SEPARATOR.$this->txAuthFile;
if ( file_exists($authFile) ) if (file_exists($authFile)) {
{
$txAuthData = file_get_contents($authFile); $txAuthData = file_get_contents($authFile);
$txAuthData = json_decode($txAuthData); $txAuthData = json_decode($txAuthData);
if ( $txAuthData->username && $txAuthData->password ) if ($txAuthData->username && $txAuthData->password) {
{
$this->txAuth = $txAuthData; $this->txAuth = $txAuthData;
} } else {
else{
throw new BuildException("Transifex credentials malformat. Check your $authFile for 'username' and 'password' keys."); throw new BuildException("Transifex credentials malformat. Check your $authFile for 'username' and 'password' keys.");
} }
} } else {
else{
throw new BuildException("Transifex credentials not found. $authFile missing."); throw new BuildException("Transifex credentials not found. $authFile missing.");
} }
$this->root = $root; $this->root = $root;
$this->jsDir = $root . $this->jsDir; $this->jsDir = $root.$this->jsDir;
$this->ymlDir = $root . $this->ymlDir; $this->ymlDir = $root.$this->ymlDir;
} }
/** /**
@ -75,18 +72,16 @@ class BuildTransifexTranslations extends Task
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $this->txAuth->username . ":" . $this->txAuth->password); curl_setopt($ch, CURLOPT_USERPWD, $this->txAuth->username.':'.$this->txAuth->password);
// get resources // get resources
$url = $this->txapi.'/project/'.$this->txproject.'/resources/'; $url = $this->txapi.'/project/'.$this->txproject.'/resources/';
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
$resources = curl_exec($ch); $resources = curl_exec($ch);
if ( !$resources ) if (!$resources) {
{ throw new BuildException('Cannot fetch resources');
throw new BuildException("Cannot fetch resources"); } else {
}
else{
$resources = json_decode($resources); $resources = json_decode($resources);
} }
@ -95,11 +90,9 @@ class BuildTransifexTranslations extends Task
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
$languages = curl_exec($ch); $languages = curl_exec($ch);
if ( !$languages ) if (!$languages) {
{ throw new BuildException('Cannot fetch languages');
throw new BuildException("Cannot fetch languages"); } else {
}
else{
$languages = json_decode($languages); $languages = json_decode($languages);
} }
@ -108,13 +101,11 @@ class BuildTransifexTranslations extends Task
// add source_language_code to languages list // add source_language_code to languages list
$sourceLangs = array(); $sourceLangs = array();
foreach ($resources as $resource) foreach ($resources as $resource) {
{
$lang = new StdClass(); $lang = new StdClass();
$locale = $resource->source_language_code; $locale = $resource->source_language_code;
$lang->language_code = $locale; $lang->language_code = $locale;
if ( !array_key_exists($locale, $sourceLangs) ) if (!array_key_exists($locale, $sourceLangs)) {
{
$sourceLangs[$locale] = $lang; $sourceLangs[$locale] = $lang;
} }
} }
@ -122,15 +113,12 @@ class BuildTransifexTranslations extends Task
$languages = array_merge($languages, $sourceLangs); $languages = array_merge($languages, $sourceLangs);
// get each resource translations // get each resource translations
foreach ($resources as $resource) foreach ($resources as $resource) {
{ foreach ($languages as $language) {
foreach ($languages as $language)
{
$url = $this->txapi.'/project/'.$this->txproject.'/resource/'.$resource->slug.'/translation/'.$language->language_code; $url = $this->txapi.'/project/'.$this->txproject.'/resource/'.$resource->slug.'/translation/'.$language->language_code;
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch); $data = curl_exec($ch);
if ( $data ) if ($data) {
{
$this->saveTranslation($resource->slug, $language->language_code, $data); $this->saveTranslation($resource->slug, $language->language_code, $data);
} }
} }
@ -141,44 +129,36 @@ class BuildTransifexTranslations extends Task
/** /**
* Clear any existing translation files * Clear any existing translation files
* and create directory structure if needed * and create directory structure if needed.
*/ */
private function resetTranslations() private function resetTranslations()
{ {
if ( file_exists($this->jsDir) ) if (file_exists($this->jsDir)) {
{
echo "Clearing js translations...\n"; echo "Clearing js translations...\n";
$iterator = new GlobIterator($this->jsDir . DIRECTORY_SEPARATOR . '*.js'); $iterator = new GlobIterator($this->jsDir.DIRECTORY_SEPARATOR.'*.js');
foreach ($iterator as $fileInfo) foreach ($iterator as $fileInfo) {
{ if ($fileInfo->isFile()) {
if ( $fileInfo->isFile() )
{
$del = unlink($fileInfo->getRealPath()); $del = unlink($fileInfo->getRealPath());
} }
} }
} }
if ( file_exists($this->ymlDir) ) if (file_exists($this->ymlDir)) {
{
echo "Clearing yml translations...\n"; echo "Clearing yml translations...\n";
$iterator = new GlobIterator($this->ymlDir . DIRECTORY_SEPARATOR . '*.yml'); $iterator = new GlobIterator($this->ymlDir.DIRECTORY_SEPARATOR.'*.yml');
foreach ($iterator as $fileInfo) foreach ($iterator as $fileInfo) {
{ if ($fileInfo->isFile()) {
if ( $fileInfo->isFile() )
{
$del = unlink($fileInfo->getRealPath()); $del = unlink($fileInfo->getRealPath());
} }
} }
} }
if ( !file_exists($this->jsDir) ) if (!file_exists($this->jsDir)) {
{
echo "Creating js folders...\n"; echo "Creating js folders...\n";
mkdir($this->jsDir); mkdir($this->jsDir);
} }
if ( !file_exists($this->ymlDir) ) if (!file_exists($this->ymlDir)) {
{
echo "Creating yml folders...\n"; echo "Creating yml folders...\n";
mkdir($this->ymlDir); mkdir($this->ymlDir);
} }
@ -186,23 +166,22 @@ class BuildTransifexTranslations extends Task
/** /**
* Hook that detect the translation type via resource slug * Hook that detect the translation type via resource slug
* and call corect saving function with data * and call corect saving function with data.
*
* @param string $resource Transifex resrouce slug * @param string $resource Transifex resrouce slug
* @param string $locale Transifex locale * @param string $locale Transifex locale
* @param string $data Raw Transifex translation data * @param string $data Raw Transifex translation data
*/ */
private function saveTranslation($resource, $locale, $data) private function saveTranslation($resource, $locale, $data)
{ {
if ( !$resource || !$locale || !$data ) if (!$resource || !$locale || !$data) {
{
return; return;
} }
$data = json_decode($data); $data = json_decode($data);
$translation = rtrim($data->content); $translation = rtrim($data->content);
switch ($resource) switch ($resource) {
{
case 'js': case 'js':
$this->saveJSTranslation($locale, $translation); $this->saveJSTranslation($locale, $translation);
break; break;
@ -215,7 +194,8 @@ class BuildTransifexTranslations extends Task
/** /**
* Save a JS translation file * Save a JS translation file
* Uses JSTemplate to fit with SilverStripe requirements * Uses JSTemplate to fit with SilverStripe requirements.
*
* @param string $locale Locale code * @param string $locale Locale code
* @param string $json JSON translation key:value * @param string $json JSON translation key:value
*/ */
@ -223,16 +203,16 @@ class BuildTransifexTranslations extends Task
{ {
echo "Saving $locale.js\n"; echo "Saving $locale.js\n";
file_put_contents( file_put_contents(
$this->jsDir . DIRECTORY_SEPARATOR . $locale . '.js', $this->jsDir.DIRECTORY_SEPARATOR.$locale.'.js',
$this->getBanner('js') . $this->getBanner('js').
str_replace( str_replace(
array( array(
'%TRANSLATIONS%', '%TRANSLATIONS%',
'%LOCALE%' '%LOCALE%',
), ),
array( array(
$json, $json,
$locale $locale,
), ),
$this->getJSTemplate() $this->getJSTemplate()
) )
@ -240,7 +220,8 @@ class BuildTransifexTranslations extends Task
} }
/** /**
* Save a YML translation file * Save a YML translation file.
*
* @param string $locale Locale code * @param string $locale Locale code
* @param string $yml YML translation * @param string $yml YML translation
*/ */
@ -248,35 +229,34 @@ class BuildTransifexTranslations extends Task
{ {
echo "Saving $locale.yml\n"; echo "Saving $locale.yml\n";
if ($locale !== 'en') if ($locale !== 'en') {
{ $content = $this->getBanner('yml').$yml;
$content = $this->getBanner('yml') . $yml; } else {
}
else{
$content = $yml; $content = $yml;
} }
file_put_contents( file_put_contents(
$this->ymlDir . DIRECTORY_SEPARATOR . $locale . '.yml', $this->ymlDir.DIRECTORY_SEPARATOR.$locale.'.yml',
$content $content
); );
} }
/** /**
* Return the commented file banner * Return the commented file banner.
*
* @param string $type File type e.g js * @param string $type File type e.g js
*
* @return string The commented file banner * @return string The commented file banner
*/ */
private function getBanner($type) private function getBanner($type)
{ {
switch ( strtolower($type) ) switch (strtolower($type)) {
{
case 'yml': case 'yml':
$comment = "#"; $comment = '#';
break; break;
default: default:
$comment = "//"; $comment = '//';
break; break;
} }
@ -285,11 +265,13 @@ $comment DO NOT MODIFY. Generated by build task.
$comment Contribute here: https://www.transifex.com/projects/p/gridfieldbulkeditingtools/ $comment Contribute here: https://www.transifex.com/projects/p/gridfieldbulkeditingtools/
TMPL; TMPL;
return $banner; return $banner;
} }
/** /**
* Return the SilverStripe JS lang file template * Return the SilverStripe JS lang file template.
*
* @return string The JS file template * @return string The JS file template
*/ */
private function getJSTemplate() private function getJSTemplate()
@ -301,6 +283,7 @@ if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
ss.i18n.addDictionary('%LOCALE%', %TRANSLATIONS%); ss.i18n.addDictionary('%LOCALE%', %TRANSLATIONS%);
} }
TMPL; TMPL;
return $tmpl; return $tmpl;
} }
} }