/** * {@inheritdoc} */ public function store(\SplFileInfo $localFile, $destFsAlias, $deleteRawFile = false) { $filesystem = $this->mountManager->getFilesystem($destFsAlias); $file = $this->factory->createFromRawFile($localFile, $destFsAlias); $error = sprintf('Unable to move the file "%s" to the "%s" filesystem.', $localFile->getPathname(), $destFsAlias); if (false === ($resource = fopen($localFile->getPathname(), 'r'))) { throw new FileTransferException($error); } try { $options = []; $mimeType = $file->getMimeType(); if (null !== $mimeType) { $options['ContentType'] = $mimeType; } $isFileWritten = $filesystem->writeStream($file->getKey(), $resource, $options); } catch (FileExistsException $e) { throw new FileTransferException($error, $e->getCode(), $e); } if (false === $isFileWritten) { throw new FileTransferException($error); } $this->saver->save($file); if (true === $deleteRawFile) { $this->deleteRawFile($localFile); } return $file; }
/** * Handle the command. * * @param DiskRepositoryInterface $disks * @param FileRepositoryInterface $files * @param FileFieldTypeParser $parser * @param Request $request * @param MountManager $manager * * @return null|bool|FileInterface */ public function handle(DiskRepositoryInterface $disks, FileRepositoryInterface $files, FileFieldTypeParser $parser, Request $request, MountManager $manager) { $path = trim(array_get($this->fieldType->getConfig(), 'path'), './'); $file = $request->file($this->fieldType->getInputName()); $value = $request->get($this->fieldType->getInputName() . '_id'); /** * Make sure we have at least * some kind of input. */ if ($file === null) { if (!$value) { return null; } return $files->find($value); } // Make sure we have a valid upload disk. First by slug. if (!($disk = $disks->findBySlug($slug = array_get($this->fieldType->getConfig(), 'disk')))) { // If that fails look up by id. if (!($disk = $disks->find($id = array_get($this->fieldType->getConfig(), 'disk')))) { return null; } } // Make the path. $path = $parser->parse($path, $this->fieldType); $path = (!empty($path) ? $path . '/' : null) . $file->getClientOriginalName(); return $manager->putStream($disk->path($path), fopen($file->getRealPath(), 'r+')); }
/** * Retrieve a file content from a virtual file system. * In case no filesystem has this file registered, null is returned. * * @param string $path * * @throws NotLoadableException * * @return Binary|null|string */ protected function retrieveContentFileFromVfs($path) { $content = null; $mimeType = null; foreach ($this->filesystemAliases as $alias) { $fs = $this->mountManager->getFilesystem($alias); if ($fs->has($path)) { //TODO: we should use readStream, the problem is that // \Liip\ImagineBundle\Model\Binary expects the full content... $content = $fs->read($path); $mimeType = $fs->getMimetype($path); } } if (null === $content) { // the path is not stored on any vfs return null; } if (false === $content) { throw new NotLoadableException(sprintf('Unable to read the file "%s" from the filesystem.', $path)); } if (false === $mimeType || null === $mimeType) { return $content; } return new Binary($content, $mimeType); }
/** * {@inheritdoc} */ public function data(ServerRequestInterface $request, Document $document) { $this->assertAdmin($request->getAttribute('actor')); $file = array_get($request->getUploadedFiles(), 'favicon'); $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'favicon'); $file->moveTo($tmpFile); $extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION); if ($extension !== 'ico') { $manager = new ImageManager(); $encodedImage = $manager->make($tmpFile)->resize(64, 64, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->encode('png'); file_put_contents($tmpFile, $encodedImage); $extension = 'png'; } $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($this->app->publicPath() . '/assets'))]); if (($path = $this->settings->get('favicon_path')) && $mount->has($file = "target://{$path}")) { $mount->delete($file); } $uploadName = 'favicon-' . Str::lower(Str::quickRandom(8)) . '.' . $extension; $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $this->settings->set('favicon_path', $uploadName); return parent::data($request, $document); }
/** * Handle the command. * * @param DiskRepositoryInterface $disks * @param FileRepositoryInterface $files * @param FileFieldTypeParser $parser * @param Request $request * @param MountManager $manager * @return null|bool|FileInterface */ public function handle(DiskRepositoryInterface $disks, FileRepositoryInterface $files, FileFieldTypeParser $parser, Request $request, MountManager $manager) { $path = trim(array_get($this->fieldType->getConfig(), 'path'), './'); $entry = $this->fieldType->getEntry(); $file = $request->file($this->fieldType->getInputName()); $value = $request->get($this->fieldType->getInputName() . '_id'); /** * Make sure we have at least * some kind of input. */ if ($file === null) { if (!$value) { return null; } return $files->find($value); } // Make sure we have a valid upload disk. if (!($disk = $disks->find($id = array_get($this->fieldType->getConfig(), 'disk')))) { throw new \Exception("The configured disk [{$id}] for [{$this->fieldType->getInputName()}] could not be found."); } // Make the path. $path = $parser->parse($path, $this->fieldType); $path = (!empty($path) ? $path . '/' : null) . $file->getClientOriginalName(); return $manager->putStream($disk->path($path), fopen($file->getRealPath(), 'r+')); }
/** * @param UploadAvatar $command * @return \Flarum\Core\User * @throws \Flarum\Core\Exception\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); if ($actor->id !== $user->id) { $this->assertCan($actor, 'edit', $user); } $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar'); $command->file->moveTo($tmpFile); try { $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true); $this->validator->assertValid(['avatar' => $file]); $manager = new ImageManager(); // Explicitly tell Intervention to encode the image as JSON (instead of having to guess from the extension) $encodedImage = $manager->make($tmpFile)->fit(100, 100)->encode('jpg', 100); file_put_contents($tmpFile, $encodedImage); $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user, $actor); return $user; } catch (Exception $e) { @unlink($tmpFile); throw $e; } }
/** * @param UploadAvatar $command * @return \Flarum\Core\User * @throws \Flarum\Core\Exception\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); if ($actor->id !== $user->id) { $this->assertCan($actor, 'edit', $user); } $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'avatar'); $command->file->moveTo($tmpFile); $file = new UploadedFile($tmpFile, $command->file->getClientFilename(), $command->file->getClientMediaType(), $command->file->getSize(), $command->file->getError(), true); $this->validator->assertValid(['avatar' => $file]); $manager = new ImageManager(); $manager->make($tmpFile)->fit(100, 100)->save(); $this->events->fire(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user, $actor); return $user; }
/** * @param UploadAvatar $command * @return \Flarum\Core\Users\User * @throws \Flarum\Core\Exceptions\PermissionDeniedException */ public function handle(UploadAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); // Make sure the current user is allowed to edit the user profile. // This will let admins and the user themselves pass through, and // throw an exception otherwise. if ($actor->id !== $user->id) { $user->assertCan($actor, 'edit'); } $tmpFile = tempnam(sys_get_temp_dir(), 'avatar'); $command->file->moveTo($tmpFile); $manager = new ImageManager(); $manager->make($tmpFile)->fit(100, 100)->save(); event(new AvatarWillBeSaved($user, $actor, $tmpFile)); $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => $this->uploadDir]); if ($user->avatar_path && $mount->has($file = "target://{$user->avatar_path}")) { $mount->delete($file); } $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $user->changeAvatarPath($uploadName); $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $user->save(); $this->dispatchEventsFor($user); return $user; }
/** * Handle the command. * * @param MountManager $manager * @return File */ public function handle(MountManager $manager) { try { return $manager->get($this->file->location()); } catch (\Exception $e) { return null; } }
public function saveImage($tmpFile) { $dir = date('Ym/d'); $mount = new MountManager(['source' => new Filesystem(new LocalFS(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new LocalFS(public_path('assets/uploads')))]); $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$dir}/{$uploadName}"); return $this->config['urlPrefix'] . 'uploads/' . $dir . '/' . $uploadName; }
public function testCallForwarder() { $manager = new MountManager(); $mock = Mockery::mock('League\\Flysystem\\FilesystemInterface'); $mock->shouldReceive('aMethodCall')->once()->andReturn('a result'); $manager->mountFilesystem('prot', $mock); $this->assertEquals($manager->aMethodCall('prot://file.ext'), 'a result'); }
/** * {@inheritdoc} */ public function move(FileInterface $file, $srcFsAlias, $destFsAlias) { $isFileMoved = $this->mountManager->move(sprintf('%s://%s', $srcFsAlias, $file->getKey()), sprintf('%s://%s', $destFsAlias, $file->getKey())); if (!$isFileMoved) { throw new FileTransferException(sprintf('Impossible to move the file "%s" from "%s" to "%s".', $file->getKey(), $srcFsAlias, $destFsAlias)); } $file->setStorage($destFsAlias); $this->saver->save($file); }
public function testRemoveOnNonExistentFile() { $filesystem = $this->getFilesystemMock(); $filesystem->expects($this->once())->method('delete')->with('not_found.txt')->will($this->throwException(new \League\Flysystem\FileNotFoundException('dummy path'))); $this->mountManager->expects($this->once())->method('getFilesystem')->with('dir')->will($this->returnValue($filesystem)); $this->mapping->expects($this->once())->method('getUploadDestination')->will($this->returnValue('dir')); $this->mapping->expects($this->once())->method('getFileName')->will($this->returnValue('not_found.txt')); $this->storage->remove($this->object, $this->mapping); }
/** * @param FileNode $from * @param FileNode $to * * @return FileNode * @throws TransferFailedException */ public function moveTo(FileNode $from, FileNode $to) { $mountManager = new MountManager(['from' => $from->getFilesystem(), 'to' => $to->getFilesystem()]); $this->log(LogLevel::INFO, "Moving file from: '{from}', to: '{to}'", ['from' => $from, 'to' => $to]); if (!$mountManager->move('from://' . $from->getPath(), 'to://' . $to->getPath())) { throw new TransferFailedException($from, $to); } return $to; }
/** * Handle the command. * * @param MountManager $manager */ public function handle(MountManager $manager) { if (!($disk = $this->folder->getDisk())) { return; } if (!$this->folder->isForceDeleting()) { return; } $manager->deleteDir($disk->getSlug() . '://' . $this->folder->getSlug()); }
/** * Publish the directory to the given directory. * * @param string $from * @param string $to * * @return void */ protected function publishDirectory($from, $to) { $manager = new MountManager(['from' => new Flysystem(new LocalAdapter($from)), 'to' => new Flysystem(new LocalAdapter($to))]); foreach ($manager->listContents('from://', true) as $file) { if ($file['type'] === 'file') { $manager->put('to://' . $file['path'], $manager->read('from://' . $file['path'])); } } $this->status($from, $to, 'Directory'); }
/** * Mount FTP * * @param string $host * @param string $username * @param string $password * @param string[] $opt * @return $this */ public function mountFtp($host, $username = '', $password = '', array $opt = []) { if (isset($this->settings[$host]['host'])) { $this->fs = $this->mounts->getFilesystem($host); return $this; } $opts = array_merge($opt, ['host' => $host, 'username' => $username, 'password' => $password]); $this->fs = new Filesystem(new Adapter\Ftp($opts)); return $this; }
/** * Moves the contents of an Atuin App into the server's Atuin Filesystem * * @param \League\Flysystem\MountManager $manager */ protected function moveAppContents($directory, $manager) { $contents = $manager->listContents('source://' . $directory); foreach ($contents as $entry) { if ($entry['type'] == 'dir') { $this->moveAppContents($entry['path'], $manager); } else { $manager->put('local://' . $entry['path'], $manager->read('source://' . $entry['path']), ['visibility' => AdapterInterface::VISIBILITY_PUBLIC]); } } }
/** * {@inheritdoc} */ public function export($key, $localPathname, $storageAlias) { if (!is_dir(dirname($localPathname))) { throw new \LogicException(sprintf('The export directory "%s" does not exist.', dirname($localPathname))); } $storageFs = $this->mountManager->getFilesystem($storageAlias); $rawFile = $this->fileFetcher->fetch($storageFs, $key); $copied = $this->copyFile($rawFile->getPathname(), $localPathname); //TODO: files should also be copied in the archive folder to be able to generate the ZIP file on the fly $this->localFs->remove($rawFile->getPathname()); return $copied; }
/** * Get the filesystem manager. * * @return MountManager * @throws \Exception */ public static function getFilesystem() { $config = new Config(); $manager = new MountManager(); foreach ($config->filesystems() as $name => $fsConfig) { $adapterName = '\\League\\Flysystem\\Adapter\\' . self::camelcase($fsConfig['type']); $adapter = new $adapterName($fsConfig['root']); $fs = new Filesystem($adapter); $manager->mountFilesystem($name, $fs); } return $manager; }
/** * Fire just before saving a folder. * * @param EntryInterface|FolderInterface $entry */ public function deleting(EntryInterface $entry) { $this->manager->deleteDir($entry->diskPath()); // Delete contained files. foreach ($entry->getFiles() as $file) { $this->files->delete($file); } // Delete contained folders. foreach ($entry->getChildren() as $folder) { $this->folders->delete($folder); } }
/** * Fired just after * saving the form entry. * * This is basically a validator * but I am putting it here because * it's far easier to test being that * the disk is being loaded already. * * @param MountManager $manager * @param MessageBag $messages * @param Redirector $redirector */ public function onSaved(MountManager $manager, MessageBag $messages, Redirector $redirector) { /* @var DiskFormBuilder $builder */ $builder = $this->forms->get('disk'); /* @var DiskInterface $entry */ $entry = $builder->getFormEntry(); app()->call('Anomaly\\FilesModule\\Disk\\Listener\\RegisterDisks@handle'); try { $manager->has($entry->path('test.me')); } catch (\Exception $e) { $messages->error($e->getMessage()); $this->setFormResponse($redirector->to('admin/files/disks/edit/' . $entry->getId())); } }
/** * Handle the file upload. * * @param DiskRepositoryInterface $disks * @param ResponseFactory $response * @param MountManager $manager * @param Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function handle(DiskRepositoryInterface $disks, ResponseFactory $response, MountManager $manager, Request $request) { $path = trim($request->get('path'), '.'); $file = $request->file('upload'); $disk = $request->get('disk'); if (is_numeric($disk)) { $disk = $disks->find($disk); } elseif (is_string($disk)) { $disk = $disks->findBySlug($disk); } $file = $manager->putStream($disk->path(ltrim(trim($path, '/') . '/' . $file->getClientOriginalName(), '/')), fopen($file->getRealPath(), 'r+')); /* @var FileInterface $file */ return $response->json($file->getAttributes()); }
/** * Duplicate a file given it's URL * * @param string $url * @return string */ public function duplicate($url) { // Make the destination path $current_path = $this->helpers->path($url); $filename = basename($current_path); $dst_disk = $this->disks ? $this->disks->getFilesystem('dst') : $this->disk; $new_path = $this->storage->makeNestedAndUniquePath($filename, $dst_disk); // Copy, supporting alternative destination disks if ($this->disks) { $this->disks->copy('src://' . $current_path, 'dst://' . $new_path); } else { $this->disk->copy($current_path, $new_path); } // Return the Upchuck URL return $this->helpers->url($new_path); }
public function filterPrefix(array $arguments) { try { return parent::filterPrefix($arguments); } catch (\InvalidArgumentException $e) { return array(static::DEFAULT_PREFIX, $arguments); } }
/** * @param Translator $translator * @param RequestStack $request_stack * @param Session $session * @param string $param_prefix * @param string $param_temp_path * @param string $param_thumbnail_directory_prefix * @param string $param_thumbnail_driver * @param string $param_thumbnail_size * @param string $param_max_file_size * @param string $param_max_files_upload * @param string $param_file_extensions_allowed * @param string $local_filesystem * @param string $remote_filesystem * @param MountManager $oneup_mountmanager * @param mixed $options */ public function __construct(Translator $translator, RequestStack $request_stack, Session $session, $param_prefix, $param_temp_path, $param_thumbnail_directory_prefix, $param_thumbnail_driver, $param_thumbnail_size, $param_max_file_size, $param_max_files_upload, $param_file_extensions_allowed, $local_filesystem, $remote_filesystem, $oneup_mountmanager, $options = null) { $this->session = $session; $this->request = $request_stack->getCurrentRequest(); $this->options = $options; $this->trans = $translator; $this->params['param_prefix'] = $param_prefix; $this->params['param_temp_path'] = $param_temp_path; $this->params['param_thumbnail_directory_prefix'] = $param_thumbnail_directory_prefix; $this->params['param_thumbnail_driver'] = $param_thumbnail_driver; $this->params['param_thumbnail_size'] = $param_thumbnail_size; $this->params['param_max_file_size'] = $param_max_file_size; $this->params['param_max_files_upload'] = $param_max_files_upload; $this->params['param_file_extensions_allowed'] = $param_file_extensions_allowed; $this->local_filesystem = $oneup_mountmanager->getFileSystem($local_filesystem); $this->remote_filesystem = $oneup_mountmanager->getFileSystem($remote_filesystem); }
public function handle(Request $request) { $images = $request->http->getUploadedFiles()['images']; $results = []; foreach ($images as $image_key => $image) { $tmpFile = tempnam(sys_get_temp_dir(), 'image'); $image->moveTo($tmpFile); $urlGenerator = app('Flarum\\Http\\UrlGeneratorInterface'); $dir = 'uploads/' . date('Ym/d'); $path = './assets/' . $dir; $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($path))]); $uploadName = Str::lower(Str::quickRandom()) . '.jpg'; $mount->move("source://" . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $results['img_' . $image_key] = Core::url() . '/assets/' . $dir . '/' . $uploadName; } return new JsonResponse($results); }
/** * Delete an upload * * @param string $url A URL like was returned from moveUpload() * @return void */ public function delete($url) { // Convert to a path $path = $this->helpers->path($url); // Delete the path if it still exists if ($this->manager->has('disk://' . $path)) { $this->manager->delete('disk://' . $path); } }
/** * @param ProductInterface $fromProduct * @param ProductInterface $toProduct * @param AttributeInterface $fromAttribute * @param AttributeInterface $toAttribute * @param string $fromLocale * @param string $toLocale * @param string $fromScope * @param string $toScope */ protected function copySingleValue(ProductInterface $fromProduct, ProductInterface $toProduct, AttributeInterface $fromAttribute, AttributeInterface $toAttribute, $fromLocale, $toLocale, $fromScope, $toScope) { $fromValue = $fromProduct->getValue($fromAttribute->getCode(), $fromLocale, $fromScope); if (null !== $fromValue) { $toValue = $toProduct->getValue($toAttribute->getCode(), $toLocale, $toScope); if (null === $toValue) { $toValue = $this->productBuilder->addProductValue($toProduct, $toAttribute, $toLocale, $toScope); } $file = null; if (null !== $fromValue->getMedia()) { $filesystem = $this->mountManager->getFilesystem(FileStorage::CATALOG_STORAGE_ALIAS); $rawFile = $this->rawFileFetcher->fetch($filesystem, $fromValue->getMedia()->getKey()); $file = $this->rawFileStorer->store($rawFile, FileStorage::CATALOG_STORAGE_ALIAS, false); $file->setOriginalFilename($fromValue->getMedia()->getOriginalFilename()); } $toValue->setMedia($file); } }
/** * Upload a file. * * @param UploadedFile $file * @param FolderInterface $folder * @return bool|FileInterface */ public function upload(UploadedFile $file, FolderInterface $folder) { $rules = 'required'; if ($allowed = $folder->getAllowedTypes()) { $rules .= '|mimes:' . implode(',', $allowed); } $validation = $this->validator->make(['file' => $file], ['file' => $rules]); if (!$validation->passes()) { return false; } $disk = $folder->getDisk(); /* @var FileInterface $entry */ $entry = $this->manager->put($disk->getSlug() . '://' . $folder->getSlug() . '/' . $file->getClientOriginalName(), file_get_contents($file->getRealPath())); if (in_array($entry->getExtension(), $this->config->get('anomaly.module.files::mimes.types.image'))) { $size = getimagesize($file->getRealPath()); $this->files->save($entry->setAttribute('width', $size[0])->setAttribute('height', $size[1])); } return $entry; }