9 * This class is used to hold the location and do limited manipulation
10 * of files stored temporarily (usually this will be $wgTmpDirectory)
13 * @ingroup FileBackend
15 class TempFSFile
extends FSFile
{
16 protected $canDelete = true; // garbage collect the temp file
18 /** @var Array of active temp files to purge on shutdown */
19 protected static $instances = array();
22 * Make a new temporary file on the file system.
23 * Temporary files may be purged when the file object falls out of scope.
25 * @param $prefix string
26 * @param $extension string
27 * @return TempFSFile|null
29 public static function factory( $prefix, $extension = '' ) {
30 $base = wfTempDir() . '/' . $prefix . dechex( mt_rand( 0, 99999999 ) );
31 $ext = ( $extension != '' ) ?
".{$extension}" : "";
32 for ( $attempt = 1; true; $attempt++
) {
33 $path = "{$base}-{$attempt}{$ext}";
35 $newFileHandle = fopen( $path, 'x' );
37 if ( $newFileHandle ) {
38 fclose( $newFileHandle );
41 if ( $attempt >= 15 ) {
42 return null; // give up
45 $tmpFile = new self( $path );
46 if ( php_sapi_name() != 'cli' ) {
47 self
::$instances[] = $tmpFile; // defer purge till shutdown
53 * Purge this file off the file system
55 * @return bool Success
57 public function purge() {
58 $this->canDelete
= false; // done
60 $ok = unlink( $this->path
);
66 * Clean up the temporary file only after an object goes out of scope
68 * @param $object Object
71 public function bind( $object ) {
72 if ( is_object( $object ) ) {
73 $object->tempFSFileReferences
[] = $this;
78 * Set flag to not clean up after the temporary file
82 public function preserve() {
83 $this->canDelete
= false;
87 * Cleans up after the temporary file by deleting it
89 function __destruct() {
90 if ( $this->canDelete
) {
92 unlink( $this->path
);