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