/** * Constructor. * * @param File $file A File instance */ public function __construct(File $file) { if ($file instanceof UploadedFile) { parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); } else { parent::__construct($file->getPathname(), $file->getBasename(), $file->getMimeType(), $file->getSize(), 0, true); } }
/** * Sends the file using the encryption manager with the php://output internal stream */ public function sendContent() { if (!$this->isSuccessful()) { parent::sendContent(); return; } $this->encryptionManager->decryptFile($this->file->getPathname(), 'php://output', $this->fileSize); }
/** * Store a file and return the hash * @param File $file * @return string $hash */ public function storeFile(File $file) { $hash = md5_file($file->getPathname()); if (!$this->fileSystem->exists($this->getPath($hash))) { $this->fileSystem->rename($file->getPathname(), $this->getPath($hash)); } return $hash; }
/** * Sets the file to stream. * * @param \SplFileInfo|string $file The file to stream * @param string $contentDisposition * @param bool $autoEtag * @param bool $autoLastModified * * @return BinaryFileResponse * * @throws FileException */ public function setFile($file, $contentDisposition = null, $etag = false, $lastModified = true) { if (!$file instanceof File) { if ($file instanceof \SplFileInfo) { $file = new File($file->getPathname()); } else { $file = new File((string) $file); } } if (!$file->isReadable()) { throw new FileException('File must be readable.'); } $this->file = $file; if ($etag === true) { $this->setAutoEtag(); } elseif (!empty($etag)) { $this->setEtag($etag); } if ($lastModified === true) { $this->setAutoLastModified(); } elseif (!empty($lastModified)) { is_numeric($lastModified) && ($lastModified = '@' . $lastModified); $this->setLastModified(new \DateTime($lastModified)); } if ($contentDisposition) { $this->setContentDisposition($contentDisposition); } return $this; }
/** * @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; }
/** * @param File $file * @return Sale[] */ public function crawl(File $file) { $sales = []; $crawler = new Crawler(file_get_contents($file->getPathname())); /** @var $saleItem \DOMElement */ foreach ($crawler->filterXPath('//Data/Items/Item') as $saleItem) { $saleObj = new Sale(); $tag = $saleItem->getAttribute('Tag'); $tagEntity = $this->getEm()->getRepository('AffiliateDashboardBundle:Tag')->findbyName($tag); if (!$tagEntity) { $tagEntity = new Tag(); $tagEntity->setName($tag); $this->getEm()->persist($tagEntity); $this->getEm()->flush(); } $saleObj->setAsin($saleItem->getAttribute('ASIN')); $saleObj->setCategory($saleItem->getAttribute('Category')); $saleObj->setDate(new \DateTime(date('Y-m-d H:i:s', $saleItem->getAttribute('EDate')))); $saleObj->setEarnings($this->parseFloat($saleItem->getAttribute('Earnings'))); $saleObj->setLinkType($saleItem->getAttribute('LinkType')); $saleObj->setPrice($this->parseFloat($saleItem->getAttribute('Price'))); $saleObj->setQty((int) $saleItem->getAttribute('Qty')); $saleObj->setRate($this->parseFloat($saleItem->getAttribute('Rate'))); $saleObj->setRevenue($this->parseFloat($saleItem->getAttribute('Revenue'))); $saleObj->setAffiliateTag($tagEntity); $saleObj->setSeller($saleItem->getAttribute('Seller') ?: null); $saleObj->setTitle($saleItem->getAttribute('Title')); $sales[] = $saleObj; } return $sales; }
/** * 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; }
public function testGuessExtensionIsBasedOnMimeType() { $file = new File(__DIR__ . '/Fixtures/test'); $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif'); MimeTypeGuesser::getInstance()->register($guesser); $this->assertEquals('gif', $file->guessExtension()); }
/** * @param File $file * * @return NotImageGivenException */ public static function create(File $file) { $msg = sprintf('File "%s" is not an image, expected mime type is image/*, given - ', $file->getPathname(), $file->getMimeType()); $me = new static($msg); $me->failedFile = $file; return $me; }
/** * @param File $file * * @return $this */ public function setFile(File $file) { $this->file = $file; if ($file->getPathname()) { $this->filename = sha1(uniqid(mt_rand(), true)) . '.' . $file->guessExtension(); } return $this; }
/** * @return mixed * @VirtualProperty */ public function getProductImage() { $filePath = __DIR__ . '/../../../web/productPhoto/' . $this->image; if (file_exists($filePath)) { $file = new File($filePath); return array('fileInfo' => array('type' => $file->getMimeType(), 'encodeType' => 'base64'), 'fileInBinary' => base64_encode(file_get_contents($file->getPathname()))); } return null; }
/** * @requires extension fileinfo */ public function testGuessExtensionWithReset() { $file = new File(__DIR__ . '/Fixtures/other-file.example'); $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif'); MimeTypeGuesser::getInstance()->register($guesser); $this->assertEquals('gif', $file->guessExtension()); MimeTypeGuesser::reset(); $this->assertNull($file->guessExtension()); }
/** * @param File $file * @param $namespace * @param $image_hash * @param $image_thumb * @return File */ public function copyToCache(File $file, $namespace, $image_hash, $image_thumb) { $dest = $this->createDestinationPath($namespace, $image_hash, $image_thumb); umask(00); if (!@copy($file->getPathname(), $dest)) { $err = error_get_last(); throw new FileException($err['message']); } return new File($dest); }
/** * @return Image */ public function processImage() { // create an image manager instance with favored driver $manager = new ImageManager(['driver' => $this->configuration->getDriver()]); $this->image = $manager->make($this->nativeImage->getPathname()); foreach ($this->processors as $processor) { $processor->process($this->image); } return $this->image; }
/** * Resize user avatar from uploaded picture * @param \Symfony\Component\HttpFoundation\File\UploadedFile|\Symfony\Component\HttpFoundation\File\File $original * @param int $user_id * @param string $size * @throws \Exception * @return null */ public function resizeAndSave($original, $user_id, $size = 'small') { $sizeConvert = ['big' => [400, 400], 'medium' => [200, 200], 'small' => [100, 100]]; if (!array_key_exists($size, $sizeConvert)) { return null; } $image = new Image(); $image->setCacheDir(root . '/Private/Cache/images'); $image->open($original->getPathname())->cropResize($sizeConvert[$size][0], $sizeConvert[$size][1])->save(root . '/upload/user/avatar/' . $size . '/' . $user_id . '.jpg', 'jpg', static::COMPRESS_QUALITY); return null; }
/** * Replaces the current file with a new file. * * @param UploadedFile $file The target file * @param File $filesystemFile The source file */ public function replaceFromFilesystem(UploadedFile $file, File $filesystemFile) { $file->setOriginalFilename($filesystemFile->getBasename()); $file->setExtension($filesystemFile->getExtension()); $file->setMimeType($filesystemFile->getMimeType()); $file->setSize($filesystemFile->getSize()); $storage = $this->getStorage($file); if ($filesystemFile->getSize() > $this->container->get("partkeepr_systemservice")->getFreeDiskSpace()) { throw new DiskSpaceExhaustedException(); } $storage->write($file->getFullFilename(), file_get_contents($filesystemFile->getPathname()), true); }
/** * {@inheritDoc} */ public function create(File $file) { $mc = $this->getMediaClass(); $baseFile = new $mc(); $baseFile->setPath($file->getPathname()); $baseFile->setName($file->getClientOriginalName()); if ($baseFile instanceof BaseFile) { $baseFile->setCreatedAt(new \DateTime()); $baseFile->setSize($file->getSize()); $baseFile->setContentType($file->getMimeType()); } return $baseFile; }
/** * Sends the file. * * {@inheritdoc} */ public function sendContent() { if (!$this->isSuccessful()) { return parent::sendContent(); } if (0 === $this->maxlen) { return $this; } $out = fopen('php://output', 'wb'); $file = fopen($this->file->getPathname(), 'rb'); stream_copy_to_stream($file, $out, $this->maxlen, $this->offset); fclose($out); fclose($file); return $this; }
/** * Upload local file to storage * * @access public * @param mixed $pathname * @param bool $unlinkAfterUpload (default: true) * @return string */ public function uploadByPath($pathname, $unlinkAfterUpload = true) { $file = new File($pathname); $filename = $file->getBasename(); $fileMimeType = $file->getMimeType(); if ($this->allowedTypes && !in_array($fileMimeType, $this->allowedTypes)) { throw new \InvalidArgumentException(sprintf('Files of type %s are not allowed.', $fileMimeType)); } $adapter = $this->filesystem->getAdapter(); if (!$adapter instanceof Local) { $adapter->setMetadata($filename, ['contentType' => $fileMimeType]); } $adapter->write($filename, file_get_contents($file->getPathname())); if ($unlinkAfterUpload) { unlink($file->getPathname()); } return $filename; }
/** * @param $thumbnailType * @param File $file * @return string */ protected function generateThumbnail($thumbnailType, File $file) { $filename = $file->getPathname(); $imageSpec = new ImageSpecification(); if ($thumbnailType === ThumbnailManager::TYPE_LOGO) { //resize collection logo $media = $this->application->getMediaFromUri($filename); if ($this->shouldResize($media, 120, 24)) { $this->setSpecificationSize($imageSpec, 120, 24); } $filename = $this->resizeMediaFile($file, $imageSpec); return $filename; } elseif ($thumbnailType === ThumbnailManager::TYPE_PRESENTATION) { //resize collection logo $this->setSpecificationSize($imageSpec, 650, 200); $filename = $this->resizeMediaFile($file, $imageSpec); return $filename; } return $filename; }
public function postBuild(Fixture $fixture) { /** @var Media $media */ $media = $fixture->getEntity(); $filePath = $media->getOriginalFilename(); $data = new File($filePath, true); $contentType = $this->mimeTypeGuesser->guess($data->getPathname()); if (method_exists($data, 'getClientOriginalName')) { $media->setOriginalFilename($data->getClientOriginalName()); } else { $media->setOriginalFilename($data->getFilename()); } if ($media->getName() === null) { $media->setName($media->getOriginalFilename()); } $media->setContent($data); $media->setContentType($contentType); $media->setFolder($this->folder); $this->fileHandler->prepareMedia($media); $this->fileHandler->updateMedia($media); $this->fileHandler->saveMedia($media); }
/** * Sets the file to stream. * * @param \SplFileInfo|string $file The file to stream * @param string $contentDisposition * @param bool $autoEtag * @param bool $autoLastModified * * @return BinaryFileResponse * * @throws FileException */ public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) { if (!$file instanceof File) { if ($file instanceof \SplFileInfo) { $file = new File($file->getPathname()); } else { $file = new File((string) $file); } } if (!$file->isReadable()) { throw new FileException('File must be readable.'); } $this->file = $file; if ($autoEtag) { $this->setAutoEtag(); } if ($autoLastModified) { $this->setAutoLastModified(); } if ($contentDisposition) { $this->setContentDisposition($contentDisposition); } return $this; }
/** * @param File $file */ public function setLocalFile(File $file) { $this->localFile = $file; $this->body = file_get_contents($file->getPathname()); $this->setContentType($file->getMimeType()); $this->setContentLength($file->getSize()); $this->setETag(md5_file($file->getPathname())); }
public function getTemplateData(File $file, $refresh = false) { //from cache if (!$refresh) { return $this->importData; } $archive = new \ZipArchive(); $fileName = $file->getBasename('.zip'); $extractPath = $this->templateDirectory . DIRECTORY_SEPARATOR . $fileName; if ($archive->open($file->getPathname())) { $fs = new FileSystem(); $fs->mkdir($extractPath); if (!$archive->extractTo($extractPath)) { throw new \Exception("The workspace archive couldn't be extracted"); } $archive->close(); $resolver = new Resolver($extractPath); $this->importData = $resolver->resolve(); return $this->importData; } throw new \Exception("The workspace archive couldn't be opened"); }
private function optimizeJpg(File $file) { $path = $file->getPathname(); $cmd = "jpegtran -copy none -optimize -progressive -outfile {$path} {$path}"; shell_exec($cmd); }
/** * Sets the correct content-type * * @param File $file * @param Response $response */ private function setContentType(File $file, Response $response) { $extension = pathinfo($file->getPathname(), PATHINFO_EXTENSION); switch ($extension) { case 'css': $contentType = 'text/css'; break; case 'js': $contentType = 'application/javascript'; break; case 'png': $contentType = 'image/png'; break; case 'jpg': case 'jpeg': $contentType = 'image/jpeg'; break; case 'gif': $contentType = 'image/gif'; break; case 'txt': $contentType = 'text/plain'; break; default: $contentType = $file->getMimeType(); break; } $response->headers->set('Content-Type', $contentType); }
/** * Extract archive * * @param \Symfony\Component\HttpFoundation\File\File $file * @param \Thelia\Core\Archiver\ArchiverInterface $archiver * * @return \Symfony\Component\HttpFoundation\File\File First file in unarchiver */ public function extractArchive(File $file, ArchiverInterface $archiver) { $archiver->open($file->getPathname()); $extractpath = dirname($archiver->getArchivePath()) . DS . uniqid(); $archiver->extract($extractpath); /** @var \DirectoryIterator $item */ foreach (new \DirectoryIterator($extractpath) as $item) { if (!$item->isDot() && $item->isFile()) { $file = new File($item->getPathname()); break; } } return $file; }
/** * Generate Thumbnail images with ImageMagick. * * @param string $imageData Image Data * @param int $height Height value * @param int $width Width value * @param int $type Type * * @return string Resized image data * * @throws \RuntimeException */ public function resize($imageData, $height, $width, $type = ElcodiMediaImageResizeTypes::FORCE_MEASURES) { if (ElcodiMediaImageResizeTypes::NO_RESIZE === $type) { return $imageData; } $originalFile = new File(tempnam(sys_get_temp_dir(), '_original')); $resizedFile = new File(tempnam(sys_get_temp_dir(), '_resize')); file_put_contents($originalFile, $imageData); //ImageMagick params $pb = new ProcessBuilder(); $pb->add($this->imageConverterBin)->add($originalFile->getPathname())->add('-profile')->add($this->profile); //Lanczos filter for reduction $pb->add('-filter')->add('Lanczos'); if ($width == 0) { $width = ''; } if ($height == 0) { $height = ''; } /** * Apply some filters depending on type of resizing. */ if ($width || $height) { $pb->add('-resize'); switch ($type) { case ElcodiMediaImageResizeTypes::INSET: $pb->add($width . 'x' . $height); break; case ElcodiMediaImageResizeTypes::INSET_FILL_WHITE: $pb->add($width . 'x' . $height)->add('-gravity')->add('center')->add('-extent')->add($width . 'x' . $height); break; case ElcodiMediaImageResizeTypes::OUTBOUNDS_FILL_WHITE: $pb->add($width . 'x' . $height . ''); break; case ElcodiMediaImageResizeTypes::OUTBOUND_CROP: $pb->add($width . 'x' . $height . '^')->add('-gravity')->add('center')->add('-crop')->add($width . 'x' . $height . '+0+0'); break; case ElcodiMediaImageResizeTypes::FORCE_MEASURES: default: $pb->add($width . 'x' . $height . '!'); break; } } $proc = $pb->add($resizedFile->getPathname())->getProcess(); $proc->run(); if (false !== strpos($proc->getOutput(), 'ERROR')) { throw new \RuntimeException($proc->getOutput()); } $imageContent = file_get_contents($resizedFile->getRealPath()); unlink($originalFile); unlink($resizedFile); return $imageContent; }
public function remove(File $file) { $this->filesystem->remove($file->getPathname()); }
/** * @param File $file */ public function setFile(File $file) { $this->file = $file; if (strlen($file->getPathname()) > 0) { $this->media->setContent($file); $this->media->setContentType($file->getMimeType()); $this->media->setUrl('/uploads/media/' . $this->media->getUuid() . '.' . $this->media->getContent()->getExtension()); } }