Exemplo n.º 1
0
 /**
  * Test that importFromStream() downloads a file from the input stream.
  */
 public function testImportFromStream()
 {
     $transit = new Transit('stream.jpg');
     $transit->setDirectory(TEMP_DIR);
     // Nothing in stream
     try {
         $transit->importFromStream();
         $this->assertTrue(false);
     } catch (Exception $e) {
         $this->assertTrue(true);
     }
 }
Exemplo n.º 2
0
 /**
  * Before saving the data, try uploading the file, if successful save to database.
  *
  * @uses Transit\Transit
  *
  * @param Model $model
  * @return bool
  */
 public function beforeSave(Model $model)
 {
     $alias = $model->alias;
     $cleanup = array();
     if (empty($model->data[$alias])) {
         return true;
     }
     // Loop through the data and upload the file
     foreach ($model->data[$alias] as $field => $file) {
         if (empty($this->settings[$alias][$field])) {
             continue;
         }
         // Gather attachment settings
         $attachment = $this->_settingsCallback($model, $this->settings[$alias][$field]);
         $data = array();
         // Initialize Transit
         $transit = new Transit($file);
         $transit->setDirectory($attachment['tempDir']);
         $this->_uploads[$alias] = $transit;
         // Set transformers and transporter
         $this->_addTransformers($model, $transit, $attachment);
         $this->_setTransporter($model, $transit, $attachment);
         // Attempt upload or import
         try {
             $overwrite = $attachment['overwrite'];
             // File upload
             if (is_array($file)) {
                 $response = $transit->upload($overwrite);
                 // Remote import
             } else {
                 if (preg_match('/^http/i', $file)) {
                     $response = $transit->importFromRemote($overwrite);
                     // Local import
                 } else {
                     if (file_exists($file)) {
                         $response = $transit->importFromLocal($overwrite);
                         // Stream import
                     } else {
                         $response = $transit->importFromStream($overwrite);
                     }
                 }
             }
             // Successful upload or import
             if ($response) {
                 $dbColumnMap = array($attachment['dbColumn']);
                 // Rename and move file
                 $data[$attachment['dbColumn']] = $this->_renameAndMove($model, $transit->getOriginalFile(), $attachment);
                 // Transform the files and save their path
                 if ($attachment['transforms']) {
                     $transit->transform();
                     $transformedFiles = $transit->getTransformedFiles();
                     $count = 0;
                     foreach ($attachment['transforms'] as $transform) {
                         if ($transform['self']) {
                             $tempFile = $transit->getOriginalFile();
                             $dbColumnMap[0] = $transform['dbColumn'];
                         } else {
                             $tempFile = $transformedFiles[$count];
                             $dbColumnMap[] = $transform['dbColumn'];
                             $count++;
                         }
                         $data[$transform['dbColumn']] = $this->_renameAndMove($model, $tempFile, $transform);
                     }
                 }
                 $metaData = $transit->getOriginalFile()->toArray();
                 // Transport the files and save their remote path
                 if ($attachment['transport']) {
                     if ($transportedFiles = $transit->transport()) {
                         foreach ($transportedFiles as $i => $transportedFile) {
                             $data[$dbColumnMap[$i]] = $transportedFile;
                         }
                     }
                 }
             }
             // Trigger form errors if validation fails
         } catch (ValidationException $e) {
             $dbColumns = array_merge(array($attachment['dbColumn']), array_keys($attachment['transforms']));
             foreach ($dbColumns as $dbCol) {
                 unset($model->data[$alias][$dbCol]);
             }
             // Allow empty uploads
             if ($attachment['allowEmpty']) {
                 if (!empty($attachment['defaultPath']) && !$model->id) {
                     $model->data[$alias][$attachment['dbColumn']] = $attachment['defaultPath'];
                 }
                 continue;
             }
             // Invalidate and stop
             $model->invalidate($field, __d('uploader', $e->getMessage()));
             if ($attachment['stopSave']) {
                 return false;
             }
             // Log exceptions that shouldn't be shown to the client
         } catch (Exception $e) {
             $model->invalidate($field, __d('uploader', 'An unknown error has occurred'));
             $this->log($e->getMessage(), LOG_DEBUG);
             // Rollback the files since it threw errors
             $transit->rollback();
             if ($attachment['stopSave']) {
                 return false;
             }
         }
         // Save file meta data
         $cleanup = $data;
         if ($attachment['metaColumns'] && $data && !empty($metaData)) {
             foreach ($attachment['metaColumns'] as $method => $column) {
                 if (isset($metaData[$method]) && $column) {
                     $data[$column] = $metaData[$method];
                 }
             }
         }
         // Merge upload data with model data
         if ($data) {
             $model->data[$alias] = $data + $model->data[$alias];
         }
     }
     // If we are doing an update, delete the previous files that are being replaced
     if ($model->id && $cleanup) {
         $this->_cleanupOldFiles($model, $cleanup);
     }
     return true;
 }
Exemplo n.º 3
0
 /**
  * Validate the field against the validation rules.
  *
  * @uses Transit\Transit
  * @uses Transit\File
  * @uses Transit\Validator\ImageValidator
  *
  * @param Model $model
  * @param array $data
  * @param string $method
  * @param array $params
  * @return bool
  * @throws UnexpectedValueException
  */
 protected function _validate(Model $model, $data, $method, array $params)
 {
     foreach ($data as $field => $value) {
         if ($this->_allowEmpty($model, $field, $value)) {
             return true;
         } else {
             if ($this->_isEmpty($value)) {
                 return false;
             }
         }
         $file = null;
         // Upload, use temp file
         if (is_array($value)) {
             $file = new File($value);
             // Import, copy file for validation
         } else {
             if (!empty($value)) {
                 $target = TMP . md5($value);
                 $transit = new Transit($value);
                 $transit->setDirectory(TMP);
                 // Already imported from previous validation
                 if (file_exists($target)) {
                     $file = new File($target);
                     // Local file
                 } else {
                     if (file_exists($value)) {
                         $file = new File($value);
                         // Attempt to copy from remote
                     } else {
                         if (preg_match('/^http/i', $value)) {
                             if ($transit->importFromRemote()) {
                                 $file = $transit->getOriginalFile();
                                 $file->rename(basename($target));
                             }
                             // Or from stream
                         } else {
                             if ($transit->importFromStream()) {
                                 $file = $transit->getOriginalFile();
                                 $file->rename(basename($target));
                             }
                         }
                     }
                 }
                 // Save temp so we can delete later
                 if ($file) {
                     $this->_tempFile = $file;
                 }
             }
         }
         if (!$file) {
             $this->log(sprintf('Invalid upload or import for validation: %s', json_encode($value)), LOG_DEBUG);
             return false;
         }
         $validator = new ImageValidator();
         $validator->setFile($file);
         return call_user_func_array(array($validator, $method), $params);
     }
     return false;
 }
Exemplo n.º 4
0
<?php

require_once 'include.php';
use Transit\Transit;
use Transit\Transformer\Image\CropTransformer;
use Transit\Transporter\Aws\S3Transporter;
use Transit\Validator\ImageValidator;
if ($_FILES) {
    $validator = new ImageValidator();
    $validator->addRule('size', 'File size is too large', 2003000);
    $transit = new Transit($_FILES['file']);
    $transit->setDirectory(__DIR__ . '/tmp/')->setValidator($validator)->setTransporter(new S3Transporter('access', 'secret', array('bucket' => '', 'region' => '')))->addTransformer(new CropTransformer(array('width' => 100)));
    try {
        if ($transit->upload()) {
            $transit->getOriginalFile()->rename(function ($name) {
                return md5($name);
            });
            if ($transit->transform()) {
                debug($transit->getAllFiles());
                debug($transit->transport());
            }
        }
    } catch (Exception $e) {
        debug($e->getMessage());
    }
}
?>

<!DOCTYPE html>
<head>
	<title>Transit - Upload</title>