Esempio n. 1
0
 /**
  * Get original name of file.
  *
  * @return string
  */
 public function getName()
 {
     if ($this->file instanceof UploadedFile) {
         return $this->file->getClientOriginalName();
     }
     return $this->file->getFilename();
 }
Esempio n. 2
0
 /**
  * @param \Symfony\Component\HttpFoundation\File\File $img
  * @param string                                      $path
  *
  * @return string
  */
 public function saveImg(File $img, $path)
 {
     $imageLib = new ImageLib();
     $imageLib->load($path . $img->getFilename());
     $outputImgName = md5($img->getFilename() . time()) . '.' . $img->getExtension();
     //$imageLib->resizeImage(100, 100, array('crop', 'tr'), true);
     $imageLib->saveImage($path . $outputImgName, 100);
     return $outputImgName;
 }
Esempio n. 3
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormViewInterface $view, FormInterface $form, array $options)
 {
     $configs = $form->getAttribute('configs');
     $datas = $form->getClientData();
     if (!empty($datas)) {
         if ($form->getAttribute('multiple')) {
             $datas = is_scalar($datas) ? explode(',', $datas) : $datas;
             $value = array();
             foreach ($datas as $data) {
                 if (!$data instanceof File) {
                     $data = new File($form->getAttribute('rootDir') . '/' . $data);
                 }
                 $value[] = $configs['folder'] . '/' . $data->getFilename();
             }
             $value = implode(',', $value);
         } else {
             if (!$datas instanceof File) {
                 $datas = new File($form->getAttribute('rootDir') . '/' . $datas);
             }
             $value = $configs['folder'] . '/' . $datas->getFilename();
         }
         $view->set('value', $value);
     }
     $view->set('type', 'hidden')->set('configs', $form->getAttribute('configs'));
 }
 /**
  * @param Closure $callback
  * @param InterventionRequest $interventionRequest
  * @return Response
  */
 public function getResponse(Closure $callback, InterventionRequest $interventionRequest)
 {
     try {
         $this->cacheFile = new File($this->cacheFilePath);
         $response = new Response(file_get_contents($this->cacheFile->getPathname()), Response::HTTP_OK, ['Content-Type' => $this->cacheFile->getMimeType(), 'Content-Disposition' => 'filename="' . $this->realImage->getFilename() . '"', 'X-Generator-Cached' => true]);
         $response->setLastModified(new \DateTime(date("Y-m-d H:i:s", $this->cacheFile->getMTime())));
     } catch (FileNotFoundException $e) {
         if (is_callable($callback)) {
             $image = $callback($interventionRequest);
             if ($image instanceof Image) {
                 $this->saveImage($image);
                 $this->cacheFile = new File($this->cacheFilePath);
                 if (null !== $this->dispatcher) {
                     // create the ImageSavedEvent and dispatch it
                     $event = new ImageSavedEvent($image, $this->cacheFile);
                     $this->dispatcher->dispatch(ImageSavedEvent::NAME, $event);
                 }
                 // send HTTP header and output image data
                 $response = new Response(file_get_contents($this->cacheFile->getPathname()), Response::HTTP_OK, ['Content-Type' => $image->mime(), 'Content-Disposition' => 'filename="' . $this->realImage->getFilename() . '"', 'X-Generator-First-Render' => true]);
                 $response->setLastModified(new \DateTime('now'));
             } else {
                 throw new \RuntimeException("Image is not a valid InterventionImage instance.", 1);
             }
         } else {
             throw new \RuntimeException("No image handle closure defined", 1);
         }
     }
     $this->initializeGarbageCollection();
     return $response;
 }
 /**
  * Handle request to convert it to a Response object.
  */
 public function handle()
 {
     try {
         if (!$this->request->query->has('image')) {
             throw new FileNotFoundException("No valid image path found in URI", 1);
         }
         $nativePath = $this->configuration->getImagesPath() . '/' . $this->request->query->get('image');
         $this->nativeImage = new File($nativePath);
         $this->parseQuality();
         if ($this->configuration->hasCaching()) {
             $cache = new FileCache($this->request, $this->nativeImage, $this->configuration->getCachePath(), $this->logger, $this->quality, $this->configuration->getTtl(), $this->configuration->getGcProbability(), $this->configuration->getUseFileChecksum());
             $cache->setDispatcher($this->dispatcher);
             /** @var Response response */
             $this->response = $cache->getResponse(function (InterventionRequest $interventionRequest) {
                 return $interventionRequest->processImage();
             }, $this);
         } else {
             $this->processImage();
             $this->response = new Response((string) $this->image->encode(null, $this->quality), Response::HTTP_OK, ['Content-Type' => $this->image->mime(), 'Content-Disposition' => 'filename="' . $this->nativeImage->getFilename() . '"', 'X-Generator-First-Render' => true]);
             $this->response->setLastModified(new \DateTime('now'));
         }
     } catch (FileNotFoundException $e) {
         $this->response = $this->getNotFoundResponse($e->getMessage());
     } catch (\RuntimeException $e) {
         $this->response = $this->getBadRequestResponse($e->getMessage());
     }
 }
 /**
  * @return array
  */
 public function getSplitFiles()
 {
     $file = new File($this->archivePath);
     $finder = new Finder();
     $finder->files()->in(dirname($this->archivePath))->notName($file->getFilename())->sortByModifiedTime();
     return iterator_to_array($finder);
 }
Esempio n. 7
0
 public function setFileAttribute(\Symfony\Component\HttpFoundation\File\File $file)
 {
     $this->attributes['file'] = $file;
     $this->original_name = $file instanceof UploadedFile ? $file->getClientOriginalName() : $file->getFilename();
     $this->size = $file->getSize();
     $this->content_type = $file->getMimeType();
 }
Esempio n. 8
0
 /**
  * Sets the Content-Disposition header with the given filename.
  *
  * @param string $disposition      ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
  * @param string $filename         Optionally use this filename instead of the real name of the file
  * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
  *
  * @return BinaryFileResponse
  */
 public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
 {
     if ($filename === '') {
         $filename = $this->file->getFilename();
     }
     $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
     $this->headers->set('Content-Disposition', $dispositionHeader);
     return $this;
 }
Esempio n. 9
0
File: Image.php Progetto: nass59/Lab
 /**
  * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
  * of 'UploadedFile' is injected into this setter to trigger the  update. If this
  * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
  * must be able to accept an instance of 'File' as the bundle will inject one here
  * during Doctrine hydration.
  *
  * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
  *
  * @return $this
  */
 public function setImageFile(File $image = null)
 {
     $this->imageFile = $image;
     if ($image) {
         $this->modifiedAt = new \DateTime('now');
         $this->fileName = $image->getFilename();
     }
     return $this;
 }
Esempio n. 10
0
 public function setImageFile(File $imageFile)
 {
     if ($imageFile instanceof File) {
         $this->imageFile = $imageFile;
         if (!$this->name) {
             $this->name = $imageFile->getFilename();
         }
         $this->updatedAt = new \DateTime('now');
     }
 }
Esempio n. 11
0
 /**
  * @inheritDoc
  */
 public function transform(File $file, ResourceAnnotationInterface $config)
 {
     /** @var  ResourceImage $config */
     //create copy with image extension instead of .tmp, required to save with Imagine
     $newName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $file->getFilename() . '.' . $file->guessExtension();
     if (copy($file->getRealPath(), $newName)) {
         $newFile = new File($newName);
         return $this->imageResize($newFile, $config->maxWith, $config->maxHeight, $config->enlarge, $config->keepRatio);
     } else {
         return $file;
     }
 }
Esempio n. 12
0
 /**
  * Creates a file object from a file on the disk.
  */
 public function fromFile($filePath)
 {
     if ($filePath === null) {
         return;
     }
     $file = new FileObj($filePath);
     $this->file_name = $file->getFilename();
     $this->file_size = $file->getSize();
     $this->content_type = $file->getMimeType();
     $this->disk_name = $this->getDiskName();
     $this->putFile($uploadedFile->getRealPath(), $this->disk_name);
 }
Esempio n. 13
0
 /**
  * Set the avatar of the object to be a specific file
  *
  * @param  File|null $file The avatar file
  * @return self
  */
 public function setAvatarFile($file)
 {
     if ($file) {
         // We don't use File's fread() because it's unavailable in less
         // recent PHP versions
         $path = $file->getPath() . '/' . $file->getFilename();
         $content = file_get_contents($path);
         $path = $this->getAvatarPath(null, false, false);
         $filename = $this->getAvatarFileName($content);
         $file->move(DOC_ROOT . $path, $filename);
         $this->setAvatar($path . $filename);
     }
     return $this;
 }
 public static function validateFileExtension(File $file, $extensions = array())
 {
     if (empty($extensions)) {
         $extensions = self::getSecureFileExtensions();
     }
     if ($file instanceof UploadedFile) {
         $filename = $file->getClientOriginalName();
     } else {
         $filename = $file->getFilename();
     }
     $errors = array();
     $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
     if (!preg_match($regex, $filename)) {
         $errors[] = "只允许上传以下扩展名的文件:" . $extensions;
     }
     return $errors;
 }
Esempio n. 15
0
 private function prepareResponse(File $file, $filename = null)
 {
     $mimeType = $file->getMimeType();
     if ($mimeType == 'application/pdf') {
         $disposition = 'inline';
     } else {
         $disposition = 'attachment';
     }
     $response = new Response();
     $response->headers->set('Cache-Control', 'private');
     $response->headers->set('Content-Type', $mimeType);
     $response->headers->set('Content-Disposition', $disposition . '; filename="' . ($filename ? $filename : $file->getFilename()) . '"');
     $response->headers->set('Content-Length', $file->getSize());
     $response->sendHeaders();
     readfile($file);
     return $response;
 }
Esempio n. 16
0
 /**
  * Sets the Content-Disposition header with the given filename.
  *
  * @param string $disposition      ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
  * @param string $filename         Optionally use this filename instead of the real name of the file
  * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
  *
  * @return BinaryFileResponse
  */
 public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
 {
     if ($filename === '') {
         $filename = $this->file->getFilename();
     }
     if ('' === $filenameFallback && (!preg_match('/^[\\x20-\\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
         $encoding = mb_detect_encoding($filename, null, true);
         for ($i = 0; $i < mb_strlen($filename, $encoding); ++$i) {
             $char = mb_substr($filename, $i, 1, $encoding);
             if ('%' === $char || ord($char) < 32 || ord($char) > 126) {
                 $filenameFallback .= '_';
             } else {
                 $filenameFallback .= $char;
             }
         }
     }
     $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
     $this->headers->set('Content-Disposition', $dispositionHeader);
     return $this;
 }
Esempio n. 17
0
 /**
  * @param File $file
  * @return string
  */
 protected function getNormalizedFilename(File $file)
 {
     if ($file instanceof UploadedFile) {
         $originalFilename = $file->getClientOriginalName();
         $size = $file->getClientSize();
     } else {
         $originalFilename = $file->getFilename();
         $size = $file->getSize();
     }
     $name = preg_replace(self::REGEX_FILENAME_EXT, '', $originalFilename);
     $name = preg_replace(self::REGEX_INVALID_FILENAME_CHARS, '_', $name);
     $hash = substr(sha1(json_encode(array(time(), $name, $size))), 0, 7);
     $ext = $file->getExtension();
     if (!$ext) {
         $ext = explode('.', $originalFilename);
         $ext = end($ext);
     }
     $filename = sprintf('%s_%s.%s', $name, $hash, $ext);
     return $filename;
 }
Esempio n. 18
0
 /**
  * Validates the file as being supported by Colibri, verifying its size, extension...
  * @param $file
  * @return boolean
  * @throws \Exception
  */
 public function supported(File $file)
 {
     $filePath = $file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename();
     $fileData = getimagesize($filePath);
     $maxSize = 1101004;
     // 1.05 Mo
     $mimes = array('image/jpeg', 'image/png', 'image/gif');
     $fileSize = $file->getSize();
     $fileType = $file->getMimeType();
     if ($fileSize > $maxSize) {
         throw new \Exception("File size too big. Got {$fileSize}, max {$maxSize}");
     }
     if (!in_array($fileType, $mimes)) {
         throw new \Exception("File extension not supported. Got {$fileType}.");
     }
     if ($fileData[0] > 2400 || $fileData[1] > 2400) {
         throw new \Exception("L'image est trop grande, max 2400x2400, reçu {$fileData['0']}x{$fileData['1']}px");
     }
     return true;
 }
Esempio n. 19
0
 protected function validateFileNameLength(File $file)
 {
     $errors = array();
     if (!$file->getFilename()) {
         $errors[] = "文件名为空,请给文件取个名吧。";
     }
     if (strlen($file->getFilename()) > 240) {
         $errors[] = "文件名超出了240个字符的限制,请重命名后再试。";
     }
     return $errors;
 }
 /**
  * @param \App\Events\Files\Uploaded $event
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function handle(Uploaded $event)
 {
     $uploadUuid = $event->uploadUuid;
     $request = $event->request;
     /*
     |--------------------------------------------------
     | Move file to its final permanent destination.
     |--------------------------------------------------
     */
     $hash = hash_file('sha256', app('filestream')->getAbsolutePath($uploadUuid));
     $destination = $hash;
     if (config('filesystems.load_balancing.enabled')) {
         $config = config('filesystems.load_balancing');
         $folders = [];
         for ($i = 0; $i < $config['depth']; $i++) {
             $folders[] = substr($hash, -1 * ($i + 1) * $config['length'], $config['length']);
         }
         $destination = implode(DIRECTORY_SEPARATOR, array_merge($folders, [$hash]));
     }
     $filesystem = app('filesystem')->disk();
     !$filesystem->exists($destination) ? $filesystem->move($uploadUuid, $destination) : $filesystem->delete($uploadUuid);
     /*
     |---------------------------------
     | Check the tag and its limit.
     |---------------------------------
     */
     /** @var \App\Models\User $me */
     $me = app('sentinel')->getUser();
     $tag = $request->get('qqtag');
     $tagLimit = config('filesystems.allowed_tags_and_limits.' . $tag);
     if ($tagLimit > 0) {
         $allFilesWithSameTagBelongingToUser = $me->load(['files' => function (BelongsToMany $query) use($tag) {
             $query->wherePivot('tag', '=', $tag);
         }])->files;
         if (($numberOfFilesToDeleteToComplyWitTagLimit = $allFilesWithSameTagBelongingToUser->count() - $tagLimit + 1) > 0) {
             while ($numberOfFilesToDeleteToComplyWitTagLimit > 0) {
                 $pivotToDelete = $allFilesWithSameTagBelongingToUser->shift();
                 app('filestream')->deleteFile($pivotToDelete->hash, $tag);
                 $numberOfFilesToDeleteToComplyWitTagLimit--;
             }
         }
     }
     /*
     |------------------------------------
     | Persist file record in database.
     |------------------------------------
     */
     $uploadedFile = new SymfonyFile(app('filestream')->getAbsolutePath($destination));
     if (!($file = File::find($hash = $uploadedFile->getFilename()))) {
         $file = new File();
         $file->hash = $hash;
         $file->disk = 'local';
         $file->path = trim(str_replace(config('filesystems.disks.local.root'), '', $uploadedFile->getPathname()), DIRECTORY_SEPARATOR);
         $file->mime = $uploadedFile->getMimeType();
         $file->size = $uploadedFile->getSize();
         $file->save();
     }
     $me->files()->newPivotStatement()->whereTag($tag)->whereFileHash($hash)->delete();
     $file->uploaders()->attach([$me->getUserId() => ['uuid' => $request->get('qquuid'), 'original_client_name' => $request->get('qqfilename'), 'tag' => $tag]]);
     return response()->json(['success' => true, 'hash' => $file->hash])->setStatusCode(IlluminateResponse::HTTP_CREATED);
 }
Esempio n. 21
0
File: Sdk.php Progetto: phppro/sdk
 /**
  * @param string|array $location
  * @param File         $file
  * @param array        $extraData
  * @param array        $options
  *
  * @return $this
  *
  * @throws ValidationException
  * @throws Exception
  */
 public function uploadBulk($location, File $file, $extraData = [], $options = [])
 {
     try {
         $this->call('POST', $this->buildUri($location, ['bulk' => true, 'upload' => true]), ['content' => base64_encode(file_get_contents($file->getRealPath())), 'type' => $this->getContentTypeByExtension($file->guessExtension()), 'filename' => $file->getFilename()] + $extraData, $options);
     } catch (Exception $e) {
         $this->throwSdkException($e);
     }
     return $this;
 }
Esempio n. 22
0
 /**
  * @param File $data
  *
  * @return Media
  */
 public function createNew($data)
 {
     if ($data instanceof File) {
         /* @var $data File */
         $media = new Media();
         if (method_exists($media, 'getClientOriginalName')) {
             $media->setName($data->getClientOriginalName());
         } else {
             $media->setName($data->getFilename());
         }
         $media->setContent($data);
         return $media;
     }
 }
 /**
  * The GET method that displays a file field's file
  *
  * @return Image / File
  */
 public function displayFile()
 {
     //get the stored path of the original
     $path = $this->request->input('path');
     $data = File::get($path);
     $file = new SFile($path);
     $headers = array('Content-Type' => $file->getMimeType(), 'Content-Length' => $file->getSize(), 'Content-Disposition' => 'attachment; filename="' . $file->getFilename() . '"');
     return response()->make($data, 200, $headers);
 }
Esempio n. 24
0
 /**
  * Given a single File, assuming is an image, create a new
  * Image object containing all needed information.
  *
  * This method also persists and flush created entity
  *
  * @param File $file File where to get the image
  *
  * @return ImageInterface Image created
  *
  * @throws InvalidImageException File is not an image
  */
 public function createImage(File $file)
 {
     $fileMime = $file->getMimeType();
     if (strpos($fileMime, 'image/') !== 0) {
         throw new InvalidImageException();
     }
     /**
      * @var ImageInterface $image
      */
     $image = $this->imageFactory->create();
     $imageSizeData = getimagesize($file->getPathname());
     $name = $file->getFilename();
     $image->setWidth($imageSizeData[0])->setHeight($imageSizeData[1])->setContentType($fileMime)->setSize($file->getSize())->setExtension($file->getExtension())->setName($name);
     return $image;
 }
Esempio n. 25
0
 /**
  * Given a single File, assuming is an image, create a new
  * Image object containing all needed information.
  *
  * This method also persists and flush created entity
  *
  * @param File $file File where to get the image
  *
  * @return ImageInterface Image created
  *
  * @throws InvalidImageException File is not an image
  */
 public function createImage(File $file)
 {
     $fileMime = $file->getMimeType();
     if ('application/octet-stream' === $fileMime) {
         $imageSizeData = getimagesize($file->getPathname());
         $fileMime = $imageSizeData['mime'];
     }
     if (strpos($fileMime, 'image/') !== 0) {
         throw new InvalidImageException();
     }
     $extension = $file->getExtension();
     if (!$extension && $file instanceof UploadedFile) {
         $extension = $file->getClientOriginalExtension();
     }
     /**
      * @var ImageInterface $image
      */
     $image = $this->imageFactory->create();
     if (!isset($imageSizeData)) {
         $imageSizeData = getimagesize($file->getPathname());
     }
     $name = $file->getFilename();
     $image->setWidth($imageSizeData[0])->setHeight($imageSizeData[1])->setContentType($fileMime)->setSize($file->getSize())->setExtension($extension)->setName($name);
     return $image;
 }
 /**
  * @param FileInfo $info
  *
  * @return null|string
  */
 protected function getFilenameFromFileInfo(FileInfo $info)
 {
     return $info instanceof UploadedFile ? $info->getClientOriginalName() : $info->getFilename();
 }
Esempio n. 27
0
 /**
  * $current_uri String actual uri of the file
  * $dest_folder String future uri of the file starting from web/upload folder
  * $lifetime DateTime lifetime of the file. If time goes over this limit, the file will be deleted.
  **/
 public function upload(File $file, $dest_folder = '', \DateTime $lifetime = null)
 {
     if ($file instanceof UploadedFile) {
         if ($file->getError() !== null && $file->getError() !== 0) {
             throw new UploadException($file->getErrorMessage());
         }
     }
     //preparing dir name
     $dest_folder = date('Ymd') . '/' . date('G') . '/' . $dest_folder;
     //checking mimetypes
     $mimeTypePassed = false;
     foreach ($this->allowedMimetypes as $mimeType) {
         if (preg_match('@' . $mimeType . '@', $file->getMimeType())) {
             $mimeTypePassed = true;
         }
     }
     if (!$mimeTypePassed) {
         throw new InvalidMimeTypeException('Only following filetypes are allowed : ' . implode(', ', $this->allowedMimetypes));
     }
     $fs = new Filesystem();
     if (!$fs->exists($this->uploadDir . $dest_folder)) {
         $fs->mkdir($this->uploadDir . $dest_folder);
     }
     $em = $this->entityManager;
     $media = new Media();
     $media->setMime($file->getMimeType());
     // If there's one, we try to generate a new name
     $extension = $file->getExtension();
     // Sanitizing the filename
     $slugify = new Slugify();
     if ($file instanceof UploadedFile) {
         if (empty($extension)) {
             $extension = $file->getClientOriginalExtension();
             if (empty($extension)) {
                 $extension = $file->guessClientExtension();
             }
         }
         $filename = $slugify->slugify(basename($file->getClientOriginalName(), $extension)) . '.' . $extension;
     } else {
         if (empty($extension)) {
             $extension = $file->guessClientExtension();
         }
         $filename = $slugify->slugify(basename($file->getFilename(), $extension)) . '.' . $extension;
     }
     // A media can have a lifetime and will be deleted with the cleanup function
     if (!empty($lifetime)) {
         $media->setLifetime($lifetime);
     }
     // Checking for a media with the same name
     $mediaExists = $this->entityManager->getRepository('AlpixelMediaBundle:Media')->findOneByUri($dest_folder . $filename);
     $mediaExists = count($mediaExists) > 0;
     if ($mediaExists === false) {
         $mediaExists = $fs->exists($this->uploadDir . $dest_folder . $filename);
     }
     if ($mediaExists === true) {
         $filename = basename($filename, '.' . $extension);
         $i = 1;
         do {
             $media->setName($filename . '-' . $i++ . '.' . $extension);
             $media->setUri($dest_folder . $media->getName());
             $mediaExists = $this->entityManager->getRepository('AlpixelMediaBundle:Media')->findOneByUri($media->getUri());
             $mediaExists = count($mediaExists) > 0;
             if ($mediaExists === false) {
                 $mediaExists = $fs->exists($this->uploadDir . $dest_folder . $filename);
             }
         } while ($mediaExists === true);
     } else {
         $media->setName($filename);
         $media->setUri($dest_folder . $media->getName());
     }
     $file->move($this->uploadDir . $dest_folder, $media->getName());
     chmod($this->uploadDir . $dest_folder . $media->getName(), 0664);
     // Getting the salt defined in parameters.yml
     $secret = $this->container->getParameter('secret');
     $media->setSecretKey(hash('sha256', $secret . $media->getName() . $media->getUri()));
     $em->persist($media);
     $em->flush();
     return $media;
 }
Esempio n. 28
0
 /**
  * Import
  *
  * @param \Thelia\Model\Import                        $import
  * @param \Symfony\Component\HttpFoundation\File\File $file
  * @param null|\Thelia\Model\Lang                     $language
  *
  * @return \Thelia\Core\Event\ImportEvent
  */
 public function import(Import $import, File $file, Lang $language = null)
 {
     $archiver = $this->matchArchiverByExtension($file->getFilename());
     if ($archiver !== null) {
         $file = $this->extractArchive($file, $archiver);
     }
     $serializer = $this->matchSerializerByExtension($file->getFilename());
     if ($serializer === null) {
         throw new FormValidationException(Translator::getInstance()->trans('The extension "%extension" is not allowed', ['%extension' => pathinfo($file->getFilename(), PATHINFO_EXTENSION)]));
     }
     $importHandleClass = $import->getHandleClass();
     /** @var \Thelia\ImportExport\Import\AbstractImport $instance */
     $instance = new $importHandleClass();
     // Configure handle class
     $instance->setLang($language);
     $instance->setFile($file);
     // Process import
     $event = new ImportEvent($instance, $serializer);
     $this->eventDispatcher->dispatch(TheliaEvents::IMPORT_BEGIN, $event);
     $errors = $this->processImport($event->getImport(), $event->getSerializer());
     $event->setErrors($errors);
     $this->eventDispatcher->dispatch(TheliaEvents::IMPORT_FINISHED, $event);
     $this->eventDispatcher->dispatch(TheliaEvents::IMPORT_SUCCESS, $event);
     return $event;
 }
Esempio n. 29
0
 /**
  * Creates a custom ResourceIcon entity from a File (wich should contain an image).
  * (for instance if the thumbnail of a resource is changed)
  *
  * @param File $file
  * @param Workspace $workspace (for the storage directory...)
  *
  * @return \Claroline\CoreBundle\Entity\Resource\ResourceIcon
  */
 public function createCustomIcon(File $file, Workspace $workspace = null)
 {
     $this->om->startFlushSuite();
     $extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
     if (is_null($workspace)) {
         $dest = $this->thumbDir;
         $hashName = $this->ut->generateGuid() . "." . $extension;
     } else {
         $dest = $this->thumbDir . DIRECTORY_SEPARATOR . $workspace->getCode();
         $hashName = $workspace->getCode() . DIRECTORY_SEPARATOR . $this->ut->generateGuid() . "." . $extension;
     }
     $file->move($dest, $hashName);
     //entity creation
     $icon = $this->om->factory('Claroline\\CoreBundle\\Entity\\Resource\\ResourceIcon');
     $icon->setRelativeUrl("{$this->basepath}/{$hashName}");
     $icon->setMimeType('custom');
     $icon->setShortcut(false);
     $this->om->persist($icon);
     $this->createShortcutIcon($icon, $workspace);
     $this->om->endFlushSuite();
     return $icon;
 }
Esempio n. 30
0
 /**
  * @param Temp|UploadedFile|File $file
  * @param array $options
  * @return array
  * @throws \Exception
  */
 public function manipulateImage($file, array $options)
 {
     // Detect file type
     if ($file instanceof Temp) {
         $sanitizedFilename = $this->sanitizeFilename($file->filename);
     } elseif ($file instanceof UploadedFile) {
         $sanitizedFilename = $this->sanitizeFilename($file->getClientOriginalName());
     } elseif ($file instanceof File) {
         $actualFilename = str_replace('_source.', '.', $file->getFilename());
         $sanitizedFilename = $this->sanitizeFilename($actualFilename);
         $sourceFile = clone $file;
     } else {
         throw new \Exception('Unexpected file of class ' . get_class($file));
     }
     $images = [];
     $pathParts = pathinfo($sanitizedFilename);
     // Move uploaded file and rename it as source file if this is needed.
     // We need to generate unique name if the name is already in use.
     if (!isset($sourceFile)) {
         $filename = $pathParts['filename'] . '_source.' . $pathParts['extension'];
         $sourceFile = $file->move($this->getThumbnailPath(), $filename);
     }
     $images['original']['source'] = $sourceFile;
     // If we have retina factor
     if ($this->getRetinaFactor()) {
         // Generate retina image by just copying the source.
         $retinaFilename = $this->generateRetinaName($sanitizedFilename);
         FileFacade::copy($sourceFile->getRealPath(), $this->getThumbnailPath() . $retinaFilename);
         $images['original']['retina'] = Image::make($this->getThumbnailPath() . $retinaFilename);
         // The original image is scaled down version of the source.
         $originalImage = Image::make($sourceFile->getRealPath());
         $width = round($originalImage->getWidth() / $this->getRetinaFactor());
         $height = round($originalImage->getHeight() / $this->getRetinaFactor());
         $originalImage->resize($width, $height);
         $images['original']['original_file'] = $originalImage->save($this->getThumbnailPath() . $sanitizedFilename);
         // Generate thumbs
         foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) {
             // Create retina thumb
             $images['thumbnails'][$thumbnailName]['retina'] = $this->createThumbnail($sourceFile->getRealPath(), $thumbnailName, $this->generateRetinaName($sanitizedFilename), $thumbnailOptions['width'] * $this->getRetinaFactor(), $thumbnailOptions['height'] * $this->getRetinaFactor(), $thumbnailOptions['type'], array_get($thumbnailOptions, 'color'));
             // Create original thumb
             $images['thumbnails'][$thumbnailName]['original'] = $this->createThumbnail($sourceFile->getRealPath(), $thumbnailName, $sanitizedFilename, $thumbnailOptions['width'], $thumbnailOptions['height'], $thumbnailOptions['type'], array_get($thumbnailOptions, 'color'));
         }
     } else {
         // Copy source file.
         $filename = $this->sanitizeFilename($file->getFilename());
         FileFacade::copy($sourceFile->getRealPath(), $this->getThumbnailPath() . $filename);
         $images['original']['original_file'] = Image::make($this->getThumbnailPath() . $filename);
         // Generate thumbs
         foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) {
             // Create original thumb
             $images['thumbnails'][$thumbnailName]['original'] = $this->createThumbnail($sourceFile->getRealPath(), $thumbnailName, $sanitizedFilename, $thumbnailOptions['width'], $thumbnailOptions['height'], $thumbnailOptions['type']);
         }
     }
     return $images;
 }