1<?php
2
3use MediaWiki\FileBackend\FSFile\TempFSFileFactory;
4
5/**
6 * Location holder of files stored temporarily
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup FileBackend
25 */
26
27use Wikimedia\AtEase\AtEase;
28
29/**
30 * This class is used to hold the location and do limited manipulation
31 * of files stored temporarily (this will be whatever wfTempDir() returns)
32 *
33 * @ingroup FileBackend
34 */
35class TempFSFile extends FSFile {
36	/** @var bool Garbage collect the temp file */
37	protected $canDelete = false;
38
39	/** @var array Map of (path => 1) for paths to delete on shutdown */
40	protected static $pathsCollect = null;
41
42	/**
43	 * Do not call directly. Use TempFSFileFactory
44	 *
45	 * @param string $path
46	 */
47	public function __construct( $path ) {
48		parent::__construct( $path );
49
50		if ( self::$pathsCollect === null ) {
51			// @codeCoverageIgnoreStart
52			self::$pathsCollect = [];
53			register_shutdown_function( [ __CLASS__, 'purgeAllOnShutdown' ] );
54			// @codeCoverageIgnoreEnd
55		}
56	}
57
58	/**
59	 * Make a new temporary file on the file system.
60	 * Temporary files may be purged when the file object falls out of scope.
61	 *
62	 * @deprecated since 1.34, use TempFSFileFactory directly
63	 *
64	 * @param string $prefix
65	 * @param string $extension Optional file extension
66	 * @param string|null $tmpDirectory Optional parent directory
67	 * @return TempFSFile|null
68	 */
69	public static function factory( $prefix, $extension = '', $tmpDirectory = null ) {
70		return ( new TempFSFileFactory( $tmpDirectory ) )->newTempFSFile( $prefix, $extension );
71	}
72
73	/**
74	 * @todo Is there any useful way to test this? Would it be useful to make this non-static on
75	 * TempFSFileFactory?
76	 *
77	 * @return string Filesystem path to a temporary directory
78	 * @throws RuntimeException if no writable temporary directory can be found
79	 */
80	public static function getUsableTempDirectory() {
81		$tmpDir = array_map( 'getenv', [ 'TMPDIR', 'TMP', 'TEMP' ] );
82		$tmpDir[] = sys_get_temp_dir();
83		$tmpDir[] = ini_get( 'upload_tmp_dir' );
84		foreach ( $tmpDir as $tmp ) {
85			if ( $tmp != '' && is_dir( $tmp ) && is_writable( $tmp ) ) {
86				return $tmp;
87			}
88		}
89
90		// PHP on Windows will detect C:\Windows\Temp as not writable even though PHP can write to
91		// it so create a directory within that called 'mwtmp' with a suffix of the user running
92		// the current process.
93		// The user is included as if various scripts are run by different users they will likely
94		// not be able to access each others temporary files.
95		if ( PHP_OS_FAMILY === 'Windows' ) {
96			$tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'mwtmp-' . get_current_user();
97			if ( !is_dir( $tmp ) ) {
98				mkdir( $tmp );
99			}
100			if ( is_dir( $tmp ) && is_writable( $tmp ) ) {
101				return $tmp;
102			}
103		}
104
105		throw new RuntimeException(
106			'No writable temporary directory could be found. ' .
107			'Please explicitly specify a writable directory in configuration.' );
108	}
109
110	/**
111	 * Purge this file off the file system
112	 *
113	 * @return bool Success
114	 */
115	public function purge() {
116		$this->canDelete = false; // done
117		AtEase::suppressWarnings();
118		$ok = unlink( $this->path );
119		AtEase::restoreWarnings();
120
121		unset( self::$pathsCollect[$this->path] );
122
123		return $ok;
124	}
125
126	/**
127	 * Clean up the temporary file only after an object goes out of scope
128	 *
129	 * @param object $object
130	 * @return TempFSFile This object
131	 */
132	public function bind( $object ) {
133		if ( is_object( $object ) ) {
134			if ( !isset( $object->tempFSFileReferences ) ) {
135				// Init first since $object might use __get() and return only a copy variable
136				$object->tempFSFileReferences = [];
137			}
138			$object->tempFSFileReferences[] = $this;
139		}
140
141		return $this;
142	}
143
144	/**
145	 * Set flag to not clean up after the temporary file
146	 *
147	 * @return TempFSFile This object
148	 */
149	public function preserve() {
150		$this->canDelete = false;
151
152		unset( self::$pathsCollect[$this->path] );
153
154		return $this;
155	}
156
157	/**
158	 * Set flag clean up after the temporary file
159	 *
160	 * @return TempFSFile This object
161	 */
162	public function autocollect() {
163		$this->canDelete = true;
164
165		self::$pathsCollect[$this->path] = 1;
166
167		return $this;
168	}
169
170	/**
171	 * Try to make sure that all files are purged on error
172	 *
173	 * This method should only be called internally
174	 *
175	 * @codeCoverageIgnore
176	 */
177	public static function purgeAllOnShutdown() {
178		foreach ( self::$pathsCollect as $path => $unused ) {
179			AtEase::suppressWarnings();
180			unlink( $path );
181			AtEase::restoreWarnings();
182		}
183	}
184
185	/**
186	 * Cleans up after the temporary file by deleting it
187	 */
188	public function __destruct() {
189		if ( $this->canDelete ) {
190			$this->purge();
191		}
192	}
193}
194