Example #1
0
 /**
  * Handles the upload request. This is a static function to ensure that it is easily
  * accessible to other classes without having to instantiate a {@link Controller} object. 
  * A lot of this code is lifted from {@link AssetAdmin}.
  *
  * @todo Error handling on this is crap.
  * @param SS_HTTPRequest
  * @param Folder A folder that will be the destination of the upload.
  * @return array|string
  */
 public static function handle_upload(SS_HTTPRequest $r, $folder = null, $allowed_extensions = null)
 {
     if (!$folder) {
         $folder = singleton('Folder');
     }
     $newFiles = array();
     $errorResponse = "";
     if (isset($_FILES['file']) && is_array($_FILES['file'])) {
         $file_array = $_FILES['file'];
         foreach ($file_array['tmp_name'] as $index => $value) {
             if (is_uploaded_file($value)) {
                 $tmpFile = array('tmp_name' => $value, 'name' => $file_array['name'][$index], 'size' => $file_array['size'][$index], 'error' => $file_array['error'][$index]);
                 // validate files (only if not logged in as admin)
                 if (!File::$apply_restrictions_to_admin && Permission::check('ADMIN')) {
                     $valid = true;
                 } else {
                     // Set up the validator instance with rules
                     $validator = new Upload_Validator();
                     if (!$allowed_extensions) {
                         $allowed_extensions = File::$allowed_extensions;
                     }
                     $validator->setAllowedExtensions($allowed_extensions);
                     $validator->setAllowedMaxFileSize(self::$allowed_max_file_size);
                     // Do the upload validation with the rules
                     $upload = new Upload();
                     $upload->setValidator($validator);
                     $valid = $upload->validate($tmpFile);
                     if (!$valid) {
                         $errors = $upload->getErrors();
                         if ($errors) {
                             foreach ($errors as $error) {
                                 $errorResponse .= $error;
                             }
                         }
                     }
                 }
                 // move file to given folder
                 if ($valid) {
                     $newFile = $folder->addUploadToFolder($tmpFile);
                     $newFiles[] = $newFile;
                 } else {
                     return $errorResponse;
                 }
                 foreach ($newFiles as $newFile) {
                     $fileIDs[] = $newFile;
                     $fileObj = DataObject::get_one('File', "\"File\".\"ID\"={$newFile}");
                     if (method_exists($fileObj, 'onAfterUpload')) {
                         $fileObj->onAfterUpload();
                     }
                 }
             }
         }
     } else {
         return "File is too large.";
     }
     return $newFiles;
 }
 public function __construct($controller, $name, $fields = null, $actions = null)
 {
     $fields = new FieldList($Nickname = TextField::create('Nickname')->setTitle(_t('Member.NICKNAME', 'Member.NICKNAME')), $Location = BootstrapGeoLocationField::create('Location')->setTitle(_t('Member.LOCATION', 'Member.LOCATION')), $About = TextareaField::create('About')->setTitle(_t('DonatorProfile.ABOUT', 'DonatorProfile.ABOUT'))->setPlaceholder(_t('DonatorProfile.ABOUTDESCRIPTION', 'DonatorProfile.ABOUTDESCRIPTION')), $Active = CheckboxField::create('Active')->setTitle(_t('Member.ACTIVE', 'Member.ACTIVE')), $Avatar = BootstrapFileField::create('Avatar')->setTitle(_t('Member.AVATAR', 'Member.AVATAR')));
     $Location->setRightTitle(_t('Member.LOCATIONDESCRIPTION', 'Member.LOCATIONDESCRIPTION'));
     $About->setRightTitle(_t('DonatorProfile.ABOUTDESCRIPTION', 'DonatorProfile.ABOUTDESCRIPTION'));
     // Upload Parameters
     $exts = array('jpg', 'jpeg', 'gif', 'png');
     $validator = new Upload_Validator();
     $validator->setAllowedExtensions($exts);
     $validator->setAllowedMaxFileSize(5000000);
     $upload = Upload::create();
     $upload->setValidator($validator);
     // Avatar Upload Folder
     $Avatar->setFolderName("Uploads/Members/" . Member::currentUser()->ID . "/Avatars");
     $Avatar->setUpload($upload);
     $actions = new FieldList($Submit = BootstrapLoadingFormAction::create('doSave')->setTitle(_t('HostelEditForm.SAVEBUTTON', 'HostelEditForm.SAVEBUTTON')));
     parent::__construct($controller, $name, $fields, $actions, new RequiredFields("Nickname", "Location", "About"));
     $this->loadDataFrom(Member::currentUser());
 }
 public function __construct($controller, $name, $fields = null, $actions = null)
 {
     $fields = new FieldList($Nickname = TextField::create('Nickname')->setTitle(_t('Member.NICKNAME', 'Member.NICKNAME')), $Location = BootstrapGeoLocationField::create('Location')->setTitle(_t('Member.LOCATION', 'Member.LOCATION')), $Adults = DropdownField::create('Adults')->setTitle(_t('RefugeeProfile.ADULTS', 'RefugeeProfile.ADULTS'))->setSource(Config::inst()->get('Member', 'people_sum')), $Children = DropdownField::create('Children')->setTitle(_t('RefugeeProfile.CHILDREN', 'RefugeeProfile.CHILDREN'))->setSource(Config::inst()->get('Member', 'people_sum')), $Baby = CheckboxField::create('Baby')->setTitle(_t('RefugeeProfile.BABY', 'RefugeeProfile.BABY')), $About = TextareaField::create('About')->setTitle(_t('RefugeeProfile.ABOUT', 'RefugeeProfile.ABOUT'))->setPlaceholder(_t('RefugeeProfile.ABOUTDESCRIPTION', 'RefugeeProfile.ABOUTDESCRIPTION')), $Active = CheckboxField::create('Active')->setTitle(_t('Member.ACTIVE', 'Member.ACTIVE')), $Avatar = BootstrapFileField::create('Avatar')->setTitle(_t('Member.AVATAR', 'Member.AVATAR')));
     $Location->setRightTitle(_t('Member.LOCATIONDESCRIPTION', 'Member.LOCATIONDESCRIPTION'));
     $Adults->setRightTitle(_t('RefugeeProfile.ADULTSDESCRIPTION', 'RefugeeProfile.ADULTSDESCRIPTION'));
     $Children->setRightTitle(_t('RefugeeProfile.CHILDRENDESCRIPTION', 'RefugeeProfile.CHILDRENDESCRIPTION'));
     $Baby->setRightTitle(_t('RefugeeProfile.BABYDESCRIPTION', 'RefugeeProfile.BABYDESCRIPTION'));
     $About->setRightTitle(_t('RefugeeProfile.ABOUTDESCRIPTION', 'RefugeeProfile.ABOUTDESCRIPTION'));
     // Upload Parameters
     $exts = array('jpg', 'jpeg', 'gif', 'png');
     $validator = new Upload_Validator();
     $validator->setAllowedExtensions($exts);
     $validator->setAllowedMaxFileSize(5000000);
     $upload = Upload::create();
     $upload->setValidator($validator);
     // Avatar Upload Folder
     $Avatar->setFolderName("Uploads/Members/" . Member::currentUser()->ID . "/Avatars");
     $Avatar->setUpload($upload);
     $actions = new FieldList($Submit = BootstrapLoadingFormAction::create('doSave')->setTitle(_t('RefugeeEditForm.SAVEBUTTON', 'RefugeeEditForm.SAVEBUTTON')));
     parent::__construct($controller, $name, $fields, $actions, new RequiredFields("Nickname", "Location", "Adults", "Children", "About"));
     $this->loadDataFrom(Member::currentUser());
 }
Example #4
0
    /**
     * This method processes the results of the UploadForm.
     * It will save the uploaded files to /assets/ and create new File objects as required.
     */
    function doUpload($data, $form)
    {
        $newFiles = array();
        $fileIDs = array();
        $fileNames = array();
        $fileSizeWarnings = '';
        $uploadErrors = '';
        $jsErrors = '';
        $status = '';
        $statusMessage = '';
        $processedFiles = array();
        foreach ($data['Files'] as $param => $files) {
            if (!is_array($files)) {
                $files = array($files);
            }
            foreach ($files as $key => $value) {
                $processedFiles[$key][$param] = $value;
            }
        }
        // Load POST data from arrays in to the correct dohickey.
        $processedData = array();
        foreach ($data as $dataKey => $value) {
            if ($dataKey == 'Files') {
                continue;
            }
            if (is_array($value)) {
                $i = 0;
                foreach ($value as $fileId => $dataValue) {
                    if (!isset($processedData[$i])) {
                        $processedData[$i] = array();
                    }
                    $processedData[$i][$dataKey] = $dataValue;
                    $i++;
                }
            }
        }
        $processedData = array_reverse($processedData);
        if ($data['FolderID'] && $data['FolderID'] != '') {
            $folder = DataObject::get_by_id("Folder", $data['FolderID']);
            if (!$folder) {
                throw new InvalidArgumentException(sprintf("Folder #%d doesn't exist", (int) $data['FolderID']));
            }
        } else {
            $folder = singleton('Folder');
        }
        foreach ($processedFiles as $filePostId => $tmpFile) {
            if ($tmpFile['error'] == UPLOAD_ERR_NO_TMP_DIR) {
                $status = 'bad';
                $statusMessage = _t('AssetAdmin.NOTEMP', 'There is no temporary folder for uploads. Please set upload_tmp_dir in php.ini.');
                break;
            }
            if ($tmpFile['tmp_name']) {
                // Workaround open_basedir problems
                if (ini_get("open_basedir")) {
                    $newtmp = TEMP_FOLDER . '/' . $tmpFile['name'];
                    move_uploaded_file($tmpFile['tmp_name'], $newtmp);
                    $tmpFile['tmp_name'] = $newtmp;
                }
                // validate files (only if not logged in as admin)
                if (!File::$apply_restrictions_to_admin && Permission::check('ADMIN')) {
                    $valid = true;
                } else {
                    // Set up the validator instance with rules
                    $validator = new Upload_Validator();
                    $validator->setAllowedExtensions(File::$allowed_extensions);
                    $validator->setAllowedMaxFileSize(self::$allowed_max_file_size);
                    // Do the upload validation with the rules
                    $upload = new Upload();
                    $upload->setValidator($validator);
                    $valid = $upload->validate($tmpFile);
                    if (!$valid) {
                        $errors = $upload->getErrors();
                        if ($errors) {
                            foreach ($errors as $error) {
                                $jsErrors .= "alert('" . Convert::raw2js($error) . "');";
                            }
                        }
                    }
                }
                // move file to given folder
                if ($valid) {
                    if ($newFile = $folder->addUploadToFolder($tmpFile)) {
                        if (self::$metadata_upload_enabled && isset($processedData[$filePostId])) {
                            $fileObject = DataObject::get_by_id('File', $newFile);
                            $metadataForm = new Form($this, 'MetadataForm', $fileObject->uploadMetadataFields(), new FieldSet());
                            $metadataForm->loadDataFrom($processedData[$filePostId]);
                            $metadataForm->saveInto($fileObject);
                            $fileObject->write();
                        }
                        $newFiles[] = $newFile;
                    }
                }
            }
        }
        if ($newFiles) {
            $numFiles = sizeof($newFiles);
            $statusMessage = sprintf(_t('AssetAdmin.UPLOADEDX', "Uploaded %s files"), $numFiles);
            $status = "good";
        } else {
            if ($status != 'bad') {
                $statusMessage = _t('AssetAdmin.NOTHINGTOUPLOAD', 'There was nothing to upload');
                $status = "";
            }
        }
        $fileObj = false;
        foreach ($newFiles as $newFile) {
            $fileIDs[] = $newFile;
            $fileObj = DataObject::get_one('File', "\"File\".\"ID\"={$newFile}");
            // notify file object after uploading
            if (method_exists($fileObj, 'onAfterUpload')) {
                $fileObj->onAfterUpload();
            }
            $fileNames[] = $fileObj->Name;
        }
        // workaround for content editors image upload.Passing an extra hidden field
        // in the content editors view of 'UploadMode' @see HtmlEditorField
        // this will be refactored for 2.5
        if (isset($data['UploadMode']) && $data['UploadMode'] == "CMSEditor" && $fileObj) {
            // we can use $fileObj considering that the uploader in the cmseditor can only upload
            // one file at a time. Once refactored to multiple files this is going to have to be changed
            $width = is_a($fileObj, 'Image') ? $fileObj->getWidth() : '100';
            $height = is_a($fileObj, 'Image') ? $fileObj->getHeight() : '100';
            $values = array('Filename' => $fileObj->Filename, 'Width' => $width, 'Height' => $height);
            return Convert::raw2json($values);
        }
        $sFileIDs = implode(',', $fileIDs);
        $sFileNames = implode(',', $fileNames);
        echo <<<HTML
\t\t\t<script type="text/javascript">
\t\t\t/* IDs: {$sFileIDs} */
\t\t\t/* Names: {$sFileNames} */
\t\t\t
\t\t\tvar form = parent.document.getElementById('Form_EditForm');
\t\t\tparent.statusMessage("{$statusMessage}","{$status}");
\t\t\t{$jsErrors}
\t\t\tparent.document.getElementById('sitetree').getTreeNodeByIdx( "{$folder->ID}" ).getElementsByTagName('a')[0].className += ' contents';
\t\t\tform.getPageFromServer(form.elements.ID.value);
\t\t\t</script>
HTML;
    }
Example #5
0
	/**
	 * Set filesize maximums (in bytes).
	 * Automatically converts extensions to lowercase
	 * for easier matching.
	 * 
	 * Example: 
	 * <code>
	 * array('*' => 200, 'jpg' => 1000)
	 * </code>
	 *
	 * @deprecated 2.5 Please use Upload_Validator::setAllowedMaxFileSize() instead
	 *
	 * @param array|int $rules
	 */
	public function setAllowedMaxFileSize($rules) {
		Deprecation::notice('2.5', 'Use Upload_Validator::setAllowedMaxFileSize() instead.');
		$this->validator->setAllowedMaxFileSize($rules);
	}
 /**
  * @param ISummit $summit
  * @param $speaker_id
  * @param $tmp_file
  * @return BetterImage
  */
 public function uploadSpeakerPic(ISummit $summit, $speaker_id, $tmp_file)
 {
     $speaker_repository = $this->speaker_repository;
     return $this->tx_service->transaction(function () use($summit, $speaker_id, $tmp_file, $speaker_repository) {
         $speaker_id = intval($speaker_id);
         $speaker = $speaker_repository->getById($speaker_id);
         if (is_null($speaker)) {
             throw new NotFoundEntityException('PresentationSpeaker');
         }
         $image = new BetterImage();
         $upload = new Upload();
         $validator = new Upload_Validator();
         $validator->setAllowedExtensions(array('png', 'jpg', 'jpeg', 'gif'));
         $validator->setAllowedMaxFileSize(800 * 1024);
         // 300Kb
         $upload->setValidator($validator);
         if (!$upload->loadIntoFile($tmp_file, $image, 'profile-images')) {
             throw new EntityValidationException($upload->getErrors());
         }
         $image->write();
         return $image;
     });
 }
 /**
  * Set filesize maximums (in bytes).
  * Automatically converts extensions to lowercase
  * for easier matching.
  * 
  * Example: 
  * <code>
  * array('*' => 200, 'jpg' => 1000)
  * </code>
  *
  * @deprecated 2.5 Please use Upload_Validator::setAllowedMaxFileSize() instead
  *
  * @param array|int $rules
  */
 public function setAllowedMaxFileSize($rules)
 {
     user_error('Upload::setAllowedMaxFileSize() is deprecated. Please use Upload_Validator::setAllowedMaxFileSize() instead', E_USER_NOTICE);
     $this->validator->setAllowedMaxFileSize($rules);
 }