Наследование: use trait Nette\SmartObject
Пример #1
1
 /**
  * @ORM\PreFlush()
  */
 public function preUpload()
 {
     if ($this->file) {
         if ($this->file instanceof FileUpload) {
             $basename = $this->file->getSanitizedName();
             $basename = $this->suggestName($this->getFilePath(), $basename);
             $this->setName($basename);
         } else {
             $basename = trim(Strings::webalize($this->file->getBasename(), '.', FALSE), '.-');
             $basename = $this->suggestName(dirname($this->file->getPathname()), $basename);
             $this->setName($basename);
         }
         if ($this->_oldPath && $this->_oldPath !== $this->path) {
             @unlink($this->getFilePathBy($this->_oldProtected, $this->_oldPath));
         }
         if ($this->file instanceof FileUpload) {
             $this->file->move($this->getFilePath());
         } else {
             copy($this->file->getPathname(), $this->getFilePath());
         }
         return $this->file = NULL;
     }
     if (($this->_oldPath || $this->_oldProtected !== NULL) && ($this->_oldPath != $this->path || $this->_oldProtected != $this->protected)) {
         $oldFilePath = $this->getFilePathBy($this->_oldProtected !== NULL ? $this->_oldProtected : $this->protected, $this->_oldPath ?: $this->path);
         if (file_exists($oldFilePath)) {
             rename($oldFilePath, $this->getFilePath());
         }
     }
 }
Пример #2
0
 public function create(Product $product, FileUpload $fileUpload)
 {
     switch ($fileUpload->getContentType()) {
         case 'image/jpeg':
             $suffix = 'jpg';
             break;
         case 'image/png':
             $suffix = 'png';
             break;
         case 'image/gif':
             $suffix = 'gif';
             break;
         default:
             throw new EntityInvalidArgumentException(sprintf('File is of an unknown type %s.', $fileUpload->getContentType()));
     }
     $baseName = sprintf('%s-%%s.%s', Strings::webalize($product->getName()), $suffix);
     do {
         $fileName = sprintf($baseName, Random::generate(5, '0-9a-zA-Z'));
         $path = sprintf('%s/%s', $this->imagesDir, $fileName);
     } while (file_exists($path));
     $fileUpload->move($path);
     $image = new ProductImage($product, $fileName);
     $this->createEntity($image);
     $product->addImage($image);
     return $image;
 }
Пример #3
0
 /**
  * @param Nette\Http\FileUpload $file
  * @param string $path
  * @param array $enabledExt
  * @return bool
  */
 protected function saveFile($file, $path, $enabledExt = array('jpg', 'jpeg'))
 {
     if ($file->error) {
         return false;
     }
     $filename = $file->getName();
     if (!in_array(self::getExtensionByName($filename), $enabledExt)) {
         return false;
     }
     try {
         $src = imagecreatefromjpeg($file->getTemporaryFile());
         list($width, $height) = getimagesize($file->getTemporaryFile());
         $aspectRatio = $width / $height;
         if ($aspectRatio > 1) {
             $targetWidth = self::MAX_DIMENSION;
             $targetHeight = round(self::MAX_DIMENSION / $aspectRatio);
         } else {
             $targetWidth = round(self::MAX_DIMENSION * $aspectRatio);
             $targetHeight = self::MAX_DIMENSION;
         }
         $bigThumbnail = imagecreatetruecolor($targetWidth, $targetHeight);
         imagecopyresampled($bigThumbnail, $src, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
         imagejpeg($bigThumbnail, self::SAVE_DIR . $path, 75);
     } catch (\Exception $e) {
         return false;
     }
     return true;
 }
Пример #4
0
 /**
  * @param FileUpload|NULL $file
  * @param string $folder
  *
  * @return array|bool
  */
 protected function saveImage(FileUpload $file = NULL, $folder = '')
 {
     if ($this->mainManager instanceof MagicManager) {
         $folder = $this->mainManager->getImageFolder();
     } else {
         if ($folder == '') {
             $folder = 'misc';
         }
     }
     // Main image
     $image = NULL;
     if (isset($file) && $file->isOk()) {
         // Save ...
         $year = date('Y');
         $month = date('m');
         $namespace = "{$folder}/{$year}/{$month}";
         $this->imageStorage->setNamespace($namespace);
         $image = $this->imageStorage->save($file->getContents(), $file->getName());
         $filename = pathinfo($image->getFile(), PATHINFO_BASENAME);
         // Prepare thumbnail
         $this->imgPipe->setNamespace($namespace);
         $this->imgPipe->request($filename, '200x200', 'exact');
         $this->imgPipe->setNamespace($namespace);
         $this->imgPipe->request($filename, '100x100', 'exact');
         $data = ['namespace' => $namespace, 'filename' => $filename];
         return $data;
     } else {
         return FALSE;
     }
 }
Пример #5
0
 /**
  * @param FileUpload $file
  * @return Image
  * @throws NotImageUploadedException
  * @throws FileSizeException
  * @throws DBALException
  * @throws InvalidStateException
  */
 public function processImage(FileUpload $file)
 {
     if (!$file->isImage()) {
         throw new NotImageUploadedException();
     }
     if (\filesize($file->getTemporaryFile()) > Image::MAX_FILE_SIZE) {
         throw new FileSizeException();
     }
     try {
         $this->em->beginTransaction();
         $image = new Image($file);
         $this->em->persist($image)->flush();
         $file->move($this->composeImageLocation($image));
         $this->em->commit();
     } catch (InvalidStateException $is) {
         $this->em->rollback();
         $this->em->close();
         $this->logger->addError('Error occurs while moving temp. image file to new location.');
         throw $is;
     } catch (DBALException $e) {
         $this->em->rollback();
         $this->em->close();
         $this->logger->addError('Image error');
         // todo err message
         throw $e;
     }
     return $image;
 }
Пример #6
0
 /**
  * @param FileUpload $fileUpload
  */
 public function upload(FileUpload $fileUpload, $path)
 {
     if (!$fileUpload->isOk()) {
         throw new ImageUploadedException('Chyba při nahrávání obrázku');
     }
     $fileUpload->move($path);
 }
Пример #7
0
 /**
  * Process form file upload from FileUpload wrapper class.
  *
  * @param FileUpload $file
  * @return string
  */
 public static function upload(FileUpload $file)
 {
     $filename = $file->getSanitizedName();
     $folder = date('Y');
     $file->move(self::getUploadDir() . $folder . '/' . $filename);
     return $folder . '/' . $filename;
 }
Пример #8
0
 /**
  * @param FileUpload $file
  * @return array|void
  */
 public function save(FileUpload $file)
 {
     if ($file->isImage()) {
         return $this->imageSaver->save($file);
     } else {
         return $this->fileSaver->save($file);
     }
 }
Пример #9
0
 /**
  * @param FileUpload $file
  * @return string
  */
 public function save(FileUpload $file)
 {
     do {
         $filename = Strings::random(5) . '-' . $file->getSanitizedName();
         $targetFile = $this->getAbsolutePath() . '/' . $filename;
     } while (file_exists($targetFile));
     $image = $file->toImage();
     $image->save($targetFile);
     return $filename;
 }
Пример #10
0
 /**
  * @param FileUpload $file
  * @return mixed|void
  * @throws NotAllowedFileException
  */
 public function save(FileUpload $file)
 {
     $filename = $file->getSanitizedName();
     $parts = explode('.', $filename);
     $last = end($parts);
     if (in_array($last, $this->notAllowed)) {
         throw new NotAllowedFileException("File with {$last} suffix is not allowed.");
     }
     $file->move($this->dir . '/' . $filename);
 }
Пример #11
0
 protected function processImageUpload(Nette\Http\FileUpload $upload, $targetDir, $id)
 {
     $dir = 'upload' . DIRECTORY_SEPARATOR . $targetDir . DIRECTORY_SEPARATOR . $id;
     if (!file_exists($this->rootDir . DIRECTORY_SEPARATOR . $dir)) {
         Nette\Utils\FileSystem::createDir($this->rootDir . DIRECTORY_SEPARATOR . $dir);
     }
     $path = $dir . DIRECTORY_SEPARATOR . $upload->getSanitizedName();
     $upload->move($this->rootDir . DIRECTORY_SEPARATOR . $path);
     return $path;
 }
Пример #12
0
 /**
  * @param FileUpload $fileUpload
  * @return string
  */
 public static function sanitizeFileName(FileUpload $fileUpload)
 {
     $filename = $fileUpload->getSanitizedName();
     $filename = Strings::lower($filename);
     $fileInfo = new \SplFileInfo($filename);
     $suffix = $fileInfo->getExtension();
     $basename = $fileInfo->getBasename(".{$suffix}");
     $hash = md5($fileUpload->getContents());
     $hash = Strings::substring($hash, 0, 9);
     return Strings::substring($basename, 0, 50) . "_{$hash}.{$suffix}";
 }
Пример #13
0
 protected function saveFile(FileUpload $upload)
 {
     if ($upload->ok) {
         $pathinfo = pathinfo($upload->name);
         $extension = in_array($pathinfo['extension'], $this->disableExtension) ? 'txt' : $pathinfo['extension'];
         $file = $this->path . '/' . md5(uniqid(rand(), true)) . '.' . $extension;
         $upload->move($this->wwwDir . '/' . $file);
         return ['name' => $upload->name, 'src' => $file];
     }
     return NULL;
 }
Пример #14
0
             $values->avatar = $this->_uploadTitleImage($values->avatar);
             if (is_file("www/" . $this->avatar_path . $values->old_avatar)) {
                 unlink($this->www_dir . "/www/" . $this->avatar_path . $values->old_avatar);
             }
             $this->hlavne_menu->uloz(["avatar" => $values->avatar], $values->id);
         } else {
             throw new Database\DriverException('Pre titulný obrázok nebol použitý obrázok a tak nebol uložený!' . $e->getMessage());
         }
     } else {
         throw new Database\DriverException('Pri pokuse o uloženie došlo k chybe! Pravdepodobná príčina je:' . $this->presenter->upload_error[$values->avatar->error] . $e->getMessage());
     }
 } catch (Database\DriverException $e) {
Пример #15
0
 /**
  * @param FileUpload $file
  * @return mixed|void
  */
 public function save(FileUpload $file)
 {
     $filename = $file->getSanitizedName();
     /** @var \Nette\Image */
     $image = $file->toImage();
     $image->save($this->dir . '/' . $filename);
     foreach ($this->dimensions as $prefix => $dimension) {
         $image->resize($dimension[0], $dimension[1], Image::SHRINK_ONLY);
         $image->save($this->dir . '/' . $prefix . '_' . $filename);
     }
 }
Пример #16
0
 /**
  * @param FileUpload $file
  * @return Image
  * @throws \Nette\InvalidArgumentException
  */
 public function upload(FileUpload $file)
 {
     if (!$file->isOk() || !$file->isImage()) {
         throw new Nette\InvalidArgumentException();
     }
     do {
         $name = Random::generate() . '.' . $file->getSanitizedName();
     } while (file_exists($path = $this->imagesDir . "/" . $this->namespace . $this->originalPrefix . "/" . $name));
     $file->move($path);
     $this->onUploadImage($path, $this->namespace);
     $this->namespace = NULL;
     return new Image($path);
 }
Пример #17
0
 /**
  * @param string $namespace
  * @param FileUpload $fileUpload
  * @return SplFileInfo
  * @throws UploadErrorException
  */
 public function singleFileToDir($namespace, FileUpload $fileUpload)
 {
     if ($error = $fileUpload->getError()) {
         throw new UploadErrorException($error);
     }
     /** @var IManager $manager */
     $manager = $this->managerProvider->get($fileUpload);
     $relativePath = Utils::normalizePath($manager->getStorage()->getRelativePath() . '/' . $namespace);
     $this->onFileBegin($fileUpload, $relativePath);
     $uploadedFile = $manager->upload($namespace, $fileUpload);
     $this->onFileComplete($uploadedFile, $fileUpload, $relativePath);
     return $uploadedFile;
 }
Пример #18
0
 /**
  * Ověří mimetype předaného souboru.
  * @param \Nette\Http\FileUpload $file Nahraný soubor k ověření.
  * @return bool Má soubor správný mimetype?
  */
 public function checkType(\Nette\Http\FileUpload $file)
 {
     if (\Nette\Utils\Arrays::searchKey($this->getMimeTypes(), $file->getContentType()) !== FALSE) {
         return TRUE;
     } else {
         // Pokud se nepodaří ověřit mimetype, ověříme alespoň koncovku.
         if (array_search($this->getExtension($file->getName()), array_unique($this->getMimeTypes())) !== FALSE) {
             return TRUE;
         } else {
             return FALSE;
         }
     }
 }
Пример #19
0
 /**
  * @param FileUpload $fileUpload
  * @param string $namespace
  * @param callable $callback
  * @return string Absolute name
  */
 public function saveUpload(FileUpload $fileUpload, $namespace = NULL, callable $callback = NULL)
 {
     if (!$fileUpload->isOk() || !$fileUpload->isImage()) {
         return NULL;
     }
     $image = $this->createImage();
     $image->setNamespace($namespace);
     $image->setName($fileUpload->getSanitizedName());
     if ($callback) {
         $callback($image);
     }
     $image->saveUpload($fileUpload);
     return (string) $image;
 }
Пример #20
0
 /**
  * @param Nette\Http\FileUpload $file
  * @param $path
  */
 public function upload(Nette\Http\FileUpload $file, $path)
 {
     try {
         $tempFile = $file->getTemporaryFile();
         $uploadPath = $this->wwwDir . $path;
         $mainFile = $uploadPath . time() . '-' . $file->getName();
         move_uploaded_file($tempFile, $mainFile);
         return $mainFile;
     } catch (\Exception $e) {
         header('HTTP/1.1 500 Internal Server Error');
         header('Content-type: text/plain');
         exit($e->getMessage());
     }
 }
Пример #21
0
 public function put(FileUpload $file)
 {
     if (!$file->ok) {
         $this->errors[] = "Při nahrávání obrázku " . $file->name . " nastala chyba " . $file->error;
         return false;
     }
     // Allow certain file formats
     $fileType = $this->verifyFileType(basename($file->name));
     if (!$fileType) {
         $this->errors[] = "Nahraný soubor " . $file->name . " není jedním z povolených typů: " . implode(", ", self::allowedFileTypes());
         return false;
     }
     // Check if image file is a actual image or fake image
     $dimensionErrors = self::checkImageDimensions($file->temporaryFile);
     if (!empty($dimensionErrors)) {
         $this->errors = $dimensionErrors;
         return false;
     }
     // Check file size
     if (($file_size = $file->size) > self::MAX_IMG_FILE_SIZE) {
         $errors[] = "Velikost souboru " . $file_size / 1024 . "kb přesáhla povolený limit " . self::MAX_IMG_FILE_SIZE / 1024 . "kb";
         return false;
     }
     // if everything is ok, try to upload file
     $destFile = $this->uniqueFilename($file->name);
     $finalFileName = $this->imgFolder . $destFile;
     if (!$file->move($finalFileName)) {
         $errors[] = "Nahraný obrázek se nepodařilo uložit.";
         return false;
     }
     return $destFile;
 }
 private function getInvalidMetadata(FileUpload $song) : array
 {
     $invalidMetadata = [];
     $songReader = new \SongReader($song->getTemporaryFile());
     if (!$songReader->getDuration()) {
         $invalidMetadata[] = 'playtime_string';
     }
     if (!$songReader->getAuthor()) {
         $invalidMetadata[] = 'artist';
     }
     if (!$songReader->getTitle()) {
         $invalidMetadata[] = 'title';
     }
     if (!$songReader->getAlbum()) {
         $invalidMetadata[] = 'album';
     }
     return $invalidMetadata;
 }
Пример #23
0
 public function thumbate(FileUpload $file, Thumb $thumb)
 {
     /** @var $image Image */
     $image = $file->toImage();
     $dimension = $thumb->getDimension();
     // Resize to thumb dimension
     $image->resize($dimension->getWidth(), $dimension->getHeight(), $dimension->getFlag());
     // Image name
     $imagename = $thumb->getImagename();
     // File name
     $filename = $imagename . '.' . Utils::ext($file->name);
     // Gets properly directory
     $path = Utils::dirs($this->repository, $thumb->getPath(), $filename);
     // Store image data
     $this->images[] = ArrayHash::from(['path' => Utils::dirs($this->repository, $thumb->getPath()), 'fullpath' => $path, 'filename' => $filename, 'name' => $imagename, 'ext' => Utils::ext($file->name)]);
     // Save to file
     $image->save($path);
 }
Пример #24
0
 public function __construct(FileUpload $file)
 {
     if (!$file->isImage()) {
         throw new NotImageUploadedException();
     }
     $this->id = Uuid::uuid4();
     $pathInfo = pathinfo($file->getSanitizedName());
     if (!isset($pathInfo['extension'])) {
         throw new FileNameException('Filename must have extension');
     }
     $this->extension = $pathInfo['extension'];
     $this->originalName = $pathInfo['filename'];
     $imgSize = $file->getImageSize();
     $this->width = $imgSize[0];
     $this->height = $imgSize[1];
     $this->fileSize = $file->getSize();
     $this->uploadedAt = new \DateTime('now');
 }
Пример #25
0
 /**
  * 
  * @param \Nette\Http\FileUpload $file
  * @return string
  */
 private function getImageBase64(\Nette\Http\FileUpload $file)
 {
     $type = $file->getContentType();
     $img = Image::fromFile($file);
     $img->resize(100, 100, Image::EXACT);
     $img_string = "";
     switch ($type) {
         case 'image/png':
             $img_string = $img->toString(Image::PNG);
             break;
         case 'image/jpeg':
             $img_string = $img->toString(Image::JPEG);
             break;
         case 'image/gif':
             $img_string = $img->toString(Image::GIF);
             break;
     }
     return 'data:' . $type . ';base64,' . base64_encode($img_string);
 }
Пример #26
0
 /**
  * Prida soubor do db
  * @param \Nette\Http\FileUpload $file
  * @return type 
  */
 public function addFile($file, $userId = NULL)
 {
     if ($file instanceof \Nette\Http\FileUpload) {
         if (!$file->isOk()) {
             return false;
         }
         $folder = $this->getFolder('', FALSE);
         if (!$folder) {
             throw new VirtualDriveException('Current folder not found', 3011);
         }
         $name = $this->model->addFile($file, $folder['folder_id'], 0, $userId);
         /*if(!file_exists($this->getFullPath(TRUE).'/images')){
               @mkdir($this->getFullPath(TRUE).'/images', 0777, TRUE);
           }*/
         $filename = $this->uploadFile($file, $name);
         return $this->_getIdFromFileName($filename);
     } else {
         throw new VirtualDriveException('Wrong file type!', 3012);
     }
 }
Пример #27
0
 /**
  * Return file upload error message.
  * @param  FileUpload $file
  * @param  UI\Presenter $presenter
  * @return bool
  */
 public static function hasFileError(FileUpload $file, UI\Presenter &$presenter, $noFileError = TRUE)
 {
     switch ($file->getError()) {
         case UPLOAD_ERR_INI_SIZE:
             $presenter->flashMessage('The uploaded file exceeds the upload_max_filesize directive in php.ini.', 'error');
             $return = FALSE;
             break;
         case UPLOAD_ERR_FORM_SIZE:
             $presenter->flashMessage('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.', 'error');
             $return = FALSE;
             break;
         case UPLOAD_ERR_PARTIAL:
             $presenter->flashMessage('The uploaded file was only partially uploaded.', 'error');
             $return = FALSE;
             break;
         case UPLOAD_ERR_NO_FILE:
             if ($noFileError === FALSE) {
                 $presenter->flashMessage('No file was uploaded.', 'error');
             }
             $return = $noFileError;
             break;
         case UPLOAD_ERR_NO_TMP_DIR:
             $presenter->flashMessage('Missing a temporary folder.', 'error');
             $return = FALSE;
             break;
         case UPLOAD_ERR_CANT_WRITE:
             $this->flashMessage('Failed to write file to disk.', 'error');
             $return = FALSE;
             break;
         case UPLOAD_ERR_EXTENSION:
             $presenter->flashMessage('File upload stopped by extension.', 'error');
             $return = FALSE;
             break;
         default:
             $presenter->flashMessage('Chyba při zpracování souboru ' . $file->getName(), 'error');
             $return = FALSE;
             break;
     }
     return $return;
 }
Пример #28
0
 /**
  * Save file into filesystem and insert information into database.
  * Checks extension and gives file mime type.
  * @param FileUpload $file
  * @param int $goods_id
  * @param string $name
  * @param string $description
  * @return bool success
  */
 public function insertPhoto($file, $goods_id, $name = '', $description = '')
 {
     $photo = new Photo($this->db);
     $filename = $file->getName();
     $ext = self::getExtensionByName($filename);
     // povolene pripony
     $enabledExt = explode(' ', self::ENABLED_EXTENSION);
     if (!in_array($ext, $enabledExt)) {
         return false;
     }
     $lastPhoto_id = $photo->insert(array('name' => $name ? $name : $filename, 'goods_id' => $goods_id, 'description' => $description));
     $photoFileName = $file->getTemporaryFile();
     $photoFileNameBig = self::SAVE_DIR . $lastPhoto_id . '.big.jpg';
     $photoFileNameSmall = self::SAVE_DIR . $lastPhoto_id . '.small.jpg';
     try {
         $src = imagecreatefromjpeg($photoFileName);
         list($width, $height) = getimagesize($photoFileName);
         $aspectRatio = $width / $height;
         if ($aspectRatio > 1) {
             $targetWidth = 800;
             $targetHeight = round(800 / $aspectRatio);
         } else {
             $targetWidth = round(800 * $aspectRatio);
             $targetHeight = 800;
         }
         $bigThumbnail = imagecreatetruecolor($targetWidth, $targetHeight);
         imagecopyresampled($bigThumbnail, $src, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
         imagejpeg($bigThumbnail, $photoFileNameBig, 75);
         $smallThumbnail = imagecreatetruecolor(round($targetWidth / 2.5), round($targetHeight / 2.5));
         imagecopyresampled($smallThumbnail, $src, 0, 0, 0, 0, round($targetWidth / 2.5), round($targetHeight / 2.5), $width, $height);
         imagejpeg($smallThumbnail, $photoFileNameSmall, 50);
     } catch (\Exception $e) {
         $photo = new Photo($this->db);
         $photo->where('id', $lastPhoto_id)->delete();
         return false;
     }
     return true;
 }
Пример #29
0
 public function savaOriginImage($namespace, FileUpload $file)
 {
     if (!$file->isOk() || !$file->isImage()) {
         throw new ImageStorageException("invalid image");
     }
     $i = 1;
     $name = $file->getSanitizedName();
     $path = $this->getPath($namespace, $name);
     while (file_exists($path)) {
         $name = $i . '-' . $file->getSanitizedName();
         $path = $this->getPath($namespace, $name);
         $i++;
     }
     $file->move($path);
     return $name;
 }
Пример #30
0
 /**
  * @param  FileUpload
  * @param  string|NULL
  * @param  array|string|NULL
  * @return string  filepath (namespace/file.ext)
  * @throws ImageStorageException
  */
 public function upload(FileUpload $image, $namespace = NULL, $mimeTypes = NULL)
 {
     if (!$image->isOk()) {
         throw new ImageStorageException('File is broken');
     }
     if (!$image->isImage()) {
         $contentType = $image->getContentType();
         $isValid = FALSE;
         if (isset($mimeTypes)) {
             $mimeTypes = is_array($mimeTypes) ? $mimeTypes : explode(',', $mimeTypes);
             $isValid = in_array($contentType, $mimeTypes, TRUE);
         }
         if (!$isValid) {
             throw new ImageStorageException('File must be image, ' . $contentType . ' given');
         }
     }
     $sanitizedName = $image->getSanitizedName();
     $ext = pathinfo($sanitizedName, PATHINFO_EXTENSION);
     $sanitizedName = pathinfo($sanitizedName, PATHINFO_FILENAME) . '.' . Strings::lower($ext);
     $file = $this->generateFilePath($sanitizedName, $namespace);
     $path = $this->getPath($file);
     $image->move($path);
     return $file;
 }