Ejemplo n.º 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;
 }
Ejemplo n.º 2
0
 public function validate($validator)
 {
     if (!isset($_FILES[$this->name])) {
         return true;
     }
     $tmpFile = $_FILES[$this->name];
     $valid = $this->upload->validate($tmpFile);
     if (!$valid) {
         $errors = $this->upload->getErrors();
         if ($errors) {
             foreach ($errors as $error) {
                 $validator->validationError($this->name, $error, "validation", false);
             }
         }
         return false;
     }
     return true;
 }
Ejemplo n.º 3
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;
    }
Ejemplo n.º 4
0
 public function copyFiles($settings, $gid)
 {
     //Допустимые типы
     $validTypes = array('image/jpg', 'image/jpeg', 'image/gif', 'image/wbmp');
     //Поле с которого происходит выбор файлов
     Upload::$index = 'images';
     //Максимальный размер в кб
     Upload::$size = 15000;
     //Передача типов в класс
     Upload::validType($validTypes);
     //Проверка валидности файлов
     $files = Upload::validate();
     //Загрузка во временную директорию
     $result = Upload::uploadFiles($files, 'tmp', true);
     Bufer::add(array('result' => $result));
     $dir_galery_pic = 'uploads/images/galery/' . $gid . '/pic';
     $dir_galery_thumb = 'uploads/images/galery/' . $gid . '/thumb';
     //Если есть файлы, прошедшие проверку
     if (!empty($result['valid'])) {
         foreach ($result['valid'] as $file) {
             $image = $file['hashname'] . '.' . $file['ext'];
             $preview_w = $settings['preview_w'];
             $preview_h = $settings['preview_h'];
             $quality = isset($settings['quality']) ? $settings['quality'] : 100;
             $imageInfo = getimagesize($file['fullpath'], $quality);
             $img = new Images($file['fullpath']);
             $resizeThumb = $img->resize($preview_w, $preview_h, $dir_galery_thumb, $image);
             $width = isset($settings['resize_w']) ? $settings['resize_w'] : $imageInfo[0];
             $height = isset($settings['resize_h']) ? $settings['resize_h'] : $imageInfo[1];
             $img = new Images($file['fullpath']);
             $resizeBig = $img->resize($width, $height, $dir_galery_pic, $image);
             if (isset($settings['watermark_text'])) {
                 $alfa = $settings['water_set']['fontAlpha'];
                 $position = $settings['water_set']['position'];
                 $align = $settings['water_set']['align'];
                 $font = $settings['water_set']['fontFamily'];
                 $size = $settings['water_set']['fontSize'];
                 $color = $settings['water_set']['fontColor'];
                 $margin = $settings['water_set']['margin'];
                 $text = $settings['watermark_text'];
                 $img = new Images($dir_galery_pic . '/' . $image);
                 $img->waterSettings(array('fontAlpha' => $alfa, 'fontSize' => $size, 'fontFamily' => $font, 'fontColor' => $color, 'position' => $position, 'align' => $align, 'margin' => 10));
                 $arrInfo = $img->waterMarkText($text, $dir_galery_pic, false);
             }
             if (isset($settings['watermark_image'])) {
                 $alfa = $settings['water_set']['imgAlpha'];
                 $position = $settings['water_set']['position'];
                 $align = $settings['water_set']['align'];
                 $margin = $settings['water_set']['margin'];
                 $image = $settings['watermark_image'];
                 $img = new Images($dir_galery_pic . '/' . $image);
                 $img->waterSettings(array('imgAlpha' => $alfa, 'position' => $position, 'align' => $align, 'margin' => 10));
                 $arrInfo = $img->waterMarkImg($image, $dir_galery, false);
             }
             $images[] = array('pic' => $dir_galery_pic . '/' . $image, 'thumb' => $dir_galery_thumb . '/' . $image);
             Upload::deleteFile($file['fullpath']);
         }
     }
     if (isset($images) && isset($gid)) {
         $result = $this->addImagesOnDb($gid, $images);
     }
 }
Ejemplo n.º 5
0
 /**
  * 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
     }
 }
Ejemplo n.º 6
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)
    {
        foreach ($data['Files'] as $param => $files) {
            if (!is_array($files)) {
                $files = array($files);
            }
            foreach ($files as $key => $value) {
                $processedFiles[$key][$param] = $value;
            }
        }
        if ($data['ID'] && $data['ID'] != 'root') {
            $folder = DataObject::get_by_id("Folder", $data['ID']);
        } else {
            $folder = singleton('Folder');
        }
        $newFiles = array();
        $fileSizeWarnings = '';
        $uploadErrors = '';
        $jsErrors = '';
        $status = '';
        $statusMessage = '';
        foreach ($processedFiles as $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 (!self::$apply_restrictions_to_admin && Permission::check('ADMIN')) {
                    $valid = true;
                } else {
                    $upload = new Upload();
                    $upload->setAllowedExtensions(self::$allowed_extensions);
                    $upload->setAllowedMaxFileSize(self::$allowed_max_file_size);
                    $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) {
                    $newFiles[] = $folder->addUploadToFolder($tmpFile);
                }
            }
        }
        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 = "";
            }
        }
        $fileIDs = array();
        $fileNames = array();
        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;
        }
        $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\tform.getPageFromServer(form.elements.ID.value);
\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\t</script>
HTML;
    }