/** * 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; }
function getCMSFields() { $image = new CustomUploadField('Thumbnail', 'Thumbnail'); //save to path marketing/case_study $image->setFolderName('marketing/case_study'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); return new FieldList(new TextField('Name'), new TextField('Tagline'), new TextField('Link'), $image); }
function getCMSFields() { $fields = new FieldList(); $image = new CustomUploadField('Thumbnail', 'Thumbnail'); $image->setFolderName('marketing/youtube_vids_thumbs'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push(new TextField('Url')); $fields->push($image); }
function getCMSFields() { $attach = new CustomUploadField('Attachment', 'File'); $attach->setFolderName('marketing/graphics'); $image = new CustomUploadField('Thumbnail', 'Thumbnail'); $image->setFolderName('marketing/graphics'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); return new FieldList(new TextField('Name'), $image, $attach); }
function getCMSFields() { $fields = new FieldList(); $image = new CustomUploadField('Image', 'Image'); $image->setFolderName('marketing/section_link'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push(new TextField('Link')); $fields->push($image); return $fields; }
function getCMSFields() { $fields = new FieldList(); $image = new CustomUploadField('Thumbnail', 'Thumbnail'); $image->setFolderName('assets/vid_thumbs'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push(new TextField('YoutubeID', 'YouTube ID')); $fields->push(new TextField('Caption')); $fields->push($image); return $fields; }
function getCMSFields() { $fields = new FieldList(); $files = new GridField('Files', 'Create/Edit File', $this->Files(), GridFieldConfig_RecordEditor::create(10)); $files->getConfig()->getComponentByType('GridFieldDataColumns')->setDisplayFields(array('Name' => 'FileName', 'SmallPreview' => 'Thumbnail')); $image = new CustomUploadField('Thumbnail', 'Thumbnail'); $image->setFolderName('marketing/graphics'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push(new TextField('Name')); $fields->push($image); if ($this->ID > 0) { $fields->push($files); } return $fields; }
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()); }
function getCMSFields() { $fields = new FieldList(); $fields->push(new TextField('Title', 'Title')); $fields->push($description = new HtmlEditorField('Description')); $description->setRows(5); $fields->push(new TextField('ButtonLink', 'Button Link')); $fields->push(new TextField('ButtonLabel', 'Button Label')); $fields->push(new TextField('SortOrder', 'Sort Order')); $image = new CustomUploadField('Image', 'Image'); $image->setFolderName('marketing'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push($image); $fields->push(new HiddenField('ParentPageID', 'ParentPageID')); return $fields; }
public function validate() { $res = parent::validate(); // width validation if (!$this->isValidWidth()) { $this->errors[] = sprintf("Max. Allowed Image Width is %d px", $this->allowedMaxImageWidth); $res = false; } return $res; }
public function __construct($controller, $name, $fields = null, $actions = null) { $fields = new FieldList($Version = BootstrapSemVerField::create('Version')->setTitle(_t('BoxVersion.VERSION', 'BoxVersion.VERSION')), $Description = TextareaField::create('Description')->setTitle(_t('Box.DESCRIPTION', 'Box.DESCRIPTION')), $File = new BootstrapUploadField('File', _t('Box.FILE', 'Box.FILE')), $BoxID = HiddenField::create('BoxID')); $actions = new FieldList($Submit = BootstrapLoadingFormAction::create('doAdd')->setTitle(_t('BoxAddForm.DOADD', 'BoxAddForm.DOADD'))); parent::__construct($controller, $name, $fields, $actions, new RequiredFields("Version", "Description", "File", "BoxID")); if (isset($GLOBALS['BoxID'])) { $Box = Box::get()->byID($GLOBALS['BoxID']); $BoxID->setValue($Box->ID); $Description->setValue($Box->Description); $File->setFolderName("Uploads/Boxes/" . $Box->Slug); } // Upload Parameters $exts = array('box'); $validator = new Upload_Validator(); $validator->setAllowedExtensions($exts); //$validator->setAllowedMaxFileSize(5000000); $upload = Upload::create(); $upload->setValidator($validator); $File->setUpload($upload); $this->loadDataFrom(singleton('BoxProvider')); }
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()); }
function getCMSFields() { $fields = new FieldList(); $fields->push(new TextField('Name', 'Name')); $fields->push($description = new HtmlEditorField('Description')); $description->setRows(5); $fields->push(new TextField('ReleaseLink', 'Release Link')); $fields->push(new TextField('SortOrder', 'Sort Order')); $fields->push(new TextField('YoutubeID', 'YouTube ID for video Link')); //$fields->merge($this->Video()->getCMSFields()); $image = new CustomUploadField('Logo', 'Logo'); $image->setFolderName('marketing'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push($image); $presentation = new UploadField('Presentation', 'Presentation'); $presentation->setFolderName('marketing'); $fields->push($presentation); $fields->push(new HiddenField('ParentPageID', 'ParentPageID')); return $fields; }
function getCMSFields() { $fields = new FieldList(); $fields->push(new TextField('Name', 'Name')); $fields->push(new CheckboxField('ShowGlobe', 'Show Globe')); $fields->push($description = new HtmlEditorField('Description')); $description->setRows(5); $fields->push(new TextField('SortOrder', 'Sort Order')); $image = new CustomUploadField('Image', 'Image'); $image->setFolderName('marketing'); $image->setAllowedFileCategories('image'); $image_validator = new Upload_Validator(); $image_validator->setAllowedExtensions(array('jpg', 'png', 'jpeg')); $image->setValidator($image_validator); $fields->push($image); $files = new UploadField('CollateralFiles', 'Files', $this->CollateralFiles()); $files->setFolderName('marketing'); $fields->push($files); $config = new GridFieldConfig_RecordEditor(3); $config->addComponent(new GridFieldSortableRows('SortOrder')); $fields->push(new GridField('CollateralLinks', 'CollateralLinks', $this->CollateralLinks(), $config)); $fields->push(new HiddenField('ParentPageID', 'ParentPageID')); return $fields; }
/** * Handles media objects from kapost * @param {mixed} $blog_id Site Config related to this content object * @param {array} $content Content object to be handled * @return {xmlrpcresp} XML-RPC Response object */ protected function newMediaObject($blog_id, $content) { $fileName = $content['name']; $validator = new Upload_Validator(array('name' => $fileName)); $validator->setAllowedExtensions(File::config()->allowed_extensions); //Verify we have a valid extension if ($validator->isValidExtension() == false) { return $this->httpError(403, _t('KapostService.FILE_NOT_ALLOWED', '_File extension is not allowed')); } //Generate default filename $nameFilter = FileNameFilter::create(); $file = $nameFilter->filter($fileName); while ($file[0] == '_' || $file[0] == '.') { $file = substr($file, 1); } $doubleBarrelledExts = array('.gz', '.bz', '.bz2'); $ext = ""; if (preg_match('/^(.*)(\\.[^.]+)$/', $file, $matches)) { $file = $matches[1]; $ext = $matches[2]; // Special case for double-barrelled if (in_array($ext, $doubleBarrelledExts) && preg_match('/^(.*)(\\.[^.]+)$/', $file, $matches)) { $file = $matches[1]; $ext = $matches[2] . $ext; } } $origFile = $file; //Find the kapost media folder $kapostMediaFolder = Folder::find_or_make($this->config()->kapost_media_folder); if (file_exists($kapostMediaFolder->getFullPath() . '/' . $file . $ext)) { if (self::config()->duplicate_assets == 'overwrite') { $obj = File::get()->filter('Filename', Convert::raw2sql($kapostMediaFolder->Filename . $file . $ext))->first(); if (!empty($obj) && $obj !== false && $obj->ID > 0) { //Update the Title for the image $obj->Title = !empty($content['alt']) ? $content['alt'] : str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $obj->Name)); $obj->write(); //Write the file to the file system $f = fopen($kapostMediaFolder->getFullPath() . '/' . $file . $ext, 'w'); fwrite($f, $content['bits']); fclose($f); return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL()); } return $this->httpError(404, _t('KapostService.FILE_NOT_FOUND', '_File not found')); } else { if (self::config()->duplicate_assets == 'ignore') { return $this->httpError(409, _t('KapostService.DUPLICATE_FILE', '_Duplicate file detected, please rename the file and try again')); } else { if (self::config()->duplicate_assets == 'smart_rename' && file_exists($kapostMediaFolder->getFullPath() . '/' . $file . $ext)) { $obj = File::get()->filter('Filename', Convert::raw2sql($kapostMediaFolder->Filename . $file . $ext))->first(); if (!empty($obj) && $obj !== false && $obj->ID > 0) { $fileHash = sha1_file($kapostMediaFolder->getFullPath() . '/' . $file . $ext); if ($fileHash == sha1($content['bits'])) { return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL()); } } } $i = 1; while (file_exists($kapostMediaFolder->getFullPath() . '/' . $file . $ext)) { $i++; $oldFile = $file; if (strpos($file, '.') !== false) { $file = preg_replace('/[0-9]*(\\.[^.]+$)/', $i . '\\1', $file); } else { if (strpos($file, '_') !== false) { $file = preg_replace('/_([^_]+$)/', '_' . $i, $file); } else { $file .= '_' . $i; } } if ($oldFile == $file && $i > 2) { return $this->httpError(500, _t('KapostService.FILE_RENAME_FAIL', '_Could not fix {filename} with {attempts} attempts', array('filename' => $file . $ext, 'attempts' => $i))); } } //Write the file to the file system $f = fopen($kapostMediaFolder->getFullPath() . '/' . $file . $ext, 'w'); fwrite($f, $content['bits']); fclose($f); //Write the file to the database $className = File::get_class_for_file_extension(substr($ext, 1)); $obj = new $className(); $obj->Name = $file . $ext; $obj->Title = !empty($content['alt']) ? $content['alt'] : str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $obj->Name)); $obj->FileName = $kapostMediaFolder->getRelativePath() . '/' . $file . $ext; $obj->ParentID = $kapostMediaFolder->ID; //If subsites is enabled add it to the correct subsite if (File::has_extension('FileSubsites')) { $obj->SubsiteID = $blog_id; } $obj->write(); $this->extend('updateNewMediaAsset', $blog_id, $content, $obj); return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL()); } } } else { //Write the file to the file system $f = fopen($kapostMediaFolder->getFullPath() . '/' . $file . $ext, 'w'); fwrite($f, $content['bits']); fclose($f); //Write the file to the database $className = File::get_class_for_file_extension(substr($ext, 1)); $obj = new $className(); $obj->Name = $file . $ext; $obj->Title = !empty($content['alt']) ? $content['alt'] : str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $obj->Name)); $obj->FileName = $kapostMediaFolder->getRelativePath() . '/' . $file . $ext; $obj->ParentID = $kapostMediaFolder->ID; //If subsites is enabled add it to the correct subsite if (File::has_extension('FileSubsites')) { $obj->SubsiteID = $blog_id; } $obj->write(); $this->extend('updateNewMediaAsset', $blog_id, $content, $obj); return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL()); } }
/** * Determines if the temporary file has a valid extension * * @deprecated 2.5 Please use Upload_Validator::isValidExtension() instead * * @param array $tmpFile * @return boolean */ public function isValidExtension($tmpFile) { user_error('Upload::isValidExtension() is deprecated. Please use Upload_Validator::isValidExtension() instead', E_USER_NOTICE); $validator = new Upload_Validator(); $validator->setTmpFile($tmpFile); return $validator->isValidExtension(); }
/** * 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; }
public function validate() { if (parent::validate() === false) { return false; } try { $result = $this->isValidMime(); if ($result === false) { $this->errors[] = _t('File.INVALIDMIME', 'File extension does not match known MIME type'); return false; } } catch (MimeUploadValidator_Exception $e) { $this->errors[] = _t('File.FAILEDMIMECHECK', 'MIME validation failed: {message}', 'Argument 1: Message about why MIME type detection failed', array('message' => $e->getMessage())); return false; } return true; }
/** * @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; }); }
/** * The main upload handler. Takes the $_FILES data from the request and stores a File * record {@see $defaults['file_class']}. Returns the ID of this new file to the * Javascript handler, for insertion into the parent form. * Note: This handler may require authentication, and that may not be possible * if the PHP setting "session_use_only_cookies" is on. * * @return int */ public function upload() { if (isset($_FILES["Filedata"]) && is_uploaded_file($_FILES["Filedata"]["tmp_name"])) { $upload_folder = $this->getUploadFolder(); if ($this->Backend()) { if (isset($_REQUEST['FolderID'])) { if ($folder = DataObject::get_by_id("Folder", Convert::raw2sql($_REQUEST['FolderID']))) { $upload_folder = self::relative_asset_dir($folder->Filename); } } } $ext = strtolower(end(explode('.', $_FILES['Filedata']['name']))); $class = in_array($ext, self::$image_extensions) ? $this->getSetting('image_class') : $this->getSetting('file_class'); $file = new $class(); // Perform check on allowed file extension, preventing upload of unallowed file types $u = new Upload(); $u->setValidator($validator = new Upload_Validator()); $validator->setAllowedExtensions(File::$allowed_extensions); if ($u->validate($_FILES['Filedata'])) { $u->loadIntoFile($_FILES['Filedata'], $file, $upload_folder); } else { return _t('Uploadify.FILETYPENOTALLOWED', 'File type not allowed!'); } $file->write(); if (method_exists($file, 'onAfterUpload')) { $file->onAfterUpload(); } echo $file->ID; } else { echo ' '; // return something or SWFUpload won't fire uploadSuccess } }
/** * Determines if the temporary file has a valid extension * * @deprecated 2.5 Please use Upload_Validator::isValidExtension() instead * * @param array $tmpFile * @return boolean */ public function isValidExtension($tmpFile) { Deprecation::notice('2.5', 'Use Upload_Validator::isValidExtension() instead.'); $validator = new Upload_Validator(); $validator->setTmpFile($tmpFile); return $validator->isValidExtension(); }
/** * Clear out all errors (mostly set by {loadUploaded()}) * including the validator's errors */ public function clearErrors() { $this->errors = array(); $this->validator->clearErrors(); }