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(); }
/** * Resize image * * @param int $width Thumbnail width * @param int $height Thumbnail height * @param string $fileName Source file name * @return \Response Image content */ public function resize($width, $height, $fileName) { $destFile = $this->createThumb($width, $height, $fileName); $fileContent = $this->getFileContent($destFile); $file = new SymfonyFile($destFile); return response()->make($fileContent, 200, ['content-type' => $file->getMimeType()]); }
public function process(File $file, Image $image) { $imageData = $this->intervention->make($file->getRealPath()); $imageData->brightness($this->brightness); $imageData->blur($this->blur); $imageData->save(null, $this->compression); }
public function testGetDefaultExtensionIsBasedOnMimeType() { $file = new File(__DIR__ . '/Fixtures/test'); $guesser = $this->createMockGuesser($file->getPath(), 'image/gif'); MimeTypeGuesser::getInstance()->register($guesser); $this->assertEquals('.gif', $file->getDefaultExtension()); }
/** * Get original name of file. * * @return string */ public function getName() { if ($this->file instanceof UploadedFile) { return $this->file->getClientOriginalName(); } return $this->file->getFilename(); }
private function regenerateSpeakerPhotoPath($speaker) { // If speaker photo does not exist, null it out and return. if (!$this->fileExists($speaker['photo_path'])) { echo "[info] {$speaker['name']}'s photo was not found in file system. Removing record of it from profile." . PHP_EOL; $this->execute("UPDATE users SET photo_path = '' WHERE id = {$speaker['id']}"); return; } // Need to guess extension. Cannot trust current file extensions. $file = new File(__DIR__ . '/../web/uploads/' . $speaker['photo_path']); $extension = $file->guessExtension(); // Otherwise, generate a new filename. $generator = new PseudoRandomStringGenerator(new Factory()); $newFileName = $generator->generate(40) . '.' . $extension; $oldFilePath = __DIR__ . '/../web/uploads/' . $speaker['photo_path']; $newFilePath = __DIR__ . '/../web/uploads/' . $newFileName; // If photo name is changed in file system, update record in database. if (rename($oldFilePath, $newFilePath)) { try { $this->execute("UPDATE users SET photo_path = '{$newFileName}' WHERE id = '{$speaker['id']}'"); echo "[info] Regenerated photo path for {$speaker['name']}." . PHP_EOL; } catch (\Exception $e) { // If update fails for any reason, revert filename in file system. rename($newFilePath, $oldFilePath); } } }
protected function handle() { $request = $this->getRequest(); $posts = $request->request; $file_path = $posts->get('image_path'); $x = $posts->get('x'); $y = $posts->get('y'); $w = $posts->get('w'); $h = $posts->get('h'); $path_info = pathinfo($file_path); $imagine = new Imagine(); $raw_image = $imagine->open($file_path); $large_image = $raw_image->copy(); $large_image->crop(new Point($x, $y), new Box($w, $h)); $large_file_path = "{$path_info['dirname']}/{$path_info['filename']}_large.{$path_info['extension']}"; $large_image->save($large_file_path, array('quality' => 70)); $origin_dir_name = $path_info['dirname']; $new_directory = str_replace('/tmp', '', $origin_dir_name); $new_file = new File($large_file_path); $new_file->move($new_directory, "{$path_info['filename']}.{$path_info['extension']}"); $container = $this->getContainer(); $cdn_url = $container->getParameter('cdn_url'); $new_uri = $cdn_url . '/upload/' . $path_info['filename'] . '.' . $path_info['extension']; @unlink($large_file_path); @unlink($file_path); return new JsonResponse(array('picture_uri' => $new_uri)); }
protected static function boot() { parent::boot(); static::updating(function ($model) { $changed = $model->getDirty(); if (isset($changed['name'])) { $slug = $model->gallery->slug; $path = public_path() . '/gallery_assets/galleries/' . $slug; //Get old file $oldPath = $path . '/' . $model->file; $file = new File($oldPath); //Set the new file with original extension $newName = strtolower(str_slug($model->name) . '_' . str_random(5)) . '.' . $file->getExtension(); $renamed = $path . '/' . $newName; //Rename asset if (rename($file, $renamed)) { $model->setAttribute('file', $newName); return true; } else { return false; } } return true; }); static::deleting(function ($model) { $slug = $model->gallery->slug; $path = public_path() . '/gallery_assets/galleries/' . $slug; $oldPath = $path . '/' . $model->file; $file = new File($oldPath); @unlink($file); //@ to prevent errors return true; }); }
public function run(File $file) { $image = $this->intervention->make($file->getRealPath()); $image->orientate(); $image->save(null, 100); $image->destroy(); }
/** * @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); }
/** * {@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 $imageFileObject * @param $finalMimeType * * @dataProvider imagesAsOctetStreamProvider */ public function testCreateImagesFromApplicationOctetStream(File $imageFileObject, $finalMimeType) { $this->assertEquals('application/octet-stream', $imageFileObject->getMimeType()); $image = $this->imageManager->createImage($imageFileObject); $this->assertInstanceOf('Elcodi\\Component\\Media\\Entity\\Interfaces\\ImageInterface', $image); $this->assertEquals($finalMimeType, $image->getContentType()); }
/** * @param FormEvent $event */ public function move(FormEvent $event) { $data = $event->getData(); if (is_callable($this->dstDir)) { $dstDir = call_user_func($this->dstDir, $event->getForm()->getParent()->getData()); } else { $dstDir = $this->dstDir; } if (!empty($data)) { foreach ($data as $key => $path) { // First check if the file is still in tmp directory $originalFilename = $this->rootDir . '/../web/' . trim($path, '/'); $destinationFilename = $this->rootDir . '/../web/' . trim($dstDir, '/') . '/' . basename($path); $webPath = rtrim($dstDir, '/') . '/' . basename($path); if (file_exists($originalFilename)) { // if it does, then move it to the destination and update the data $file = new File($originalFilename); $file->move(dirname($destinationFilename)); // modify the form data with the new path $data[$key] = $webPath; } else { // otherwise check if it is already on the destination if (file_exists($destinationFilename)) { // if it does, simply modify the form data with the new path // modify the form data with the new path $data[$key] = $webPath; } else { // TODO : check if we need to throw an exception here unset($data[$key]); } } } $event->setData($data); } }
/** * 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; }
/** * 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 array $parameters * * @return mixed|void */ public function missingMethod($parameters = array()) { if (is_array($parameters)) { $parameters = implode('/', $parameters); } # If parameters is a file if ($file = $this->path($parameters)) { $response = \with(new AssetCollection(array(new FileAsset($file))))->dump(); } elseif ($aParameters = json_decode($parameters, TRUE)) { array_walk($aParameters, function (&$item) { $item = new FileAsset($this->path($item)); }); $response = \with(new AssetCollection($aParameters))->dump(); } if (isset($response)) { $headers = array(); if (preg_match('/.css/i', $parameters)) { $headers['Content-Type'] = 'text/css'; } elseif (preg_match('/.js/i', $parameters)) { $headers['Content-Type'] = 'text/javascript'; } elseif (preg_match('/.html|.htm|.php/i', $parameters)) { $headers['Content-Type'] = 'text/html'; } else { $file = new File($file); $mime = $file->getMimeType(); if ($mime) { $headers['Content-Type'] = $mime; } else { $headers['Content-Type'] = 'text/html'; } } return Response::make($response, 200, $headers); } return Response::make('', 404); }
/** * @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; }
/** * @Route("/download/{resource}", name="bkstg_resource_download_resource") * @ParamConverter("resource", class="BkstgResourceBundle:Resource") */ public function downloadAction(Resource $resource) { $file = new File($resource->getAbsolutePath()); $headers = array('Content-Type' => $file->getMimeType(), 'Content-Disposition' => 'attachment; filename="' . $resource->getPath() . '"'); $filename = $resource->getAbsolutePath(); return new HttpFoundation\Response(file_get_contents($filename), 200, $headers); }
/** * @param Contribution $contribution * @param File $file * * @return string */ public function generateRelativePath(Contribution $contribution, File $file) { $path = $contribution->getAuthProvider() . DIRECTORY_SEPARATOR; $path .= $contribution->getIdentifier(); $path .= '.' . ($file->guessExtension() ?: $file->getExtension()); return $path; }
/** * @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; }
/** * Handles image upload and resize * * @param string $context * @param File $uploadedFile * @param string $fileName * @param bool $useHashAsFilename * * @return string */ public function upload($context, File $uploadedFile, $fileName = null, $useHashAsFilename = null) { if (null === $useHashAsFilename) { $useHashAsFilename = $this->config['use_hash_as_image_name']; } $contextPath = $this->config['base_path'] . '/' . $context; if (true === $useHashAsFilename) { $fileName = $this->generateHash(); } $fileName .= '.' . $uploadedFile->guessExtension(); if ($this->filesystem->exists($contextPath . '/' . $fileName) && true === $useHashAsFilename) { $this->upload($contextPath, $uploadedFile, $fileName, $useHashAsFilename); } elseif ($this->filesystem->exists($contextPath . '/' . $fileName) && false === $useHashAsFilename) { throw new IcrLogicException("File {$fileName} exists! Please choose another name!"); } // Upload original file $this->filesystem->dumpFile($contextPath . '/' . $fileName, file_get_contents($uploadedFile->getRealPath())); foreach ($this->config['contexts'][$context] as $sizeName => $values) { // Process and manipulate $manipulator = $this->manipulatorFactory->create($values['operation']); $abstractImage = $this->openImageHandler->openImage($uploadedFile->getPathname()); $image = $manipulator->manipulate($abstractImage, $values['width'], $values['height']); $path = $contextPath . '/' . $sizeName . '/'; $this->filesystem->dumpFile($path . '/' . $fileName, $image); } return $fileName; }
/** * 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); } }
/** * @param \Exolnet\Image\Image $image * @param \Symfony\Component\HttpFoundation\File\File $file */ public function updateImage(Image $image, File $file) { $this->destroy($image); $fileName = $image->getId() . '-' . Str::slug($file->getBasename()) . '.' . $file->guessExtension(); $image->setFilename($fileName); $image->save(); $this->store($image, $file); }
/** * 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); }
/** * @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; }
public function thumb(Request $request, $id) { $photo = Photo::findOrFail($id); $file = new File($photo->path); $photo->makeThumbnail(); $headers = array('Content-Type: ' . $file->getMimeType()); return response()->download($photo->path . '.' . $file->guessExtension(), $photo->name, $headers); }
/** * Constructor * * @param string $streetNames Path of the file containing the street names */ public function __construct($streetNames) { $file = new File($streetNames); $splFileObject = $file->openFile('r'); while (!$splFileObject->eof()) { $this->streetNames[] = trim($splFileObject->fgets()); } }
/** * 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; }
/** * @param File $image * @param string $prefix * @param String $path * @return string */ public function moveFile(File $image, $path, $prefix = '') { $extension = $image->guessExtension(); $code = strtoupper($this->request->get('code')); $fileName = $code . '-' . $prefix . '.' . $extension; $image->move(public_path() . $path, $fileName); return $path . $fileName; }
/** * Save uploaded file without validation * * @param File $file * @param string $newLocation * @param string $newName * @throws FileException * @return File */ protected function saveFile(File $file, $newLocation, $newName = "") { $name = $file->getClientOriginalName(); if ($newName) { $name = $newName; } return $file->move($this->createFolderIfNotExist($newLocation), $this->getUniqueFileName($name, $newLocation)); }