9 * @brief 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 * PHP warnings are assumed to be logged rather than output.
21 * @ingroup FileBackend
24 class FSFileBackend
extends FileBackendStore
{
25 protected $basePath; // string; directory holding the container directories
26 /** @var Array Map of container names to root paths */
27 protected $containerPaths = array(); // for custom container paths
28 protected $fileMode; // integer; file permission mode
30 protected $hadWarningErrors = array();
33 * @see FileBackendStore::__construct()
34 * Additional $config params include:
35 * basePath : File system directory that holds containers.
36 * containerPaths : Map of container names to custom file system directories.
37 * This should only be used for backwards-compatibility.
38 * fileMode : Octal UNIX file permissions to use on files stored.
40 public function __construct( array $config ) {
41 parent
::__construct( $config );
43 // Remove any possible trailing slash from directories
44 if ( isset( $config['basePath'] ) ) {
45 $this->basePath
= rtrim( $config['basePath'], '/' ); // remove trailing slash
47 $this->basePath
= null; // none; containers must have explicit paths
50 if ( isset( $config['containerPaths'] ) ) {
51 $this->containerPaths
= (array)$config['containerPaths'];
52 foreach ( $this->containerPaths
as &$path ) {
53 $path = rtrim( $path, '/' ); // remove trailing slash
57 $this->fileMode
= isset( $config['fileMode'] )
63 * @see FileBackendStore::resolveContainerPath()
66 protected function resolveContainerPath( $container, $relStoragePath ) {
67 // Check that container has a root directory
68 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
69 // Check for sane relative paths (assume the base paths are OK)
70 if ( $this->isLegalRelPath( $relStoragePath ) ) {
71 return $relStoragePath;
78 * Sanity check a relative file system path for validity
80 * @param $path string Normalized relative path
83 protected function isLegalRelPath( $path ) {
84 // Check for file names longer than 255 chars
85 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
88 if ( wfIsWindows() ) { // NTFS
89 return !preg_match( '![:*?"<>|]!', $path );
96 * Given the short (unresolved) and full (resolved) name of
97 * a container, return the file system path of the container.
99 * @param $shortCont string
100 * @param $fullCont string
101 * @return string|null
103 protected function containerFSRoot( $shortCont, $fullCont ) {
104 if ( isset( $this->containerPaths
[$shortCont] ) ) {
105 return $this->containerPaths
[$shortCont];
106 } elseif ( isset( $this->basePath
) ) {
107 return "{$this->basePath}/{$fullCont}";
109 return null; // no container base path defined
113 * Get the absolute file system path for a storage path
115 * @param $storagePath string Storage path
116 * @return string|null
118 protected function resolveToFSPath( $storagePath ) {
119 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
120 if ( $relPath === null ) {
121 return null; // invalid
123 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $storagePath );
124 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
125 if ( $relPath != '' ) {
126 $fsPath .= "/{$relPath}";
132 * @see FileBackendStore::isPathUsableInternal()
135 public function isPathUsableInternal( $storagePath ) {
136 $fsPath = $this->resolveToFSPath( $storagePath );
137 if ( $fsPath === null ) {
138 return false; // invalid
140 $parentDir = dirname( $fsPath );
142 if ( file_exists( $fsPath ) ) {
143 $ok = is_file( $fsPath ) && is_writable( $fsPath );
145 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
152 * @see FileBackendStore::doStoreInternal()
155 protected function doStoreInternal( array $params ) {
156 $status = Status
::newGood();
158 $dest = $this->resolveToFSPath( $params['dst'] );
159 if ( $dest === null ) {
160 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
164 if ( file_exists( $dest ) ) {
165 if ( !empty( $params['overwrite'] ) ) {
166 $ok = unlink( $dest );
168 $status->fatal( 'backend-fail-delete', $params['dst'] );
172 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
177 $ok = copy( $params['src'], $dest );
179 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
183 $this->chmod( $dest );
189 * @see FileBackendStore::doCopyInternal()
192 protected function doCopyInternal( array $params ) {
193 $status = Status
::newGood();
195 $source = $this->resolveToFSPath( $params['src'] );
196 if ( $source === null ) {
197 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
201 $dest = $this->resolveToFSPath( $params['dst'] );
202 if ( $dest === null ) {
203 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
207 if ( file_exists( $dest ) ) {
208 if ( !empty( $params['overwrite'] ) ) {
209 $ok = unlink( $dest );
211 $status->fatal( 'backend-fail-delete', $params['dst'] );
215 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
220 $ok = copy( $source, $dest );
222 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
226 $this->chmod( $dest );
232 * @see FileBackendStore::doMoveInternal()
235 protected function doMoveInternal( array $params ) {
236 $status = Status
::newGood();
238 $source = $this->resolveToFSPath( $params['src'] );
239 if ( $source === null ) {
240 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
244 $dest = $this->resolveToFSPath( $params['dst'] );
245 if ( $dest === null ) {
246 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
250 if ( file_exists( $dest ) ) {
251 if ( !empty( $params['overwrite'] ) ) {
252 // Windows does not support moving over existing files
253 if ( wfIsWindows() ) {
254 $ok = unlink( $dest );
256 $status->fatal( 'backend-fail-delete', $params['dst'] );
261 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
266 $ok = rename( $source, $dest );
267 clearstatcache(); // file no longer at source
269 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
277 * @see FileBackendStore::doDeleteInternal()
280 protected function doDeleteInternal( array $params ) {
281 $status = Status
::newGood();
283 $source = $this->resolveToFSPath( $params['src'] );
284 if ( $source === null ) {
285 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
289 if ( !is_file( $source ) ) {
290 if ( empty( $params['ignoreMissingSource'] ) ) {
291 $status->fatal( 'backend-fail-delete', $params['src'] );
293 return $status; // do nothing; either OK or bad status
296 $ok = unlink( $source );
298 $status->fatal( 'backend-fail-delete', $params['src'] );
306 * @see FileBackendStore::doCreateInternal()
309 protected function doCreateInternal( array $params ) {
310 $status = Status
::newGood();
312 $dest = $this->resolveToFSPath( $params['dst'] );
313 if ( $dest === null ) {
314 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
318 if ( file_exists( $dest ) ) {
319 if ( !empty( $params['overwrite'] ) ) {
320 $ok = unlink( $dest );
322 $status->fatal( 'backend-fail-delete', $params['dst'] );
326 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
331 $bytes = file_put_contents( $dest, $params['content'] );
332 if ( $bytes === false ) {
333 $status->fatal( 'backend-fail-create', $params['dst'] );
337 $this->chmod( $dest );
343 * @see FileBackendStore::doPrepareInternal()
346 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
347 $status = Status
::newGood();
348 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
349 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
350 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
351 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
352 $status->fatal( 'directorycreateerror', $params['dir'] );
353 } elseif ( !is_writable( $dir ) ) {
354 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
355 } elseif ( !is_readable( $dir ) ) {
356 $status->fatal( 'directorynotreadableerror', $params['dir'] );
362 * @see FileBackendStore::doSecureInternal()
365 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
366 $status = Status
::newGood();
367 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
368 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
369 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
370 // Seed new directories with a blank index.html, to prevent crawling...
371 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
372 $bytes = file_put_contents( "{$dir}/index.html", '' );
374 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
378 // Add a .htaccess file to the root of the container...
379 if ( !empty( $params['noAccess'] ) ) {
380 if ( !file_exists( "{$contRoot}/.htaccess" ) ) {
381 $bytes = file_put_contents( "{$contRoot}/.htaccess", "Deny from all\n" );
383 $storeDir = "mwstore://{$this->name}/{$shortCont}";
384 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
393 * @see FileBackendStore::doCleanInternal()
396 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
397 $status = Status
::newGood();
398 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
399 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
400 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
401 wfSuppressWarnings();
402 if ( is_dir( $dir ) ) {
403 rmdir( $dir ); // remove directory if empty
410 * @see FileBackendStore::doFileExists()
411 * @return array|bool|null
413 protected function doGetFileStat( array $params ) {
414 $source = $this->resolveToFSPath( $params['src'] );
415 if ( $source === null ) {
416 return false; // invalid storage path
419 $this->trapWarnings(); // don't trust 'false' if there were errors
420 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
421 $hadError = $this->untrapWarnings();
425 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
426 'size' => $stat['size']
428 } elseif ( !$hadError ) {
429 return false; // file does not exist
431 return null; // failure
436 * @see FileBackendStore::doClearCache()
438 protected function doClearCache( array $paths = null ) {
439 clearstatcache(); // clear the PHP file stat cache
443 * @see FileBackendStore::getFileListInternal()
444 * @return array|FSFileBackendFileList|null
446 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
447 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
448 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
449 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
450 $exists = is_dir( $dir );
452 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
453 return array(); // nothing under this dir
455 $readable = is_readable( $dir );
457 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
458 return null; // bad permissions?
460 return new FSFileBackendFileList( $dir );
464 * @see FileBackendStore::getLocalReference()
465 * @return FSFile|null
467 public function getLocalReference( array $params ) {
468 $source = $this->resolveToFSPath( $params['src'] );
469 if ( $source === null ) {
472 return new FSFile( $source );
476 * @see FileBackendStore::getLocalCopy()
477 * @return null|TempFSFile
479 public function getLocalCopy( array $params ) {
480 $source = $this->resolveToFSPath( $params['src'] );
481 if ( $source === null ) {
485 // Create a new temporary file with the same extension...
486 $ext = FileBackend
::extensionFromPath( $params['src'] );
487 $tmpFile = TempFSFile
::factory( wfBaseName( $source ) . '_', $ext );
491 $tmpPath = $tmpFile->getPath();
493 // Copy the source file over the temp file
494 $ok = copy( $source, $tmpPath );
499 $this->chmod( $tmpPath );
505 * Chmod a file, suppressing the warnings
507 * @param $path string Absolute file system path
508 * @return bool Success
510 protected function chmod( $path ) {
511 wfSuppressWarnings();
512 $ok = chmod( $path, $this->fileMode
);
519 * Listen for E_WARNING errors and track whether any happen
523 protected function trapWarnings() {
524 $this->hadWarningErrors
[] = false; // push to stack
525 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
526 return false; // invoke normal PHP error handler
530 * Stop listening for E_WARNING errors and return true if any happened
534 protected function untrapWarnings() {
535 restore_error_handler(); // restore previous handler
536 return array_pop( $this->hadWarningErrors
); // pop from stack
539 private function handleWarning() {
540 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
541 return true; // suppress from PHP handler
546 * Wrapper around RecursiveDirectoryIterator that catches
547 * exception or does any custom behavoir that we may want.
548 * Do not use this class from places outside FSFileBackend.
550 * @ingroup FileBackend
552 class FSFileBackendFileList
implements Iterator
{
553 /** @var RecursiveIteratorIterator */
555 protected $suffixStart; // integer
556 protected $pos = 0; // integer
559 * @param $dir string file system directory
561 public function __construct( $dir ) {
562 $dir = realpath( $dir ); // normalize
563 $this->suffixStart
= strlen( $dir ) +
1; // size of "path/to/dir/"
565 # Get an iterator that will return leaf nodes (non-directories)
566 if ( MWInit
::classExists( 'FilesystemIterator' ) ) { // PHP >= 5.3
567 # RecursiveDirectoryIterator extends FilesystemIterator.
568 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
569 $flags = FilesystemIterator
::CURRENT_AS_FILEINFO | FilesystemIterator
::SKIP_DOTS
;
570 $this->iter
= new RecursiveIteratorIterator(
571 new RecursiveDirectoryIterator( $dir, $flags ) );
572 } else { // PHP < 5.3
573 # RecursiveDirectoryIterator extends DirectoryIterator
574 $this->iter
= new RecursiveIteratorIterator(
575 new RecursiveDirectoryIterator( $dir ) );
577 } catch ( UnexpectedValueException
$e ) {
578 $this->iter
= null; // bad permissions? deleted?
583 * @see Iterator::current()
584 * @return string|bool String or false
586 public function current() {
587 // Return only the relative path and normalize slashes to FileBackend-style
588 // Make sure to use the realpath since the suffix is based upon that
589 return str_replace( '\\', '/',
590 substr( realpath( $this->iter
->current() ), $this->suffixStart
) );
594 * @see Iterator::key()
597 public function key() {
602 * @see Iterator::next()
605 public function next() {
608 } catch ( UnexpectedValueException
$e ) {
615 * @see Iterator::rewind()
618 public function rewind() {
621 $this->iter
->rewind();
622 } catch ( UnexpectedValueException
$e ) {
628 * @see Iterator::valid()
631 public function valid() {
632 return $this->iter
&& $this->iter
->valid();