4 const DELETE_ORIGINAL
= 1;
7 * Fetch the FileStore object for a given storage group
9 static function get( $group ) {
12 if( isset( $wgFileStore[$group] ) ) {
13 $info = $wgFileStore[$group];
14 return new FileStore( $group,
17 intval( $info['hash'] ) );
23 private function __construct( $group, $directory, $path, $hash ) {
24 $this->mGroup
= $group;
25 $this->mDirectory
= $directory;
27 $this->mHashLevel
= $hash;
31 * Acquire a lock; use when performing write operations on a store.
32 * This is attached to your master database connection, so if you
33 * suffer an uncaught error the lock will be released when the
34 * connection is closed.
36 * @fixme Probably only works on MySQL. Abstract to the Database class?
38 static function lock() {
39 $dbw = wfGetDB( DB_MASTER
);
40 $lockname = $dbw->addQuotes( FileStore
::lockName() );
41 $result = $dbw->query( "SELECT GET_LOCK($lockname, 5) AS lockstatus", __METHOD__
);
42 $row = $dbw->fetchObject( $result );
43 $dbw->freeResult( $result );
45 if( $row->lockstatus
== 1 ) {
48 wfDebug( __METHOD__
." failed to acquire lock\n" );
54 * Release the global file store lock.
56 static function unlock() {
57 $dbw = wfGetDB( DB_MASTER
);
58 $lockname = $dbw->addQuotes( FileStore
::lockName() );
59 $result = $dbw->query( "SELECT RELEASE_LOCK($lockname)", __METHOD__
);
60 $row = $dbw->fetchObject( $result );
61 $dbw->freeResult( $result );
64 private static function lockName() {
65 global $wgDBname, $wgDBprefix;
66 return "MediaWiki.{$wgDBname}.{$wgDBprefix}FileStore";
70 * Copy a file into the file store from elsewhere in the filesystem.
71 * Should be protected by FileStore::lock() to avoid race conditions.
73 * @param $key storage key string
75 * DELETE_ORIGINAL - remove the source file on transaction commit.
77 * @throws FSException if copy can't be completed
78 * @return FSTransaction
80 function insert( $key, $sourcePath, $flags=0 ) {
81 $destPath = $this->filePath( $key );
82 return $this->copyFile( $sourcePath, $destPath, $flags );
86 * Copy a file from the file store to elsewhere in the filesystem.
87 * Should be protected by FileStore::lock() to avoid race conditions.
89 * @param $key storage key string
91 * DELETE_ORIGINAL - remove the source file on transaction commit.
93 * @throws FSException if copy can't be completed
94 * @return FSTransaction on success
96 function export( $key, $destPath, $flags=0 ) {
97 $sourcePath = $this->filePath( $key );
98 return $this->copyFile( $sourcePath, $destPath, $flags );
101 private function copyFile( $sourcePath, $destPath, $flags=0 ) {
102 if( !file_exists( $sourcePath ) ) {
104 throw new FSException( "missing source file '$sourcePath'\n" );
107 $transaction = new FSTransaction();
109 if( $flags & self
::DELETE_ORIGINAL
) {
110 $transaction->addCommit( FSTransaction
::DELETE_FILE
, $sourcePath );
113 if( file_exists( $destPath ) ) {
114 // An identical file is already present; no need to copy.
116 if( !file_exists( dirname( $destPath ) ) ) {
117 wfSuppressWarnings();
118 $ok = mkdir( dirname( $destPath ), 0777, true );
122 throw new FSException(
123 "failed to create directory for '$destPath'\n" );
127 wfSuppressWarnings();
128 $ok = copy( $sourcePath, $destPath );
132 wfDebug( __METHOD__
." copied '$sourcePath' to '$destPath'\n" );
133 $transaction->addRollback( FSTransaction
::DELETE_FILE
, $destPath );
135 throw new FSException(
136 __METHOD__
." failed to copy '$sourcePath' to '$destPath'\n" );
144 * Delete a file from the file store.
145 * Caller's responsibility to make sure it's not being used by another row.
147 * File is not actually removed until transaction commit.
148 * Should be protected by FileStore::lock() to avoid race conditions.
150 * @param $key storage key string
151 * @throws FSException if file can't be deleted
152 * @return FSTransaction
154 function delete( $key ) {
155 $destPath = $this->filePath( $key );
156 if( false === $destPath ) {
157 throw new FSExcepton( "file store does not contain file '$key'" );
159 return FileStore
::deleteFile( $destPath );
164 * Delete a non-managed file on a transactional basis.
166 * File is not actually removed until transaction commit.
167 * Should be protected by FileStore::lock() to avoid race conditions.
169 * @param $path file to remove
170 * @throws FSException if file can't be deleted
171 * @return FSTransaction
173 * @fixme Might be worth preliminary permissions check
175 static function deleteFile( $path ) {
176 if( file_exists( $path ) ) {
177 $transaction = new FSTransaction();
178 $transaction->addCommit( FSTransaction
::DELETE_FILE
, $path );
181 throw new FSException( "cannot delete missing file '$path'" );
186 * Stream a contained file directly to HTTP output.
187 * Will throw a 404 if file is missing; 400 if invalid key.
188 * @return true on success, false on failure
190 function stream( $key ) {
191 $path = $this->filePath( $key );
192 if( $path === false ) {
193 wfHttpError( 400, "Bad request", "Invalid or badly-formed filename." );
197 if( file_exists( $path ) ) {
198 // Set the filename for more convenient save behavior from browsers
199 // FIXME: Is this safe?
200 header( 'Content-Disposition: inline; filename="' . $key . '"' );
202 require_once 'StreamFile.php';
203 wfStreamFile( $path );
205 return wfHttpError( 404, "Not found",
206 "The requested resource does not exist." );
211 * Confirm that the given file key is valid.
212 * Note that a valid key may refer to a file that does not exist.
214 * Key should consist of a 32-digit base-36 SHA-1 hash and
215 * an optional alphanumeric extension, all lowercase.
216 * The whole must not exceed 64 characters.
221 static function validKey( $key ) {
222 return preg_match( '/^[0-9a-z]{32}(\.[0-9a-z]{1,31})?$/', $key );
227 * Calculate file storage key from a file on disk.
228 * You must pass an extension to it, as some files may be calculated
229 * out of a temporary file etc.
231 * @param $path to file
233 * @return string or false if could not open file or bad extension
235 static function calculateKey( $path, $extension ) {
236 wfSuppressWarnings();
237 $hash = sha1_file( $path );
239 if( $hash === false ) {
240 wfDebug( __METHOD__
.": couldn't hash file '$path'\n" );
244 $base36 = wfBaseConvert( $hash, 16, 36, 32 );
245 if( $extension == '' ) {
248 $key = $base36 . '.' . $extension;
252 if( self
::validKey( $key ) ) {
255 wfDebug( __METHOD__
.": generated bad key '$key'\n" );
261 * Return filesystem path to the given file.
262 * Note that the file may or may not exist.
263 * @return string or false if an invalid key
265 function filePath( $key ) {
266 if( self
::validKey( $key ) ) {
267 return $this->mDirectory
. DIRECTORY_SEPARATOR
.
268 $this->hashPath( $key, DIRECTORY_SEPARATOR
);
275 * Return URL path to the given file, if the store is public.
276 * @return string or false if not public
278 function urlPath( $key ) {
279 if( $this->mUrl
&& self
::validKey( $key ) ) {
280 return $this->mUrl
. '/' . $this->hashPath( $key, '/' );
286 private function hashPath( $key, $separator ) {
288 for( $i = 0; $i < $this->mHashLevel
; $i++
) {
292 return implode( $separator, $parts );
297 * Wrapper for file store transaction stuff.
299 * FileStore methods may return one of these for undoable operations;
300 * you can then call its rollback() or commit() methods to perform
301 * final cleanup if dependent database work fails or succeeds.
303 class FSTransaction
{
304 const DELETE_FILE
= 1;
307 * Combine more items into a fancier transaction
309 function add( FSTransaction
$transaction ) {
310 $this->mOnCommit
= array_merge(
311 $this->mOnCommit
, $transaction->mOnCommit
);
312 $this->mOnRollback
= array_merge(
313 $this->mOnRollback
, $transaction->mOnRollback
);
317 * Perform final actions for success.
318 * @return true if actions applied ok, false if errors
321 return $this->apply( $this->mOnCommit
);
325 * Perform final actions for failure.
326 * @return true if actions applied ok, false if errors
328 function rollback() {
329 return $this->apply( $this->mOnRollback
);
332 // --- Private and friend functions below...
334 function __construct() {
335 $this->mOnCommit
= array();
336 $this->mOnRollback
= array();
339 function addCommit( $action, $path ) {
340 $this->mOnCommit
[] = array( $action, $path );
343 function addRollback( $action, $path ) {
344 $this->mOnRollback
[] = array( $action, $path );
347 private function apply( $actions ) {
349 foreach( $actions as $item ) {
350 list( $action, $path ) = $item;
351 if( $action == self
::DELETE_FILE
) {
352 wfSuppressWarnings();
353 $ok = unlink( $path );
356 wfDebug( __METHOD__
.": deleting file '$path'\n" );
358 wfDebug( __METHOD__
.": failed to delete file '$path'\n" );
359 $result = $result && $ok;
366 class FSException
extends MWException
{ }