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
50 protected $hadWarningErrors = array();
53 * @see FileBackendStore::__construct()
54 * Additional $config params include:
55 * - basePath : File system directory that holds containers.
56 * - containerPaths : Map of container names to custom file system directories.
57 * This should only be used for backwards-compatibility.
58 * - fileMode : Octal UNIX file permissions to use on files stored.
60 public function __construct( array $config ) {
61 parent
::__construct( $config );
63 // Remove any possible trailing slash from directories
64 if ( isset( $config['basePath'] ) ) {
65 $this->basePath
= rtrim( $config['basePath'], '/' ); // remove trailing slash
67 $this->basePath
= null; // none; containers must have explicit paths
70 if ( isset( $config['containerPaths'] ) ) {
71 $this->containerPaths
= (array)$config['containerPaths'];
72 foreach ( $this->containerPaths
as &$path ) {
73 $path = rtrim( $path, '/' ); // remove trailing slash
77 $this->fileMode
= isset( $config['fileMode'] ) ?
$config['fileMode'] : 0644;
78 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
79 $this->fileOwner
= $config['fileOwner'];
80 $info = posix_getpwuid( posix_getuid() );
81 $this->currentUser
= $info['name']; // cache this, assuming it doesn't change
85 protected function resolveContainerPath( $container, $relStoragePath ) {
86 // Check that container has a root directory
87 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
88 // Check for sane relative paths (assume the base paths are OK)
89 if ( $this->isLegalRelPath( $relStoragePath ) ) {
90 return $relStoragePath;
97 * Sanity check a relative file system path for validity
99 * @param string $path Normalized relative path
102 protected function isLegalRelPath( $path ) {
103 // Check for file names longer than 255 chars
104 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
107 if ( wfIsWindows() ) { // NTFS
108 return !preg_match( '![:*?"<>|]!', $path );
115 * Given the short (unresolved) and full (resolved) name of
116 * a container, return the file system path of the container.
118 * @param string $shortCont
119 * @param string $fullCont
120 * @return string|null
122 protected function containerFSRoot( $shortCont, $fullCont ) {
123 if ( isset( $this->containerPaths
[$shortCont] ) ) {
124 return $this->containerPaths
[$shortCont];
125 } elseif ( isset( $this->basePath
) ) {
126 return "{$this->basePath}/{$fullCont}";
128 return null; // no container base path defined
132 * Get the absolute file system path for a storage path
134 * @param string $storagePath Storage path
135 * @return string|null
137 protected function resolveToFSPath( $storagePath ) {
138 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
139 if ( $relPath === null ) {
140 return null; // invalid
142 list( , $shortCont, ) = FileBackend
::splitStoragePath( $storagePath );
143 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
144 if ( $relPath != '' ) {
145 $fsPath .= "/{$relPath}";
150 public function isPathUsableInternal( $storagePath ) {
151 $fsPath = $this->resolveToFSPath( $storagePath );
152 if ( $fsPath === null ) {
153 return false; // invalid
155 $parentDir = dirname( $fsPath );
157 if ( file_exists( $fsPath ) ) {
158 $ok = is_file( $fsPath ) && is_writable( $fsPath );
160 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
163 if ( $this->fileOwner
!== null && $this->currentUser
!== $this->fileOwner
) {
165 trigger_error( __METHOD__
. ": PHP process owner is not '{$this->fileOwner}'." );
171 protected function doCreateInternal( array $params ) {
172 $status = Status
::newGood();
174 $dest = $this->resolveToFSPath( $params['dst'] );
175 if ( $dest === null ) {
176 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
180 if ( !empty( $params['async'] ) ) { // deferred
181 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
183 $status->fatal( 'backend-fail-create', $params['dst'] );
186 $this->trapWarnings();
187 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
188 $this->untrapWarnings();
189 if ( $bytes === false ) {
190 $status->fatal( 'backend-fail-create', $params['dst'] );
193 $cmd = implode( ' ', array(
194 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
195 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
196 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
198 $status->value
= new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
199 $tempFile->bind( $status->value
);
200 } else { // immediate write
201 $this->trapWarnings();
202 $bytes = file_put_contents( $dest, $params['content'] );
203 $this->untrapWarnings();
204 if ( $bytes === false ) {
205 $status->fatal( 'backend-fail-create', $params['dst'] );
208 $this->chmod( $dest );
215 * @see FSFileBackend::doExecuteOpHandlesInternal()
217 protected function _getResponseCreate( $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
224 protected function doStoreInternal( array $params ) {
225 $status = Status
::newGood();
227 $dest = $this->resolveToFSPath( $params['dst'] );
228 if ( $dest === null ) {
229 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
233 if ( !empty( $params['async'] ) ) { // deferred
234 $cmd = implode( ' ', array(
235 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
236 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
237 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
239 $status->value
= new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
240 } else { // immediate write
241 $this->trapWarnings();
242 $ok = copy( $params['src'], $dest );
243 $this->untrapWarnings();
244 // In some cases (at least over NFS), copy() returns true when it fails
245 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
246 if ( $ok ) { // PHP bug
247 unlink( $dest ); // remove broken file
248 trigger_error( __METHOD__
. ": copy() failed but returned true." );
250 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
253 $this->chmod( $dest );
260 * @see FSFileBackend::doExecuteOpHandlesInternal()
262 protected function _getResponseStore( $errors, Status
$status, array $params, $cmd ) {
263 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
264 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
265 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
269 protected function doCopyInternal( array $params ) {
270 $status = Status
::newGood();
272 $source = $this->resolveToFSPath( $params['src'] );
273 if ( $source === null ) {
274 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
278 $dest = $this->resolveToFSPath( $params['dst'] );
279 if ( $dest === null ) {
280 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
284 if ( !is_file( $source ) ) {
285 if ( empty( $params['ignoreMissingSource'] ) ) {
286 $status->fatal( 'backend-fail-copy', $params['src'] );
288 return $status; // do nothing; either OK or bad status
291 if ( !empty( $params['async'] ) ) { // deferred
292 $cmd = implode( ' ', array(
293 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
294 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
295 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
297 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
298 } else { // immediate write
299 $this->trapWarnings();
300 $ok = ( $source === $dest ) ?
true : copy( $source, $dest );
301 $this->untrapWarnings();
302 // In some cases (at least over NFS), copy() returns true when it fails
303 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
304 if ( $ok ) { // PHP bug
305 $this->trapWarnings();
306 unlink( $dest ); // remove broken file
307 $this->untrapWarnings();
308 trigger_error( __METHOD__
. ": copy() failed but returned true." );
310 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
313 $this->chmod( $dest );
320 * @see FSFileBackend::doExecuteOpHandlesInternal()
322 protected function _getResponseCopy( $errors, Status
$status, array $params, $cmd ) {
323 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
324 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
325 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
329 protected function doMoveInternal( array $params ) {
330 $status = Status
::newGood();
332 $source = $this->resolveToFSPath( $params['src'] );
333 if ( $source === null ) {
334 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
338 $dest = $this->resolveToFSPath( $params['dst'] );
339 if ( $dest === null ) {
340 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
344 if ( !is_file( $source ) ) {
345 if ( empty( $params['ignoreMissingSource'] ) ) {
346 $status->fatal( 'backend-fail-move', $params['src'] );
348 return $status; // do nothing; either OK or bad status
351 if ( !empty( $params['async'] ) ) { // deferred
352 $cmd = implode( ' ', array(
353 wfIsWindows() ?
'MOVE /Y' : 'mv', // (overwrite)
354 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
355 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
357 $status->value
= new FSFileOpHandle( $this, $params, 'Move', $cmd );
358 } else { // immediate write
359 $this->trapWarnings();
360 $ok = ( $source === $dest ) ?
true : rename( $source, $dest );
361 $this->untrapWarnings();
362 clearstatcache(); // file no longer at source
364 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
373 * @see FSFileBackend::doExecuteOpHandlesInternal()
375 protected function _getResponseMove( $errors, Status
$status, array $params, $cmd ) {
376 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
377 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
378 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
382 protected function doDeleteInternal( array $params ) {
383 $status = Status
::newGood();
385 $source = $this->resolveToFSPath( $params['src'] );
386 if ( $source === null ) {
387 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
391 if ( !is_file( $source ) ) {
392 if ( empty( $params['ignoreMissingSource'] ) ) {
393 $status->fatal( 'backend-fail-delete', $params['src'] );
395 return $status; // do nothing; either OK or bad status
398 if ( !empty( $params['async'] ) ) { // deferred
399 $cmd = implode( ' ', array(
400 wfIsWindows() ?
'DEL' : 'unlink',
401 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
403 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd );
404 } else { // immediate write
405 $this->trapWarnings();
406 $ok = unlink( $source );
407 $this->untrapWarnings();
409 $status->fatal( 'backend-fail-delete', $params['src'] );
418 * @see FSFileBackend::doExecuteOpHandlesInternal()
420 protected function _getResponseDelete( $errors, Status
$status, array $params, $cmd ) {
421 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
422 $status->fatal( 'backend-fail-delete', $params['src'] );
423 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
427 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
428 $status = Status
::newGood();
429 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
430 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
431 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
432 $existed = is_dir( $dir ); // already there?
433 // Create the directory and its parents as needed...
434 $this->trapWarnings();
435 if ( !wfMkdirParents( $dir ) ) {
436 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
437 } elseif ( !is_writable( $dir ) ) {
438 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
439 } elseif ( !is_readable( $dir ) ) {
440 $status->fatal( 'directorynotreadableerror', $params['dir'] );
442 $this->untrapWarnings();
443 // Respect any 'noAccess' or 'noListing' flags...
444 if ( is_dir( $dir ) && !$existed ) {
445 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
450 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
451 $status = Status
::newGood();
452 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
453 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
454 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
455 // Seed new directories with a blank index.html, to prevent crawling...
456 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
457 $this->trapWarnings();
458 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
459 $this->untrapWarnings();
460 if ( $bytes === false ) {
461 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
464 // Add a .htaccess file to the root of the container...
465 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
466 $this->trapWarnings();
467 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
468 $this->untrapWarnings();
469 if ( $bytes === false ) {
470 $storeDir = "mwstore://{$this->name}/{$shortCont}";
471 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
477 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
478 $status = Status
::newGood();
479 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
480 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
481 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
482 // Unseed new directories with a blank index.html, to allow crawling...
483 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
484 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
485 $this->trapWarnings();
486 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
487 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
489 $this->untrapWarnings();
491 // Remove the .htaccess file from the root of the container...
492 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
493 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
494 $this->trapWarnings();
495 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
496 $storeDir = "mwstore://{$this->name}/{$shortCont}";
497 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
499 $this->untrapWarnings();
504 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
505 $status = Status
::newGood();
506 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
507 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
508 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
509 $this->trapWarnings();
510 if ( is_dir( $dir ) ) {
511 rmdir( $dir ); // remove directory if empty
513 $this->untrapWarnings();
517 protected function doGetFileStat( array $params ) {
518 $source = $this->resolveToFSPath( $params['src'] );
519 if ( $source === null ) {
520 return false; // invalid storage path
523 $this->trapWarnings(); // don't trust 'false' if there were errors
524 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
525 $hadError = $this->untrapWarnings();
529 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
530 'size' => $stat['size']
532 } elseif ( !$hadError ) {
533 return false; // file does not exist
535 return null; // failure
540 * @see FileBackendStore::doClearCache()
542 protected function doClearCache( array $paths = null ) {
543 clearstatcache(); // clear the PHP file stat cache
546 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
547 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
548 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
549 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
551 $this->trapWarnings(); // don't trust 'false' if there were errors
552 $exists = is_dir( $dir );
553 $hadError = $this->untrapWarnings();
555 return $hadError ?
null : $exists;
559 * @see FileBackendStore::getDirectoryListInternal()
562 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
563 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
564 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
565 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
566 $exists = is_dir( $dir );
568 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
569 return array(); // nothing under this dir
570 } elseif ( !is_readable( $dir ) ) {
571 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
572 return null; // bad permissions?
574 return new FSFileBackendDirList( $dir, $params );
578 * @see FileBackendStore::getFileListInternal()
579 * @return Array|FSFileBackendFileList|null
581 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
582 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
583 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
584 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
585 $exists = is_dir( $dir );
587 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
588 return array(); // nothing under this dir
589 } elseif ( !is_readable( $dir ) ) {
590 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
591 return null; // bad permissions?
593 return new FSFileBackendFileList( $dir, $params );
596 protected function doGetLocalReferenceMulti( array $params ) {
597 $fsFiles = array(); // (path => FSFile)
599 foreach ( $params['srcs'] as $src ) {
600 $source = $this->resolveToFSPath( $src );
601 if ( $source === null ||
!is_file( $source ) ) {
602 $fsFiles[$src] = null; // invalid path or file does not exist
604 $fsFiles[$src] = new FSFile( $source );
611 protected function doGetLocalCopyMulti( array $params ) {
612 $tmpFiles = array(); // (path => TempFSFile)
614 foreach ( $params['srcs'] as $src ) {
615 $source = $this->resolveToFSPath( $src );
616 if ( $source === null ) {
617 $tmpFiles[$src] = null; // invalid path
619 // Create a new temporary file with the same extension...
620 $ext = FileBackend
::extensionFromPath( $src );
621 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
623 $tmpFiles[$src] = null;
625 $tmpPath = $tmpFile->getPath();
626 // Copy the source file over the temp file
627 $this->trapWarnings();
628 $ok = copy( $source, $tmpPath );
629 $this->untrapWarnings();
631 $tmpFiles[$src] = null;
633 $this->chmod( $tmpPath );
634 $tmpFiles[$src] = $tmpFile;
643 protected function directoriesAreVirtual() {
647 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
651 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
652 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
656 foreach ( $pipes as $index => $pipe ) {
657 // Result will be empty on success in *NIX. On Windows,
658 // it may be something like " 1 file(s) [copied|moved].".
659 $errs[$index] = stream_get_contents( $pipe );
663 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
664 $status = Status
::newGood();
665 $function = '_getResponse' . $fileOpHandle->call
;
666 $this->$function( $errs[$index], $status, $fileOpHandle->params
, $fileOpHandle->cmd
);
667 $statuses[$index] = $status;
668 if ( $status->isOK() && $fileOpHandle->chmodPath
) {
669 $this->chmod( $fileOpHandle->chmodPath
);
673 clearstatcache(); // files changed
678 * Chmod a file, suppressing the warnings
680 * @param string $path Absolute file system path
681 * @return bool Success
683 protected function chmod( $path ) {
684 $this->trapWarnings();
685 $ok = chmod( $path, $this->fileMode
);
686 $this->untrapWarnings();
692 * Return the text of an index.html file to hide directory listings
696 protected function indexHtmlPrivate() {
701 * Return the text of a .htaccess file to make a directory private
705 protected function htaccessPrivate() {
706 return "Deny from all\n";
710 * Clean up directory separators for the given OS
712 * @param string $path FS path
715 protected function cleanPathSlashes( $path ) {
716 return wfIsWindows() ?
strtr( $path, '/', '\\' ) : $path;
720 * Listen for E_WARNING errors and track whether any happen
724 protected function trapWarnings() {
725 $this->hadWarningErrors
[] = false; // push to stack
726 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
730 * Stop listening for E_WARNING errors and return true if any happened
734 protected function untrapWarnings() {
735 restore_error_handler(); // restore previous handler
736 return array_pop( $this->hadWarningErrors
); // pop from stack
740 * @param integer $errno
741 * @param string $errstr
745 public function handleWarning( $errno, $errstr ) {
746 wfDebugLog( 'FSFileBackend', $errstr ); // more detailed error logging
747 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
748 return true; // suppress from PHP handler
753 * @see FileBackendStoreOpHandle
755 class FSFileOpHandle
extends FileBackendStoreOpHandle
{
756 public $cmd; // string; shell command
757 public $chmodPath; // string; file to chmod
760 * @param FSFileBackend $backend
761 * @param array $params
762 * @param string $call
764 * @param integer|null $chmodPath
766 public function __construct(
767 FSFileBackend
$backend, array $params, $call, $cmd, $chmodPath = null
769 $this->backend
= $backend;
770 $this->params
= $params;
773 $this->chmodPath
= $chmodPath;
778 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
779 * catches exception or does any custom behavoir that we may want.
780 * Do not use this class from places outside FSFileBackend.
782 * @ingroup FileBackend
784 abstract class FSFileBackendList
implements Iterator
{
787 protected $suffixStart; // integer
788 protected $pos = 0; // integer
790 protected $params = array();
793 * @param string $dir file system directory
794 * @param array $params
796 public function __construct( $dir, array $params ) {
797 $path = realpath( $dir ); // normalize
798 if ( $path === false ) {
801 $this->suffixStart
= strlen( $path ) +
1; // size of "path/to/dir/"
802 $this->params
= $params;
805 $this->iter
= $this->initIterator( $path );
806 } catch ( UnexpectedValueException
$e ) {
807 $this->iter
= null; // bad permissions? deleted?
812 * Return an appropriate iterator object to wrap
814 * @param string $dir file system directory
817 protected function initIterator( $dir ) {
818 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
819 # Get an iterator that will get direct sub-nodes
820 return new DirectoryIterator( $dir );
821 } else { // recursive
822 # Get an iterator that will return leaf nodes (non-directories)
823 # RecursiveDirectoryIterator extends FilesystemIterator.
824 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
825 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
826 return new RecursiveIteratorIterator(
827 new RecursiveDirectoryIterator( $dir, $flags ),
828 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
834 * @see Iterator::key()
837 public function key() {
842 * @see Iterator::current()
843 * @return string|bool String or false
845 public function current() {
846 return $this->getRelPath( $this->iter
->current()->getPathname() );
850 * @see Iterator::next()
853 public function next() {
856 $this->filterViaNext();
857 } catch ( UnexpectedValueException
$e ) { // bad permissions? deleted?
858 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
864 * @see Iterator::rewind()
867 public function rewind() {
870 $this->iter
->rewind();
871 $this->filterViaNext();
872 } catch ( UnexpectedValueException
$e ) { // bad permissions? deleted?
873 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
878 * @see Iterator::valid()
881 public function valid() {
882 return $this->iter
&& $this->iter
->valid();
886 * Filter out items by advancing to the next ones
888 protected function filterViaNext() {}
891 * Return only the relative path and normalize slashes to FileBackend-style.
892 * Uses the "real path" since the suffix is based upon that.
894 * @param string $path
897 protected function getRelPath( $dir ) {
898 $path = realpath( $dir );
899 if ( $path === false ) {
902 return strtr( substr( $path, $this->suffixStart
), '\\', '/' );
906 class FSFileBackendDirList
extends FSFileBackendList
{
907 protected function filterViaNext() {
908 while ( $this->iter
->valid() ) {
909 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
910 $this->iter
->next(); // skip non-directories and dot files
918 class FSFileBackendFileList
extends FSFileBackendList
{
919 protected function filterViaNext() {
920 while ( $this->iter
->valid() ) {
921 if ( !$this->iter
->current()->isFile() ) {
922 $this->iter
->next(); // skip non-files and dot files