PSR2 cleanup

This commit is contained in:
Damian Mooyman 2016-11-29 16:18:48 +13:00
parent d4abfea4eb
commit bc19b2a491
No known key found for this signature in database
GPG Key ID: 78B823A10DE27D1A
7 changed files with 2772 additions and 2625 deletions

View File

@ -167,7 +167,7 @@ class Upload extends Controller
{
// Validate filename
$filename = $this->getValidFilename($tmpFile, $folderPath);
if(!$filename) {
if (!$filename) {
return false;
}
@ -196,14 +196,14 @@ class Upload extends Controller
// Validate filename
$filename = $this->getValidFilename($tmpFile, $folderPath);
if(!$filename) {
if (!$filename) {
return false;
}
$filename = $this->resolveExistingFile($filename);
// Save changes to underlying record (if it's a DataObject)
$this->storeTempFile($tmpFile, $filename, $this->file);
if($this->file instanceof DataObject) {
if ($this->file instanceof DataObject) {
$this->file->write();
}
@ -244,7 +244,7 @@ class Upload extends Controller
*/
protected function getValidFilename($tmpFile, $folderPath = null)
{
if(!is_array($tmpFile)) {
if (!is_array($tmpFile)) {
throw new InvalidArgumentException(
"Upload::load() Not passed an array. Most likely, the form hasn't got the right enctype"
);
@ -253,18 +253,18 @@ class Upload extends Controller
// Validate
$this->clearErrors();
$valid = $this->validate($tmpFile);
if(!$valid) {
if (!$valid) {
return false;
}
// Clean filename
if(!$folderPath) {
if (!$folderPath) {
$folderPath = $this->config()->uploads_folder;
}
$nameFilter = FileNameFilter::create();
$file = $nameFilter->filter($tmpFile['name']);
$filename = basename($file);
if($folderPath) {
if ($folderPath) {
$filename = File::join_paths($folderPath, $filename);
}
return $filename;
@ -283,7 +283,7 @@ class Upload extends Controller
protected function resolveExistingFile($filename)
{
// Create a new file record (or try to retrieve an existing one)
if(!$this->file) {
if (!$this->file) {
$fileClass = File::get_class_for_file_extension(
File::get_file_extension($filename)
);
@ -291,7 +291,7 @@ class Upload extends Controller
}
// Skip this step if not writing File dataobjects
if(! ($this->file instanceof File) ) {
if (! ($this->file instanceof File)) {
return $filename;
}
@ -299,9 +299,9 @@ class Upload extends Controller
$existing = File::find($filename);
// If replacing (or no file exists) confirm this filename is safe
if($this->replaceFile || !$existing) {
if ($this->replaceFile || !$existing) {
// If replacing files, make sure to update the OwnerID
if(!$this->file->ID && $this->replaceFile && $existing) {
if (!$this->file->ID && $this->replaceFile && $existing) {
$this->file = $existing;
$this->file->OwnerID = Member::currentUserID();
}
@ -311,8 +311,8 @@ class Upload extends Controller
// if filename already exists, version the filename (e.g. test.gif to test-v2.gif, test-v2.gif to test-v3.gif)
$renamer = $this->getNameGenerator($filename);
foreach($renamer as $newName) {
if(!File::find($newName)) {
foreach ($renamer as $newName) {
if (!File::find($newName)) {
return $newName;
}
}
@ -353,7 +353,7 @@ class Upload extends Controller
$validator = $this->validator;
$validator->setTmpFile($tmpFile);
$isValid = $validator->validate();
if($validator->getErrors()) {
if ($validator->getErrors()) {
$this->errors = array_merge($this->errors, $validator->getErrors());
}
return $isValid;

View File

@ -26,7 +26,8 @@ use Exception;
* - Files can't be edited once uploaded.
* - Attached files can only be removed, not deleted.
*/
class AssetField extends FormField {
class AssetField extends FormField
{
use UploadReceiver;
/**
@ -157,7 +158,8 @@ class AssetField extends FormField {
* @param string $name The internal field name, passed to forms.
* @param string $title The field label.
*/
public function __construct($name, $title = null) {
public function __construct($name, $title = null)
{
$this->addExtraClass('ss-upload'); // class, used by js
$this->addExtraClass('ss-uploadfield'); // class, used by css for uploadfield only
@ -186,7 +188,8 @@ class AssetField extends FormField {
* @param string
* @return $this
*/
public function setTemplateFileButtons($template) {
public function setTemplateFileButtons($template)
{
$this->templateFileButtons = $template;
return $this;
}
@ -194,7 +197,8 @@ class AssetField extends FormField {
/**
* @return string
*/
public function getTemplateFileButtons() {
public function getTemplateFileButtons()
{
return $this->_templates($this->templateFileButtons, '_FileButtons');
}
@ -203,12 +207,13 @@ class AssetField extends FormField {
*
* @return boolean
*/
public function canPreviewFolder() {
if(!$this->isActive()) {
public function canPreviewFolder()
{
if (!$this->isActive()) {
return false;
}
$can = $this->getConfig('canPreviewFolder');
if(is_bool($can)) {
if (is_bool($can)) {
return $can;
}
return Permission::check($can);
@ -222,7 +227,8 @@ class AssetField extends FormField {
* required permission code
* @return $this Self reference
*/
public function setCanPreviewFolder($canPreviewFolder) {
public function setCanPreviewFolder($canPreviewFolder)
{
return $this->setConfig('canPreviewFolder', $canPreviewFolder);
}
@ -230,7 +236,8 @@ class AssetField extends FormField {
* @param string
* @return $this
*/
public function setDisplayFolderName($name) {
public function setDisplayFolderName($name)
{
$this->displayFolderName = $name;
return $this;
}
@ -238,7 +245,8 @@ class AssetField extends FormField {
/**
* @return string
*/
public function getDisplayFolderName() {
public function getDisplayFolderName()
{
return $this->displayFolderName;
}
@ -248,7 +256,8 @@ class AssetField extends FormField {
* @param DataObject $record
* @return $this
*/
public function setRecord($record) {
public function setRecord($record)
{
$this->record = $record;
return $this;
}
@ -259,7 +268,8 @@ class AssetField extends FormField {
*
* @return DataObject
*/
public function getRecord() {
public function getRecord()
{
if (!$this->record
&& $this->form
&& ($record = $this->form->getRecord())
@ -270,16 +280,17 @@ class AssetField extends FormField {
return $this->record;
}
public function setValue($value, $record = null) {
public function setValue($value, $record = null)
{
// Extract value from underlying record
if(empty($value) && $this->getName() && $record instanceof DataObject) {
if (empty($value) && $this->getName() && $record instanceof DataObject) {
$name = $this->getName();
$value = $record->$name;
}
// Convert asset container to tuple value
if($value instanceof AssetContainer) {
if($value->exists()) {
if ($value instanceof AssetContainer) {
if ($value->exists()) {
$value = array(
'Filename' => $value->getFilename(),
'Hash' => $value->getHash(),
@ -294,9 +305,9 @@ class AssetField extends FormField {
// trigger a single or multiple file submission. Note that this may be
// included in addition to re-submitted File IDs as above, so these
// should be added to the list instead of operated on independently.
if($uploadedFile = $this->extractUploadedFileData($value)) {
if ($uploadedFile = $this->extractUploadedFileData($value)) {
$value = $this->saveTemporaryFile($uploadedFile, $error);
if(!$value) {
if (!$value) {
throw new ValidationException($error);
}
}
@ -305,19 +316,21 @@ class AssetField extends FormField {
return parent::setValue($value, $record);
}
public function Value() {
public function Value()
{
// Re-override FileField Value to use data value
return $this->dataValue();
}
public function saveInto(DataObjectInterface $record) {
public function saveInto(DataObjectInterface $record)
{
// Check required relation details are available
$name = $this->getName();
if(!$name) {
if (!$name) {
return $this;
}
$value = $this->Value();
foreach(array('Filename', 'Hash', 'Variant') as $part) {
foreach (array('Filename', 'Hash', 'Variant') as $part) {
$partValue = isset($value[$part])
? $value[$part]
: null;
@ -335,7 +348,8 @@ class AssetField extends FormField {
* @param mixed $val
* @return $this self reference
*/
public function setConfig($key, $val) {
public function setConfig($key, $val)
{
$this->ufConfig[$key] = $val;
return $this;
}
@ -348,8 +362,9 @@ class AssetField extends FormField {
* @param string $key
* @return mixed
*/
public function getConfig($key) {
if(isset($this->ufConfig[$key])) {
public function getConfig($key)
{
if (isset($this->ufConfig[$key])) {
return $this->ufConfig[$key];
}
}
@ -359,7 +374,8 @@ class AssetField extends FormField {
*
* @return boolean
*/
public function getAutoUpload() {
public function getAutoUpload()
{
return $this->getConfig('autoUpload');
}
@ -369,7 +385,8 @@ class AssetField extends FormField {
* @param boolean $autoUpload
* @return $this Self reference
*/
public function setAutoUpload($autoUpload) {
public function setAutoUpload($autoUpload)
{
return $this->setConfig('autoUpload', $autoUpload);
}
@ -378,12 +395,13 @@ class AssetField extends FormField {
*
* @return boolean
*/
public function canUpload() {
if(!$this->isActive()) {
public function canUpload()
{
if (!$this->isActive()) {
return false;
}
$can = $this->getConfig('canUpload');
if(is_bool($can)) {
if (is_bool($can)) {
return $can;
}
return Permission::check($can);
@ -397,7 +415,8 @@ class AssetField extends FormField {
* permission code
* @return $this Self reference
*/
public function setCanUpload($canUpload) {
public function setCanUpload($canUpload)
{
return $this->setConfig('canUpload', $canUpload);
}
@ -406,7 +425,8 @@ class AssetField extends FormField {
*
* @return bool
*/
public function isActive() {
public function isActive()
{
return !$this->isDisabled() && !$this->isReadonly();
}
@ -415,7 +435,8 @@ class AssetField extends FormField {
*
* @return int
*/
public function getPreviewMaxWidth() {
public function getPreviewMaxWidth()
{
return $this->getConfig('previewMaxWidth');
}
@ -425,7 +446,8 @@ class AssetField extends FormField {
* @param int $previewMaxWidth
* @return $this Self reference
*/
public function setPreviewMaxWidth($previewMaxWidth) {
public function setPreviewMaxWidth($previewMaxWidth)
{
return $this->setConfig('previewMaxWidth', $previewMaxWidth);
}
@ -434,7 +456,8 @@ class AssetField extends FormField {
*
* @return int
*/
public function getPreviewMaxHeight() {
public function getPreviewMaxHeight()
{
return $this->getConfig('previewMaxHeight');
}
@ -444,7 +467,8 @@ class AssetField extends FormField {
* @param int $previewMaxHeight
* @return $this Self reference
*/
public function setPreviewMaxHeight($previewMaxHeight) {
public function setPreviewMaxHeight($previewMaxHeight)
{
return $this->setConfig('previewMaxHeight', $previewMaxHeight);
}
@ -455,7 +479,8 @@ class AssetField extends FormField {
* @see javascript/UploadField_uploadtemplate.js
* @return string
*/
public function getUploadTemplateName() {
public function getUploadTemplateName()
{
return $this->getConfig('uploadTemplateName');
}
@ -465,7 +490,8 @@ class AssetField extends FormField {
* @param string $uploadTemplateName
* @return $this Self reference
*/
public function setUploadTemplateName($uploadTemplateName) {
public function setUploadTemplateName($uploadTemplateName)
{
return $this->setConfig('uploadTemplateName', $uploadTemplateName);
}
@ -476,7 +502,8 @@ class AssetField extends FormField {
* @see javascript/DownloadField_downloadtemplate.js
* @return string
*/
public function getDownloadTemplateName() {
public function getDownloadTemplateName()
{
return $this->getConfig('downloadTemplateName');
}
@ -486,22 +513,25 @@ class AssetField extends FormField {
* @param string $downloadTemplateName
* @return $this Self reference
*/
public function setDownloadTemplateName($downloadTemplateName) {
public function setDownloadTemplateName($downloadTemplateName)
{
return $this->setConfig('downloadTemplateName', $downloadTemplateName);
}
public function extraClass() {
if($this->isDisabled()) {
public function extraClass()
{
if ($this->isDisabled()) {
$this->addExtraClass('disabled');
}
if($this->isReadonly()) {
if ($this->isReadonly()) {
$this->addExtraClass('readonly');
}
return parent::extraClass();
}
public function Field($properties = array()) {
public function Field($properties = array())
{
// Calculated config as per jquery.fileupload-ui.js
$config = array(
'allowedMaxFileNumber' => 1, // Only one file allowed for AssetField
@ -547,12 +577,13 @@ class AssetField extends FormField {
* @param Validator $validator
* @return boolean
*/
public function validate($validator) {
public function validate($validator)
{
$name = $this->getName();
$value = $this->Value();
// If there is no file then quit
if(!$value) {
if (!$value) {
return true;
}
@ -573,8 +604,8 @@ class AssetField extends FormField {
$this->getUpload()->validate($tmpFile);
// Check all errors
if($errors = $this->getUpload()->getErrors()) {
foreach($errors as $error) {
if ($errors = $this->getUpload()->getErrors()) {
foreach ($errors as $error) {
$validator->validationError($name, $error, "validation");
}
return false;
@ -589,24 +620,25 @@ class AssetField extends FormField {
* @param array $postVars Array of posted form data
* @return array data for uploaded file
*/
protected function extractUploadedFileData($postVars) {
protected function extractUploadedFileData($postVars)
{
// Note: Format of posted file parameters in php is a feature of using
// <input name='{$Name}[Upload]' /> for multiple file uploads
// Skip empty file
if(empty($postVars['tmp_name'])) {
if (empty($postVars['tmp_name'])) {
return null;
}
// Return single level array for posted file
/** @skipUpgrade */
if(empty($postVars['tmp_name']['Upload'])) {
if (empty($postVars['tmp_name']['Upload'])) {
return $postVars;
}
// Extract posted feedback value
$tmpFile = array();
foreach(array('name', 'type', 'tmp_name', 'error', 'size') as $field) {
foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $field) {
/** @skipUpgrade */
$tmpFile[$field] = $postVars[$field]['Upload'];
}
@ -621,14 +653,15 @@ class AssetField extends FormField {
* @param string $error Error message
* @return array Result of saved file, or null if error
*/
protected function saveTemporaryFile($tmpFile, &$error = null) {
protected function saveTemporaryFile($tmpFile, &$error = null)
{
$error = null;
if (empty($tmpFile)) {
$error = _t('UploadField.FIELDNOTSET', 'File information not found');
return null;
}
if($tmpFile['error']) {
if ($tmpFile['error']) {
$error = $tmpFile['error'];
return null;
}
@ -663,7 +696,8 @@ class AssetField extends FormField {
* @param string $variant
* @return array Encoded list of file attributes
*/
protected function encodeAssetAttributes($filename, $hash, $variant) {
protected function encodeAssetAttributes($filename, $hash, $variant)
{
// Force regeneration of file thumbnail for this tuple (without saving into db)
$object = DBFile::create();
$object->setValue(array('Filename' => $filename, 'Hash' => $hash, 'Variant' => $variant));
@ -691,8 +725,9 @@ class AssetField extends FormField {
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function upload(HTTPRequest $request) {
if($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
public function upload(HTTPRequest $request)
{
if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
return $this->httpError(403);
}
@ -700,7 +735,7 @@ class AssetField extends FormField {
$token = $this
->getForm()
->getSecurityToken();
if(!$token->checkRequest($request)) {
if (!$token->checkRequest($request)) {
return $this->httpError(400);
}
@ -710,14 +745,14 @@ class AssetField extends FormField {
// Extract uploaded files from Form data
$uploadedFile = $this->extractUploadedFileData($postVars);
if(!$uploadedFile) {
if (!$uploadedFile) {
return $this->httpError(400);
}
// Save the temporary files into a File objects
// and save data/error on a per file basis
$result = $this->saveTemporaryFile($uploadedFile, $error);
if(empty($result)) {
if (empty($result)) {
$return = array('error' => $error);
} else {
$return = $this->encodeAssetAttributes($result['Filename'], $result['Hash'], $result['Variant']);
@ -732,7 +767,8 @@ class AssetField extends FormField {
return $response;
}
public function performReadonlyTransformation() {
public function performReadonlyTransformation()
{
$clone = clone $this;
$clone->addExtraClass('readonly');
$clone->setReadonly(true);
@ -746,15 +782,18 @@ class AssetField extends FormField {
* @param string $default Default value to return if no value could be calculated
* @return string Foreign class name.
*/
public function getRelationAutosetClass($default = 'SilverStripe\\Assets\\File') {
public function getRelationAutosetClass($default = 'SilverStripe\\Assets\\File')
{
// Don't autodetermine relation if no relationship between parent record
if(!$this->relationAutoSetting) return $default;
if (!$this->relationAutoSetting) {
return $default;
}
// Check record and name
$name = $this->getName();
$record = $this->getRecord();
if(empty($name) || empty($record)) {
if (empty($name) || empty($record)) {
return $default;
} else {
$class = $record->getRelationClass($name);
@ -765,15 +804,16 @@ class AssetField extends FormField {
/**
* @return AssetStore
*/
protected function getAssetStore() {
protected function getAssetStore()
{
return Injector::inst()->get('AssetStore');
}
public function getAttributes() {
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
['type' => 'file']
);
}
}

View File

@ -46,7 +46,8 @@ use SilverStripe\Core\Object;
* }
* </code>
*/
class FileField extends FormField {
class FileField extends FormField
{
use UploadReceiver;
/**
@ -66,7 +67,8 @@ class FileField extends FormField {
* @param string $title The field label.
* @param int $value The value of the field.
*/
public function __construct($name, $title = null, $value = null) {
public function __construct($name, $title = null, $value = null)
{
$this->constructUploadReceiver();
parent::__construct($name, $title, $value);
}
@ -75,7 +77,8 @@ class FileField extends FormField {
* @param array $properties
* @return string
*/
public function Field($properties = array()) {
public function Field($properties = array())
{
$properties = array_merge($properties, array(
'MaxFileSize' => $this->getValidator()->getAllowedMaxFileSize()
));
@ -83,7 +86,8 @@ class FileField extends FormField {
return parent::Field($properties);
}
public function getAttributes() {
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
array('type' => 'file')
@ -93,8 +97,9 @@ class FileField extends FormField {
/**
* @param DataObject|DataObjectInterface $record
*/
public function saveInto(DataObjectInterface $record) {
if(!isset($_FILES[$this->name])) {
public function saveInto(DataObjectInterface $record)
{
if (!isset($_FILES[$this->name])) {
return;
}
@ -103,17 +108,17 @@ class FileField extends FormField {
);
/** @var File $file */
if($this->relationAutoSetting) {
if ($this->relationAutoSetting) {
// assume that the file is connected via a has-one
$objectClass = DataObject::getSchema()->hasOneComponent(get_class($record), $this->name);
if($objectClass === File::class || empty($objectClass)) {
if ($objectClass === File::class || empty($objectClass)) {
// Create object of the appropriate file class
$file = Object::create($fileClass);
} else {
// try to create a file matching the relation
$file = Object::create($objectClass);
}
} else if($record instanceof File) {
} elseif ($record instanceof File) {
$file = $record;
} else {
$file = Object::create($fileClass);
@ -121,11 +126,11 @@ class FileField extends FormField {
$this->upload->loadIntoFile($_FILES[$this->name], $file, $this->getFolderName());
if($this->upload->isError()) {
if ($this->upload->isError()) {
return;
}
if($this->relationAutoSetting) {
if ($this->relationAutoSetting) {
if (empty($objectClass)) {
return;
}
@ -136,21 +141,27 @@ class FileField extends FormField {
}
}
public function Value() {
public function Value()
{
return isset($_FILES[$this->getName()]) ? $_FILES[$this->getName()] : null;
}
public function validate($validator) {
if(!isset($_FILES[$this->name])) return true;
public function validate($validator)
{
if (!isset($_FILES[$this->name])) {
return true;
}
$tmpFile = $_FILES[$this->name];
$valid = $this->upload->validate($tmpFile);
if(!$valid) {
if (!$valid) {
$errors = $this->upload->getErrors();
if($errors) foreach($errors as $error) {
if ($errors) {
foreach ($errors as $error) {
$validator->validationError($this->name, $error, "validation");
}
}
return false;
}
@ -163,7 +174,8 @@ class FileField extends FormField {
* @param bool $auto
* @return $this
*/
public function setRelationAutoSetting($auto) {
public function setRelationAutoSetting($auto)
{
$this->relationAutoSetting = $auto;
return $this;
}
@ -173,8 +185,8 @@ class FileField extends FormField {
*
* @return bool
*/
public function getRelationAutoSetting() {
public function getRelationAutoSetting()
{
return $this->relationAutoSetting;
}
}

View File

@ -29,7 +29,8 @@ use SilverStripe\ORM\ValidationException;
*
* @mixin FormField
*/
trait FileUploadReceiver {
trait FileUploadReceiver
{
use UploadReceiver;
/**
@ -56,7 +57,8 @@ trait FileUploadReceiver {
*/
protected $items;
protected function constructFileUploadReceiver() {
protected function constructFileUploadReceiver()
{
$this->constructUploadReceiver();
}
@ -67,7 +69,8 @@ trait FileUploadReceiver {
* @param DataObject $record
* @return $this
*/
public function setRecord($record) {
public function setRecord($record)
{
$this->record = $record;
return $this;
}
@ -77,7 +80,8 @@ trait FileUploadReceiver {
*
* @return DataObject
*/
public function getRecord() {
public function getRecord()
{
if ($this->record) {
return $this->record;
}
@ -127,33 +131,34 @@ trait FileUploadReceiver {
* @return $this Self reference
* @throws ValidationException
*/
public function setValue($value, $record = null) {
public function setValue($value, $record = null)
{
// If we're not passed a value directly, we can attempt to infer the field
// value from the second parameter by inspecting its relations
$items = new ArrayList();
// Determine format of presented data
if(empty($value) && $record) {
if (empty($value) && $record) {
// If a record is given as a second parameter, but no submitted values,
// then we should inspect this instead for the form values
if(($record instanceof DataObject) && $record->hasMethod($this->getName())) {
if (($record instanceof DataObject) && $record->hasMethod($this->getName())) {
// If given a dataobject use reflection to extract details
$data = $record->{$this->getName()}();
if($data instanceof DataObject) {
if ($data instanceof DataObject) {
// If has_one, add sole item to default list
$items->push($data);
} elseif($data instanceof SS_List) {
} elseif ($data instanceof SS_List) {
// For many_many and has_many relations we can use the relation list directly
$items = $data;
}
} elseif($record instanceof SS_List) {
} elseif ($record instanceof SS_List) {
// If directly passing a list then save the items directly
$items = $record;
}
} elseif(!empty($value['Files'])) {
} elseif (!empty($value['Files'])) {
// If value is given as an array (such as a posted form), extract File IDs from this
$class = $this->getRelationAutosetClass();
$items = DataObject::get($class)->byIDs($value['Files']);
@ -163,10 +168,10 @@ trait FileUploadReceiver {
// trigger a single or multiple file submission. Note that this may be
// included in addition to re-submitted File IDs as above, so these
// should be added to the list instead of operated on independently.
if($uploadedFiles = $this->extractUploadedFileData($value)) {
foreach($uploadedFiles as $tempFile) {
if ($uploadedFiles = $this->extractUploadedFileData($value)) {
foreach ($uploadedFiles as $tempFile) {
$file = $this->saveTemporaryFile($tempFile, $error);
if($file) {
if ($file) {
$items->add($file);
} else {
throw new ValidationException($error);
@ -177,8 +182,8 @@ trait FileUploadReceiver {
// Filter items by what's allowed to be viewed
$filteredItems = new ArrayList();
$fileIDs = array();
foreach($items as $file) {
if($file->exists() && $file->canView()) {
foreach ($items as $file) {
if ($file->exists() && $file->canView()) {
$filteredItems->push($file);
$fileIDs[] = $file->ID;
}
@ -203,7 +208,8 @@ trait FileUploadReceiver {
* @param SS_List $items
* @return $this self reference
*/
public function setItems(SS_List $items) {
public function setItems(SS_List $items)
{
return $this->setValue(null, $items);
}
@ -212,7 +218,8 @@ trait FileUploadReceiver {
*
* @return SS_List|File[]
*/
public function getItems() {
public function getItems()
{
return $this->items ? $this->items : new ArrayList();
}
@ -221,12 +228,14 @@ trait FileUploadReceiver {
*
* @return array
*/
public function getItemIDs() {
public function getItemIDs()
{
$value = $this->Value();
return empty($value['Files']) ? array() : $value['Files'];
}
public function Value() {
public function Value()
{
// Re-override FileField Value to use data value
return $this->dataValue();
}
@ -235,10 +244,11 @@ trait FileUploadReceiver {
* @param DataObject|DataObjectInterface $record
* @return $this
*/
public function saveInto(DataObjectInterface $record) {
public function saveInto(DataObjectInterface $record)
{
// Check required relation details are available
$fieldname = $this->getName();
if(!$fieldname) {
if (!$fieldname) {
return $this;
}
@ -247,10 +257,10 @@ trait FileUploadReceiver {
// Check type of relation
$relation = $record->hasMethod($fieldname) ? $record->$fieldname() : null;
if($relation && ($relation instanceof RelationList || $relation instanceof UnsavedRelationList)) {
if ($relation && ($relation instanceof RelationList || $relation instanceof UnsavedRelationList)) {
// has_many or many_many
$relation->setByIDList($idList);
} elseif($class = DataObject::getSchema()->hasOneComponent(get_class($record), $fieldname)) {
} elseif ($class = DataObject::getSchema()->hasOneComponent(get_class($record), $fieldname)) {
// Assign has_one ID
$id = $idList ? reset($idList) : 0;
$record->{"{$fieldname}ID"} = $id;
@ -272,7 +282,8 @@ trait FileUploadReceiver {
* @param string $error Error message
* @return AssetContainer File object, or null if error
*/
protected function saveTemporaryFile($tmpFile, &$error = null) {
protected function saveTemporaryFile($tmpFile, &$error = null)
{
// Determine container object
$error = null;
$fileObject = null;
@ -282,7 +293,7 @@ trait FileUploadReceiver {
return null;
}
if($tmpFile['error']) {
if ($tmpFile['error']) {
$error = $tmpFile['error'];
return null;
}
@ -291,14 +302,14 @@ trait FileUploadReceiver {
// to default if there is no automatic relation
if ($relationClass = $this->getRelationAutosetClass(null)) {
// Allow File to be subclassed
if($relationClass === File::class && isset($tmpFile['name'])) {
if ($relationClass === File::class && isset($tmpFile['name'])) {
$relationClass = File::get_class_for_file_extension(
File::get_file_extension($tmpFile['name'])
);
}
// Create new object explicitly. Otherwise rely on Upload::load to choose the class.
$fileObject = Object::create($relationClass);
if(! ($fileObject instanceof DataObject) || !($fileObject instanceof AssetContainer)) {
if (! ($fileObject instanceof DataObject) || !($fileObject instanceof AssetContainer)) {
throw new InvalidArgumentException("Invalid asset container $relationClass");
}
}
@ -329,16 +340,17 @@ trait FileUploadReceiver {
* @param string $default Default value to return if no value could be calculated
* @return string Foreign class name.
*/
public function getRelationAutosetClass($default = File::class) {
public function getRelationAutosetClass($default = File::class)
{
// Don't autodetermine relation if no relationship between parent record
if(!$this->getRelationAutoSetting()) {
if (!$this->getRelationAutoSetting()) {
return $default;
}
// Check record and name
$name = $this->getName();
$record = $this->getRecord();
if(empty($name) || empty($record)) {
if (empty($name) || empty($record)) {
return $default;
} else {
$class = $record->getRelationClass($name);
@ -352,7 +364,8 @@ trait FileUploadReceiver {
* @param bool $auto
* @return $this
*/
public function setRelationAutoSetting($auto) {
public function setRelationAutoSetting($auto)
{
$this->relationAutoSetting = $auto;
return $this;
}
@ -362,7 +375,8 @@ trait FileUploadReceiver {
*
* @return bool
*/
public function getRelationAutoSetting() {
public function getRelationAutoSetting()
{
return $this->relationAutoSetting;
}
@ -372,26 +386,27 @@ trait FileUploadReceiver {
* @param array $postVars Array of posted form data
* @return array List of temporary file data
*/
protected function extractUploadedFileData($postVars) {
protected function extractUploadedFileData($postVars)
{
// Note: Format of posted file parameters in php is a feature of using
// <input name='{$Name}[Uploads][]' /> for multiple file uploads
$tmpFiles = array();
if( !empty($postVars['tmp_name'])
if (!empty($postVars['tmp_name'])
&& is_array($postVars['tmp_name'])
&& !empty($postVars['tmp_name']['Uploads'])
) {
for($i = 0; $i < count($postVars['tmp_name']['Uploads']); $i++) {
for ($i = 0; $i < count($postVars['tmp_name']['Uploads']); $i++) {
// Skip if "empty" file
if(empty($postVars['tmp_name']['Uploads'][$i])) {
if (empty($postVars['tmp_name']['Uploads'][$i])) {
continue;
}
$tmpFile = array();
foreach(array('name', 'type', 'tmp_name', 'error', 'size') as $field) {
foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $field) {
$tmpFile[$field] = $postVars[$field]['Uploads'][$i];
}
$tmpFiles[] = $tmpFile;
}
} elseif(!empty($postVars['tmp_name'])) {
} elseif (!empty($postVars['tmp_name'])) {
// Fallback to allow single file uploads (method used by AssetUploadField)
$tmpFiles[] = $postVars;
}

View File

@ -45,7 +45,8 @@ use Exception;
* Caution: The form field does not include any JavaScript or CSS when used outside of the CMS context,
* since the required frontend dependencies are included through CMS bundling.
*/
class UploadField extends FormField {
class UploadField extends FormField
{
use FileUploadReceiver;
/**
@ -217,7 +218,8 @@ class UploadField extends FormField {
* @param SS_List $items If no items are defined, the field will try to auto-detect an existing relation on
* @link $record}, with the same name as the field name.
*/
public function __construct($name, $title = null, SS_List $items = null) {
public function __construct($name, $title = null, SS_List $items = null)
{
// TODO thats the first thing that came to my head, feel free to change it
$this->addExtraClass('ss-upload'); // class, used by js
$this->addExtraClass('ss-uploadfield'); // class, used by css for uploadfield only
@ -238,7 +240,8 @@ class UploadField extends FormField {
* @param string $template
* @return $this
*/
public function setTemplateFileButtons($template) {
public function setTemplateFileButtons($template)
{
$this->templateFileButtons = $template;
return $this;
}
@ -246,7 +249,8 @@ class UploadField extends FormField {
/**
* @return string
*/
public function getTemplateFileButtons() {
public function getTemplateFileButtons()
{
return $this->_templates($this->templateFileButtons, '_FileButtons');
}
@ -256,7 +260,8 @@ class UploadField extends FormField {
* @param string $template
* @return $this
*/
public function setTemplateFileEdit($template) {
public function setTemplateFileEdit($template)
{
$this->templateFileEdit = $template;
return $this;
}
@ -264,7 +269,8 @@ class UploadField extends FormField {
/**
* @return string
*/
public function getTemplateFileEdit() {
public function getTemplateFileEdit()
{
return $this->_templates($this->templateFileEdit, '_FileEdit');
}
@ -273,8 +279,11 @@ class UploadField extends FormField {
*
* @return boolean
*/
public function canPreviewFolder() {
if(!$this->isActive()) return false;
public function canPreviewFolder()
{
if (!$this->isActive()) {
return false;
}
$can = $this->getConfig('canPreviewFolder');
return (is_bool($can)) ? $can : Permission::check($can);
}
@ -287,7 +296,8 @@ class UploadField extends FormField {
* required permission code
* @return UploadField Self reference
*/
public function setCanPreviewFolder($canPreviewFolder) {
public function setCanPreviewFolder($canPreviewFolder)
{
return $this->setConfig('canPreviewFolder', $canPreviewFolder);
}
@ -299,7 +309,8 @@ class UploadField extends FormField {
*
* @return boolean
*/
public function getOverwriteWarning() {
public function getOverwriteWarning()
{
return $this->getConfig('overwriteWarning');
}
@ -312,7 +323,8 @@ class UploadField extends FormField {
* @param boolean $overwriteWarning
* @return UploadField Self reference
*/
public function setOverwriteWarning($overwriteWarning) {
public function setOverwriteWarning($overwriteWarning)
{
return $this->setConfig('overwriteWarning', $overwriteWarning);
}
@ -320,7 +332,8 @@ class UploadField extends FormField {
* @param string $name
* @return $this
*/
public function setDisplayFolderName($name) {
public function setDisplayFolderName($name)
{
$this->displayFolderName = $name;
return $this;
}
@ -328,7 +341,8 @@ class UploadField extends FormField {
/**
* @return String
*/
public function getDisplayFolderName() {
public function getDisplayFolderName()
{
return $this->displayFolderName;
}
@ -340,9 +354,10 @@ class UploadField extends FormField {
*
* @return SS_List[ViewableData_Customised]
*/
public function getCustomisedItems() {
public function getCustomisedItems()
{
$customised = new ArrayList();
foreach($this->getItems() as $file) {
foreach ($this->getItems() as $file) {
$customised->push($this->customiseFile($file));
}
return $customised;
@ -355,7 +370,8 @@ class UploadField extends FormField {
* @param ViewableData|AssetContainer $file
* @return ViewableData_Customised
*/
protected function customiseFile(AssetContainer $file) {
protected function customiseFile(AssetContainer $file)
{
$file = $file->customise(array(
'UploadFieldThumbnailURL' => $this->getThumbnailURLForFile($file),
'UploadFieldDeleteLink' => $this->getItemHandler($file->ID)->DeleteLink(),
@ -377,7 +393,8 @@ class UploadField extends FormField {
* @param mixed $val
* @return UploadField self reference
*/
public function setConfig($key, $val) {
public function setConfig($key, $val)
{
$this->ufConfig[$key] = $val;
return $this;
}
@ -390,8 +407,11 @@ class UploadField extends FormField {
* @param string $key
* @return mixed
*/
public function getConfig($key) {
if(!isset($this->ufConfig[$key])) return null;
public function getConfig($key)
{
if (!isset($this->ufConfig[$key])) {
return null;
}
return $this->ufConfig[$key];
}
@ -400,7 +420,8 @@ class UploadField extends FormField {
*
* @return boolean
*/
public function getAutoUpload() {
public function getAutoUpload()
{
return $this->getConfig('autoUpload');
}
@ -410,7 +431,8 @@ class UploadField extends FormField {
* @param boolean $autoUpload
* @return UploadField Self reference
*/
public function setAutoUpload($autoUpload) {
public function setAutoUpload($autoUpload)
{
return $this->setConfig('autoUpload', $autoUpload);
}
@ -421,15 +443,16 @@ class UploadField extends FormField {
*
* @return integer|null Maximum limit, or null for no limit
*/
public function getAllowedMaxFileNumber() {
public function getAllowedMaxFileNumber()
{
$allowedMaxFileNumber = $this->getConfig('allowedMaxFileNumber');
// if there is a has_one relation with that name on the record and
// allowedMaxFileNumber has not been set, it's wanted to be 1
if(empty($allowedMaxFileNumber)) {
if (empty($allowedMaxFileNumber)) {
$record = $this->getRecord();
$name = $this->getName();
if($record && DataObject::getSchema()->hasOneComponent(get_class($record), $name)) {
if ($record && DataObject::getSchema()->hasOneComponent(get_class($record), $name)) {
return 1; // Default for has_one
} else {
return null; // Default for has_many and many_many
@ -445,7 +468,8 @@ class UploadField extends FormField {
* @param integer|null $allowedMaxFileNumber Maximum limit. 0 or null will be treated as unlimited
* @return UploadField Self reference
*/
public function setAllowedMaxFileNumber($allowedMaxFileNumber) {
public function setAllowedMaxFileNumber($allowedMaxFileNumber)
{
return $this->setConfig('allowedMaxFileNumber', $allowedMaxFileNumber);
}
@ -454,8 +478,11 @@ class UploadField extends FormField {
*
* @return boolean
*/
public function canUpload() {
if(!$this->isActive()) return false;
public function canUpload()
{
if (!$this->isActive()) {
return false;
}
$can = $this->getConfig('canUpload');
return (is_bool($can)) ? $can : Permission::check($can);
}
@ -468,7 +495,8 @@ class UploadField extends FormField {
* permission code
* @return UploadField Self reference
*/
public function setCanUpload($canUpload) {
public function setCanUpload($canUpload)
{
return $this->setConfig('canUpload', $canUpload);
}
@ -478,8 +506,11 @@ class UploadField extends FormField {
*
* @return boolean
*/
public function canAttachExisting() {
if(!$this->isActive()) return false;
public function canAttachExisting()
{
if (!$this->isActive()) {
return false;
}
$can = $this->getConfig('canAttachExisting');
return (is_bool($can)) ? $can : Permission::check($can);
}
@ -489,7 +520,8 @@ class UploadField extends FormField {
*
* @return boolean
*/
public function isActive() {
public function isActive()
{
return !$this->isDisabled() && !$this->isReadonly();
}
@ -501,7 +533,8 @@ class UploadField extends FormField {
* required permission code
* @return UploadField Self reference
*/
public function setCanAttachExisting($canAttachExisting) {
public function setCanAttachExisting($canAttachExisting)
{
return $this->setConfig('canAttachExisting', $canAttachExisting);
}
@ -510,7 +543,8 @@ class UploadField extends FormField {
*
* @return integer
*/
public function getPreviewMaxWidth() {
public function getPreviewMaxWidth()
{
return $this->getConfig('previewMaxWidth');
}
@ -520,7 +554,8 @@ class UploadField extends FormField {
* @param integer $previewMaxWidth
* @return UploadField Self reference
*/
public function setPreviewMaxWidth($previewMaxWidth) {
public function setPreviewMaxWidth($previewMaxWidth)
{
return $this->setConfig('previewMaxWidth', $previewMaxWidth);
}
@ -529,7 +564,8 @@ class UploadField extends FormField {
*
* @return integer
*/
public function getPreviewMaxHeight() {
public function getPreviewMaxHeight()
{
return $this->getConfig('previewMaxHeight');
}
@ -539,7 +575,8 @@ class UploadField extends FormField {
* @param integer $previewMaxHeight
* @return UploadField Self reference
*/
public function setPreviewMaxHeight($previewMaxHeight) {
public function setPreviewMaxHeight($previewMaxHeight)
{
return $this->setConfig('previewMaxHeight', $previewMaxHeight);
}
@ -550,7 +587,8 @@ class UploadField extends FormField {
* @see javascript/UploadField_uploadtemplate.js
* @return string
*/
public function getUploadTemplateName() {
public function getUploadTemplateName()
{
return $this->getConfig('uploadTemplateName');
}
@ -560,7 +598,8 @@ class UploadField extends FormField {
* @param string $uploadTemplateName
* @return UploadField Self reference
*/
public function setUploadTemplateName($uploadTemplateName) {
public function setUploadTemplateName($uploadTemplateName)
{
return $this->setConfig('uploadTemplateName', $uploadTemplateName);
}
@ -571,7 +610,8 @@ class UploadField extends FormField {
* @see javascript/DownloadField_downloadtemplate.js
* @return string
*/
public function getDownloadTemplateName() {
public function getDownloadTemplateName()
{
return $this->getConfig('downloadTemplateName');
}
@ -581,7 +621,8 @@ class UploadField extends FormField {
* @param string $downloadTemplateName
* @return Uploadfield Self reference
*/
public function setDownloadTemplateName($downloadTemplateName) {
public function setDownloadTemplateName($downloadTemplateName)
{
return $this->setConfig('downloadTemplateName', $downloadTemplateName);
}
@ -592,12 +633,13 @@ class UploadField extends FormField {
* @param DataObject $file File context to generate fields for
* @return FieldList List of form fields
*/
public function getFileEditFields(DataObject $file) {
public function getFileEditFields(DataObject $file)
{
// Empty actions, generate default
if(empty($this->fileEditFields)) {
if (empty($this->fileEditFields)) {
$fields = $file->getCMSFields();
// Only display main tab, to avoid overly complex interface
if($fields->hasTabSet() && ($mainTab = $fields->findOrMakeTab('Root.Main'))) {
if ($fields->hasTabSet() && ($mainTab = $fields->findOrMakeTab('Root.Main'))) {
$fields = $mainTab->Fields();
}
return $fields;
@ -609,7 +651,7 @@ class UploadField extends FormField {
}
// Method to call on the given file
if($file->hasMethod($this->fileEditFields)) {
if ($file->hasMethod($this->fileEditFields)) {
return $file->{$this->fileEditFields}();
}
@ -623,7 +665,8 @@ class UploadField extends FormField {
* @param FieldList|string
* @return Uploadfield Self reference
*/
public function setFileEditFields($fileEditFields) {
public function setFileEditFields($fileEditFields)
{
$this->fileEditFields = $fileEditFields;
return $this;
}
@ -635,9 +678,10 @@ class UploadField extends FormField {
* @param DataObject $file File context to generate form actions for
* @return FieldList Field list containing FormAction
*/
public function getFileEditActions(DataObject $file) {
public function getFileEditActions(DataObject $file)
{
// Empty actions, generate default
if(empty($this->fileEditActions)) {
if (empty($this->fileEditActions)) {
$actions = new FieldList($saveAction = new FormAction('doEdit', _t('UploadField.DOEDIT', 'Save')));
$saveAction->addExtraClass('ss-ui-action-constructive icon-accept');
return $actions;
@ -649,7 +693,7 @@ class UploadField extends FormField {
}
// Method to call on the given file
if($file->hasMethod($this->fileEditActions)) {
if ($file->hasMethod($this->fileEditActions)) {
return $file->{$this->fileEditActions}();
}
@ -663,7 +707,8 @@ class UploadField extends FormField {
* @param FieldList|string
* @return Uploadfield Self reference
*/
public function setFileEditActions($fileEditActions) {
public function setFileEditActions($fileEditActions)
{
$this->fileEditActions = $fileEditActions;
return $this;
}
@ -675,19 +720,20 @@ class UploadField extends FormField {
* @param DataObject $file File context to generate validator from
* @return Validator Validator object
*/
public function getFileEditValidator(DataObject $file) {
public function getFileEditValidator(DataObject $file)
{
// Empty validator
if(empty($this->fileEditValidator)) {
if (empty($this->fileEditValidator)) {
return null;
}
// Validator instance
if($this->fileEditValidator instanceof Validator) {
if ($this->fileEditValidator instanceof Validator) {
return $this->fileEditValidator;
}
// Method to call on the given file
if($file->hasMethod($this->fileEditValidator)) {
if ($file->hasMethod($this->fileEditValidator)) {
return $file->{$this->fileEditValidator}();
}
@ -701,7 +747,8 @@ class UploadField extends FormField {
* @param Validator|string
* @return Uploadfield Self reference
*/
public function setFileEditValidator($fileEditValidator) {
public function setFileEditValidator($fileEditValidator)
{
$this->fileEditValidator = $fileEditValidator;
return $this;
}
@ -711,7 +758,8 @@ class UploadField extends FormField {
* @param File|AssetContainer $file
* @return string URL to thumbnail
*/
protected function getThumbnailURLForFile(AssetContainer $file) {
protected function getThumbnailURLForFile(AssetContainer $file)
{
if (!$file->exists()) {
return null;
}
@ -730,13 +778,14 @@ class UploadField extends FormField {
}
// Check if unsized icon is available
if($file->hasMethod('getIcon')) {
if ($file->hasMethod('getIcon')) {
return $file->getIcon();
}
return null;
}
public function getAttributes() {
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
array(
@ -746,18 +795,20 @@ class UploadField extends FormField {
);
}
public function extraClass() {
if($this->isDisabled()) {
public function extraClass()
{
if ($this->isDisabled()) {
$this->addExtraClass('disabled');
}
if($this->isReadonly()) {
if ($this->isReadonly()) {
$this->addExtraClass('readonly');
}
return parent::extraClass();
}
public function Field($properties = array()) {
public function Field($properties = array())
{
// Calculated config as per jquery.fileupload-ui.js
$allowedMaxFileNumber = $this->getAllowedMaxFileNumber();
$config = array(
@ -792,7 +843,7 @@ class UploadField extends FormField {
// Validation: Number of files
if ($allowedMaxFileNumber) {
if($allowedMaxFileNumber > 1) {
if ($allowedMaxFileNumber > 1) {
$config['errorMessages']['maxNumberOfFiles'] = _t(
'UploadField.MAXNUMBEROFFILESSHORT',
'Can only upload {count} files',
@ -826,16 +877,19 @@ class UploadField extends FormField {
* @param Validator $validator
* @return boolean
*/
public function validate($validator) {
public function validate($validator)
{
$name = $this->getName();
$files = $this->getItems();
// If there are no files then quit
if($files->count() == 0) return true;
if ($files->count() == 0) {
return true;
}
// Check max number of files
$maxFiles = $this->getAllowedMaxFileNumber();
if($maxFiles && ($files->count() > $maxFiles)) {
if ($maxFiles && ($files->count() > $maxFiles)) {
$validator->validationError(
$name,
_t(
@ -850,7 +904,7 @@ class UploadField extends FormField {
// Revalidate each file against nested validator
$this->upload->clearErrors();
foreach($files as $file) {
foreach ($files as $file) {
// Generate $_FILES style file attribute array for upload validator
$tmpFile = array(
'name' => $file->Name,
@ -863,8 +917,8 @@ class UploadField extends FormField {
}
// Check all errors
if($errors = $this->upload->getErrors()) {
foreach($errors as $error) {
if ($errors = $this->upload->getErrors()) {
foreach ($errors as $error) {
$validator->validationError($name, $error, "validation");
}
return false;
@ -877,7 +931,8 @@ class UploadField extends FormField {
* @param HTTPRequest $request
* @return UploadField_ItemHandler
*/
public function handleItem(HTTPRequest $request) {
public function handleItem(HTTPRequest $request)
{
return $this->getItemHandler($request->param('ID'));
}
@ -885,7 +940,8 @@ class UploadField extends FormField {
* @param int $itemID
* @return UploadField_ItemHandler
*/
public function getItemHandler($itemID) {
public function getItemHandler($itemID)
{
return UploadField_ItemHandler::create($this, $itemID);
}
@ -893,8 +949,9 @@ class UploadField extends FormField {
* @param HTTPRequest $request
* @return UploadField_SelectHandler
*/
public function handleSelect(HTTPRequest $request) {
if(!$this->canAttachExisting()) {
public function handleSelect(HTTPRequest $request)
{
if (!$this->canAttachExisting()) {
return $this->httpError(403);
}
return UploadField_SelectHandler::create($this, $this->getFolderName());
@ -907,7 +964,8 @@ class UploadField extends FormField {
* @param File|AssetContainer $file Object which contains a file
* @return array Array encoded list of file attributes
*/
protected function encodeFileAttributes(AssetContainer $file) {
protected function encodeFileAttributes(AssetContainer $file)
{
// Collect all output data.
$customised = $this->customiseFile($file);
return array(
@ -930,14 +988,17 @@ class UploadField extends FormField {
* @return HTTPResponse
* @return HTTPResponse
*/
public function upload(HTTPRequest $request) {
if($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
public function upload(HTTPRequest $request)
{
if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
return $this->httpError(403);
}
// Protect against CSRF on destructive action
$token = $this->getForm()->getSecurityToken();
if(!$token->checkRequest($request)) return $this->httpError(400);
if (!$token->checkRequest($request)) {
return $this->httpError(400);
}
// Get form details
$name = $this->getName();
@ -951,7 +1012,7 @@ class UploadField extends FormField {
// and save data/error on a per file basis
foreach ($uploadedFiles as $tempFile) {
$file = $this->saveTemporaryFile($tempFile, $error);
if(empty($file)) {
if (empty($file)) {
array_push($return, array('error' => $error));
} else {
array_push($return, $this->encodeFileAttributes($file));
@ -972,14 +1033,19 @@ class UploadField extends FormField {
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function attach(HTTPRequest $request) {
if(!$request->isPOST()) return $this->httpError(403);
if(!$this->canAttachExisting()) return $this->httpError(403);
public function attach(HTTPRequest $request)
{
if (!$request->isPOST()) {
return $this->httpError(403);
}
if (!$this->canAttachExisting()) {
return $this->httpError(403);
}
// Retrieve file attributes required by front end
$return = array();
$files = File::get()->byIDs($request->postVar('ids'));
foreach($files as $file) {
foreach ($files as $file) {
$return[] = $this->encodeFileAttributes($file);
}
$response = new HTTPResponse(Convert::raw2json($return));
@ -993,7 +1059,8 @@ class UploadField extends FormField {
* @param string $originalFile Filename
* @return bool
*/
protected function checkFileExists($originalFile) {
protected function checkFileExists($originalFile)
{
// Check both original and safely filtered filename
$nameFilter = FileNameFilter::create();
@ -1014,10 +1081,11 @@ class UploadField extends FormField {
* @param HTTPRequest $request
* @return HTTPResponse
*/
public function fileexists(HTTPRequest $request) {
public function fileexists(HTTPRequest $request)
{
// Assert that requested filename doesn't attempt to escape the directory
$originalFile = $request->requestVar('filename');
if($originalFile !== basename($originalFile)) {
if ($originalFile !== basename($originalFile)) {
$return = array(
'error' => _t('File.NOVALIDUPLOAD', 'File is not a valid upload')
);
@ -1030,15 +1098,17 @@ class UploadField extends FormField {
// Encode and present response
$response = new HTTPResponse(Convert::raw2json($return));
$response->addHeader('Content-Type', 'application/json');
if (!empty($return['error'])) $response->setStatusCode(400);
if (!empty($return['error'])) {
$response->setStatusCode(400);
}
return $response;
}
public function performReadonlyTransformation() {
public function performReadonlyTransformation()
{
$clone = clone $this;
$clone->addExtraClass('readonly');
$clone->setReadonly(true);
return $clone;
}
}

View File

@ -36,7 +36,8 @@ trait UploadReceiver
/**
* Bootstrap Uploadable field
*/
protected function constructUploadReceiver() {
protected function constructUploadReceiver()
{
// Set Upload instance
$this->setUpload(Upload::create());
@ -56,7 +57,8 @@ trait UploadReceiver
*
* @return Upload
*/
public function getUpload() {
public function getUpload()
{
return $this->upload;
}
@ -66,7 +68,8 @@ trait UploadReceiver
* @param Upload $upload
* @return $this Self reference
*/
public function setUpload(Upload $upload) {
public function setUpload(Upload $upload)
{
$this->upload = $upload;
return $this;
}
@ -81,7 +84,8 @@ trait UploadReceiver
* @param array $rules List of extensions
* @return $this
*/
public function setAllowedExtensions($rules) {
public function setAllowedExtensions($rules)
{
$this->getValidator()->setAllowedExtensions($rules);
return $this;
}
@ -96,7 +100,8 @@ trait UploadReceiver
* @param string,... $categories Additional category names
* @return $this
*/
public function setAllowedFileCategories($category) {
public function setAllowedFileCategories($category)
{
$extensions = File::get_category_extensions(func_get_args());
return $this->setAllowedExtensions($extensions);
}
@ -107,7 +112,8 @@ trait UploadReceiver
*
* @return array
*/
public function getAllowedExtensions() {
public function getAllowedExtensions()
{
return $this->getValidator()->getAllowedExtensions();
}
@ -116,7 +122,8 @@ trait UploadReceiver
*
* @return Upload_Validator
*/
public function getValidator() {
public function getValidator()
{
return $this->getUpload()->getValidator();
}
@ -126,7 +133,8 @@ trait UploadReceiver
* @param Upload_Validator $validator
* @return $this Self reference
*/
public function setValidator(Upload_Validator $validator) {
public function setValidator(Upload_Validator $validator)
{
$this->getUpload()->setValidator($validator);
return $this;
}
@ -137,7 +145,8 @@ trait UploadReceiver
* @param string $folderName
* @return $this Self reference
*/
public function setFolderName($folderName) {
public function setFolderName($folderName)
{
$this->folderName = $folderName;
return $this;
}
@ -147,7 +156,8 @@ trait UploadReceiver
*
* @return string
*/
public function getFolderName() {
public function getFolderName()
{
return ($this->folderName !== false)
? $this->folderName
: Upload::config()->uploads_folder;