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::doCreateInternal()
184 protected function doCreateInternal( 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 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
196 $status->fatal( 'backend-fail-create', $params['dst'] );
199 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
200 if ( $bytes === false ) {
201 $status->fatal( 'backend-fail-create', $params['dst'] );
204 $cmd = implode( ' ', array(
205 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
206 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
207 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
209 $status->value
= new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
210 $tempFile->bind( $status->value
);
211 } else { // immediate write
212 $bytes = file_put_contents( $dest, $params['content'] );
213 if ( $bytes === false ) {
214 $status->fatal( 'backend-fail-create', $params['dst'] );
217 $this->chmod( $dest );
224 * @see FSFileBackend::doExecuteOpHandlesInternal()
226 protected function _getResponseCreate( $errors, Status
$status, array $params, $cmd ) {
227 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
228 $status->fatal( 'backend-fail-create', $params['dst'] );
229 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
234 * @see FileBackendStore::doStoreInternal()
237 protected function doStoreInternal( array $params ) {
238 $status = Status
::newGood();
240 $dest = $this->resolveToFSPath( $params['dst'] );
241 if ( $dest === null ) {
242 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
246 if ( !empty( $params['async'] ) ) { // deferred
247 $cmd = implode( ' ', array(
248 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
249 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
250 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
252 $status->value
= new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
253 } else { // immediate write
254 $ok = copy( $params['src'], $dest );
255 // In some cases (at least over NFS), copy() returns true when it fails
256 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
257 if ( $ok ) { // PHP bug
258 unlink( $dest ); // remove broken file
259 trigger_error( __METHOD__
. ": copy() failed but returned true." );
261 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
264 $this->chmod( $dest );
271 * @see FSFileBackend::doExecuteOpHandlesInternal()
273 protected function _getResponseStore( $errors, Status
$status, array $params, $cmd ) {
274 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
275 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
276 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
281 * @see FileBackendStore::doCopyInternal()
284 protected function doCopyInternal( array $params ) {
285 $status = Status
::newGood();
287 $source = $this->resolveToFSPath( $params['src'] );
288 if ( $source === null ) {
289 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
293 $dest = $this->resolveToFSPath( $params['dst'] );
294 if ( $dest === null ) {
295 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
299 if ( !is_file( $source ) ) {
300 if ( empty( $params['ignoreMissingSource'] ) ) {
301 $status->fatal( 'backend-fail-copy', $params['src'] );
303 return $status; // do nothing; either OK or bad status
306 if ( !empty( $params['async'] ) ) { // deferred
307 $cmd = implode( ' ', array(
308 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
309 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
310 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
312 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
313 } else { // immediate write
314 $ok = copy( $source, $dest );
315 // In some cases (at least over NFS), copy() returns true when it fails
316 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
317 if ( $ok ) { // PHP bug
318 unlink( $dest ); // remove broken file
319 trigger_error( __METHOD__
. ": copy() failed but returned true." );
321 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
324 $this->chmod( $dest );
331 * @see FSFileBackend::doExecuteOpHandlesInternal()
333 protected function _getResponseCopy( $errors, Status
$status, array $params, $cmd ) {
334 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
335 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
336 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
341 * @see FileBackendStore::doMoveInternal()
344 protected function doMoveInternal( array $params ) {
345 $status = Status
::newGood();
347 $source = $this->resolveToFSPath( $params['src'] );
348 if ( $source === null ) {
349 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
353 $dest = $this->resolveToFSPath( $params['dst'] );
354 if ( $dest === null ) {
355 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
359 if ( !is_file( $source ) ) {
360 if ( empty( $params['ignoreMissingSource'] ) ) {
361 $status->fatal( 'backend-fail-move', $params['src'] );
363 return $status; // do nothing; either OK or bad status
366 if ( !empty( $params['async'] ) ) { // deferred
367 $cmd = implode( ' ', array(
368 wfIsWindows() ?
'MOVE /Y' : 'mv', // (overwrite)
369 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
370 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
372 $status->value
= new FSFileOpHandle( $this, $params, 'Move', $cmd );
373 } else { // immediate write
374 $ok = rename( $source, $dest );
375 clearstatcache(); // file no longer at source
377 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
386 * @see FSFileBackend::doExecuteOpHandlesInternal()
388 protected function _getResponseMove( $errors, Status
$status, array $params, $cmd ) {
389 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
390 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
391 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
396 * @see FileBackendStore::doDeleteInternal()
399 protected function doDeleteInternal( array $params ) {
400 $status = Status
::newGood();
402 $source = $this->resolveToFSPath( $params['src'] );
403 if ( $source === null ) {
404 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
408 if ( !is_file( $source ) ) {
409 if ( empty( $params['ignoreMissingSource'] ) ) {
410 $status->fatal( 'backend-fail-delete', $params['src'] );
412 return $status; // do nothing; either OK or bad status
415 if ( !empty( $params['async'] ) ) { // deferred
416 $cmd = implode( ' ', array(
417 wfIsWindows() ?
'DEL' : 'unlink',
418 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
420 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd );
421 } else { // immediate write
422 $ok = unlink( $source );
424 $status->fatal( 'backend-fail-delete', $params['src'] );
433 * @see FSFileBackend::doExecuteOpHandlesInternal()
435 protected function _getResponseDelete( $errors, Status
$status, array $params, $cmd ) {
436 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
437 $status->fatal( 'backend-fail-delete', $params['src'] );
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