Documentation followups from lastnight
[lhc/web/wiklou.git] / includes / filerepo / backend / TempFSFile.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 */
6
7 /**
8 * This class is used to hold the location and do limited manipulation
9 * of files stored temporarily (usually this will be $wgTmpDirectory)
10 *
11 * @ingroup FileBackend
12 */
13 class TempFSFile extends FSFile {
14 protected $canDelete = true; // garbage collect the temp file
15
16 /** @var Array of active temp files to purge on shutdown */
17 protected static $instances = array();
18
19 /**
20 * Make a new temporary file on the file system.
21 * Temporary files may be purged when the file object falls out of scope.
22 *
23 * @param $prefix string
24 * @param $extension string
25 * @return TempFSFile|null
26 */
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}";
32 wfSuppressWarnings();
33 $newFileHandle = fopen( $path, 'x' );
34 wfRestoreWarnings();
35 if ( $newFileHandle ) {
36 fclose( $newFileHandle );
37 break; // got it
38 }
39 if ( $attempt >= 15 ) {
40 return null; // give up
41 }
42 }
43 $tmpFile = new self( $path );
44 return $tmpFile;
45 }
46
47 /**
48 * Purge this file off the file system
49 *
50 * @return bool Success
51 */
52 public function purge() {
53 $this->canDelete = false; // done
54 wfSuppressWarnings();
55 $ok = unlink( $this->path );
56 wfRestoreWarnings();
57 return $ok;
58 }
59
60 /**
61 * Clean up the temporary file only after an object goes out of scope
62 *
63 * @param $object Object
64 * @return void
65 */
66 public function bind( $object ) {
67 if ( is_object( $object ) ) {
68 $object->tempFSFileReferences[] = $this;
69 }
70 }
71
72 /**
73 * Set flag to not clean up after the temporary file
74 *
75 * @return void
76 */
77 public function preserve() {
78 $this->canDelete = false;
79 }
80
81 /**
82 * Cleans up after the temporary file by deleting it
83 */
84 function __destruct() {
85 if ( $this->canDelete ) {
86 wfSuppressWarnings();
87 unlink( $this->path );
88 wfRestoreWarnings();
89 }
90 }
91 }