From 84b9912c53120b5e6d920d6a33b87ca1e07bf93d Mon Sep 17 00:00:00 2001 From: helpfulrobot Date: Fri, 1 Jan 2016 03:06:51 +1300 Subject: [PATCH] Converted to PSR-2 --- code/AjaxFileField.php | 345 +++++++++++++++++++++-------------------- code/XHRUpload.php | 109 ++++++------- 2 files changed, 233 insertions(+), 221 deletions(-) diff --git a/code/AjaxFileField.php b/code/AjaxFileField.php index d030f75..5d30b8f 100644 --- a/code/AjaxFileField.php +++ b/code/AjaxFileField.php @@ -5,62 +5,67 @@ * Similar to FileIFrameField, except it allows XHR uploads via the file-uploader javascript. * */ -class AjaxFileField extends FileField{ - - private static $allowed_actions = array( - 'save', - 'saveXHR' - ); +class AjaxFileField extends FileField +{ + + private static $allowed_actions = array( + 'save', + 'saveXHR' + ); - protected $buttonClasses,$config = array(); + protected $buttonClasses,$config = array(); - protected $sessionstoreid; - - public function addButtonClass($class){ - $this->buttonClasses[] = $class; - } - - /** - * Set or override specific configs - * see thirdparty/valums/reademe.md - */ - public function setConfig($config = array()){ - $this->config = $config; - } + protected $sessionstoreid; + + public function addButtonClass($class) + { + $this->buttonClasses[] = $class; + } + + /** + * Set or override specific configs + * see thirdparty/valums/reademe.md + */ + public function setConfig($config = array()) + { + $this->config = $config; + } - public function setSessionStoreId($id) { - $this->sessionstoreid = $id; + public function setSessionStoreId($id) + { + $this->sessionstoreid = $id; - return $this; - } - - public function Field($properties = array()){ - Requirements::javascript('ajaxuploadfield/thirdparty/valums/client/fileuploader.min.js','fileuploader'); - - //configure javascript - $htmlid = $this->XML_val('Name')."_uploader"; - $thislink = $this->Link('save'); - $options = array( - 'action' => $thislink, - 'multiple' => false, //prevent multiple file uploads - ); - $allowedextensions = $this->getValidator()->getAllowedExtensions(); - if(is_array($allowedextensions)){ - $options['allowedExtensions'] = $allowedextensions; - } - if($maxfilesize = $this->getValidator()->getAllowedMaxFileSize()){ - $options['sizeLimit'] = $maxfilesize; - } - if(Director::isDev()){ - $options['debug'] = true; - } - $options = array_merge($options,$this->config); - $encodedoptions = json_encode($options); - $extraclasses = count($this->buttonClasses) ? 'class=\"'.implode(" ",$this->buttonClasses).'\"' : ""; - $replacementhtml = 'title.'\" />'; - - //store globally reachable js reference, to allow later customisations - $script =<<XML_val('Name')."_uploader"; + $thislink = $this->Link('save'); + $options = array( + 'action' => $thislink, + 'multiple' => false, //prevent multiple file uploads + ); + $allowedextensions = $this->getValidator()->getAllowedExtensions(); + if (is_array($allowedextensions)) { + $options['allowedExtensions'] = $allowedextensions; + } + if ($maxfilesize = $this->getValidator()->getAllowedMaxFileSize()) { + $options['sizeLimit'] = $maxfilesize; + } + if (Director::isDev()) { + $options['debug'] = true; + } + $options = array_merge($options, $this->config); + $encodedoptions = json_encode($options); + $extraclasses = count($this->buttonClasses) ? 'class=\"'.implode(" ", $this->buttonClasses).'\"' : ""; + $replacementhtml = 'title.'\" />'; + + //store globally reachable js reference, to allow later customisations + $script =<<id()); - - if($this->form){ - $record = $this->form->getRecord(); - } - $fieldName = $this->name; - if(isset($record) && $record) { - $imageField = $record->$fieldName(); - } else { - $imageField = ""; - } - - $html = "
"; - if($imageField && $imageField->exists()) { - $html .= '
'; - if($imageField->hasMethod('Thumbnail') && $imageField->Thumbnail()) { - $html .= "Thumbnail()->getURL()."\" />"; - } else if($imageField->CMSThumbnail()) { - $html .= "CMSThumbnail()->getURL()."\" />"; - } - $html .= '
'; - } - $html .= $this->createTag("input", - array( - "type" => "file", - "name" => $this->name, - "id" => $this->id(), - 'disabled' => $this->disabled - ) - ); - $html .= $this->createTag("input", - array( - "type" => "hidden", - "name" => "MAX_FILE_SIZE", - "value" => $maxfilesize - ) - ); - $html .= "
"; - return $html; - } - - /** - * Saves uplaoded image into file. - * The function can handle three different ways of uploading an image: XHR, iframe, form post, - * where the first two are done via the fileuploader script. - * - * A dummy file array is created for Upload to properly process. - * - */ - public function save($data = null, $form = null) { - $json = array(); - $this->upload->setValidator(new XHRUpload_Validator()); //hack solution to allow XHR uploads - $fileparts = null; + + Requirements::customScript($script, 'uploader'.$this->id()); + + if ($this->form) { + $record = $this->form->getRecord(); + } + $fieldName = $this->name; + if (isset($record) && $record) { + $imageField = $record->$fieldName(); + } else { + $imageField = ""; + } + + $html = "
"; + if ($imageField && $imageField->exists()) { + $html .= '
'; + if ($imageField->hasMethod('Thumbnail') && $imageField->Thumbnail()) { + $html .= "Thumbnail()->getURL()."\" />"; + } elseif ($imageField->CMSThumbnail()) { + $html .= "CMSThumbnail()->getURL()."\" />"; + } + $html .= '
'; + } + $html .= $this->createTag("input", + array( + "type" => "file", + "name" => $this->name, + "id" => $this->id(), + 'disabled' => $this->disabled + ) + ); + $html .= $this->createTag("input", + array( + "type" => "hidden", + "name" => "MAX_FILE_SIZE", + "value" => $maxfilesize + ) + ); + $html .= "
"; + return $html; + } + + /** + * Saves uplaoded image into file. + * The function can handle three different ways of uploading an image: XHR, iframe, form post, + * where the first two are done via the fileuploader script. + * + * A dummy file array is created for Upload to properly process. + * + */ + public function save($data = null, $form = null) + { + $json = array(); + $this->upload->setValidator(new XHRUpload_Validator()); //hack solution to allow XHR uploads + $fileparts = null; - if (isset($_GET['qqfile'])) { - $fileparts = $this->saveXHR($_GET['qqfile']); - } elseif (isset($_FILES['qqfile'])) { //TODO: this could probably be replaced by setting the field name in javascript - $fileparts = $_FILES['qqfile']; - } elseif(isset($_FILES[$this->Name()])) { - $fileparts = $_FILES[$this->Name()]; - } - if(!$fileparts){ - return $this->returnJSON(array("error","No file was uploaded.")); - } - //create database entry for image - // $desiredClass = $this->dataClass(); - $desiredClass = "Image"; //TODO: temp - make a subclass, or handle image uploads - $fileObject = Object::create($desiredClass); - $this->upload->loadIntoFile($fileparts, $fileObject, $this->folderName); + if (isset($_GET['qqfile'])) { + $fileparts = $this->saveXHR($_GET['qqfile']); + } elseif (isset($_FILES['qqfile'])) { //TODO: this could probably be replaced by setting the field name in javascript + $fileparts = $_FILES['qqfile']; + } elseif (isset($_FILES[$this->Name()])) { + $fileparts = $_FILES[$this->Name()]; + } + if (!$fileparts) { + return $this->returnJSON(array("error", "No file was uploaded.")); + } + //create database entry for image + // $desiredClass = $this->dataClass(); + $desiredClass = "Image"; //TODO: temp - make a subclass, or handle image uploads + $fileObject = Object::create($desiredClass); + $this->upload->loadIntoFile($fileparts, $fileObject, $this->folderName); - if($this->upload->isError()){ - $errors = $this->upload->getErrors(); - $json = array('error',implode(",",$errors)); - return $this->returnJSON($json); - } + if ($this->upload->isError()) { + $errors = $this->upload->getErrors(); + $json = array('error',implode(",", $errors)); + return $this->returnJSON($json); + } - $file = $this->upload->getFile(); - if($member = Member::currentUser()){ - $file->OwnerID = $member->ID; - } - $file->write(); + $file = $this->upload->getFile(); + if ($member = Member::currentUser()) { + $file->OwnerID = $member->ID; + } + $file->write(); - if($this->sessionstoreid){ - Session::set($this->sessionstoreid.".".$file->ID, $file->ID); - } + if ($this->sessionstoreid) { + Session::set($this->sessionstoreid.".".$file->ID, $file->ID); + } - //TODO: record linking + //TODO: record linking - //if ajax, then return file details - $json = $file->toMap(); - if($file instanceof Image){ - $json['thumbnailurl'] = $file->CMSThumbnail()->getURL(); - } + //if ajax, then return file details + $json = $file->toMap(); + if ($file instanceof Image) { + $json['thumbnailurl'] = $file->CMSThumbnail()->getURL(); + } - return $this->returnJSON($json); - } - - function returnJSON($jsonarray){ - return htmlspecialchars(json_encode($jsonarray), ENT_NOQUOTES); - } - - /** - * Save XmlHttpRequest (ajax) submitted image into new file. - * (only supported by newer browsers) - * - * @todo: performance handling - see http://lenss.nl/2010/09/drag-drop-uploads-with-xmlhttprequest2-and-php-revised/ - * - */ - function saveXHR($filename){ - //TODO: use base_convert(uniqid(),10,36) to add uniqueness to each file - $tempfilepath = TEMP_FOLDER.'/'.$filename; - $upload = file_put_contents($tempfilepath,file_get_contents('php://input')); - $size = (isset($_SERVER["CONTENT_LENGTH"]))? (int)$_SERVER["CONTENT_LENGTH"] : 0; - if(!$size) return null; //TODO: throwing an error message would help here - return array( - 'tmp_name' => $tempfilepath, - 'name' => $filename, - 'size' => $size - ); - } - -} \ No newline at end of file + return $this->returnJSON($json); + } + + public function returnJSON($jsonarray) + { + return htmlspecialchars(json_encode($jsonarray), ENT_NOQUOTES); + } + + /** + * Save XmlHttpRequest (ajax) submitted image into new file. + * (only supported by newer browsers) + * + * @todo: performance handling - see http://lenss.nl/2010/09/drag-drop-uploads-with-xmlhttprequest2-and-php-revised/ + * + */ + public function saveXHR($filename) + { + //TODO: use base_convert(uniqid(),10,36) to add uniqueness to each file + $tempfilepath = TEMP_FOLDER.'/'.$filename; + $upload = file_put_contents($tempfilepath, file_get_contents('php://input')); + $size = (isset($_SERVER["CONTENT_LENGTH"]))? (int)$_SERVER["CONTENT_LENGTH"] : 0; + if (!$size) { + return null; + } //TODO: throwing an error message would help here + return array( + 'tmp_name' => $tempfilepath, + 'name' => $filename, + 'size' => $size + ); + } +} diff --git a/code/XHRUpload.php b/code/XHRUpload.php index 1236f7c..df6e710 100644 --- a/code/XHRUpload.php +++ b/code/XHRUpload.php @@ -1,58 +1,61 @@ tmpFile['name']) || empty($this->tmpFile['name'])) return true; +class XHRUpload_Validator extends Upload_Validator +{ + + + /** + * Run through the rules for this validator checking against + * the temporary file set by {@link setTmpFile()} to see if + * the file is deemed valid or not. + * + * @return boolean + */ + public function validate() + { + // we don't validate for empty upload fields yet + if (!isset($this->tmpFile['name']) || empty($this->tmpFile['name'])) { + return true; + } - $isRunningTests = (class_exists('SapphireTest', false) && SapphireTest::is_running_test()); - //needed to allow XHR uploads - /*if(isset($this->tmpFile['tmp_name']) && !is_uploaded_file($this->tmpFile['tmp_name']) && !$isRunningTests) { - $this->errors[] = _t('File.NOVALIDUPLOAD', 'File is not a valid upload'); - return false; - }*/ + $isRunningTests = (class_exists('SapphireTest', false) && SapphireTest::is_running_test()); + //needed to allow XHR uploads + /*if(isset($this->tmpFile['tmp_name']) && !is_uploaded_file($this->tmpFile['tmp_name']) && !$isRunningTests) { + $this->errors[] = _t('File.NOVALIDUPLOAD', 'File is not a valid upload'); + return false; + }*/ - $pathInfo = pathinfo($this->tmpFile['name']); - // filesize validation - if(!$this->isValidSize()) { - $ext = (isset($pathInfo['extension'])) ? $pathInfo['extension'] : ''; - $arg = File::format_size($this->getAllowedMaxFileSize($ext)); - $this->errors[] = sprintf( - _t( - 'File.TOOLARGE', - 'Filesize is too large, maximum %s allowed.', - PR_MEDIUM, - 'Argument 1: Filesize (e.g. 1MB)' - ), - $arg - ); - return false; - } + $pathInfo = pathinfo($this->tmpFile['name']); + // filesize validation + if (!$this->isValidSize()) { + $ext = (isset($pathInfo['extension'])) ? $pathInfo['extension'] : ''; + $arg = File::format_size($this->getAllowedMaxFileSize($ext)); + $this->errors[] = sprintf( + _t( + 'File.TOOLARGE', + 'Filesize is too large, maximum %s allowed.', + PR_MEDIUM, + 'Argument 1: Filesize (e.g. 1MB)' + ), + $arg + ); + return false; + } - // extension validation - if(!$this->isValidExtension()) { - $this->errors[] = sprintf( - _t( - 'File.INVALIDEXTENSION', - 'Extension is not allowed (valid: %s)', - PR_MEDIUM, - 'Argument 1: Comma-separated list of valid extensions' - ), - wordwrap(implode(', ', $this->allowedExtensions)) - ); - return false; - } - - return true; - } - -} \ No newline at end of file + // extension validation + if (!$this->isValidExtension()) { + $this->errors[] = sprintf( + _t( + 'File.INVALIDEXTENSION', + 'Extension is not allowed (valid: %s)', + PR_MEDIUM, + 'Argument 1: Comma-separated list of valid extensions' + ), + wordwrap(implode(', ', $this->allowedExtensions)) + ); + return false; + } + + return true; + } +}