8 * This class is used to hold the location and do limited manipulation
9 * of files stored temporarily (usually this will be $wgTmpDirectory)
11 * @ingroup FileBackend
13 class TempFSFile
extends FSFile
{
14 protected $canDelete = true; // garbage collect the temp file
16 /** @var Array of active temp files to purge on shutdown */
17 protected static $instances = array();
20 * Make a new temporary file on the file system.
21 * Temporary files may be purged when the file object falls out of scope.
23 * @param $prefix string
24 * @param $extension string
25 * @return TempFSFile|null
27 public static function factory( $prefix, $extension = '' ) {
28 $base = wfTempDir() . '/' . $prefix . dechex( mt_rand( 0, 99999999 ) );
29 $ext = ( $extension != '' ) ?
".{$extension}" : "";
30 for ( $attempt = 1; true; $attempt++
) {
31 $path = "{$base}-{$attempt}{$ext}";
33 $newFileHandle = fopen( $path, 'x' );
35 if ( $newFileHandle ) {
36 fclose( $newFileHandle );
39 if ( $attempt >= 15 ) {
40 return null; // give up
43 $tmpFile = new self( $path );
44 if ( php_sapi_name() != 'cli' ) {
45 self
::$instances[] = $tmpFile; // defer purge till shutdown
51 * Purge this file off the file system
53 * @return bool Success
55 public function purge() {
56 $this->canDelete
= false; // done
58 $ok = unlink( $this->path
);
64 * Clean up the temporary file only after an object goes out of scope
66 * @param $object Object
69 public function bind( $object ) {
70 if ( is_object( $object ) ) {
71 $object->tempFSFileReferences
[] = $this;
76 * Set flag to not clean up after the temporary file
80 public function preserve() {
81 $this->canDelete
= false;
85 * Cleans up after the temporary file by deleting it
87 function __destruct() {
88 if ( $this->canDelete
) {
90 unlink( $this->path
);