3 * File system based backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Class for a file system (FS) based file backend.
28 * All "containers" each map to a directory under the backend's base directory.
29 * For backwards-compatibility, some container paths can be set to custom paths.
30 * The wiki ID will not be used in any custom paths, so this should be avoided.
32 * Having directories with thousands of files will diminish performance.
33 * Sharding can be accomplished by using FileRepo-style hash paths.
35 * Status messages should avoid mentioning the internal FS paths.
36 * PHP warnings are assumed to be logged rather than output.
38 * @ingroup FileBackend
41 class FSFileBackend
extends FileBackendStore
{
42 protected $basePath; // string; directory holding the container directories
43 /** @var Array Map of container names to root paths */
44 protected $containerPaths = array(); // for custom container paths
45 protected $fileMode; // integer; file permission mode
46 protected $fileOwner; // string; required OS username to own files
47 protected $currentUser; // string; OS username running this script
49 protected $hadWarningErrors = array();
52 * @see FileBackendStore::__construct()
53 * Additional $config params include:
54 * - basePath : File system directory that holds containers.
55 * - containerPaths : Map of container names to custom file system directories.
56 * This should only be used for backwards-compatibility.
57 * - fileMode : Octal UNIX file permissions to use on files stored.
59 public function __construct( array $config ) {
60 parent
::__construct( $config );
62 // Remove any possible trailing slash from directories
63 if ( isset( $config['basePath'] ) ) {
64 $this->basePath
= rtrim( $config['basePath'], '/' ); // remove trailing slash
66 $this->basePath
= null; // none; containers must have explicit paths
69 if ( isset( $config['containerPaths'] ) ) {
70 $this->containerPaths
= (array)$config['containerPaths'];
71 foreach ( $this->containerPaths
as &$path ) {
72 $path = rtrim( $path, '/' ); // remove trailing slash
76 $this->fileMode
= isset( $config['fileMode'] ) ?
$config['fileMode'] : 0644;
77 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
78 $this->fileOwner
= $config['fileOwner'];
79 $info = posix_getpwuid( posix_getuid() );
80 $this->currentUser
= $info['name']; // cache this, assuming it doesn't change
85 * @see FileBackendStore::resolveContainerPath()
86 * @param $container string
87 * @param $relStoragePath string
90 protected function resolveContainerPath( $container, $relStoragePath ) {
91 // Check that container has a root directory
92 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
93 // Check for sane relative paths (assume the base paths are OK)
94 if ( $this->isLegalRelPath( $relStoragePath ) ) {
95 return $relStoragePath;
102 * Sanity check a relative file system path for validity
104 * @param $path string Normalized relative path
107 protected function isLegalRelPath( $path ) {
108 // Check for file names longer than 255 chars
109 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
112 if ( wfIsWindows() ) { // NTFS
113 return !preg_match( '![:*?"<>|]!', $path );
120 * Given the short (unresolved) and full (resolved) name of
121 * a container, return the file system path of the container.
123 * @param $shortCont string
124 * @param $fullCont string
125 * @return string|null
127 protected function containerFSRoot( $shortCont, $fullCont ) {
128 if ( isset( $this->containerPaths
[$shortCont] ) ) {
129 return $this->containerPaths
[$shortCont];
130 } elseif ( isset( $this->basePath
) ) {
131 return "{$this->basePath}/{$fullCont}";
133 return null; // no container base path defined
137 * Get the absolute file system path for a storage path
139 * @param $storagePath string Storage path
140 * @return string|null
142 protected function resolveToFSPath( $storagePath ) {
143 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
144 if ( $relPath === null ) {
145 return null; // invalid
147 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $storagePath );
148 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
149 if ( $relPath != '' ) {
150 $fsPath .= "/{$relPath}";
156 * @see FileBackendStore::isPathUsableInternal()
159 public function isPathUsableInternal( $storagePath ) {
160 $fsPath = $this->resolveToFSPath( $storagePath );
161 if ( $fsPath === null ) {
162 return false; // invalid
164 $parentDir = dirname( $fsPath );
166 if ( file_exists( $fsPath ) ) {
167 $ok = is_file( $fsPath ) && is_writable( $fsPath );
169 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
172 if ( $this->fileOwner
!== null && $this->currentUser
!== $this->fileOwner
) {
174 trigger_error( __METHOD__
. ": PHP process owner is not '{$this->fileOwner}'." );
181 * @see FileBackendStore::doStoreInternal()
184 protected function doStoreInternal( array $params ) {
185 $status = Status
::newGood();
187 $dest = $this->resolveToFSPath( $params['dst'] );
188 if ( $dest === null ) {
189 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
193 if ( !empty( $params['async'] ) ) { // deferred
194 $cmd = implode( ' ', array(
195 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
196 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
197 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
199 $status->value
= new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
200 } else { // immediate write
201 $ok = copy( $params['src'], $dest );
202 // In some cases (at least over NFS), copy() returns true when it fails
203 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
204 if ( $ok ) { // PHP bug
205 unlink( $dest ); // remove broken file
206 trigger_error( __METHOD__
. ": copy() failed but returned true." );
208 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
211 $this->chmod( $dest );
218 * @see FSFileBackend::doExecuteOpHandlesInternal()
220 protected function _getResponseStore( $errors, Status
$status, array $params, $cmd ) {
221 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
222 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
223 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
228 * @see FileBackendStore::doCopyInternal()
231 protected function doCopyInternal( array $params ) {
232 $status = Status
::newGood();
234 $source = $this->resolveToFSPath( $params['src'] );
235 if ( $source === null ) {
236 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
240 $dest = $this->resolveToFSPath( $params['dst'] );
241 if ( $dest === null ) {
242 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
246 if ( !is_file( $source ) ) {
247 if ( empty( $params['ignoreMissingSource'] ) ) {
248 $status->fatal( 'backend-fail-copy', $params['src'] );
250 return $status; // do nothing; either OK or bad status
253 if ( !empty( $params['async'] ) ) { // deferred
254 $cmd = implode( ' ', array(
255 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
256 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
257 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
259 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
260 } else { // immediate write
261 $ok = copy( $source, $dest );
262 // In some cases (at least over NFS), copy() returns true when it fails
263 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
264 if ( $ok ) { // PHP bug
265 unlink( $dest ); // remove broken file
266 trigger_error( __METHOD__
. ": copy() failed but returned true." );
268 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
271 $this->chmod( $dest );
278 * @see FSFileBackend::doExecuteOpHandlesInternal()
280 protected function _getResponseCopy( $errors, Status
$status, array $params, $cmd ) {
281 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
282 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
283 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
288 * @see FileBackendStore::doMoveInternal()
291 protected function doMoveInternal( array $params ) {
292 $status = Status
::newGood();
294 $source = $this->resolveToFSPath( $params['src'] );
295 if ( $source === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
300 $dest = $this->resolveToFSPath( $params['dst'] );
301 if ( $dest === null ) {
302 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
306 if ( !is_file( $source ) ) {
307 if ( empty( $params['ignoreMissingSource'] ) ) {
308 $status->fatal( 'backend-fail-move', $params['src'] );
310 return $status; // do nothing; either OK or bad status
313 if ( !empty( $params['async'] ) ) { // deferred
314 $cmd = implode( ' ', array(
315 wfIsWindows() ?
'MOVE /Y' : 'mv', // (overwrite)
316 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
317 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
319 $status->value
= new FSFileOpHandle( $this, $params, 'Move', $cmd );
320 } else { // immediate write
321 $ok = rename( $source, $dest );
322 clearstatcache(); // file no longer at source
324 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
333 * @see FSFileBackend::doExecuteOpHandlesInternal()
335 protected function _getResponseMove( $errors, Status
$status, array $params, $cmd ) {
336 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
337 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
338 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
343 * @see FileBackendStore::doDeleteInternal()
346 protected function doDeleteInternal( array $params ) {
347 $status = Status
::newGood();
349 $source = $this->resolveToFSPath( $params['src'] );
350 if ( $source === null ) {
351 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
355 if ( !is_file( $source ) ) {
356 if ( empty( $params['ignoreMissingSource'] ) ) {
357 $status->fatal( 'backend-fail-delete', $params['src'] );
359 return $status; // do nothing; either OK or bad status
362 if ( !empty( $params['async'] ) ) { // deferred
363 $cmd = implode( ' ', array(
364 wfIsWindows() ?
'DEL' : 'unlink',
365 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
367 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd );
368 } else { // immediate write
369 $ok = unlink( $source );
371 $status->fatal( 'backend-fail-delete', $params['src'] );
380 * @see FSFileBackend::doExecuteOpHandlesInternal()
382 protected function _getResponseDelete( $errors, Status
$status, array $params, $cmd ) {
383 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
384 $status->fatal( 'backend-fail-delete', $params['src'] );
385 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
390 * @see FileBackendStore::doCreateInternal()
393 protected function doCreateInternal( array $params ) {
394 $status = Status
::newGood();
396 $dest = $this->resolveToFSPath( $params['dst'] );
397 if ( $dest === null ) {
398 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
402 if ( !empty( $params['async'] ) ) { // deferred
403 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
405 $status->fatal( 'backend-fail-create', $params['dst'] );
408 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
409 if ( $bytes === false ) {
410 $status->fatal( 'backend-fail-create', $params['dst'] );
413 $cmd = implode( ' ', array(
414 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
415 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
416 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
418 $status->value
= new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
419 $tempFile->bind( $status->value
);
420 } else { // immediate write
421 $bytes = file_put_contents( $dest, $params['content'] );
422 if ( $bytes === false ) {
423 $status->fatal( 'backend-fail-create', $params['dst'] );
426 $this->chmod( $dest );
433 * @see FSFileBackend::doExecuteOpHandlesInternal()
435 protected function _getResponseCreate( $errors, Status
$status, array $params, $cmd ) {
436 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
437 $status->fatal( 'backend-fail-create', $params['dst'] );
438 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
443 * @see FileBackendStore::doPrepareInternal()
446 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
447 $status = Status
::newGood();
448 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
449 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
450 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
451 $existed = is_dir( $dir ); // already there?
452 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
453 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
454 } elseif ( !is_writable( $dir ) ) {
455 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
456 } elseif ( !is_readable( $dir ) ) {
457 $status->fatal( 'directorynotreadableerror', $params['dir'] );
459 if ( is_dir( $dir ) && !$existed ) {
460 // Respect any 'noAccess' or 'noListing' flags...
461 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
467 * @see FileBackendStore::doSecureInternal()
470 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
471 $status = Status
::newGood();
472 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
473 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
474 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
475 // Seed new directories with a blank index.html, to prevent crawling...
476 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
477 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
478 if ( $bytes === false ) {
479 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
483 // Add a .htaccess file to the root of the container...
484 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
485 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
486 if ( $bytes === false ) {
487 $storeDir = "mwstore://{$this->name}/{$shortCont}";
488 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
496 * @see FileBackendStore::doPublishInternal()
499 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
500 $status = Status
::newGood();
501 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
502 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
503 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
504 // Unseed new directories with a blank index.html, to allow crawling...
505 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
506 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
507 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
508 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
512 // Remove the .htaccess file from the root of the container...
513 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
514 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
515 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
516 $storeDir = "mwstore://{$this->name}/{$shortCont}";
517 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
525 * @see FileBackendStore::doCleanInternal()
528 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
529 $status = Status
::newGood();
530 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
531 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
532 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
533 wfSuppressWarnings();
534 if ( is_dir( $dir ) ) {
535 rmdir( $dir ); // remove directory if empty
542 * @see FileBackendStore::doFileExists()
543 * @return array|bool|null
545 protected function doGetFileStat( array $params ) {
546 $source = $this->resolveToFSPath( $params['src'] );
547 if ( $source === null ) {
548 return false; // invalid storage path
551 $this->trapWarnings(); // don't trust 'false' if there were errors
552 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
553 $hadError = $this->untrapWarnings();
557 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
558 'size' => $stat['size']
560 } elseif ( !$hadError ) {
561 return false; // file does not exist
563 return null; // failure
568 * @see FileBackendStore::doClearCache()
570 protected function doClearCache( array $paths = null ) {
571 clearstatcache(); // clear the PHP file stat cache
575 * @see FileBackendStore::doDirectoryExists()
578 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
579 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
580 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
581 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
583 $this->trapWarnings(); // don't trust 'false' if there were errors
584 $exists = is_dir( $dir );
585 $hadError = $this->untrapWarnings();
587 return $hadError ?
null : $exists;
591 * @see FileBackendStore::getDirectoryListInternal()
594 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
595 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
596 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
597 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
598 $exists = is_dir( $dir );
600 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
601 return array(); // nothing under this dir
602 } elseif ( !is_readable( $dir ) ) {
603 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
604 return null; // bad permissions?
606 return new FSFileBackendDirList( $dir, $params );
610 * @see FileBackendStore::getFileListInternal()
611 * @return Array|FSFileBackendFileList|null
613 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
614 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
615 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
616 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
617 $exists = is_dir( $dir );
619 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
620 return array(); // nothing under this dir
621 } elseif ( !is_readable( $dir ) ) {
622 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
623 return null; // bad permissions?
625 return new FSFileBackendFileList( $dir, $params );
629 * @see FileBackendStore::doGetLocalReferenceMulti()
632 protected function doGetLocalReferenceMulti( array $params ) {
633 $fsFiles = array(); // (path => FSFile)
635 foreach ( $params['srcs'] as $src ) {
636 $source = $this->resolveToFSPath( $src );
637 if ( $source === null ||
!is_file( $source ) ) {
638 $fsFiles[$src] = null; // invalid path or file does not exist
640 $fsFiles[$src] = new FSFile( $source );
648 * @see FileBackendStore::doGetLocalCopyMulti()
651 protected function doGetLocalCopyMulti( array $params ) {
652 $tmpFiles = array(); // (path => TempFSFile)
654 foreach ( $params['srcs'] as $src ) {
655 $source = $this->resolveToFSPath( $src );
656 if ( $source === null ) {
657 $tmpFiles[$src] = null; // invalid path
659 // Create a new temporary file with the same extension...
660 $ext = FileBackend
::extensionFromPath( $src );
661 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
663 $tmpFiles[$src] = null;
665 $tmpPath = $tmpFile->getPath();
666 // Copy the source file over the temp file
667 wfSuppressWarnings();
668 $ok = copy( $source, $tmpPath );
671 $tmpFiles[$src] = null;
673 $this->chmod( $tmpPath );
674 $tmpFiles[$src] = $tmpFile;
684 * @see FileBackendStore::directoriesAreVirtual()
687 protected function directoriesAreVirtual() {
692 * @see FileBackendStore::doExecuteOpHandlesInternal()
693 * @return Array List of corresponding Status objects
695 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
699 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
700 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
704 foreach ( $pipes as $index => $pipe ) {
705 // Result will be empty on success in *NIX. On Windows,
706 // it may be something like " 1 file(s) [copied|moved].".
707 $errs[$index] = stream_get_contents( $pipe );
711 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
712 $status = Status
::newGood();
713 $function = '_getResponse' . $fileOpHandle->call
;
714 $this->$function( $errs[$index], $status, $fileOpHandle->params
, $fileOpHandle->cmd
);
715 $statuses[$index] = $status;
716 if ( $status->isOK() && $fileOpHandle->chmodPath
) {
717 $this->chmod( $fileOpHandle->chmodPath
);
721 clearstatcache(); // files changed
726 * Chmod a file, suppressing the warnings
728 * @param $path string Absolute file system path
729 * @return bool Success
731 protected function chmod( $path ) {
732 wfSuppressWarnings();
733 $ok = chmod( $path, $this->fileMode
);
740 * Return the text of an index.html file to hide directory listings
744 protected function indexHtmlPrivate() {
749 * Return the text of a .htaccess file to make a directory private
753 protected function htaccessPrivate() {
754 return "Deny from all\n";
758 * Clean up directory separators for the given OS
760 * @param $path string FS path
763 protected function cleanPathSlashes( $path ) {
764 return wfIsWindows() ?
strtr( $path, '/', '\\' ) : $path;
768 * Listen for E_WARNING errors and track whether any happen
772 protected function trapWarnings() {
773 $this->hadWarningErrors
[] = false; // push to stack
774 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
775 return false; // invoke normal PHP error handler
779 * Stop listening for E_WARNING errors and return true if any happened
783 protected function untrapWarnings() {
784 restore_error_handler(); // restore previous handler
785 return array_pop( $this->hadWarningErrors
); // pop from stack
791 private function handleWarning() {
792 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
793 return true; // suppress from PHP handler
798 * @see FileBackendStoreOpHandle
800 class FSFileOpHandle
extends FileBackendStoreOpHandle
{
801 public $cmd; // string; shell command
802 public $chmodPath; // string; file to chmod
806 * @param $params array
809 * @param $chmodPath null
811 public function __construct( $backend, array $params, $call, $cmd, $chmodPath = null ) {
812 $this->backend
= $backend;
813 $this->params
= $params;
816 $this->chmodPath
= $chmodPath;
821 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
822 * catches exception or does any custom behavoir that we may want.
823 * Do not use this class from places outside FSFileBackend.
825 * @ingroup FileBackend
827 abstract class FSFileBackendList
implements Iterator
{
830 protected $suffixStart; // integer
831 protected $pos = 0; // integer
833 protected $params = array();
836 * @param $dir string file system directory
837 * @param $params array
839 public function __construct( $dir, array $params ) {
840 $dir = realpath( $dir ); // normalize
841 $this->suffixStart
= strlen( $dir ) +
1; // size of "path/to/dir/"
842 $this->params
= $params;
845 $this->iter
= $this->initIterator( $dir );
846 } catch ( UnexpectedValueException
$e ) {
847 $this->iter
= null; // bad permissions? deleted?
852 * Return an appropriate iterator object to wrap
854 * @param $dir string file system directory
857 protected function initIterator( $dir ) {
858 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
859 # Get an iterator that will get direct sub-nodes
860 return new DirectoryIterator( $dir );
861 } else { // recursive
862 # Get an iterator that will return leaf nodes (non-directories)
863 # RecursiveDirectoryIterator extends FilesystemIterator.
864 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
865 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
866 return new RecursiveIteratorIterator(
867 new RecursiveDirectoryIterator( $dir, $flags ),
868 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
874 * @see Iterator::key()
877 public function key() {
882 * @see Iterator::current()
883 * @return string|bool String or false
885 public function current() {
886 return $this->getRelPath( $this->iter
->current()->getPathname() );
890 * @see Iterator::next()
893 public function next() {
896 $this->filterViaNext();
897 } catch ( UnexpectedValueException
$e ) {
904 * @see Iterator::rewind()
907 public function rewind() {
910 $this->iter
->rewind();
911 $this->filterViaNext();
912 } catch ( UnexpectedValueException
$e ) {
918 * @see Iterator::valid()
921 public function valid() {
922 return $this->iter
&& $this->iter
->valid();
926 * Filter out items by advancing to the next ones
928 protected function filterViaNext() {}
931 * Return only the relative path and normalize slashes to FileBackend-style.
932 * Uses the "real path" since the suffix is based upon that.
934 * @param $path string
937 protected function getRelPath( $path ) {
938 return strtr( substr( realpath( $path ), $this->suffixStart
), '\\', '/' );
942 class FSFileBackendDirList
extends FSFileBackendList
{
943 protected function filterViaNext() {
944 while ( $this->iter
->valid() ) {
945 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
946 $this->iter
->next(); // skip non-directories and dot files
954 class FSFileBackendFileList
extends FSFileBackendList
{
955 protected function filterViaNext() {
956 while ( $this->iter
->valid() ) {
957 if ( !$this->iter
->current()->isFile() ) {
958 $this->iter
->next(); // skip non-files and dot files