MediaWiki  REL1_22
TempFSFile.php
Go to the documentation of this file.
00001 <?php
00030 class TempFSFile extends FSFile {
00031     protected $canDelete = false; // bool; garbage collect the temp file
00032 
00034     protected static $instances = array();
00035 
00044     public static function factory( $prefix, $extension = '' ) {
00045         wfProfileIn( __METHOD__ );
00046         $base = wfTempDir() . '/' . $prefix . wfRandomString( 12 );
00047         $ext = ( $extension != '' ) ? ".{$extension}" : "";
00048         for ( $attempt = 1; true; $attempt++ ) {
00049             $path = "{$base}-{$attempt}{$ext}";
00050             wfSuppressWarnings();
00051             $newFileHandle = fopen( $path, 'x' );
00052             wfRestoreWarnings();
00053             if ( $newFileHandle ) {
00054                 fclose( $newFileHandle );
00055                 break; // got it
00056             }
00057             if ( $attempt >= 5 ) {
00058                 wfProfileOut( __METHOD__ );
00059                 return null; // give up
00060             }
00061         }
00062         $tmpFile = new self( $path );
00063         $tmpFile->canDelete = true; // safely instantiated
00064         wfProfileOut( __METHOD__ );
00065         return $tmpFile;
00066     }
00067 
00073     public function purge() {
00074         $this->canDelete = false; // done
00075         wfSuppressWarnings();
00076         $ok = unlink( $this->path );
00077         wfRestoreWarnings();
00078         return $ok;
00079     }
00080 
00087     public function bind( $object ) {
00088         if ( is_object( $object ) ) {
00089             if ( !isset( $object->tempFSFileReferences ) ) {
00090                 // Init first since $object might use __get() and return only a copy variable
00091                 $object->tempFSFileReferences = array();
00092             }
00093             $object->tempFSFileReferences[] = $this;
00094         }
00095         return $this;
00096     }
00097 
00103     public function preserve() {
00104         $this->canDelete = false;
00105         return $this;
00106     }
00107 
00113     public function autocollect() {
00114         $this->canDelete = true;
00115         return $this;
00116     }
00117 
00121     function __destruct() {
00122         if ( $this->canDelete ) {
00123             wfSuppressWarnings();
00124             unlink( $this->path );
00125             wfRestoreWarnings();
00126         }
00127     }
00128 }