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 /** @var string Directory holding the container directories */
45 /** @var array Map of container names to root paths for custom container paths */
46 protected $containerPaths = [];
48 /** @var int File permission mode */
51 /** @var string Required OS username to own files */
54 /** @var string OS username running this script */
55 protected $currentUser;
58 protected $hadWarningErrors = [];
61 * @see FileBackendStore::__construct()
62 * Additional $config params include:
63 * - basePath : File system directory that holds containers.
64 * - containerPaths : Map of container names to custom file system directories.
65 * This should only be used for backwards-compatibility.
66 * - fileMode : Octal UNIX file permissions to use on files stored.
67 * @param array $config
69 public function __construct( array $config ) {
70 parent
::__construct( $config );
72 // Remove any possible trailing slash from directories
73 if ( isset( $config['basePath'] ) ) {
74 $this->basePath
= rtrim( $config['basePath'], '/' ); // remove trailing slash
76 $this->basePath
= null; // none; containers must have explicit paths
79 if ( isset( $config['containerPaths'] ) ) {
80 $this->containerPaths
= (array)$config['containerPaths'];
81 foreach ( $this->containerPaths
as &$path ) {
82 $path = rtrim( $path, '/' ); // remove trailing slash
86 $this->fileMode
= isset( $config['fileMode'] ) ?
$config['fileMode'] : 0644;
87 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
88 $this->fileOwner
= $config['fileOwner'];
89 // cache this, assuming it doesn't change
90 $this->currentUser
= posix_getpwuid( posix_getuid() )['name'];
94 public function getFeatures() {
95 return !wfIsWindows() ? FileBackend
::ATTR_UNICODE_PATHS
: 0;
98 protected function resolveContainerPath( $container, $relStoragePath ) {
99 // Check that container has a root directory
100 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
101 // Check for sane relative paths (assume the base paths are OK)
102 if ( $this->isLegalRelPath( $relStoragePath ) ) {
103 return $relStoragePath;
111 * Sanity check a relative file system path for validity
113 * @param string $path Normalized relative path
116 protected function isLegalRelPath( $path ) {
117 // Check for file names longer than 255 chars
118 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
121 if ( wfIsWindows() ) { // NTFS
122 return !preg_match( '![:*?"<>|]!', $path );
129 * Given the short (unresolved) and full (resolved) name of
130 * a container, return the file system path of the container.
132 * @param string $shortCont
133 * @param string $fullCont
134 * @return string|null
136 protected function containerFSRoot( $shortCont, $fullCont ) {
137 if ( isset( $this->containerPaths
[$shortCont] ) ) {
138 return $this->containerPaths
[$shortCont];
139 } elseif ( isset( $this->basePath
) ) {
140 return "{$this->basePath}/{$fullCont}";
143 return null; // no container base path defined
147 * Get the absolute file system path for a storage path
149 * @param string $storagePath Storage path
150 * @return string|null
152 protected function resolveToFSPath( $storagePath ) {
153 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
154 if ( $relPath === null ) {
155 return null; // invalid
157 list( , $shortCont, ) = FileBackend
::splitStoragePath( $storagePath );
158 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
159 if ( $relPath != '' ) {
160 $fsPath .= "/{$relPath}";
166 public function isPathUsableInternal( $storagePath ) {
167 $fsPath = $this->resolveToFSPath( $storagePath );
168 if ( $fsPath === null ) {
169 return false; // invalid
171 $parentDir = dirname( $fsPath );
173 if ( file_exists( $fsPath ) ) {
174 $ok = is_file( $fsPath ) && is_writable( $fsPath );
176 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
179 if ( $this->fileOwner
!== null && $this->currentUser
!== $this->fileOwner
) {
181 trigger_error( __METHOD__
. ": PHP process owner is not '{$this->fileOwner}'." );
187 protected function doCreateInternal( array $params ) {
188 $status = Status
::newGood();
190 $dest = $this->resolveToFSPath( $params['dst'] );
191 if ( $dest === null ) {
192 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
197 if ( !empty( $params['async'] ) ) { // deferred
198 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
200 $status->fatal( 'backend-fail-create', $params['dst'] );
204 $this->trapWarnings();
205 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
206 $this->untrapWarnings();
207 if ( $bytes === false ) {
208 $status->fatal( 'backend-fail-create', $params['dst'] );
212 $cmd = implode( ' ', [
213 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
214 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
215 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
217 $handler = function ( $errors, Status
$status, array $params, $cmd ) {
218 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
219 $status->fatal( 'backend-fail-create', $params['dst'] );
220 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
223 $status->value
= new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
224 $tempFile->bind( $status->value
);
225 } else { // immediate write
226 $this->trapWarnings();
227 $bytes = file_put_contents( $dest, $params['content'] );
228 $this->untrapWarnings();
229 if ( $bytes === false ) {
230 $status->fatal( 'backend-fail-create', $params['dst'] );
234 $this->chmod( $dest );
240 protected function doStoreInternal( array $params ) {
241 $status = Status
::newGood();
243 $dest = $this->resolveToFSPath( $params['dst'] );
244 if ( $dest === null ) {
245 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
250 if ( !empty( $params['async'] ) ) { // deferred
251 $cmd = implode( ' ', [
252 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
253 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
254 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
256 $handler = function ( $errors, Status
$status, array $params, $cmd ) {
257 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
258 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
259 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
262 $status->value
= new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
263 } else { // immediate write
264 $this->trapWarnings();
265 $ok = copy( $params['src'], $dest );
266 $this->untrapWarnings();
267 // In some cases (at least over NFS), copy() returns true when it fails
268 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
269 if ( $ok ) { // PHP bug
270 unlink( $dest ); // remove broken file
271 trigger_error( __METHOD__
. ": copy() failed but returned true." );
273 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
277 $this->chmod( $dest );
283 protected function doCopyInternal( array $params ) {
284 $status = Status
::newGood();
286 $source = $this->resolveToFSPath( $params['src'] );
287 if ( $source === null ) {
288 $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'] );
300 if ( !is_file( $source ) ) {
301 if ( empty( $params['ignoreMissingSource'] ) ) {
302 $status->fatal( 'backend-fail-copy', $params['src'] );
305 return $status; // do nothing; either OK or bad status
308 if ( !empty( $params['async'] ) ) { // deferred
309 $cmd = implode( ' ', [
310 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
311 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
312 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
314 $handler = function ( $errors, Status
$status, array $params, $cmd ) {
315 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
316 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
317 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
320 $status->value
= new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
321 } else { // immediate write
322 $this->trapWarnings();
323 $ok = ( $source === $dest ) ?
true : copy( $source, $dest );
324 $this->untrapWarnings();
325 // In some cases (at least over NFS), copy() returns true when it fails
326 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
327 if ( $ok ) { // PHP bug
328 $this->trapWarnings();
329 unlink( $dest ); // remove broken file
330 $this->untrapWarnings();
331 trigger_error( __METHOD__
. ": copy() failed but returned true." );
333 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
337 $this->chmod( $dest );
343 protected function doMoveInternal( array $params ) {
344 $status = Status
::newGood();
346 $source = $this->resolveToFSPath( $params['src'] );
347 if ( $source === null ) {
348 $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'] );
360 if ( !is_file( $source ) ) {
361 if ( empty( $params['ignoreMissingSource'] ) ) {
362 $status->fatal( 'backend-fail-move', $params['src'] );
365 return $status; // do nothing; either OK or bad status
368 if ( !empty( $params['async'] ) ) { // deferred
369 $cmd = implode( ' ', [
370 wfIsWindows() ?
'MOVE /Y' : 'mv', // (overwrite)
371 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
372 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
374 $handler = function ( $errors, Status
$status, array $params, $cmd ) {
375 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
376 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
377 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
380 $status->value
= new FSFileOpHandle( $this, $params, $handler, $cmd );
381 } else { // immediate write
382 $this->trapWarnings();
383 $ok = ( $source === $dest ) ?
true : rename( $source, $dest );
384 $this->untrapWarnings();
385 clearstatcache(); // file no longer at source
387 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
396 protected function doDeleteInternal( array $params ) {
397 $status = Status
::newGood();
399 $source = $this->resolveToFSPath( $params['src'] );
400 if ( $source === null ) {
401 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
406 if ( !is_file( $source ) ) {
407 if ( empty( $params['ignoreMissingSource'] ) ) {
408 $status->fatal( 'backend-fail-delete', $params['src'] );
411 return $status; // do nothing; either OK or bad status
414 if ( !empty( $params['async'] ) ) { // deferred
415 $cmd = implode( ' ', [
416 wfIsWindows() ?
'DEL' : 'unlink',
417 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
419 $handler = function ( $errors, Status
$status, array $params, $cmd ) {
420 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
421 $status->fatal( 'backend-fail-delete', $params['src'] );
422 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
425 $status->value
= new FSFileOpHandle( $this, $params, $handler, $cmd );
426 } else { // immediate write
427 $this->trapWarnings();
428 $ok = unlink( $source );
429 $this->untrapWarnings();
431 $status->fatal( 'backend-fail-delete', $params['src'] );
441 * @param string $fullCont
442 * @param string $dirRel
443 * @param array $params
446 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
447 $status = Status
::newGood();
448 list( , $shortCont, ) = 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 // Create the directory and its parents as needed...
453 $this->trapWarnings();
454 if ( !wfMkdirParents( $dir ) ) {
455 wfDebugLog( 'FSFileBackend', __METHOD__
. ": cannot create directory $dir" );
456 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
457 } elseif ( !is_writable( $dir ) ) {
458 wfDebugLog( 'FSFileBackend', __METHOD__
. ": directory $dir is read-only" );
459 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
460 } elseif ( !is_readable( $dir ) ) {
461 wfDebugLog( 'FSFileBackend', __METHOD__
. ": directory $dir is not readable" );
462 $status->fatal( 'directorynotreadableerror', $params['dir'] );
464 $this->untrapWarnings();
465 // Respect any 'noAccess' or 'noListing' flags...
466 if ( is_dir( $dir ) && !$existed ) {
467 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
473 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
474 $status = Status
::newGood();
475 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
476 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
477 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
478 // Seed new directories with a blank index.html, to prevent crawling...
479 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
480 $this->trapWarnings();
481 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
482 $this->untrapWarnings();
483 if ( $bytes === false ) {
484 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
487 // Add a .htaccess file to the root of the container...
488 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
489 $this->trapWarnings();
490 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
491 $this->untrapWarnings();
492 if ( $bytes === false ) {
493 $storeDir = "mwstore://{$this->name}/{$shortCont}";
494 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
501 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
502 $status = Status
::newGood();
503 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
504 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
505 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
506 // Unseed new directories with a blank index.html, to allow crawling...
507 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
508 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
509 $this->trapWarnings();
510 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
511 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
513 $this->untrapWarnings();
515 // Remove the .htaccess file from the root of the container...
516 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
517 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
518 $this->trapWarnings();
519 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
520 $storeDir = "mwstore://{$this->name}/{$shortCont}";
521 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
523 $this->untrapWarnings();
529 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
530 $status = Status
::newGood();
531 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
532 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
533 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
534 $this->trapWarnings();
535 if ( is_dir( $dir ) ) {
536 rmdir( $dir ); // remove directory if empty
538 $this->untrapWarnings();
543 protected function doGetFileStat( array $params ) {
544 $source = $this->resolveToFSPath( $params['src'] );
545 if ( $source === null ) {
546 return false; // invalid storage path
549 $this->trapWarnings(); // don't trust 'false' if there were errors
550 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
551 $hadError = $this->untrapWarnings();
555 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
556 'size' => $stat['size']
558 } elseif ( !$hadError ) {
559 return false; // file does not exist
561 return null; // failure
565 protected function doClearCache( array $paths = null ) {
566 clearstatcache(); // clear the PHP file stat cache
569 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
570 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
571 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
572 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
574 $this->trapWarnings(); // don't trust 'false' if there were errors
575 $exists = is_dir( $dir );
576 $hadError = $this->untrapWarnings();
578 return $hadError ?
null : $exists;
582 * @see FileBackendStore::getDirectoryListInternal()
583 * @param string $fullCont
584 * @param string $dirRel
585 * @param array $params
588 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
589 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
590 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
591 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
592 $exists = is_dir( $dir );
594 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
596 return []; // nothing under this dir
597 } elseif ( !is_readable( $dir ) ) {
598 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
600 return null; // bad permissions?
603 return new FSFileBackendDirList( $dir, $params );
607 * @see FileBackendStore::getFileListInternal()
608 * @param string $fullCont
609 * @param string $dirRel
610 * @param array $params
611 * @return array|FSFileBackendFileList|null
613 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
614 list( , $shortCont, ) = 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" );
621 return []; // nothing under this dir
622 } elseif ( !is_readable( $dir ) ) {
623 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
625 return null; // bad permissions?
628 return new FSFileBackendFileList( $dir, $params );
631 protected function doGetLocalReferenceMulti( array $params ) {
632 $fsFiles = []; // (path => FSFile)
634 foreach ( $params['srcs'] as $src ) {
635 $source = $this->resolveToFSPath( $src );
636 if ( $source === null ||
!is_file( $source ) ) {
637 $fsFiles[$src] = null; // invalid path or file does not exist
639 $fsFiles[$src] = new FSFile( $source );
646 protected function doGetLocalCopyMulti( array $params ) {
647 $tmpFiles = []; // (path => TempFSFile)
649 foreach ( $params['srcs'] as $src ) {
650 $source = $this->resolveToFSPath( $src );
651 if ( $source === null ) {
652 $tmpFiles[$src] = null; // invalid path
654 // Create a new temporary file with the same extension...
655 $ext = FileBackend
::extensionFromPath( $src );
656 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
658 $tmpFiles[$src] = null;
660 $tmpPath = $tmpFile->getPath();
661 // Copy the source file over the temp file
662 $this->trapWarnings();
663 $ok = copy( $source, $tmpPath );
664 $this->untrapWarnings();
666 $tmpFiles[$src] = null;
668 $this->chmod( $tmpPath );
669 $tmpFiles[$src] = $tmpFile;
678 protected function directoriesAreVirtual() {
683 * @param FSFileOpHandle[] $fileOpHandles
687 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
691 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
692 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
696 foreach ( $pipes as $index => $pipe ) {
697 // Result will be empty on success in *NIX. On Windows,
698 // it may be something like " 1 file(s) [copied|moved].".
699 $errs[$index] = stream_get_contents( $pipe );
703 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
704 $status = Status
::newGood();
705 $function = $fileOpHandle->call
;
706 $function( $errs[$index], $status, $fileOpHandle->params
, $fileOpHandle->cmd
);
707 $statuses[$index] = $status;
708 if ( $status->isOK() && $fileOpHandle->chmodPath
) {
709 $this->chmod( $fileOpHandle->chmodPath
);
713 clearstatcache(); // files changed
718 * Chmod a file, suppressing the warnings
720 * @param string $path Absolute file system path
721 * @return bool Success
723 protected function chmod( $path ) {
724 $this->trapWarnings();
725 $ok = chmod( $path, $this->fileMode
);
726 $this->untrapWarnings();
732 * Return the text of an index.html file to hide directory listings
736 protected function indexHtmlPrivate() {
741 * Return the text of a .htaccess file to make a directory private
745 protected function htaccessPrivate() {
746 return "Deny from all\n";
750 * Clean up directory separators for the given OS
752 * @param string $path FS path
755 protected function cleanPathSlashes( $path ) {
756 return wfIsWindows() ?
strtr( $path, '/', '\\' ) : $path;
760 * Listen for E_WARNING errors and track whether any happen
762 protected function trapWarnings() {
763 $this->hadWarningErrors
[] = false; // push to stack
764 set_error_handler( [ $this, 'handleWarning' ], E_WARNING
);
768 * Stop listening for E_WARNING errors and return true if any happened
772 protected function untrapWarnings() {
773 restore_error_handler(); // restore previous handler
774 return array_pop( $this->hadWarningErrors
); // pop from stack
779 * @param string $errstr
783 public function handleWarning( $errno, $errstr ) {
784 wfDebugLog( 'FSFileBackend', $errstr ); // more detailed error logging
785 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
787 return true; // suppress from PHP handler
792 * @see FileBackendStoreOpHandle
794 class FSFileOpHandle
extends FileBackendStoreOpHandle
{
795 public $cmd; // string; shell command
796 public $chmodPath; // string; file to chmod
799 * @param FSFileBackend $backend
800 * @param array $params
801 * @param callable $call
803 * @param int|null $chmodPath
805 public function __construct(
806 FSFileBackend
$backend, array $params, $call, $cmd, $chmodPath = null
808 $this->backend
= $backend;
809 $this->params
= $params;
812 $this->chmodPath
= $chmodPath;
817 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
818 * catches exception or does any custom behavoir that we may want.
819 * Do not use this class from places outside FSFileBackend.
821 * @ingroup FileBackend
823 abstract class FSFileBackendList
implements Iterator
{
828 protected $suffixStart;
834 protected $params = [];
837 * @param string $dir File system directory
838 * @param array $params
840 public function __construct( $dir, array $params ) {
841 $path = realpath( $dir ); // normalize
842 if ( $path === false ) {
845 $this->suffixStart
= strlen( $path ) +
1; // size of "path/to/dir/"
846 $this->params
= $params;
849 $this->iter
= $this->initIterator( $path );
850 } catch ( UnexpectedValueException
$e ) {
851 $this->iter
= null; // bad permissions? deleted?
856 * Return an appropriate iterator object to wrap
858 * @param string $dir File system directory
861 protected function initIterator( $dir ) {
862 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
863 # Get an iterator that will get direct sub-nodes
864 return new DirectoryIterator( $dir );
865 } else { // recursive
866 # Get an iterator that will return leaf nodes (non-directories)
867 # RecursiveDirectoryIterator extends FilesystemIterator.
868 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
869 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
871 return new RecursiveIteratorIterator(
872 new RecursiveDirectoryIterator( $dir, $flags ),
873 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
879 * @see Iterator::key()
882 public function key() {
887 * @see Iterator::current()
888 * @return string|bool String or false
890 public function current() {
891 return $this->getRelPath( $this->iter
->current()->getPathname() );
895 * @see Iterator::next()
896 * @throws FileBackendError
898 public function next() {
901 $this->filterViaNext();
902 } catch ( UnexpectedValueException
$e ) { // bad permissions? deleted?
903 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
909 * @see Iterator::rewind()
910 * @throws FileBackendError
912 public function rewind() {
915 $this->iter
->rewind();
916 $this->filterViaNext();
917 } catch ( UnexpectedValueException
$e ) { // bad permissions? deleted?
918 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
923 * @see Iterator::valid()
926 public function valid() {
927 return $this->iter
&& $this->iter
->valid();
931 * Filter out items by advancing to the next ones
933 protected function filterViaNext() {
937 * Return only the relative path and normalize slashes to FileBackend-style.
938 * Uses the "real path" since the suffix is based upon that.
943 protected function getRelPath( $dir ) {
944 $path = realpath( $dir );
945 if ( $path === false ) {
949 return strtr( substr( $path, $this->suffixStart
), '\\', '/' );
953 class FSFileBackendDirList
extends FSFileBackendList
{
954 protected function filterViaNext() {
955 while ( $this->iter
->valid() ) {
956 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
957 $this->iter
->next(); // skip non-directories and dot files
965 class FSFileBackendFileList
extends FSFileBackendList
{
966 protected function filterViaNext() {
967 while ( $this->iter
->valid() ) {
968 if ( !$this->iter
->current()->isFile() ) {
969 $this->iter
->next(); // skip non-files and dot files