public function __invoke() { $version = $this->resourceDO->getVersion(); $filePath = $this->resourceDO->getFilePath(); if (!$this->resourceDO->getName() || !$this->resourceDO->getType() || !$this->resourceDO->getBaseDirectory()) { throw new CommandErrorException('Cannot delete empty resource'); } if ($this->filesystem->has($filePath)) { // Make backup of the default version if (ResourceDOInterface::DEFAULT_VERSION === $version) { $lastVersion = $this->findLastVersion(); // But only if previous existing version is not the default and not has the same content as deleting if (ResourceDOInterface::DEFAULT_VERSION !== $lastVersion) { $lastVersionResourceDO = clone $this->resourceDO; $lastVersionResourceDO->setVersion($lastVersion); $command = new DestroyEqualResourceCommand($lastVersionResourceDO, $this->resourceDO, $this->filesystem); $result = $command(); if ($result === $this->resourceDO) { // If the previous file version already the same, current version is already deleted // and backup and yet another deletion is not needed anymore return $this->resourceDO; } } $command = new BackupResourceCommand($this->resourceDO, $this->filesystem); $command($lastVersion); } $this->deleteFile($filePath); return $this->resourceDO; } return $this->resourceDO; }
protected function deleteFile($filePath) { // If file is already gone somewhere, it is OK for us if ($this->filesystem->has($filePath) && !$this->filesystem->delete($filePath)) { throw new CommandErrorException('The file cannot be removed: ' . $filePath); } }
/** * @return ResourceDOInterface SuspectResource if it have been deleted or OriginResource if the Suspect is not equal */ public function __invoke() { $originName = $this->originResourceDO->getName(); $suspectName = $this->suspectResourceDO->getName(); $originType = $this->originResourceDO->getType(); $suspectType = $this->suspectResourceDO->getType(); $originFilePath = $this->originResourceDO->getFilePath(); $suspectFilePath = $this->suspectResourceDO->getFilePath(); if (!$originName || !$originType) { throw new CommandErrorException('Cannot destroy equal resource: the origin resource is empty'); } if (!$suspectName || !$suspectType) { throw new CommandErrorException('Cannot destroy equal resource: the suspect resource is empty'); } if ($originFilePath === $suspectFilePath) { throw new CommandErrorException('Cannot destroy equal resource: Origin and Suspect have same paths'); } // Unfortunately, this condition can not always work fine. // Because some Middlewares can compress, resize etc. the resource that saved before // and the second uploaded copy will never be equal if ($originType === $suspectType && $this->filesystem->has($originFilePath) === $this->filesystem->has($suspectFilePath) && $this->filesystem->getSize($originFilePath) === $this->filesystem->getSize($suspectFilePath) && $this->getFileHash($originFilePath) === $this->getFileHash($suspectFilePath)) { $command = new DestroyResourceCommand($this->suspectResourceDO, $this->filesystem); return $command(true); } return $this->originResourceDO; }
/** * {@inheritdoc} */ public function find($path) { if ($this->filesystem->has($path) === false) { throw new NotLoadableException(sprintf('Source image "%s" not found.', $path)); } $mimeType = $this->filesystem->getMimetype($path); return new Binary($this->filesystem->read($path), $mimeType, $this->extensionGuesser->guess($mimeType)); }
/** * @override * @inheritDoc */ public function exists($path) { try { return $this->fs->has($path); } catch (Error $ex) { } catch (Exception $ex) { } throw new ReadException("File {$path} does not exist.", $ex); }
/** * @param ServerRequestInterface $request * * @return mixed|null */ public function data(ServerRequestInterface $request) { $url = $request->getUri()->getPath(); $parameters = array_merge($request->getQueryParams(), $request->getParsedBody()); $file = $this->file($url, $parameters); if (!$this->filesystem->has($file)) { $file = $this->defaultFile($url); } if (!$this->filesystem->has($file)) { return null; } return $this->filesystem->read($file); }
public function create(User $_user, string $extension, string $mime_type, string $original_name, string $temp_location, bool $is_image) { $query = "INSERT INTO `file` (user_id, extension, mime_type, md5, original_name, date_added, is_image)\n\t\t\t\t\t VALUES (:u, :e, :mt, :m, :o, :d, :i)"; $this->_pdo->perform($query, ["u" => $this->user_id = $_user->getId(), "e" => $this->extension = $extension, "mt" => $this->mime_type = $mime_type, "m" => $this->md5 = md5_file($temp_location), "o" => $this->original_name = $original_name, "d" => $this->date_added = Utility::getDateTimeForMySQLDateTime(), "i" => $this->is_image = $is_image]); $stream = fopen($temp_location, "r+"); if (!$this->_filesystem->has($this->getDirMain())) { $this->_filesystem->createDir($this->getDirMain()); } if (!$this->_filesystem->has($this->getDirSub())) { $this->_filesystem->createDir($this->getDirSub()); } $this->_filesystem->writeStream($this->getPath(), $stream, ["visibility" => AdapterInterface::VISIBILITY_PUBLIC]); fclose($stream); }
public function uploadImagePreview(int $themeId, string $path) : string { $theme = $this->getThemeById($themeId); $dir = $theme->getId(); $name = sprintf('%s.png', GenerateRandomString::gen(self::GENERATE_FILENAME_LENGTH)); $newPath = sprintf('%s/%s', $dir, $name); if ($this->fileSystem->has($dir)) { $this->fileSystem->deleteDir($dir); } $this->fileSystem->write($newPath, file_get_contents($path)); $theme->setPreview($newPath); $this->themeRepository->saveTheme($theme); return $theme->getPreview(); }
/** * Process a source image and Generate a response object * * @param String $path Path to the source image * @return Boolean */ private function serveFromSource($path) { //try and load the image from the source if ($this->source->has($path)) { $file = $this->source->get($path); // Get the template object $template = $this->templates[$this->template](); // Process the image $image = $this->processImage($file, $this->imageManager, $template); // Set the headers $this->response->headers->set('Content-Type', $image->mime); $this->response->headers->set('Content-Length', strlen($image->encoded)); $lastModified = new \DateTime(); // now $this->setHttpCacheHeaders($lastModified, md5($this->getCachePath() . $lastModified->getTimestamp()), $this->maxAge); // Send the processed image in the response $this->response->setContent($image->encoded); // Setup a callback to write the processed image to the cache // This will be called after the image has been sent to the browser $this->cacheWrite = function (FilesystemInterface $cache, $path) use($image) { // use put() to write or update $cache->put($path, $image->encoded); }; return true; } return false; }
function it_throws_an_exception_when_the_file_can_not_be_read_on_the_filesystem(FileInterface $file, FilesystemInterface $filesystem) { $file->getKey()->willReturn('path/to/file.txt'); $filesystem->has('path/to/file.txt')->willReturn(true); $filesystem->readStream('path/to/file.txt')->willReturn(false); $this->shouldThrow(new FileTransferException('Unable to fetch the file "path/to/file.txt" from the filesystem.'))->during('fetch', [$file, $filesystem]); }
/** * Write session data * @link http://php.net/manual/en/sessionhandlerinterface.write.php * @param string $session_id The session id. * @param string $session_data <p> * The encoded session data. This data is the * result of the PHP internally encoding * the $_SESSION superglobal to a serialized * string and passing it as this parameter. * Please note sessions use an alternative serialization method. * </p> * @return bool <p> * The return value (usually TRUE on success, FALSE on failure). * Note this value is returned internally to PHP for processing. * </p> * @since 5.4.0 */ public function write($session_id, $session_data) { if (!$this->driver->has($path = $this->path . $session_id)) { $this->driver->create($path); } return $this->driver->put($path, $session_data); }
/** * Return stat for given path. * Stat contains following fields: * - (int) size file size in b. required * - (int) ts file modification time in unix time. required * - (string) mime mimetype. required for folders, others - optionally * - (bool) read read permissions. required * - (bool) write write permissions. required * - (bool) locked is object locked. optionally * - (bool) hidden is object hidden. optionally * - (string) alias for symlinks - link target path relative to root path. optionally * - (string) target for symlinks - link target path. optionally * * If file does not exists - returns empty array or false. * * @param string $path file path * @return array|false **/ protected function _stat($path) { $stat = array('mime' => 'directory', 'ts' => time(), 'read' => true, 'write' => true, 'locked' => false, 'hidden' => false, 'size' => 0); // If root, just return from above if ($this->root == $path) { $stat['name'] = $this->root; return $stat; } // If not exists, return empty if (!$this->fs->has($path)) { return array(); } $meta = $this->fs->getMetadata($path); // Get timestamp/size $stat['ts'] = isset($meta['timestamp']) ? $meta['timestamp'] : $this->fs->getTimestamp($path); $stat['size'] = isset($meta['size']) ? $meta['size'] : $this->fs->getSize($path); // Check if file, if so, check mimetype if ($meta['type'] == 'file') { $stat['mime'] = isset($meta['mimetype']) ? $meta['mimetype'] : $this->fs->getMimetype($path); $imgMimes = ['image/jpeg', 'image/png', 'image/gif']; if ($this->urlBuilder && in_array($stat['mime'], $imgMimes)) { $stat['url'] = $this->urlBuilder->getUrl($path, ['ts' => $stat['ts']]); $stat['tmb'] = $this->urlBuilder->getUrl($path, ['ts' => $stat['ts'], 'w' => $this->tmbSize, 'h' => $this->tmbSize, 'fit' => $this->options['tmbCrop'] ? 'crop' : 'contain']); } } if (!isset($stat['url']) && $this->fs->getUrl()) { $stat['url'] = 1; } return $stat; }
/** * {@inheritdoc} */ public function push(BackupInterface $backup) { $backupDirectory = $backup->getName(); if (!$this->flysystem->has($backupDirectory) && !$this->flysystem->createDir($backupDirectory)) { throw new DestinationException(sprintf('Unable to create backup directory "%s" in flysystem destination.', $backupDirectory)); } $removedBackupFiles = $this->getFiles($backupDirectory); /** * @var FileInterface $backupFile */ foreach ($backup->getFiles() as $backupFile) { if (isset($removedBackupFiles[$backupFile->getRelativePath()])) { unset($removedBackupFiles[$backupFile->getRelativePath()]); } $path = $backupDirectory . '/' . $backupFile->getRelativePath(); try { if ($this->flysystem->has($path)) { if ($backupFile->getModifiedAt() > new \DateTime('@' . $this->flysystem->getTimestamp($path))) { $resource = fopen($backupFile->getPath(), 'r'); $this->flysystem->updateStream($path, $resource); fclose($resource); } } else { $resource = fopen($backupFile->getPath(), 'r'); $this->flysystem->putStream($path, $resource); fclose($resource); } } catch (\Exception $e) { throw new DestinationException(sprintf('Unable to backup file "%s" to flysystem destination.', $backupFile->getPath()), 0, $e); } } /** * @var FileInterface $removedBackupFile */ foreach ($removedBackupFiles as $removedBackupFile) { $path = $backupDirectory . '/' . $removedBackupFile->getRelativePath(); try { $this->flysystem->delete($path); } catch (\Exception $e) { throw new DestinationException(sprintf('Unable to cleanup backup destination "%s" after backup process, file "%s" could not be removed.', $backupDirectory, $path), 0, $e); } } $this->removeEmptyDirectories($backupDirectory); if (is_array($this->backups)) { $this->backups[$backup->getName()] = $backup; } }
private function touchDir(FilesystemInterface $fs, string $entityId, string $collectionUID, string $imageId) : string { $resultPath = sprintf('%s/%s/%s', $entityId, $collectionUID, $imageId); if (!$fs->has($resultPath)) { $fs->createDir($resultPath); } return $resultPath; }
/** * @param DeleteAvatar $command * @return \Flarum\Core\User * @throws PermissionDeniedException */ public function handle(DeleteAvatar $command) { $actor = $command->actor; $user = $this->users->findOrFail($command->userId); if ($actor->id !== $user->id) { $this->assertCan($actor, 'edit', $user); } $avatarPath = $user->avatar_path; $user->changeAvatarPath(null); $this->events->fire(new AvatarWillBeDeleted($user, $actor)); $user->save(); if ($this->uploadDir->has($avatarPath)) { $this->uploadDir->delete($avatarPath); } $this->dispatchEventsFor($user, $actor); return $user; }
/** * Return stat for given path. * Stat contains following fields: * - (int) size file size in b. required * - (int) ts file modification time in unix time. required * - (string) mime mimetype. required for folders, others - optionally * - (bool) read read permissions. required * - (bool) write write permissions. required * - (bool) locked is object locked. optionally * - (bool) hidden is object hidden. optionally * - (string) alias for symlinks - link target path relative to root path. optionally * - (string) target for symlinks - link target path. optionally * * If file does not exists - returns empty array or false. * * @param string $path file path * @return array|false **/ protected function _stat($path) { $stat = array('size' => 0, 'ts' => time(), 'read' => true, 'write' => true, 'locked' => false, 'hidden' => false, 'mime' => 'directory'); // If root, just return from above if ($this->root == $path) { $stat['name'] = $this->root; return $stat; } // If not exists, return empty if (!$this->fs->has($path)) { // Check if the parent doesn't have this path if ($this->_dirExists($path)) { return $stat; } // Neither a file or directory exist, return empty return array(); } try { $meta = $this->fs->getMetadata($path); } catch (\Exception $e) { return array(); } if (false === $meta) { return $stat; } // Set item filename.extension to `name` if exists if (isset($meta['filename']) && isset($meta['extension'])) { $stat['name'] = $meta['filename']; if ($meta['extension'] !== '') { $stat['name'] .= '.' . $meta['extension']; } } // Get timestamp/size if available if (isset($meta['timestamp'])) { $stat['ts'] = $meta['timestamp']; } if (isset($meta['size'])) { $stat['size'] = $meta['size']; } // Check if file, if so, check mimetype when available if ($meta['type'] == 'file') { if (isset($meta['mimetype'])) { $stat['mime'] = $meta['mimetype']; } else { $stat['mime'] = $this->fs->getMimetype($path); } $imgMimes = ['image/jpeg', 'image/png', 'image/gif']; if ($this->urlBuilder && in_array($stat['mime'], $imgMimes)) { $stat['url'] = $this->urlBuilder->getUrl($path, ['ts' => $stat['ts']]); $stat['tmb'] = $this->urlBuilder->getUrl($path, ['ts' => $stat['ts'], 'w' => $this->tmbSize, 'h' => $this->tmbSize, 'fit' => $this->options['tmbCrop'] ? 'crop' : 'contain']); } } if (!isset($stat['url']) && $this->fs->getUrl()) { $stat['url'] = 1; } return $stat; }
/** * Write settings content of a namespace * * @param string $namespace * @param array $data * @return void */ protected function write($namespace, array $data) { $file = $this->adapter->getFileName($namespace); $contents = $this->adapter->prepareForWriting($data); if (!$this->fileSystem->has($file)) { $this->fileSystem->write($file, $contents); } $this->fileSystem->update($file, $contents); }
/** * @throws FileNotFoundException If fname does not exist in filesystem */ public function __construct(string $fname, FilesystemInterface $fsystem, DecoderInterface $decoder = null) { if (!$fsystem->has($fname)) { throw new FileNotFoundException("Unable to read file {$fname}"); } $this->fname = $fname; $this->fsystem = $fsystem; $this->decoder = $decoder ?: $this->guessDecoder(); $this->reset(); }
/** * Returns information about a file. * * @param string $fileIdentifier * @param array $propertiesToExtract Array of properties which are be extracted * If empty all will be extracted * @return array * @throws FileDoesNotExistException */ public function getFileInfoByIdentifier($fileIdentifier, array $propertiesToExtract = []) { $relativeDriverPath = ltrim($fileIdentifier, '/'); if (!$this->filesystem->has($relativeDriverPath) || !$this->filesystem->get($relativeDriverPath)->isFile()) { throw new FileDoesNotExistException('File ' . $fileIdentifier . ' does not exist.', 1314516809); } $dirPath = PathUtility::dirname($fileIdentifier); $dirPath = $this->canonicalizeAndCheckFolderIdentifier($dirPath); return $this->extractFileInformation($relativeDriverPath, $dirPath, $propertiesToExtract); }
/** * Migrates a file to the new strategy if it's not present * * @internal * @param $path * @return void */ public function migrateFile($path) { if ($this->getAdapterType() !== 'local' || $this->isEncoded($path)) { return; } $encodedPath = $this->strategy->encode($path); if ($this->filesystem->has($path) && !$this->filesystem->has($encodedPath)) { $this->filesystem->rename($path, $encodedPath); } }
/** * Use flysystem to save the file in the desired location. * * @param \Onema\ClassyFile\Event\GetClassEvent $event */ public function onGetClassGenerateFile(GetClassEvent $event) { $statement = $event->getStatements(); $fileLocation = $event->getFileLocation(); $code = $event->getCode(); $name = $statement->name; if (!$this->filesystem->has($fileLocation)) { // dir doesn't exist, make it $this->filesystem->createDir($fileLocation); } $location = sprintf('%s/%s.php', $fileLocation, $name); $this->filesystem->put($location, $code); $adapter = $this->filesystem->getAdapter(); if ($adapter instanceof AbstractAdapter) { $prefix = $adapter->getPathPrefix(); $location = Util::normalizePath($location); $event->setFileLocation(sprintf('%s%s', $prefix, $location)); } }
/** * Sets the file to stream. * * @param \SplFileInfo|string $file The file to stream * @param string $contentDisposition * @param bool $autoEtag * * @return BinaryFileResponse * * @throws FileException */ public function setFile($file, $contentDisposition = null, $autoEtag = false) { if ($file instanceof File) { $file->setFilesystem($this->filesystem); } else { $file = $this->filesystem->get($file); } if (!$this->filesystem->has($file->getPath())) { throw new FileException('File must be readable.'); } $this->file = $file; if ($autoEtag) { $this->setAutoEtag(); } if ($contentDisposition) { $this->setContentDisposition($contentDisposition); } return $this; }
public function createFromUpload(File $file) { $this->pdo->beginTransaction(); try { $this->objectRepository->create(File::TYPE, $file->getUuid()); $this->uploadFile($file); $this->executeSql(' INSERT INTO files (file_uuid, name, path, mime_type) VALUES (:file_uuid, :name, :path, :mime_type) ', ['file_uuid' => $file->getUuid()->getBytes(), 'name' => $file->getName()->toString(), 'path' => $file->getPath()->toString(), 'mime_type' => $file->getMimeType()->toString()]); $file->metaDataSetInsertTimestamp(new \DateTimeImmutable()); $this->pdo->commit(); } catch (\Throwable $exception) { $this->pdo->rollBack(); if ($this->fileSystem->has($file->getUuid()->toString())) { $this->fileSystem->delete($file->getUuid()->toString()); } throw $exception; } }
/** * @param FilesystemInterface $filesystem * @param string $fileName * * @throws StorageException */ public function __construct(FilesystemInterface $filesystem, $fileName = self::DEFAULT_FILENAME) { if (!$filesystem->has($fileName)) { $filesystem->write($fileName, ''); } $handler = $filesystem->get($fileName); if (!$handler->isFile()) { throw new StorageException(sprintf('Expected path "%s" to be a file but its a "%s".', $handler->getPath(), $handler->getType())); } $this->file = $handler; }
/** * @param DeleteAvatar $command * @return \Flarum\Core\Users\User */ public function handle(DeleteAvatar $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'); } $avatarPath = $user->avatar_path; $user->changeAvatarPath(null); event(new AvatarWillBeDeleted($user, $actor)); if ($this->uploadDir->has($avatarPath)) { $this->uploadDir->delete($avatarPath); } $user->save(); $this->dispatchEventsFor($user); return $user; }
public function it_can_also_delete_after_exception(File $file) { $uuid = Uuid::uuid4(); $file->getUuid()->willReturn($uuid); $this->pdo->beginTransaction()->shouldBeCalled(); $this->objectRepository->create(File::TYPE, $uuid)->willThrow(new \RuntimeException()); $this->pdo->rollBack()->shouldBeCalled(); $this->fileSystem->has($uuid->toString())->willReturn(true); $this->fileSystem->delete($uuid->toString())->willReturn(true); $this->shouldThrow(\RuntimeException::class)->duringCreateFromUpload($file); }
/** * {@inheritdoc} */ public function fetch(FileInterface $file, FilesystemInterface $filesystem) { if (!$filesystem->has($file->getKey())) { throw new \LogicException(sprintf('The file "%s" is not present on the filesystem.', $file->getKey())); } $localPathname = tempnam(sys_get_temp_dir(), 'raw_file_fetcher_'); if (false === ($stream = $filesystem->readStream($file->getKey()))) { throw new FileTransferException(sprintf('Unable to fetch the file "%s" from the filesystem.', $file->getKey())); } if (false === file_put_contents($localPathname, $stream)) { throw new FileTransferException(sprintf('Unable to fetch the file "%s" from the filesystem.', $file->getKey())); } return new \SplFileInfo($localPathname); }
/** * @param bool $replace Replace exist file or just do nothing * @return ResourceDOInterface * @throws CommandErrorException */ public function __invoke($replace = false) { if (!$this->originResourceDO->getName() || !$this->originResourceDO->getType()) { throw new CommandErrorException('Source resource cannot be empty'); } if (!$this->newResourceDO->getName() || !$this->newResourceDO->getType()) { throw new CommandErrorException('Destination resource cannot be empty'); } $originPath = $this->originResourceDO->getFilePath(); $newPath = $this->newResourceDO->getFilePath(); if ($originPath === $newPath) { throw new CommandErrorException('Source and destination paths is equal'); } if (!$this->filesystem->has($originPath)) { throw new CommandErrorException('Origin file is not exists: ' . $originPath); } $exists = $this->filesystem->has($newPath); if (!$exists || $replace) { $this->copyFile($originPath, $newPath, $exists && $replace); return $this->newResourceDO; } return $this->originResourceDO; }
private function backupAndUpdate($path, $content) { if ($this->enableBackup) { $oldContent = $this->master->read($path); if ($oldContent !== false) { if ($this->backup->has($path)) { $this->backup->update($path, $oldContent); } else { $this->backup->write($path, $oldContent); } } } $this->master->update($path, $content); }
/** * Create a file or folder. * * @param string $path * @param string|null $contents */ protected function create($path, $contents = null) { // If the file already exists, quit $path = $this->formatPath($path); if ($this->filesystem->has($path)) { return; } // Create the file or folder if ($contents) { $this->filesystem->put($path, $contents); } else { $this->filesystem->createDir($path); } $this->output->writeln('<info>✓</info> Created <comment>' . $path . '</comment>'); }