Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / libs / filebackend / fsfile / TempFSFile.php
blobfed6812f5beaef08ae0d92763be04d21e93a92fc
1 <?php
2 /**
3 * Location holder of files stored temporarily
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup FileBackend
24 /**
25 * This class is used to hold the location and do limited manipulation
26 * of files stored temporarily (this will be whatever wfTempDir() returns)
28 * @ingroup FileBackend
30 class TempFSFile extends FSFile {
31 /** @var bool Garbage collect the temp file */
32 protected $canDelete = false;
34 /** @var array Map of (path => 1) for paths to delete on shutdown */
35 protected static $pathsCollect = null;
37 public function __construct( $path ) {
38 parent::__construct( $path );
40 if ( self::$pathsCollect === null ) {
41 self::$pathsCollect = [];
42 register_shutdown_function( [ __CLASS__, 'purgeAllOnShutdown' ] );
46 /**
47 * Make a new temporary file on the file system.
48 * Temporary files may be purged when the file object falls out of scope.
50 * @param string $prefix
51 * @param string $extension Optional file extension
52 * @param string|null $tmpDirectory Optional parent directory
53 * @return TempFSFile|null
55 public static function factory( $prefix, $extension = '', $tmpDirectory = null ) {
56 $ext = ( $extension != '' ) ? ".{$extension}" : '';
58 $attempts = 5;
59 while ( $attempts-- ) {
60 $hex = sprintf( '%06x%06x', mt_rand( 0, 0xffffff ), mt_rand( 0, 0xffffff ) );
61 if ( !is_string( $tmpDirectory ) ) {
62 $tmpDirectory = self::getUsableTempDirectory();
64 $path = wfTempDir() . '/' . $prefix . $hex . $ext;
65 MediaWiki\suppressWarnings();
66 $newFileHandle = fopen( $path, 'x' );
67 MediaWiki\restoreWarnings();
68 if ( $newFileHandle ) {
69 fclose( $newFileHandle );
70 $tmpFile = new self( $path );
71 $tmpFile->autocollect();
72 // Safely instantiated, end loop.
73 return $tmpFile;
77 // Give up
78 return null;
81 /**
82 * @return string Filesystem path to a temporary directory
83 * @throws RuntimeException
85 public static function getUsableTempDirectory() {
86 $tmpDir = array_map( 'getenv', [ 'TMPDIR', 'TMP', 'TEMP' ] );
87 $tmpDir[] = sys_get_temp_dir();
88 $tmpDir[] = ini_get( 'upload_tmp_dir' );
89 foreach ( $tmpDir as $tmp ) {
90 if ( $tmp != '' && is_dir( $tmp ) && is_writable( $tmp ) ) {
91 return $tmp;
95 // PHP on Windows will detect C:\Windows\Temp as not writable even though PHP can write to
96 // it so create a directory within that called 'mwtmp' with a suffix of the user running
97 // the current process.
98 // The user is included as if various scripts are run by different users they will likely
99 // not be able to access each others temporary files.
100 if ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' ) {
101 $tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'mwtmp-' . get_current_user();
102 if ( !file_exists( $tmp ) ) {
103 mkdir( $tmp );
105 if ( is_dir( $tmp ) && is_writable( $tmp ) ) {
106 return $tmp;
110 throw new RuntimeException(
111 'No writable temporary directory could be found. ' .
112 'Please explicitly specify a writable directory in configuration.' );
116 * Purge this file off the file system
118 * @return bool Success
120 public function purge() {
121 $this->canDelete = false; // done
122 MediaWiki\suppressWarnings();
123 $ok = unlink( $this->path );
124 MediaWiki\restoreWarnings();
126 unset( self::$pathsCollect[$this->path] );
128 return $ok;
132 * Clean up the temporary file only after an object goes out of scope
134 * @param object $object
135 * @return TempFSFile This object
137 public function bind( $object ) {
138 if ( is_object( $object ) ) {
139 if ( !isset( $object->tempFSFileReferences ) ) {
140 // Init first since $object might use __get() and return only a copy variable
141 $object->tempFSFileReferences = [];
143 $object->tempFSFileReferences[] = $this;
146 return $this;
150 * Set flag to not clean up after the temporary file
152 * @return TempFSFile This object
154 public function preserve() {
155 $this->canDelete = false;
157 unset( self::$pathsCollect[$this->path] );
159 return $this;
163 * Set flag clean up after the temporary file
165 * @return TempFSFile This object
167 public function autocollect() {
168 $this->canDelete = true;
170 self::$pathsCollect[$this->path] = 1;
172 return $this;
176 * Try to make sure that all files are purged on error
178 * This method should only be called internally
180 public static function purgeAllOnShutdown() {
181 foreach ( self::$pathsCollect as $path ) {
182 MediaWiki\suppressWarnings();
183 unlink( $path );
184 MediaWiki\restoreWarnings();
189 * Cleans up after the temporary file by deleting it
191 function __destruct() {
192 if ( $this->canDelete ) {
193 $this->purge();