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 );
178 // In some cases (at least over NFS), copy() returns true when it fails.
179 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
180 if ( $ok ) { // PHP bug
181 unlink( $dest ); // remove broken file
182 trigger_error( __METHOD__
. ": copy() failed but returned true." );
184 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
188 $this->chmod( $dest );
194 * @see FileBackendStore::doCopyInternal()
197 protected function doCopyInternal( array $params ) {
198 $status = Status
::newGood();
200 $source = $this->resolveToFSPath( $params['src'] );
201 if ( $source === null ) {
202 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
206 $dest = $this->resolveToFSPath( $params['dst'] );
207 if ( $dest === null ) {
208 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
212 if ( file_exists( $dest ) ) {
213 if ( !empty( $params['overwrite'] ) ) {
214 $ok = unlink( $dest );
216 $status->fatal( 'backend-fail-delete', $params['dst'] );
220 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
225 $ok = copy( $source, $dest );
226 // In some cases (at least over NFS), copy() returns true when it fails.
227 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
228 if ( $ok ) { // PHP bug
229 unlink( $dest ); // remove broken file
230 trigger_error( __METHOD__
. ": copy() failed but returned true." );
232 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
236 $this->chmod( $dest );
242 * @see FileBackendStore::doMoveInternal()
245 protected function doMoveInternal( array $params ) {
246 $status = Status
::newGood();
248 $source = $this->resolveToFSPath( $params['src'] );
249 if ( $source === null ) {
250 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
254 $dest = $this->resolveToFSPath( $params['dst'] );
255 if ( $dest === null ) {
256 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
260 if ( file_exists( $dest ) ) {
261 if ( !empty( $params['overwrite'] ) ) {
262 // Windows does not support moving over existing files
263 if ( wfIsWindows() ) {
264 $ok = unlink( $dest );
266 $status->fatal( 'backend-fail-delete', $params['dst'] );
271 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
276 $ok = rename( $source, $dest );
277 clearstatcache(); // file no longer at source
279 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
287 * @see FileBackendStore::doDeleteInternal()
290 protected function doDeleteInternal( array $params ) {
291 $status = Status
::newGood();
293 $source = $this->resolveToFSPath( $params['src'] );
294 if ( $source === null ) {
295 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
299 if ( !is_file( $source ) ) {
300 if ( empty( $params['ignoreMissingSource'] ) ) {
301 $status->fatal( 'backend-fail-delete', $params['src'] );
303 return $status; // do nothing; either OK or bad status
306 $ok = unlink( $source );
308 $status->fatal( 'backend-fail-delete', $params['src'] );
316 * @see FileBackendStore::doCreateInternal()
319 protected function doCreateInternal( array $params ) {
320 $status = Status
::newGood();
322 $dest = $this->resolveToFSPath( $params['dst'] );
323 if ( $dest === null ) {
324 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
328 if ( file_exists( $dest ) ) {
329 if ( !empty( $params['overwrite'] ) ) {
330 $ok = unlink( $dest );
332 $status->fatal( 'backend-fail-delete', $params['dst'] );
336 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
341 $bytes = file_put_contents( $dest, $params['content'] );
342 if ( $bytes === false ) {
343 $status->fatal( 'backend-fail-create', $params['dst'] );
347 $this->chmod( $dest );
353 * @see FileBackendStore::doPrepareInternal()
356 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
357 $status = Status
::newGood();
358 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
359 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
360 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
361 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
362 $status->fatal( 'directorycreateerror', $params['dir'] );
363 } elseif ( !is_writable( $dir ) ) {
364 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
365 } elseif ( !is_readable( $dir ) ) {
366 $status->fatal( 'directorynotreadableerror', $params['dir'] );
372 * @see FileBackendStore::doSecureInternal()
375 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
376 $status = Status
::newGood();
377 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
378 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
379 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
380 // Seed new directories with a blank index.html, to prevent crawling...
381 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
382 $bytes = file_put_contents( "{$dir}/index.html", '' );
384 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
388 // Add a .htaccess file to the root of the container...
389 if ( !empty( $params['noAccess'] ) ) {
390 if ( !file_exists( "{$contRoot}/.htaccess" ) ) {
391 $bytes = file_put_contents( "{$contRoot}/.htaccess", "Deny from all\n" );
393 $storeDir = "mwstore://{$this->name}/{$shortCont}";
394 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
403 * @see FileBackendStore::doCleanInternal()
406 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
407 $status = Status
::newGood();
408 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
409 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
410 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
411 wfSuppressWarnings();
412 if ( is_dir( $dir ) ) {
413 rmdir( $dir ); // remove directory if empty
420 * @see FileBackendStore::doFileExists()
421 * @return array|bool|null
423 protected function doGetFileStat( array $params ) {
424 $source = $this->resolveToFSPath( $params['src'] );
425 if ( $source === null ) {
426 return false; // invalid storage path
429 $this->trapWarnings(); // don't trust 'false' if there were errors
430 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
431 $hadError = $this->untrapWarnings();
435 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
436 'size' => $stat['size']
438 } elseif ( !$hadError ) {
439 return false; // file does not exist
441 return null; // failure
446 * @see FileBackendStore::doClearCache()
448 protected function doClearCache( array $paths = null ) {
449 clearstatcache(); // clear the PHP file stat cache
453 * @see FileBackendStore::doDirectoryExists()
456 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
457 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
458 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
459 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
461 $this->trapWarnings(); // don't trust 'false' if there were errors
462 $exists = is_dir( $dir );
463 $hadError = $this->untrapWarnings();
465 return $hadError ?
null : $exists;
469 * @see FileBackendStore::getDirectoryListInternal()
472 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
473 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
474 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
475 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
476 $exists = is_dir( $dir );
478 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
479 return array(); // nothing under this dir
480 } elseif ( !is_readable( $dir ) ) {
481 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
482 return null; // bad permissions?
484 return new FSFileBackendDirList( $dir, $params );
488 * @see FileBackendStore::getFileListInternal()
489 * @return array|FSFileBackendFileList|null
491 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
492 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
493 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
494 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
495 $exists = is_dir( $dir );
497 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
498 return array(); // nothing under this dir
499 } elseif ( !is_readable( $dir ) ) {
500 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
501 return null; // bad permissions?
503 return new FSFileBackendFileList( $dir, $params );
507 * @see FileBackendStore::getLocalReference()
508 * @return FSFile|null
510 public function getLocalReference( array $params ) {
511 $source = $this->resolveToFSPath( $params['src'] );
512 if ( $source === null ) {
515 return new FSFile( $source );
519 * @see FileBackendStore::getLocalCopy()
520 * @return null|TempFSFile
522 public function getLocalCopy( array $params ) {
523 $source = $this->resolveToFSPath( $params['src'] );
524 if ( $source === null ) {
528 // Create a new temporary file with the same extension...
529 $ext = FileBackend
::extensionFromPath( $params['src'] );
530 $tmpFile = TempFSFile
::factory( wfBaseName( $source ) . '_', $ext );
534 $tmpPath = $tmpFile->getPath();
536 // Copy the source file over the temp file
537 $ok = copy( $source, $tmpPath );
542 $this->chmod( $tmpPath );
548 * @see FileBackendStore::directoriesAreVirtual()
551 protected function directoriesAreVirtual() {
556 * Chmod a file, suppressing the warnings
558 * @param $path string Absolute file system path
559 * @return bool Success
561 protected function chmod( $path ) {
562 wfSuppressWarnings();
563 $ok = chmod( $path, $this->fileMode
);
570 * Listen for E_WARNING errors and track whether any happen
574 protected function trapWarnings() {
575 $this->hadWarningErrors
[] = false; // push to stack
576 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
577 return false; // invoke normal PHP error handler
581 * Stop listening for E_WARNING errors and return true if any happened
585 protected function untrapWarnings() {
586 restore_error_handler(); // restore previous handler
587 return array_pop( $this->hadWarningErrors
); // pop from stack
590 private function handleWarning() {
591 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
592 return true; // suppress from PHP handler
597 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
598 * catches exception or does any custom behavoir that we may want.
599 * Do not use this class from places outside FSFileBackend.
601 * @ingroup FileBackend
603 abstract class FSFileBackendList
implements Iterator
{
606 protected $suffixStart; // integer
607 protected $pos = 0; // integer
609 protected $params = array();
612 * @param $dir string file system directory
614 public function __construct( $dir, array $params ) {
615 $dir = realpath( $dir ); // normalize
616 $this->suffixStart
= strlen( $dir ) +
1; // size of "path/to/dir/"
617 $this->params
= $params;
620 $this->iter
= $this->initIterator( $dir );
621 } catch ( UnexpectedValueException
$e ) {
622 $this->iter
= null; // bad permissions? deleted?
627 * Return an appropriate iterator object to wrap
629 * @param $dir string file system directory
632 protected function initIterator( $dir ) {
633 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
634 # Get an iterator that will get direct sub-nodes
635 return new DirectoryIterator( $dir );
636 } else { // recursive
637 # Get an iterator that will return leaf nodes (non-directories)
638 # RecursiveDirectoryIterator extends FilesystemIterator.
639 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
640 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
641 return new RecursiveIteratorIterator(
642 new RecursiveDirectoryIterator( $dir, $flags ),
643 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
649 * @see Iterator::key()
652 public function key() {
657 * @see Iterator::current()
658 * @return string|bool String or false
660 public function current() {
661 return $this->getRelPath( $this->iter
->current()->getPathname() );
665 * @see Iterator::next()
668 public function next() {
671 $this->filterViaNext();
672 } catch ( UnexpectedValueException
$e ) {
679 * @see Iterator::rewind()
682 public function rewind() {
685 $this->iter
->rewind();
686 $this->filterViaNext();
687 } catch ( UnexpectedValueException
$e ) {
693 * @see Iterator::valid()
696 public function valid() {
697 return $this->iter
&& $this->iter
->valid();
701 * Filter out items by advancing to the next ones
703 protected function filterViaNext() {}
706 * Return only the relative path and normalize slashes to FileBackend-style.
707 * Uses the "real path" since the suffix is based upon that.
709 * @param $path string
712 protected function getRelPath( $path ) {
713 return strtr( substr( realpath( $path ), $this->suffixStart
), '\\', '/' );
717 class FSFileBackendDirList
extends FSFileBackendList
{
718 protected function filterViaNext() {
719 while ( $this->iter
->valid() ) {
720 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
721 $this->iter
->next(); // skip non-directories and dot files
729 class FSFileBackendFileList
extends FSFileBackendList
{
730 protected function filterViaNext() {
731 while ( $this->iter
->valid() ) {
732 if ( !$this->iter
->current()->isFile() ) {
733 $this->iter
->next(); // skip non-files and dot files