123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- <?php
- defined('GNUSOCIAL') || die();
- class TemporaryFileException extends Exception
- {
- }
- class TemporaryFile extends SplFileInfo
- {
- protected $resource = null;
-
- public function __construct(
- ?string $prefix = null,
- ?string $mode = null
- ) {
- $filename = tempnam(sys_get_temp_dir(), $prefix ?? 'gs-php');
- if ($filename === false) {
- throw new TemporaryFileException('Could not create file: ' . $filename);
- }
- parent::__construct($filename);
- if (($this->resource = fopen($filename, $mode ?? 'w+b')) === false) {
- $this->cleanup();
- throw new TemporaryFileException('Could not open file: ' . $filename);
- }
- }
- public function __destruct()
- {
- $this->close();
- $this->cleanup();
- }
-
- protected function close(): bool
- {
- $ret = true;
- if (!is_null($this->resource)) {
- $ret = fclose($this->resource);
- }
- if ($ret) {
- $this->resource = null;
- }
- return $ret;
- }
-
- protected function cleanup(): void
- {
- $path = $this->getRealPath();
- $this->close();
- if (file_exists($path)) {
- unlink($path);
- }
- }
-
- public function getResource()
- {
- return $this->resource;
- }
-
- public function commit(string $destpath, int $umode = 0644): void
- {
- $temppath = $this->getRealPath();
-
- if ($destpath === $temppath) {
- throw new TemporaryFileException('Cannot use self as destination');
- }
-
- $exists = file_exists($destpath);
- if (!touch($destpath)) {
- throw new TemporaryFileException(
- 'Insufficient permissions for destination: "' . $destpath . '"'
- );
- } elseif (!$exists) {
-
- unlink($destpath);
- }
- if (!$this->close()) {
- throw new TemporaryFileException('Could not close the resource');
- }
- rename($temppath, $destpath);
- chmod($destpath, $umode);
- }
- }
|