9 * Class for a file system (FS) based file backend.
11 * All "containers" each map to a directory under the backend's base directory.
12 * For backwards-compatibility, some container paths can be set to custom paths.
13 * The wiki ID will not be used in any custom paths, so this should be avoided.
15 * Having directories with thousands of files will diminish performance.
16 * Sharding can be accomplished by using FileRepo-style hash paths.
18 * Status messages should avoid mentioning the internal FS paths.
19 * Likewise, error suppression should be used to avoid path disclosure.
21 * @ingroup FileBackend
24 class FSFileBackend
extends FileBackend
{
27 * These constants are the same as the ones in FilesystemIterator, but
28 * that's only 5.3+ so copy them here. When we drop 5.2 we can remove this
30 const CURRENT_AS_FILEINFO
= 0;
31 const SKIP_DOTS
= 4096;
33 protected $basePath; // string; directory holding the container directories
34 /** @var Array Map of container names to root paths */
35 protected $containerPaths = array(); // for custom container paths
36 protected $fileMode; // integer; file permission mode
39 * @see FileBackend::__construct()
40 * Additional $config params include:
41 * basePath : File system directory that holds containers.
42 * containerPaths : Map of container names to custom file system directories.
43 * This should only be used for backwards-compatibility.
44 * fileMode : Octal UNIX file permissions to use on files stored.
46 public function __construct( array $config ) {
47 parent
::__construct( $config );
48 if ( isset( $config['basePath'] ) ) {
49 if ( substr( $this->basePath
, -1 ) === '/' ) {
50 $this->basePath
= substr( $this->basePath
, 0, -1 ); // remove trailing slash
53 $this->basePath
= null; // none; containers must have explicit paths
55 $this->containerPaths
= (array)$config['containerPaths'];
56 foreach ( $this->containerPaths
as &$path ) {
57 if ( substr( $path, -1 ) === '/' ) {
58 $path = substr( $path, 0, -1 ); // remove trailing slash
61 $this->fileMode
= isset( $config['fileMode'] )
67 * @see FileBackend::resolveContainerPath()
69 protected function resolveContainerPath( $container, $relStoragePath ) {
70 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
71 return $relStoragePath; // container has a root directory
77 * Given the short (unresolved) and full (resolved) name of
78 * a container, return the file system path of the container.
80 * @param $shortCont string
81 * @param $fullCont string
84 protected function containerFSRoot( $shortCont, $fullCont ) {
85 if ( isset( $this->containerPaths
[$shortCont] ) ) {
86 return $this->containerPaths
[$shortCont];
87 } elseif ( isset( $this->basePath
) ) {
88 return "{$this->basePath}/{$fullCont}";
90 return null; // no container base path defined
94 * Get the absolute file system path for a storage path
96 * @param $storagePath string Storage path
99 protected function resolveToFSPath( $storagePath ) {
100 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
101 if ( $relPath === null ) {
102 return null; // invalid
104 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $storagePath );
105 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
106 if ( $relPath != '' ) {
107 $fsPath .= "/{$relPath}";
113 * @see FileBackend::isPathUsableInternal()
115 public function isPathUsableInternal( $storagePath ) {
116 $fsPath = $this->resolveToFSPath( $storagePath );
117 if ( $fsPath === null ) {
118 return false; // invalid
120 $parentDir = dirname( $fsPath );
122 wfSuppressWarnings();
123 if ( file_exists( $fsPath ) ) {
124 $ok = is_file( $fsPath ) && is_writable( $fsPath );
126 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
134 * @see FileBackend::doStoreInternal()
136 protected function doStoreInternal( array $params ) {
137 $status = Status
::newGood();
139 $dest = $this->resolveToFSPath( $params['dst'] );
140 if ( $dest === null ) {
141 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
145 if ( file_exists( $dest ) ) {
146 if ( !empty( $params['overwrite'] ) ) {
147 wfSuppressWarnings();
148 $ok = unlink( $dest );
151 $status->fatal( 'backend-fail-delete', $params['dst'] );
155 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
160 wfSuppressWarnings();
161 $ok = copy( $params['src'], $dest );
164 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
168 $this->chmod( $dest );
174 * @see FileBackend::doCopyInternal()
176 protected function doCopyInternal( array $params ) {
177 $status = Status
::newGood();
179 $source = $this->resolveToFSPath( $params['src'] );
180 if ( $source === null ) {
181 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
185 $dest = $this->resolveToFSPath( $params['dst'] );
186 if ( $dest === null ) {
187 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
191 if ( file_exists( $dest ) ) {
192 if ( !empty( $params['overwrite'] ) ) {
193 wfSuppressWarnings();
194 $ok = unlink( $dest );
197 $status->fatal( 'backend-fail-delete', $params['dst'] );
201 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
206 wfSuppressWarnings();
207 $ok = copy( $source, $dest );
210 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
214 $this->chmod( $dest );
220 * @see FileBackend::doMoveInternal()
222 protected function doMoveInternal( array $params ) {
223 $status = Status
::newGood();
225 $source = $this->resolveToFSPath( $params['src'] );
226 if ( $source === null ) {
227 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
231 $dest = $this->resolveToFSPath( $params['dst'] );
232 if ( $dest === null ) {
233 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
237 if ( file_exists( $dest ) ) {
238 if ( !empty( $params['overwrite'] ) ) {
239 // Windows does not support moving over existing files
240 if ( wfIsWindows() ) {
241 wfSuppressWarnings();
242 $ok = unlink( $dest );
245 $status->fatal( 'backend-fail-delete', $params['dst'] );
250 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
255 wfSuppressWarnings();
256 $ok = rename( $source, $dest );
257 clearstatcache(); // file no longer at source
260 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
268 * @see FileBackend::doDeleteInternal()
270 protected function doDeleteInternal( array $params ) {
271 $status = Status
::newGood();
273 $source = $this->resolveToFSPath( $params['src'] );
274 if ( $source === null ) {
275 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
279 if ( !is_file( $source ) ) {
280 if ( empty( $params['ignoreMissingSource'] ) ) {
281 $status->fatal( 'backend-fail-delete', $params['src'] );
283 return $status; // do nothing; either OK or bad status
286 wfSuppressWarnings();
287 $ok = unlink( $source );
290 $status->fatal( 'backend-fail-delete', $params['src'] );
298 * @see FileBackend::doCreateInternal()
300 protected function doCreateInternal( array $params ) {
301 $status = Status
::newGood();
303 $dest = $this->resolveToFSPath( $params['dst'] );
304 if ( $dest === null ) {
305 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
309 if ( file_exists( $dest ) ) {
310 if ( !empty( $params['overwrite'] ) ) {
311 wfSuppressWarnings();
312 $ok = unlink( $dest );
315 $status->fatal( 'backend-fail-delete', $params['dst'] );
319 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
324 wfSuppressWarnings();
325 $ok = file_put_contents( $dest, $params['content'] );
328 $status->fatal( 'backend-fail-create', $params['dst'] );
332 $this->chmod( $dest );
338 * @see FileBackend::doPrepareInternal()
340 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
341 $status = Status
::newGood();
342 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
343 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
344 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
345 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
346 $status->fatal( 'directorycreateerror', $params['dir'] );
347 } elseif ( !is_writable( $dir ) ) {
348 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
349 } elseif ( !is_readable( $dir ) ) {
350 $status->fatal( 'directorynotreadableerror', $params['dir'] );
356 * @see FileBackend::doSecureInternal()
358 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
359 $status = Status
::newGood();
360 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
361 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
362 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
363 // Seed new directories with a blank index.html, to prevent crawling...
364 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
365 wfSuppressWarnings();
366 $ok = file_put_contents( "{$dir}/index.html", '' );
369 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
373 // Add a .htaccess file to the root of the container...
374 if ( !empty( $params['noAccess'] ) ) {
375 if ( !file_exists( "{$contRoot}/.htaccess" ) ) {
376 wfSuppressWarnings();
377 $ok = file_put_contents( "{$contRoot}/.htaccess", "Deny from all\n" );
380 $storeDir = "mwstore://{$this->name}/{$shortCont}";
381 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
390 * @see FileBackend::doCleanInternal()
392 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
393 $status = Status
::newGood();
394 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
395 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
396 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
397 wfSuppressWarnings();
398 if ( is_dir( $dir ) ) {
399 rmdir( $dir ); // remove directory if empty
406 * @see FileBackend::doFileExists()
408 protected function doGetFileStat( array $params ) {
409 $source = $this->resolveToFSPath( $params['src'] );
410 if ( $source === null ) {
411 return false; // invalid storage path
414 $this->trapWarnings();
415 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
416 $hadError = $this->untrapWarnings();
420 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
421 'size' => $stat['size']
423 } elseif ( !$hadError ) {
424 return false; // file does not exist
426 return null; // failure
431 * @see FileBackend::doClearCache()
433 protected function doClearCache( array $paths = null ) {
434 clearstatcache(); // clear the PHP file stat cache
438 * @see FileBackend::getFileListInternal()
440 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
441 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
442 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
443 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
444 wfSuppressWarnings();
445 $exists = is_dir( $dir );
448 return array(); // nothing under this dir
450 wfSuppressWarnings();
451 $readable = is_readable( $dir );
454 return null; // bad permissions?
456 return new FSFileBackendFileList( $dir );
460 * @see FileBackend::getLocalReference()
462 public function getLocalReference( array $params ) {
463 $source = $this->resolveToFSPath( $params['src'] );
464 if ( $source === null ) {
467 return new FSFile( $source );
471 * @see FileBackend::getLocalCopy()
473 public function getLocalCopy( array $params ) {
474 $source = $this->resolveToFSPath( $params['src'] );
475 if ( $source === null ) {
479 // Create a new temporary file with the same extension...
480 $ext = FileBackend
::extensionFromPath( $params['src'] );
481 $tmpFile = TempFSFile
::factory( wfBaseName( $source ) . '_', $ext );
485 $tmpPath = $tmpFile->getPath();
487 // Copy the source file over the temp file
488 wfSuppressWarnings();
489 $ok = copy( $source, $tmpPath );
495 $this->chmod( $tmpPath );
501 * Chmod a file, suppressing the warnings
503 * @param $path string Absolute file system path
504 * @return bool Success
506 protected function chmod( $path ) {
507 wfSuppressWarnings();
508 $ok = chmod( $path, $this->fileMode
);
515 * Suppress E_WARNING errors and track whether any happen
519 protected function trapWarnings() {
520 $this->hadWarningErrors
[] = false; // push to stack
521 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
525 * Unsuppress E_WARNING errors and return true if any happened
529 protected function untrapWarnings() {
530 restore_error_handler(); // restore previous handler
531 return array_pop( $this->hadWarningErrors
); // pop from stack
534 private function handleWarning() {
535 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
536 return true; // suppress from PHP handler
541 * Wrapper around RecursiveDirectoryIterator that catches
542 * exception or does any custom behavoir that we may want.
543 * Do not use this class from places outside FSFileBackend.
545 * @ingroup FileBackend
547 class FSFileBackendFileList
implements Iterator
{
548 /** @var RecursiveIteratorIterator */
550 protected $suffixStart; // integer
553 * @param $dir string file system directory
555 public function __construct( $dir ) {
556 $dir = realpath( $dir ); // normalize
557 $this->suffixStart
= strlen( $dir ) +
1; // size of "path/to/dir/"
559 $flags = self
::CURRENT_AS_FILEINFO | self
::SKIP_DOTS
;
560 $this->iter
= new RecursiveIteratorIterator(
561 new RecursiveDirectoryIterator( $dir, $flags ) );
562 } catch ( UnexpectedValueException
$e ) {
563 $this->iter
= null; // bad permissions? deleted?
567 public function current() {
568 // Return only the relative path and normalize slashes to FileBackend-style
569 // Make sure to use the realpath since the suffix is based upon that
570 return str_replace( '\\', '/',
571 substr( realpath( $this->iter
->current() ), $this->suffixStart
) );
574 public function key() {
575 return $this->iter
->key();
578 public function next() {
581 } catch ( UnexpectedValueException
$e ) {
586 public function rewind() {
588 $this->iter
->rewind();
589 } catch ( UnexpectedValueException
$e ) {
594 public function valid() {
595 return $this->iter
&& $this->iter
->valid();