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