/**
  * Handles an uploaded file by putting it in the $targetDir.
  * 
  * @param UploadedFile $uploadedFile File object that has been uploaded - usually taken from Request object.
  * @param string $targetDir [optional] Where to (relatively to the storage root dir) put the file?
  * @param array $allowed [optional] What files are allowed? If not matching then will throw exception.
  * @param int $maxFileSize [optional] What is the maximum allowed file size for this file?
  * @return File
  */
 public function handleUploadedFile(UploadedFile $uploadedFile, $targetDir = '/', array $allowed = array(), $maxFileSize = 0)
 {
     array_walk($allowed, function ($ext) {
         return strtolower($ext);
     });
     $targetDir = trim($targetDir, '/');
     $targetDir = $this->path . $targetDir . (empty($targetDir) ? '' : '/');
     $filenameElements = explode('.', $uploadedFile->getClientOriginalName());
     $extension = array_pop($filenameElements);
     $extension = strtolower($extension);
     $filename = implode('.', $filenameElements);
     $targetName = StringUtils::fileNameFriendly($filename . '-' . StringUtils::random() . '.' . $extension);
     $targetPath = $targetDir . $targetName;
     // create unique file name
     while (file_exists($targetPath)) {
         $targetName = StringUtils::fileNameFriendly($filename . '-' . StringUtils::random() . '.' . $extension);
         $targetPath = $targetDir . $targetName;
     }
     // basic check for allowed type
     if (!empty($allowed) && !in_array($extension, $allowed)) {
         throw new FileException('The uploaded file is not of a valid type (allowed: ' . implode(', ', $allowed) . ').');
     }
     // basic check for max allowed size
     if ($maxFileSize && $uploadedFile->getSize() > $maxFileSize) {
         throw new FileException('The uploaded file is too big (max allowed size is ' . StringUtils::bytesToString($maxFileSize) . ').');
     }
     try {
         $movedFile = $uploadedFile->move(rtrim($targetDir, '/'), $targetName);
     } catch (SfFileException $e) {
         // if exception thrown then convert it to our exception
         throw new FileException($e->getMessage(), $e->getCode());
     }
     $file = $this->convertSfFileToStorageFile($movedFile);
     return $file;
 }
Exemplo n.º 2
1
 /**
  * Orientate the image.
  *
  * @param UploadedFile $file
  * @param              $orientation
  * @return UploadedFile
  */
 protected function orientate(UploadedFile $file, $orientation)
 {
     $image = imagecreatefromjpeg($file->getRealPath());
     switch ($orientation) {
         case 2:
             imageflip($image, IMG_FLIP_HORIZONTAL);
             break;
         case 3:
             $image = imagerotate($image, 180, 0);
             break;
         case 4:
             $image = imagerotate($image, 180, 0);
             imageflip($image, IMG_FLIP_HORIZONTAL);
             break;
         case 5:
             $image = imagerotate($image, -90, 0);
             imageflip($image, IMG_FLIP_HORIZONTAL);
             break;
         case 6:
             $image = imagerotate($image, -90, 0);
             break;
         case 7:
             $image = imagerotate($image, 90, 0);
             imageflip($image, IMG_FLIP_HORIZONTAL);
             break;
         case 8:
             $image = imagerotate($image, 90, 0);
             break;
     }
     imagejpeg($image, $file->getRealPath(), 90);
     return new UploadedFile($file->getRealPath(), $file->getClientOriginalName(), $file->getMimeType(), $file->getSize());
 }
Exemplo n.º 3
1
 /**
  * {@inheritdoc}
  *
  * @param null|\Symfony\Component\HttpFoundation\File\UploadedFile $data
  */
 public function convertFieldValueFromForm($data)
 {
     if ($data === null) {
         return null;
     }
     return array("inputUri" => $data->getRealPath(), "fileName" => $data->getClientOriginalName(), "fileSize" => $data->getSize());
 }
Exemplo n.º 4
0
 public function process(UploadedFile $file)
 {
     // File extension
     $this->extension = $file->getClientOriginalExtension();
     // Mimetype for the file
     $this->mimetype = $file->getMimeType();
     // Current user or 0
     $this->user_id = Auth::user() ? Auth::user()->id : 0;
     $this->size = $file->getSize();
     list($this->path, $this->filename) = $this->upload($file);
     $this->save();
     // Check to see if image thumbnail generation is enabled
     if (static::$app['config']->get('cabinet::image_manipulation')) {
         $thumbnails = $this->generateThumbnails($this->path, $this->filename);
         $uploads = array();
         foreach ($thumbnails as $thumbnail) {
             $upload = new $this();
             $upload->filename = $thumbnail->fileSystemName;
             $upload->path = static::$app['config']->get('cabinet::upload_folder_public_path') . $this->dateFolderPath . $thumbnail->fileSystemName;
             // File extension
             $upload->extension = $thumbnail->getClientOriginalExtension();
             // Mimetype for the file
             $upload->mimetype = $thumbnail->getMimeType();
             // Current user or 0
             $upload->user_id = $this->user_id;
             $upload->size = $thumbnail->getSize();
             $upload->parent_id = $this->id;
             $upload->save();
             $uploads[] = $upload;
         }
         $this->children = $uploads;
     }
 }
Exemplo n.º 5
0
 public function testGetSize()
 {
     $file = new UploadedFile(__DIR__ . '/Fixtures/test.gif', 'original.gif', 'image/gif', filesize(__DIR__ . '/Fixtures/test.gif'), null);
     $this->assertEquals(filesize(__DIR__ . '/Fixtures/test.gif'), $file->getSize());
     $file = new UploadedFile(__DIR__ . '/Fixtures/test', 'original.gif', 'image/gif');
     $this->assertEquals(filesize(__DIR__ . '/Fixtures/test'), $file->getSize());
 }
Exemplo n.º 6
0
 public function validateMaxSize($attribute, UploadedFile $value, $parameters)
 {
     $mediaPath = public_path(config('asgard.media.config.files-path'));
     $folderSize = $this->getDirSize($mediaPath);
     preg_match('/([0-9]+)/', $folderSize, $match);
     return $match[0] + $value->getSize() < config('asgard.media.config.max-total-size');
 }
Exemplo n.º 7
0
 /**
  * converts UploadedFile to $_FILES array
  *
  * @return array
  */
 public function getFileArray()
 {
     $array = array('name' => $this->uploaded_file->getClientOriginalName(), 'type' => $this->uploaded_file->getClientMimeType(), 'tmp_name' => $this->uploaded_file->getPath() . $this->getOSDirectorySeparator() . $this->uploaded_file->getFilename(), 'error' => $this->uploaded_file->getError(), 'size' => $this->uploaded_file->getSize(), 'dimension' => array('width' => 0, 'height' => 0));
     if (preg_match('/^image/', $array['type'])) {
         list($array['dimension']['width'], $array['dimension']['height']) = getimagesize($this->uploaded_file);
     }
     return $array;
 }
 /**
  * Checks if the passed value is valid.
  *
  * @param UploadedFile   $file      The value that should be validated
  * @param Constraint     $constraint The constraint for the validation
  */
 public function validate($file, Constraint $constraint)
 {
     if (!in_array($file->getMimeType(), $this->mimeTypes)) {
         $this->context->buildViolation($constraint->messageMimeTypes)->atPath('file')->addViolation();
     }
     if ($file->getSize() > $file->getMaxFilesize()) {
         $this->context->buildViolation($constraint->messageMaxSize, array('%max_size%' => $file->getMaxFilesize()))->atPath('file')->addViolation();
     }
 }
Exemplo n.º 9
0
 /**
  * Determines if the file is too large
  * 
  * @throws Exception
  */
 private function determineFilesizeLimit()
 {
     $php_ini = ini_get('upload_max_filesize');
     $mb = str_replace('M', '', $php_ini);
     $bytes = $mb * 1048576;
     if ($this->file->getSize() > $bytes) {
         throw new \Exception('File too large');
     }
 }
Exemplo n.º 10
0
 /**
  * Setup image file
  *
  * @param UploadedFile $file
  * @param string       $style_guide
  */
 public function setupFile(UploadedFile $file, $style_guide = null)
 {
     $this->_source = $file;
     $this->setFileExtension($file->getClientOriginalExtension());
     $this->setFileNameAttribute($file->getClientOriginalName());
     $this->setMimeTypeAttribute($file->getClientMimeType());
     $this->setFileSizeAttribute($file->getSize());
     if (!empty($style_guide)) {
         $this->setStyleGuideName($style_guide);
     }
 }
Exemplo n.º 11
0
 /**
  * @param UploadedFile $uploadedFile
  * @param FileEntity   $fileEntity
  * @return bool
  */
 public function putUploadedFile(UploadedFile $uploadedFile, FileEntity $fileEntity)
 {
     list($path, $filesystem, $settings) = $this->getConfigValuesForRecordType($fileEntity->getRecordType());
     $fullPath = $path . DIRECTORY_SEPARATOR . $fileEntity->getFileName();
     $this->getFilesystem($filesystem)->putStream($fullPath, fopen($uploadedFile->getPathname(), 'r'), $settings);
     $fileEntity->setContentType($uploadedFile->getMimeType())->setSize($uploadedFile->getSize());
     /** @var EntityManager $em */
     $em = $this->container['orm.em'];
     $em->flush();
     return $fileEntity;
 }
Exemplo n.º 12
0
 /**
  * @param UploadedFile $file
  * @return Document
  */
 public function add(UploadedFile $file)
 {
     $document = new Document();
     $document->setExtension($file->guessExtension())->setMime($file->getMimeType())->setName($file->getClientOriginalName())->setSize($file->getSize());
     if (is_null($document->getExtension())) {
         $document->setExtension($file->getClientOriginalExtension());
     }
     $this->em->persist($document);
     $this->em->flush();
     $file->move($this->directory . '/' . substr($document->getId(), 0, 1), $document->getId() . '.' . $document->getExtension());
     return $document;
 }
Exemplo n.º 13
0
 /**
  * @param string $email
  * @return UploadedFile
  * @throws InvalidArgumentException
  */
 public function getFile($email)
 {
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
         throw new InvalidArgumentException();
     }
     $hash = md5(strtolower(trim($email)));
     $guzzle = new Client();
     $tempDirectory = sys_get_temp_dir();
     $guzzle->request("GET", "http://gravatar.com/avatar/" . $hash . "?d=404", [RequestOptions::SINK => $tempDirectory . '/' . $hash]);
     $file = new File($tempDirectory . '/' . $hash);
     $fileOriginalName = $hash . '.' . $file->guessExtension();
     $file = new UploadedFile($tempDirectory . '/' . $hash, $fileOriginalName, $file->getMimeType(), $file->getSize(), null, true);
     return $file;
 }
Exemplo n.º 14
0
 /**
  * @param UploadedFile $file
  * @param array        $methods
  *
  * @return mixed|void
  *
  * @throws InvalidFileTypeException
  * @throws InvalidFileException
  * @throws UploadFileNotSetException
  * @throws MaxFileSizeExceededException
  */
 public function validate(UploadedFile $file, $methods = [self::VALIDATOR_FILE_SET, self::VALIDATOR_FILE_ERRORS, self::VALIDATOR_BLOCK_FILE_TYPES, self::VALIDATOR_MAX_FILE_SIZE])
 {
     if (in_array(self::VALIDATOR_FILE_ERRORS, $methods) && $file->getError() > 0) {
         throw new InvalidFileException(sprintf('The file upload had an error("%s: %s")', $file->getError(), $file->getErrorMessage()));
     }
     if (in_array(self::VALIDATOR_FILE_SET, $methods) && $file->getFilename() == '') {
         throw new UploadFileNotSetException(sprintf('No file "%s" was set', $file->getFilename()));
     }
     if (in_array(self::VALIDATOR_BLOCK_FILE_TYPES, $methods) && in_array($file->getMimeType(), $this->blockedMimeTypes)) {
         throw new InvalidFileTypeException(sprintf('The file type "%s" was blocked', $file->getMimeType()));
     }
     if (in_array(self::VALIDATOR_MAX_FILE_SIZE, $methods) && $this->maxFileSize !== null && $file->getSize() >= $this->maxFileSize) {
         throw new MaxFileSizeExceededException(sprintf('File "%s" exceeds the configured maximum filesize of "%s"', $file->getFilename(), $this->maxFilesize));
     }
 }
Exemplo n.º 15
0
 /**
  * @param FileInterface $storageFile
  * @param UploadedFile $uploadData
  */
 public function createFromUploadedFile(FileInterface $storageFile, UploadedFile $uploadData)
 {
     $fileSystem = new Filesystem();
     $storageFile->setFileName($uploadData->getClientOriginalName());
     $storageFile->setMimeType($uploadData->getMimeType());
     $storageFile->setSize($uploadData->getSize());
     if (!$storageFile->getId()) {
         $this->save($storageFile);
     } else {
         $fileSystem->remove($this->getFilePath($storageFile));
     }
     $storageFile->setStorageId(uniqid($storageFile->getId() . '_', false));
     $uploadData->move($this->getStorageDirectory($storageFile), $storageFile->getStorageId());
     $this->save($storageFile);
 }
Exemplo n.º 16
0
 public static function upload(UploadedFile $file, $user)
 {
     $userId = $user;
     if ($user instanceof User) {
         $userId = $user->id;
     }
     $hash = md5_file($file->getPathname());
     $image = Image::whereHash($hash)->whereUploadedBy($userId)->first();
     if ($image) {
         return $image;
     }
     $image = new Image();
     try {
         $image->uploaded_by = $userId;
         $image->size = $file->getSize();
         $image->filename = $file->getClientOriginalName();
         $image->extension = $file->getClientOriginalExtension();
         $image->mime = $file->getMimeType();
         $image->hash = $hash;
         $image->save();
         $image->ensureDirectoryExists();
         foreach (self::$ImageTypes as $coverType) {
             if ($coverType['id'] === self::ORIGINAL && $image->mime === 'image/jpeg') {
                 $command = 'cp ' . $file->getPathname() . ' ' . $image->getFile($coverType['id']);
             } else {
                 // ImageMagick options reference: http://www.imagemagick.org/script/command-line-options.php
                 $command = 'convert 2>&1 "' . $file->getPathname() . '" -background white -alpha remove -alpha off -strip';
                 if ($image->mime === 'image/jpeg') {
                     $command .= ' -quality 100 -format jpeg';
                 } else {
                     $command .= ' -quality 95 -format png';
                 }
                 if (isset($coverType['width']) && isset($coverType['height'])) {
                     $command .= " -thumbnail {$coverType['width']}x{$coverType['height']}^ -gravity center -extent {$coverType['width']}x{$coverType['height']}";
                 }
                 $command .= ' "' . $image->getFile($coverType['id']) . '"';
             }
             External::execute($command);
             chmod($image->getFile($coverType['id']), 0644);
         }
         return $image;
     } catch (\Exception $e) {
         $image->delete();
         throw $e;
     }
 }
Exemplo n.º 17
0
 public function store(UploadedFile $file)
 {
     $file->getClientOriginalName();
     $fileResult = \DB::table('file')->where('name', $file->getClientOriginalName())->where('checksum', md5_file($file->getRealPath()))->first();
     if (isset($fileResult->id)) {
         return $fileResult;
     }
     $fileResult = new Models\file();
     $fileResult->name = $file->getClientOriginalName();
     $fileResult->size = $file->getSize();
     $fileResult->mime_type = $file->getMimeType();
     $fileResult->checksum = md5_file($file->getRealPath());
     $fileResult->save();
     $fileResult->path = $this->moveFile($file, $fileResult->id);
     $fileResult->save();
     return $fileResult;
 }
 public function createFromFile(UploadedFile $newMedia, SiteModel $site, UserAccountModel $user, $title = null, $sourceText = null, $sourceURL = null)
 {
     global $CONFIG;
     if ($newMedia && in_array(strtolower($newMedia->guessExtension()), MediaModel::getAllowedImageExtensions())) {
         $media = new MediaModel();
         $media->setSiteId($site->getId());
         $media->setStorageSize($newMedia->getSize());
         $media->setTitle($title);
         $media->setSourceText($sourceText);
         $media->setSourceUrl($sourceURL);
         $media->setMd5(md5_file($newMedia->getRealPath()));
         $this->create($media, $user);
         $storeDirectory = $CONFIG->fileStoreLocation . DIRECTORY_SEPARATOR . "media";
         $extension = strtolower($newMedia->guessExtension());
         $newMedia->move($storeDirectory, $media->getId() . "." . $extension);
         return $media;
     }
 }
Exemplo n.º 19
0
 public static function updateIcon(Application $app, $databox_id, $bit, $switch, UploadedFile $file)
 {
     $databox = $app->findDataboxById($databox_id);
     $statusStructure = $app['factory.status-structure']->getStructure($databox);
     if (!$statusStructure->hasStatus($bit)) {
         throw new InvalidArgumentException(sprintf('bit %s does not exists', $bit));
     }
     $status = $statusStructure->getStatus($bit);
     $switch = in_array($switch, ['on', 'off']) ? $switch : false;
     if (!$switch) {
         throw new Exception_InvalidArgument();
     }
     $url = $statusStructure->getUrl();
     $path = $statusStructure->getPath();
     if ($file->getSize() >= 65535) {
         throw new Exception_Upload_FileTooBig();
     }
     if (!$file->isValid()) {
         throw new Exception_Upload_Error();
     }
     self::deleteIcon($app, $databox_id, $bit, $switch);
     $name = "-stat_" . $bit . "_" . ($switch == 'on' ? '1' : '0') . ".gif";
     try {
         $file = $file->move($app['root.path'] . "/config/status/", $path . $name);
     } catch (FileException $e) {
         throw new Exception_Upload_CannotWriteFile();
     }
     $custom_path = $app['root.path'] . '/www/custom/status/';
     $app['filesystem']->mkdir($custom_path, 0750);
     //resize status icon 16x16px
     $imageSpec = new ImageSpecification();
     $imageSpec->setResizeMode(ImageSpecification::RESIZE_MODE_OUTBOUND);
     $imageSpec->setDimensions(16, 16);
     $filePath = sprintf("%s%s", $path, $name);
     $destPath = sprintf("%s%s", $custom_path, basename($path . $name));
     try {
         $app['media-alchemyst']->turninto($filePath, $destPath, $imageSpec);
     } catch (\MediaAlchemyst\Exception $e) {
     }
     $status['img_' . $switch] = $url . $name;
     $status['path_' . $switch] = $filePath;
     return true;
 }
Exemplo n.º 20
0
 /**
  * @param UploadedFile $uploadedFile
  * @return null|string
  */
 protected function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"')
 {
     $errMsg = '';
     if (!$uploadedFile instanceof UploadedFile) {
         $errMsg = _("No file selected");
     } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
         $errMsg = _("Larger than upload_max_filesize ") . ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
     } elseif ($uploadedFile->getClientOriginalExtension() != 'csv') {
         $errMsg = _('Invalid extension ') . $uploadedFile->getClientOriginalExtension() . ' of file ' . $uploadedFile->getClientOriginalName();
     }
     if (!empty($errMsg)) {
         return $errMsg;
     }
     /** @var LicenseCsvImport */
     $licenseCsvImport = $this->getObject('app.license_csv_import');
     $licenseCsvImport->setDelimiter($delimiter);
     $licenseCsvImport->setEnclosure($enclosure);
     return $licenseCsvImport->handleFile($uploadedFile->getRealPath());
 }
Exemplo n.º 21
0
 /**
  * Save input data to database
  */
 public function make()
 {
     // save data to db
     $this->_record->title = $this->title;
     $this->_record->text = $this->text;
     $this->_record->path = $this->path;
     $this->_record->category_id = (int) $this->categoryId;
     $this->_record->display = 0;
     // set to premoderation
     $this->_record->author_id = (int) $this->authorId;
     if ($this->_new === true) {
         $this->_record->comment_hash = $this->generateCommentHash();
     }
     $this->_record->save();
     // work with poster data
     if ($this->poster !== null) {
         // lets move poster from tmp to gallery
         $originDir = '/upload/gallery/' . $this->_record->id . '/orig/';
         $thumbDir = '/upload/gallery/' . $this->_record->id . '/thumb/';
         if (!Directory::exist($originDir)) {
             Directory::create($originDir);
         }
         if (!Directory::exist($thumbDir)) {
             Directory::create($thumbDir);
         }
         $fileName = App::$Security->simpleHash($this->poster->getClientOriginalName() . $this->poster->getSize());
         $newFullName = $fileName . '.' . $this->poster->guessExtension();
         // move poster to upload gallery directory
         $this->poster->move(Normalize::diskFullPath($originDir), $newFullName);
         // initialize image resizer
         $thumb = new Image();
         $thumb->setCacheDir(root . '/Private/Cache/images');
         // open original file, resize it and save
         $thumbSaveName = Normalize::diskFullPath($thumbDir) . '/' . $fileName . '.jpg';
         $thumb->open(Normalize::diskFullPath($originDir) . DIRECTORY_SEPARATOR . $newFullName)->cropResize($this->_configs['galleryResize'])->save($thumbSaveName, 'jpg', 90);
         $thumb = null;
         // update poster in database
         $this->_record->poster = $newFullName;
         $this->_record->save();
     }
 }
Exemplo n.º 22
0
 public function upload(UploadedFile $uploadedFile)
 {
     $this->completeFile = null;
     // pega o range-content (Content-Range: bytes 0-123/400)
     $range = $this->getContentRange();
     $rangeTotal = $range['total'];
     // pega o nome do arquivo (pode estar no Content-Disposition: attachment; filename="x")
     $originalName = $this->getContentDispositionFilename($uploadedFile->getClientOriginalName());
     if ($uploadedFile->getSize() < (int) $rangeTotal) {
         // chunk
         file_put_contents($this->path . $originalName, fopen($uploadedFile->getPathname(), 'r'), FILE_APPEND);
         $parcialFile = new File($this->path . $originalName);
         $this->completeFile = $parcialFile->getSize() < (int) $rangeTotal ? null : $parcialFile;
         return null !== $this->completeFile ? self::COMPLETE : self::PARTIAL;
     } else {
         if (is_file($this->path . $originalName)) {
             $this->completeFile = new File($this->path . $originalName);
         } else {
             $this->completeFile = $uploadedFile->move($this->path, $originalName);
         }
         return self::COMPLETE;
     }
 }
Exemplo n.º 23
0
 /**
  * @param UploadedFile $file
  *
  * @return bool
  */
 protected function validSize(UploadedFile $file) : bool
 {
     $size = $file->getSize();
     $name = e($file->getClientOriginalName());
     if ($size > $this->maxUploadSize) {
         $msg = (string) trans('validation.file_too_large', ['name' => $name]);
         $this->errors->add('attachments', $msg);
         return false;
     }
     return true;
 }
Exemplo n.º 24
0
 /**
  * Creates a PSR-7 UploadedFile instance from a Symfony one.
  *
  * @param UploadedFile $symfonyUploadedFile
  *
  * @return UploadedFileInterface
  */
 private function createUploadedFile(UploadedFile $symfonyUploadedFile)
 {
     return new DiactorosUploadedFile($symfonyUploadedFile->getRealPath(), $symfonyUploadedFile->getSize(), $symfonyUploadedFile->getError(), $symfonyUploadedFile->getClientOriginalName(), $symfonyUploadedFile->getClientMimeType());
 }
Exemplo n.º 25
0
 /**
  * upload file
  *
  * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
  * @param string                                              $path
  * @param string                                              $name
  * @param string                                              $type
  * @return array
  * @throws \browner12\uploader\UploaderException
  */
 protected function upload(UploadedFile $file, $path, $name = null, $type)
 {
     //check file size
     $this->checkSize($file->getSize());
     //check extension
     $this->checkExtension($file->getClientOriginalExtension(), $type);
     //check mime type
     $this->checkMimeType($file->getMimeType(), $type);
     //if a name is not passed, we will use the original file name
     $name = $name ?: $this->sanitizeFileName($file);
     //determine filename
     $newFilename = $name . '.' . strtolower($file->getClientOriginalExtension());
     //successful upload
     if ($file->move($path, $newFilename)) {
         //return
         return ['id' => $name, 'name' => $newFilename, 'size' => $file->getClientSize(), 'mime_type' => $file->getClientMimeType(), 'extension' => $file->getClientOriginalExtension(), 'original_name' => $file->getClientOriginalName(), 'url' => $path . $newFilename];
     }
     //failed upload
     throw new UploaderException('Could not upload ' . $type . $file->getClientOriginalName() . '.');
 }
Exemplo n.º 26
0
 /**
  * Check if the given file is valid.
  *
  * @param  \Symfony\Component\HttpFoundation\File\UploadedFile  $file
  * @return bool
  * @throws \Cartalyst\Filesystem\Exceptions\MaxFileSizeExceededException
  * @throws \Cartalyst\Filesystem\Exceptions\InvalidMimeTypeException
  */
 public function validateFile(UploadedFile $file)
 {
     // Get the filesystem manager
     $manager = $this->getManager();
     // Get all the allowed mime types
     $allowedMimes = $manager->getAllowedMimes();
     // Validate the file size
     if ($file->getSize() > $manager->getMaxFileSize()) {
         throw new MaxFileSizeExceededException();
     }
     // Validate the file mime type
     if (!empty($allowedMimes) && !in_array($file->getClientMimeType(), $allowedMimes)) {
         throw new InvalidMimeTypeException();
     }
     return true;
 }
Exemplo n.º 27
0
    /**
     * Extract the file information from the uploaded file, into the internal properties
     */
    private function setFileInfo()
    {
        if ($this->file === null) {
            return;
        }

        if ($this->file instanceof \Symfony\Component\HttpFoundation\File\UploadedFile) {
            //load file information
            $fileInfo  = pathinfo($this->file->getClientOriginalName());
            $extension = $fileInfo['extension'];
            $name      = $fileInfo['filename'];

        } else {
            $extension = $this->file->guessExtension();
            $name      = $this->file->getBasename();
        }

        //set the file type using the type mapping
        if (array_key_exists(strtolower($extension), $this->typeMapping)) {
            $this->type = $this->typeMapping[strtolower($extension)];
        } else {
            $this->type = self::TYPE_UNKNOWN;
        }

        // The filesize in bytes.
        $this->fileSize  = $this->file->getSize();
        $this->name      = $this->removeSpecialCharacters($name);
        $this->extension = $extension;
        $this->path = str_replace(Shopware()->OldPath(), '', $this->getUploadDir() . $this->getFileName());

        if (DIRECTORY_SEPARATOR !== '/') {
            $this->path = str_replace(DIRECTORY_SEPARATOR, '/', $this->path);
        }
    }
Exemplo n.º 28
0
 /**
  * Set file info from uploading file
  *
  * @param UploadedFile $file
  * @return $this
  */
 public function uploading(UploadedFile $file)
 {
     $this->setMime($file->getMimeType());
     $this->file->extension = $file->getClientOriginalExtension();
     $this->setName(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
     $this->file->bytes = $file->getSize();
     $this->file->updated_at = date('Y-m-d H:i:s');
     $this->setFileThumb(true);
     return $this;
 }
Exemplo n.º 29
0
 /**
  * Returns an array of data for upload model
  *
  * @param UploadedFile $uploadedFile
  * @return array
  */
 protected function prepareUploadData(UploadedFile $uploadedFile)
 {
     return ['extension' => $uploadedFile->getExtension(), 'mimetype' => $uploadedFile->getMimeType(), 'size' => $uploadedFile->getSize(), 'name' => $uploadedFile->getBasename('.' . $uploadedFile->getExtension())];
 }
Exemplo n.º 30
-1
 /**
  * Upload provided file and create matching FileRecord object
  *
  * @param UploadedFile $file
  * @param $clientIp
  * @return FileRecord
  */
 public function uploadFile(UploadedFile $file, $clientIp)
 {
     $extension = Str::lower($file->getClientOriginalExtension());
     $generatedName = $this->generateName($extension);
     // Create SHA-256 hash of file
     $fileHash = hash_file('sha256', $file->getPathname());
     // Check if file already exists
     $existingFile = FileRecord::where('hash', '=', $fileHash)->first();
     if ($existingFile) {
         return $existingFile;
     }
     // Query previous scans in VirusTotal for this file
     if (config('virustotal.enabled') === true) {
         $this->checkVirusTotalForHash($fileHash);
     }
     // Get filesize
     $filesize = $file->getSize();
     // Check max upload size
     $maxUploadSize = config('upload.max_size');
     if ($filesize > $maxUploadSize) {
         throw new MaxUploadSizeException();
     }
     // Move the file
     $uploadDirectory = config('upload.directory');
     $file->move($uploadDirectory, $generatedName);
     // Create the record
     /** @var FileRecord $record */
     $record = FileRecord::create(['client_name' => $file->getClientOriginalName(), 'generated_name' => $generatedName, 'filesize' => $filesize, 'hash' => $fileHash, 'uploaded_by_ip' => $clientIp]);
     return $record;
 }