Exemplo n.º 1
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.º 2
0
 public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath, $fileName)
 {
     $originalName = $file->getFilename();
     // use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
     // $relativePath = date('Y-m', filemtime($file->getPath()));
     $targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
     $targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
     $ext = $file->getExtension();
     $i = 1;
     while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
         if ($ext) {
             $prev = $i == 1 ? "" : $i;
             $targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
         } else {
             $targetFilePath = $targetFilePath . $i++;
         }
     }
     $targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
     if (!is_dir($targetDir)) {
         $ret = mkdir($targetDir, umask(), true);
         if (!$ret) {
             throw new \RuntimeException("Could not create target directory to move temporary file into.");
         }
     }
     //$file->move($targetDir, basename($targetFilePath));
     //$file->move($targetDir, basename($fileName.'.'.$ext));
     $file->move($targetDir, basename($fileName));
     return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
 }
Exemplo n.º 3
0
 public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath)
 {
     $originalName = $file->getFilename() . '.' . $file->guessExtension();
     $targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
     $targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
     $ext = $file->getExtension();
     $i = 1;
     while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
         if ($ext) {
             $prev = $i == 1 ? "" : $i;
             $targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
         } else {
             $targetFilePath = $targetFilePath . $i++;
         }
     }
     $targetDir = 'uploads';
     if (!is_dir($targetDir)) {
         $ret = mkdir($targetDir, 777, true);
         if (!$ret) {
             throw new \RuntimeException("Could not create target directory to move temporary file into.");
         }
     }
     $file->move($targetDir, basename($targetFilePath));
     return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
 }
Exemplo n.º 4
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;
 }
Exemplo n.º 5
0
 /**
  * Move an uploaded file from the /tmp directory of the local filesystem
  * to the configured location
  *
  * @param Symfony\Component\HttpFoundation\File\UploadedFile $file 
  * @return string $url A URL to to the file, resolveable in HTML
  */
 public function moveUpload(UploadedFile $file)
 {
     // Nest the uploaded file into unique sub directory and a unqiue name
     $path = $this->makeNestedAndUniquePath($file->getClientOriginalName());
     // Move the uploaded file to the destination using Flysystem and return
     // the new path
     $this->manager->move('tmp://' . $file->getFilename(), 'disk://' . $path);
     // Return the URL of the upload.
     return $this->helpers->url($path);
 }
Exemplo n.º 6
0
 /**
  * 保存一个图片到指定目录
  *
  * @param \Symfony\Component\HttpFoundation\File\UploadedFile|array $img
  * @param string $folder
  * @param int $width
  * @param int $height
  * @return string
  *
  * @throws FileException if, for any reason, the dictionary could not be created
  */
 public static function saveImg($img, $folder, $width = 300, $height = 270)
 {
     $clientName = $img->getClientOriginalName();
     $tmpName = $img->getFilename();
     $realPath = $img->getRealPath();
     $extension = $img->getClientOriginalExtension();
     $mimeType = $img->getMimeType();
     $newName = md5(date('ymdhis') . $clientName) . "." . $extension;
     // 目录不存在,创建之
     if (!is_dir($folder)) {
         if (false === @mkdir($folder, 0777, true) && !is_dir($folder)) {
             throw new FileException(sprintf('Unable to create the "%s" directory', $folder));
         }
     } elseif (!is_writable($folder)) {
         throw new FileException(sprintf('Unable to write in the "%s" directory', $folder));
     }
     // resizing an uploaded file,这样会创建一张新的图片
     Image::make($img)->fit($width, $height)->save($folder . '/' . $newName);
     return $newName;
 }
Exemplo n.º 7
0
 /**
  * Helper function to decompress zip files.
  * @param UploadedFile $file
  * @param $targetDirectory
  * @throws Exception
  */
 private function unzip(UploadedFile $file, $targetDirectory)
 {
     $filter = new \Zend_Filter_Decompress(array('adapter' => $file->getClientOriginalExtension(), 'options' => array('target' => $targetDirectory)));
     $filter->filter($file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename());
 }
Exemplo n.º 8
0
 /**
  * Get the new filename of file.
  *
  * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
  * @param array                                               $config
  *
  * @return string
  */
 protected function getFilename(UploadedFile $file, array $config)
 {
     $ext = '.' . ($file->getClientOriginalExtension() ?: $file->guessClientExtension());
     return str_finish($this->formatPath($config['path_format']), '/') . md5($file->getFilename()) . $ext;
 }
Exemplo n.º 9
0
 /**
  * @param UploadedFile $uploadedFile
  * @param string       $directory
  *
  * @return File|bool
  */
 public function createFromUploadedFile(UploadedFile $uploadedFile, $directory)
 {
     $file = File::createFromExistingFile($uploadedFile->getFilename(), $uploadedFile->getClientOriginalName(), $this->createDirs($uploadedFile->getFilename() . $uploadedFile->getClientOriginalName(), $directory));
     $movedFile = $uploadedFile->move($this->rootPath . $file->getDirectories(), $uploadedFile->getFilename());
     return $movedFile ? $file : false;
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function path()
 {
     return $this->source->getPath() . '/' . $this->source->getFilename();
 }
 public function put(UploadedFile $file, $whereToPut)
 {
     $this->file->move($file->getRealPath(), $whereToPut . "/" . $file->getFilename());
 }
 /**
  * Crea la miniatura de imagenes
  * @param UploadedFile $file 
  * @param string $path 
  * @return string Nombre del nuevo archivo
  */
 public function createThumb($file, $path)
 {
     $ext = $file->getExtension();
     $search = $this->config["images"]["images_ext"];
     if (array_search($ext, $search) !== false) {
         $fullpath = $this->getFullPath() . $path;
         $fullpaththumb = $this->getFullPath() . '/_thumbs' . $path;
         $filename = $file->getFilename();
         $filename_new = $this->removeExtension($filename) . '-' . $this->config['images']['resize']['thumbWidth'] . 'x' . $this->config['images']['resize']['thumbHeight'] . '.' . $file->getExtension();
         $fullpaththumb_name = $this->getFullPath() . '/_thumbs' . $path . $filename_new;
         if ($this->config['debug']) {
             $this->_log(__METHOD__ . " - {$fullpaththumb}");
         }
         $filethumb = new Filesystem();
         if ($filethumb->exists($fullpaththumb_name) == false) {
             if ($this->config['debug']) {
                 $this->_log(__METHOD__ . " - " . $fullpaththumb_name);
             }
             if ($filethumb->exists($fullpaththumb) == false) {
                 $filethumb->mkdir($fullpaththumb);
             }
             Imagen::open($fullpath . $file->getFilename())->zoomCrop($this->config['images']['resize']['thumbWidth'], $this->config['images']['resize']['thumbHeight'])->save($fullpaththumb_name);
         }
         return $filename_new;
     } else {
         if ($this->config['debug']) {
             $this->_log(__METHOD__ . " - {$ext}");
         }
     }
 }
Exemplo n.º 13
0
 /**
  * @param UploadedFile $fileObject
  * @return array
  */
 private function getExifReadData(UploadedFile $fileObject)
 {
     Log::debug($fileObject->getPath());
     Log::debug($fileObject->getFilename());
     Log::debug($fileObject->getBasename());
     Log::debug($fileObject->getClientMimeType());
     Log::debug($fileObject->getExtension());
     Log::debug($fileObject->getType());
     $result = [];
     $mimeType = $fileObject->getClientMimeType();
     // upload_igm and thumbnail directory make
     $dirName = date('Ym');
     $uploadDir = public_path() . '/upload_img/' . $dirName;
     $thumbnailDir = public_path() . '/thumbnail/' . $dirName;
     $this->chkDir($uploadDir);
     $this->chkDir($thumbnailDir);
     //@todo オリジナル動画をリサイズする
     $extension = explode('/', $fileObject->getClientMimeType())[1];
     $newFileName = sha1($fileObject->getFilename() . time()) . '.' . $extension;
     $saveFileName = $uploadDir . '/' . $newFileName;
     $fileObject->move($uploadDir, $newFileName);
     $thumbnail = Image::make(file_get_contents($saveFileName));
     $thumbnail->resize(100, null, function ($constraint) {
         $constraint->aspectRatio();
     });
     $thumbnail->save($thumbnailDir . '/' . $newFileName, 100);
     $result['file_name'] = $dirName . '/' . $newFileName;
     if ($mimeType !== 'image/jpeg') {
         return $result;
     }
     $exif = exif_read_data($saveFileName);
     if ($exif === false) {
         return false;
     }
     $result['file_date_time'] = isset($exif['DateTimeOriginal']) ? $exif['DateTimeOriginal'] : null;
     $result['file_size'] = $exif['FileSize'];
     $result['mime_type'] = $exif['MimeType'];
     $result['width'] = $exif['COMPUTED']['Width'];
     $result['height'] = $exif['COMPUTED']['Height'];
     $result['make'] = isset($exif['Make']) ? $exif['Make'] : null;
     $result['model'] = isset($exif['Model']) ? $exif['Model'] : null;
     $result['orientation'] = isset($exif['Orientation']) ? $exif['Orientation'] : null;
     if (isset($exif["GPSLatitude"])) {
         //緯度を60進数から10進数に変換
         $lat = $this->convert_float($exif["GPSLatitude"][0]) + $this->convert_float($exif["GPSLatitude"][1]) / 60 + $this->convert_float($exif["GPSLatitude"][2]) / 3600;
         //南緯の場合はマイナスにする
         if ($exif["GPSLatitudeRef"] == "S") {
             $lat *= -1;
         }
         //経度を60進数から10進数に変換
         $lng = $this->convert_float($exif["GPSLongitude"][0]) + $this->convert_float($exif["GPSLongitude"][1]) / 60 + $this->convert_float($exif["GPSLongitude"][2]) / 3600;
         //西経の場合はマイナスにする
         if ($exif["GPSLongitudeRef"] == "W") {
             $lng *= -1;
         }
         $result['lat'] = $lat;
         $result['lng'] = $lng;
     }
     return $result;
 }
Exemplo n.º 14
0
 /**
  * Get the name of the file
  *
  * @param UploadedFile|File|string $file
  * @return string
  */
 protected function getFileName($file)
 {
     if ($file instanceof UploadedFile) {
         return $file->getClientOriginalName();
     } elseif ($file instanceof File) {
         return $file->getFilename();
     } else {
         return basename($file);
     }
 }
Exemplo n.º 15
0
 /**
  * Extracts a file's tags.
  *
  * @param UploadedFile $file
  * @param User $artist
  * @param string $audioCodec
  * @return array the "processed" and raw tags extracted from the file
  * @throws \Exception
  */
 protected function parseOriginalTags(UploadedFile $file, User $artist, string $audioCodec)
 {
     //==========================================================================================================
     // Extract the original tags.
     //==========================================================================================================
     $getId3 = new getID3();
     // all tags read by getID3, including the cover art
     $allTags = $getId3->analyze($file->getPathname());
     // tags specific to a file format (ID3 or Atom), pre-normalization but with cover art removed
     $rawTags = [];
     // normalized tags used by Pony.fm
     $parsedTags = [];
     if ($audioCodec === 'mp3') {
         list($parsedTags, $rawTags) = $this->getId3Tags($allTags);
     } elseif (Str::startsWith($audioCodec, 'aac')) {
         list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
     } elseif ($audioCodec === 'vorbis') {
         list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
     } elseif ($audioCodec === 'flac') {
         list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
     } elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) {
         list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
     }
     //==========================================================================================================
     // Fill in the title tag if it's missing
     //==========================================================================================================
     $parsedTags['title'] = $parsedTags['title'] ?? pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
     //==========================================================================================================
     // Determine the release date.
     //==========================================================================================================
     if ($parsedTags['release_date'] === null && $parsedTags['year'] !== null) {
         $parsedTags['release_date'] = Carbon::create($parsedTags['year'], 1, 1);
     }
     //==========================================================================================================
     // Does this track have vocals?
     //==========================================================================================================
     $parsedTags['is_vocal'] = $parsedTags['lyrics'] !== null;
     //==========================================================================================================
     // Determine the genre.
     //==========================================================================================================
     $genreName = $parsedTags['genre'];
     if ($genreName) {
         $parsedTags['genre_id'] = $this->getGenreId($genreName);
     } else {
         $parsedTags['genre_id'] = $this->getGenreId('Unknown');
     }
     //==========================================================================================================
     // Extract the cover art, if any exists.
     //==========================================================================================================
     $coverId = null;
     if (array_key_exists('comments', $allTags) && array_key_exists('picture', $allTags['comments'])) {
         $image = $allTags['comments']['picture'][0];
         if ($image['image_mime'] === 'image/png') {
             $extension = 'png';
         } elseif ($image['image_mime'] === 'image/jpeg') {
             $extension = 'jpg';
         } else {
             throw new BadRequestHttpException('Unknown cover format embedded in the track file!');
         }
         // write temporary image file
         $tmpPath = Config::get('ponyfm.files_directory') . '/tmp';
         $filename = $file->getFilename() . ".cover.{$extension}";
         $imageFilePath = "{$tmpPath}/{$filename}";
         File::put($imageFilePath, $image['data']);
         $imageFile = new UploadedFile($imageFilePath, $filename, $image['image_mime']);
         $cover = Image::upload($imageFile, $artist);
         $coverId = $cover->id;
     } else {
         // no cover art was found - carry on
     }
     $parsedTags['cover_id'] = $coverId;
     //==========================================================================================================
     // Is this part of an album?
     //==========================================================================================================
     $albumId = null;
     $albumName = $parsedTags['album'];
     if ($albumName !== null) {
         $albumId = $this->getAlbumId($artist->id, $albumName, $coverId);
     }
     $parsedTags['album_id'] = $albumId;
     return [$parsedTags, $rawTags];
 }