Ejemplo n.º 1
0
 /**
  * @param Request $request
  * @param $storageKey
  *
  * @return Response
  */
 protected function createFileResponse(Request $request, $storageKey)
 {
     $response = new Response();
     $parts = explode('/', $storageKey);
     $file = $this->getFile($parts[0]);
     if (!$file) {
         return $response->setContent('File not found.')->setStatusCode(Response::HTTP_NOT_FOUND);
     }
     if ($request->get('dl') !== null) {
         $filename = $file->getFilename();
         if (count($parts) > 1) {
             $filename = $parts[count($parts) - 1];
         }
         $filenameFallback = filter_var($filename, FILTER_SANITIZE_URL);
         if ($filenameFallback != $filename) {
             $guesser = ExtensionGuesser::getInstance();
             $extension = filter_var($guesser->guess($file->getMimeType()) ?: $file->getExtension(), FILTER_SANITIZE_URL);
             $filenameFallback = $file->getStorageKey() . ($extension ? '.' . $extension : '');
         }
         $response->headers->set('Content-Disposition', $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename, $filenameFallback));
     } else {
         $response->setCache(array('etag' => $file->getStorageKey(), 'last_modified' => $file->getCreatedAt()));
         if ($response->isNotModified($request)) {
             return $response;
         }
     }
     $response->setContent($file->getContents());
     $response->headers->set('Content-type', $file->getMimeType());
     $response->headers->set('Content-length', $file->getSize());
     return $response;
 }
 /**
  * @dataProvider provideLoadCases
  */
 public function testLoad($rootDir, $path)
 {
     $loader = new FileSystemLoader(MimeTypeGuesser::getInstance(), ExtensionGuesser::getInstance(), $rootDir);
     $binary = $loader->find($path);
     $this->assertInstanceOf('Liip\\ImagineBundle\\Model\\Binary', $binary);
     $this->assertStringStartsWith('text/', $binary->getMimeType());
 }
Ejemplo n.º 3
0
Archivo: File.php Proyecto: n3b/symfony
    /**
     * Returns the extension based on the mime type.
     *
     * If the mime type is unknown, returns null.
     *
     * @return string|null The guessed extension or null if it cannot be guessed
     *
     * @api
     */
    public function guessExtension()
    {
        $type = $this->getMimeType();
        $guesser = ExtensionGuesser::getInstance();

        return $guesser->guess($type);
    }
 private function guessFileExtension($mimeType)
 {
     $candidate = ExtensionGuesser::getInstance()->guess($mimeType);
     if (!isset($candidate)) {
         return DEFAULT_FILE_EXTENSION;
     }
     return $candidate;
 }
Ejemplo n.º 5
0
 /**
  * Gets the 'liip_imagine.extension_guesser' service.
  *
  * This service is shared.
  * This method always returns the same instance of the service.
  *
  * @return \Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface A Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface instance
  */
 protected function getLiipImagine_ExtensionGuesserService()
 {
     return $this->services['liip_imagine.extension_guesser'] = \Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser::getInstance();
 }
Ejemplo n.º 6
0
 /**
  * Set media binary content according to request content.
  *
  * @param MediaInterface $media
  */
 protected function generateBinaryFromRequest(MediaInterface $media)
 {
     if (php_sapi_name() === 'cli') {
         throw new \RuntimeException('The current process cannot be executed in cli environment');
     }
     if (!$media->getContentType()) {
         throw new \RuntimeException('You must provide the content type value for your media before setting the binary content');
     }
     $request = $media->getBinaryContent();
     if (!$request instanceof Request) {
         throw new \RuntimeException('Expected Request in binary content');
     }
     $content = $request->getContent();
     // create unique id for media reference
     $guesser = ExtensionGuesser::getInstance();
     $extension = $guesser->guess($media->getContentType());
     if (!$extension) {
         throw new \RuntimeException(sprintf('Unable to guess extension for content type %s', $media->getContentType()));
     }
     $handle = tmpfile();
     fwrite($handle, $content);
     $file = new ApiMediaFile($handle);
     $file->setExtension($extension);
     $file->setMimetype($media->getContentType());
     $media->setBinaryContent($file);
 }
Ejemplo n.º 7
0
 /**
  * Returns an archive with the required content.
  *
  * @param array $nodes[] the nodes being exported
  *
  * @throws ExportResourceException
  *
  * @return array
  */
 public function download(array $elements, $forceArchive = false)
 {
     $data = [];
     if (count($elements) === 0) {
         throw new ExportResourceException('No resources were selected.');
     }
     $archive = new \ZipArchive();
     $pathArch = $this->container->get('claroline.config.platform_config_handler')->getParameter('tmp_dir') . DIRECTORY_SEPARATOR . $this->ut->generateGuid() . '.zip';
     $archive->open($pathArch, \ZipArchive::CREATE);
     $nodes = $this->expandResources($elements);
     if (!$forceArchive && count($nodes) === 1) {
         $event = $this->dispatcher->dispatch("download_{$nodes[0]->getResourceType()->getName()}", 'DownloadResource', [$this->getResourceFromNode($this->getRealTarget($nodes[0]))]);
         $extension = $event->getExtension();
         $data['name'] = empty($extension) ? $nodes[0]->getName() : $nodes[0]->getName() . '.' . $extension;
         $data['file'] = $event->getItem();
         $guesser = ExtensionGuesser::getInstance();
         $data['mimeType'] = $guesser->guess($nodes[0]->getMimeType()) !== null ? $nodes[0]->getMimeType() : null;
         return $data;
     }
     if (isset($elements[0])) {
         $currentDir = $elements[0];
     } else {
         $archive->addEmptyDir($elements[0]->getName());
     }
     foreach ($nodes as $node) {
         //we only download is we can...
         if ($this->container->get('security.context')->isGranted('EXPORT', $node)) {
             $node = $this->getRealTarget($node);
             $resource = $this->getResourceFromNode($node);
             if ($resource) {
                 if (get_class($resource) === 'Claroline\\CoreBundle\\Entity\\Resource\\ResourceShortcut') {
                     $node = $resource->getTarget();
                 }
                 $filename = $this->getRelativePath($currentDir, $node) . $node->getName();
                 $resource = $this->getResourceFromNode($node);
                 //if it's a file, we may have to add the extension back in case someone removed it from the name
                 if ($node->getResourceType()->getName() === 'file') {
                     $extension = '.' . pathinfo($resource->getHashName(), PATHINFO_EXTENSION);
                     if (!preg_match("#{$extension}#", $filename)) {
                         $filename .= $extension;
                     }
                 }
                 if ($node->getResourceType()->getName() !== 'directory') {
                     $event = $this->dispatcher->dispatch("download_{$node->getResourceType()->getName()}", 'DownloadResource', [$resource]);
                     $obj = $event->getItem();
                     if ($obj !== null) {
                         $archive->addFile($obj, iconv(mb_detect_encoding($filename), $this->getEncoding(), $filename));
                     } else {
                         $archive->addFromString(iconv(mb_detect_encoding($filename), $this->getEncoding(), $filename), '');
                     }
                 } else {
                     $archive->addEmptyDir(iconv(mb_detect_encoding($filename), $this->getEncoding(), $filename));
                 }
                 $this->dispatcher->dispatch('log', 'Log\\LogResourceExport', [$node]);
             }
         }
     }
     $archive->close();
     $tmpList = $this->container->getParameter('claroline.param.platform_generated_archive_path');
     file_put_contents($tmpList, $pathArch . "\n", FILE_APPEND);
     $data['name'] = 'archive.zip';
     $data['file'] = $pathArch;
     $data['mimeType'] = 'application/zip';
     $this->container->get('claroline.core_bundle.listener.kernel_terminate_listener')->addElementToRemove($pathArch);
     return $data;
 }
Ejemplo n.º 8
0
 /**
  * Validate file extension
  * 
  * @param  string $path
  * @return void
  */
 protected function validateFileExtension($path)
 {
     $extensions = $this->getAllowedUploadExtensions();
     // Get file mime type
     $mime = $this->filesystem->mimeType($path);
     $extensionGuesser = ExtensionGuesser::getInstance();
     $extension = $extensionGuesser->guess($mime);
     $meta = ['extension' => $extension];
     if (!in_array($extension, $extensions)) {
         throw new UnallowedFileExtensionException([$path], $meta, "Uploading [.{$extension}] file is prohibited");
     }
 }
 public function __construct()
 {
     $this->mimeTypeGuesser = MimeTypeGuesser::getInstance();
     $this->extensionGuesserFromMimeType = ExtensionGuesserFromMimetype::getInstance();
 }
Ejemplo n.º 10
0
 /**
  * Process inline images. Convert it to embedded attachments and update message body.
  *
  * @param \Swift_Message $message
  * @param EmailModel     $model
  */
 protected function processEmbeddedImages(\Swift_Message $message, EmailModel $model)
 {
     if ($model->getType() === 'html') {
         $guesser = ExtensionGuesser::getInstance();
         $body = $message->getBody();
         $body = preg_replace_callback('/<img(.*)src(\\s*)=(\\s*)["\'](.*)["\']/U', function ($matches) use($message, $guesser, $model) {
             if (count($matches) === 5) {
                 // 1st match contains any data between '<img' and 'src' parts (e.g. 'width=100')
                 $imgConfig = $matches[1];
                 // 4th match contains src attribute value
                 $srcData = $matches[4];
                 if (strpos($srcData, 'data:image') === 0) {
                     list($mime, $content) = explode(';', $srcData);
                     list($encoding, $file) = explode(',', $content);
                     $mime = str_replace('data:', '', $mime);
                     $fileName = sprintf('%s.%s', uniqid(), $guesser->guess($mime));
                     $swiftAttachment = \Swift_Image::newInstance(ContentDecoder::decode($file, $encoding), $fileName, $mime);
                     /** @var $message \Swift_Message */
                     $id = $message->embed($swiftAttachment);
                     $attachmentContent = new EmailAttachmentContent();
                     $attachmentContent->setContent($file);
                     $attachmentContent->setContentTransferEncoding($encoding);
                     $emailAttachment = new EmailAttachment();
                     $emailAttachment->setEmbeddedContentId($swiftAttachment->getId());
                     $emailAttachment->setFileName($fileName);
                     $emailAttachment->setContentType($mime);
                     $attachmentContent->setEmailAttachment($emailAttachment);
                     $emailAttachment->setContent($attachmentContent);
                     $emailAttachmentModel = new EmailAttachmentModel();
                     $emailAttachmentModel->setEmailAttachment($emailAttachment);
                     $model->addAttachment($emailAttachmentModel);
                     return sprintf('<img%ssrc="%s"', $imgConfig, $id);
                 }
             }
         }, $body);
         $message->setBody($body, 'text/html');
     }
 }
 protected function getExtension($contentNode)
 {
     if ($contentNode->hasProperty('jcr:mimeType')) {
         $mimeType = $contentNode->getPropertyValue('jcr:mimeType');
         $extension = ExtensionGuesser::getInstance()->guess($mimeType);
         if (null !== $extension) {
             return '.' . $extension;
         }
     }
     return '';
 }
Ejemplo n.º 12
0
 public function __construct()
 {
     $this->extensionGuesser = ExtensionGuesser::getInstance();
 }
Ejemplo n.º 13
0
 /**
  * Convert mime type to extension
  *
  * @param array $mimeTypes Mime types to conversation
  *
  * @return array
  */
 protected function mimeTypesToExtensions($mimeTypes)
 {
     return array_filter(array_map(function ($mimeType) {
         return ExtensionGuesser::getInstance()->guess($mimeType);
     }, $mimeTypes), 'strlen');
 }
 public function testCouldBeConstructedWithExpectedArguments()
 {
     return new FlysystemLoader(ExtensionGuesser::getInstance(), $this->flyFilesystem);
 }
Ejemplo n.º 15
0
 /**
  * Sets file metadata.
  *
  * @ORM\PrePersist()
  *
  * @return $this
  */
 public function setFileMetadata()
 {
     $httpFile = $this->createHttpFile();
     $this->mimeType = $httpFile->getMimeType();
     $extensionGuesser = ExtensionGuesser::getInstance();
     $this->extension = $extensionGuesser->guess($this->mimeType);
     return $this;
 }
 /**
  * Should return an extension guesser instance, used for file uploads
  *
  * NOTE: If you override this, you'll probably still have to register the SVGExtensionGuesser as last guesser...
  *
  * @return ExtensionGuesserInterface
  */
 public function get()
 {
     $guesser = ExtensionGuesser::getInstance();
     $guesser->register(new SVGExtensionGuesser());
     return $guesser;
 }
 /**
  * @param Media $media
  *
  * @return \Gaufrette\File
  */
 public function getOriginalFile(Media $media)
 {
     $relativePath = sprintf('/%s.%s', $media->getUuid(), ExtensionGuesser::getInstance()->guess($media->getContentType()));
     return $this->fileSystem->get($relativePath, true);
 }
 /**
  * Guess extension .
  *
  * @param Image $image
  * @return string
  */
 protected function guessExtension(Image $image)
 {
     $guesser = ExtensionGuesser::getInstance();
     return $guesser->guess($image->mime());
 }