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 ( file_exists( $dest ) ) {
194 $ok = unlink( $dest );
196 $status->fatal( 'backend-fail-delete', $params['dst'] );
201 if ( !empty( $params['async'] ) ) { // deferred
202 $cmd = implode( ' ', array( wfIsWindows() ?
'COPY' : 'cp',
203 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
204 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
206 $status->value
= new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
207 } else { // immediate write
208 $ok = copy( $params['src'], $dest );
209 // In some cases (at least over NFS), copy() returns true when it fails
210 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
211 if ( $ok ) { // PHP bug
212 unlink( $dest ); // remove broken file
213 trigger_error( __METHOD__
. ": copy() failed but returned true." );
215 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
218 $this->chmod( $dest );
225 * @see FSFileBackend::doExecuteOpHandlesInternal()
227 protected function _getResponseStore( $errors, Status
$status, array $params, $cmd ) {
228 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
229 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
230 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
235 * @see FileBackendStore::doCopyInternal()
238 protected function doCopyInternal( array $params ) {
239 $status = Status
::newGood();
241 $source = $this->resolveToFSPath( $params['src'] );
242 if ( $source === null ) {
243 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
247 $dest = $this->resolveToFSPath( $params['dst'] );
248 if ( $dest === null ) {
249 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
253 if ( !is_file( $source ) ) {
254 if ( empty( $params['ignoreMissingSource'] ) ) {
255 $status->fatal( 'backend-fail-copy', $params['src'] );
257 return $status; // do nothing; either OK or bad status
260 if ( file_exists( $dest ) ) {
261 $ok = unlink( $dest );
263 $status->fatal( 'backend-fail-delete', $params['dst'] );
268 if ( !empty( $params['async'] ) ) { // deferred
269 $cmd = implode( ' ', array( wfIsWindows() ?
'COPY' : 'cp',
270 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
271 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
273 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
274 } else { // immediate write
275 $ok = copy( $source, $dest );
276 // In some cases (at least over NFS), copy() returns true when it fails
277 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
278 if ( $ok ) { // PHP bug
279 unlink( $dest ); // remove broken file
280 trigger_error( __METHOD__
. ": copy() failed but returned true." );
282 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
285 $this->chmod( $dest );
292 * @see FSFileBackend::doExecuteOpHandlesInternal()
294 protected function _getResponseCopy( $errors, Status
$status, array $params, $cmd ) {
295 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
296 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
297 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
302 * @see FileBackendStore::doMoveInternal()
305 protected function doMoveInternal( array $params ) {
306 $status = Status
::newGood();
308 $source = $this->resolveToFSPath( $params['src'] );
309 if ( $source === null ) {
310 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
314 $dest = $this->resolveToFSPath( $params['dst'] );
315 if ( $dest === null ) {
316 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
320 if ( !is_file( $source ) ) {
321 if ( empty( $params['ignoreMissingSource'] ) ) {
322 $status->fatal( 'backend-fail-move', $params['src'] );
324 return $status; // do nothing; either OK or bad status
327 if ( file_exists( $dest ) ) {
328 // Windows does not support moving over existing files
329 if ( wfIsWindows() ) {
330 $ok = unlink( $dest );
332 $status->fatal( 'backend-fail-delete', $params['dst'] );
338 if ( !empty( $params['async'] ) ) { // deferred
339 $cmd = implode( ' ', array( wfIsWindows() ?
'MOVE' : 'mv',
340 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
341 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
343 $status->value
= new FSFileOpHandle( $this, $params, 'Move', $cmd );
344 } else { // immediate write
345 $ok = rename( $source, $dest );
346 clearstatcache(); // file no longer at source
348 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
357 * @see FSFileBackend::doExecuteOpHandlesInternal()
359 protected function _getResponseMove( $errors, Status
$status, array $params, $cmd ) {
360 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
361 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
362 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
367 * @see FileBackendStore::doDeleteInternal()
370 protected function doDeleteInternal( array $params ) {
371 $status = Status
::newGood();
373 $source = $this->resolveToFSPath( $params['src'] );
374 if ( $source === null ) {
375 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
379 if ( !is_file( $source ) ) {
380 if ( empty( $params['ignoreMissingSource'] ) ) {
381 $status->fatal( 'backend-fail-delete', $params['src'] );
383 return $status; // do nothing; either OK or bad status
386 if ( !empty( $params['async'] ) ) { // deferred
387 $cmd = implode( ' ', array( wfIsWindows() ?
'DEL' : 'unlink',
388 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
390 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd );
391 } else { // immediate write
392 $ok = unlink( $source );
394 $status->fatal( 'backend-fail-delete', $params['src'] );
403 * @see FSFileBackend::doExecuteOpHandlesInternal()
405 protected function _getResponseDelete( $errors, Status
$status, array $params, $cmd ) {
406 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
407 $status->fatal( 'backend-fail-delete', $params['src'] );
408 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
413 * @see FileBackendStore::doCreateInternal()
416 protected function doCreateInternal( array $params ) {
417 $status = Status
::newGood();
419 $dest = $this->resolveToFSPath( $params['dst'] );
420 if ( $dest === null ) {
421 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
425 if ( file_exists( $dest ) ) {
426 $ok = unlink( $dest );
428 $status->fatal( 'backend-fail-delete', $params['dst'] );
433 if ( !empty( $params['async'] ) ) { // deferred
434 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
436 $status->fatal( 'backend-fail-create', $params['dst'] );
439 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
440 if ( $bytes === false ) {
441 $status->fatal( 'backend-fail-create', $params['dst'] );
444 $cmd = implode( ' ', array( wfIsWindows() ?
'COPY' : 'cp',
445 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
446 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
448 $status->value
= new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
449 $tempFile->bind( $status->value
);
450 } else { // immediate write
451 $bytes = file_put_contents( $dest, $params['content'] );
452 if ( $bytes === false ) {
453 $status->fatal( 'backend-fail-create', $params['dst'] );
456 $this->chmod( $dest );
463 * @see FSFileBackend::doExecuteOpHandlesInternal()
465 protected function _getResponseCreate( $errors, Status
$status, array $params, $cmd ) {
466 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
467 $status->fatal( 'backend-fail-create', $params['dst'] );
468 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
473 * @see FileBackendStore::doPrepareInternal()
476 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
477 $status = Status
::newGood();
478 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
479 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
480 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
481 $existed = is_dir( $dir ); // already there?
482 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
483 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
484 } elseif ( !is_writable( $dir ) ) {
485 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
486 } elseif ( !is_readable( $dir ) ) {
487 $status->fatal( 'directorynotreadableerror', $params['dir'] );
489 if ( is_dir( $dir ) && !$existed ) {
490 // Respect any 'noAccess' or 'noListing' flags...
491 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
497 * @see FileBackendStore::doSecureInternal()
500 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
501 $status = Status
::newGood();
502 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
503 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
504 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
505 // Seed new directories with a blank index.html, to prevent crawling...
506 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
507 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
508 if ( $bytes === false ) {
509 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
513 // Add a .htaccess file to the root of the container...
514 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
515 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
516 if ( $bytes === false ) {
517 $storeDir = "mwstore://{$this->name}/{$shortCont}";
518 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
526 * @see FileBackendStore::doPublishInternal()
529 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
530 $status = Status
::newGood();
531 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
532 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
533 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
534 // Unseed new directories with a blank index.html, to allow crawling...
535 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
536 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
537 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
538 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
542 // Remove the .htaccess file from the root of the container...
543 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
544 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
545 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
546 $storeDir = "mwstore://{$this->name}/{$shortCont}";
547 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
555 * @see FileBackendStore::doCleanInternal()
558 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
559 $status = Status
::newGood();
560 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
561 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
562 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
563 wfSuppressWarnings();
564 if ( is_dir( $dir ) ) {
565 rmdir( $dir ); // remove directory if empty
572 * @see FileBackendStore::doFileExists()
573 * @return array|bool|null
575 protected function doGetFileStat( array $params ) {
576 $source = $this->resolveToFSPath( $params['src'] );
577 if ( $source === null ) {
578 return false; // invalid storage path
581 $this->trapWarnings(); // don't trust 'false' if there were errors
582 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
583 $hadError = $this->untrapWarnings();
587 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
588 'size' => $stat['size']
590 } elseif ( !$hadError ) {
591 return false; // file does not exist
593 return null; // failure
598 * @see FileBackendStore::doClearCache()
600 protected function doClearCache( array $paths = null ) {
601 clearstatcache(); // clear the PHP file stat cache
605 * @see FileBackendStore::doDirectoryExists()
608 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
609 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
610 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
611 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
613 $this->trapWarnings(); // don't trust 'false' if there were errors
614 $exists = is_dir( $dir );
615 $hadError = $this->untrapWarnings();
617 return $hadError ?
null : $exists;
621 * @see FileBackendStore::getDirectoryListInternal()
624 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
625 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
626 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
627 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
628 $exists = is_dir( $dir );
630 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
631 return array(); // nothing under this dir
632 } elseif ( !is_readable( $dir ) ) {
633 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
634 return null; // bad permissions?
636 return new FSFileBackendDirList( $dir, $params );
640 * @see FileBackendStore::getFileListInternal()
641 * @return Array|FSFileBackendFileList|null
643 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
644 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
645 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
646 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
647 $exists = is_dir( $dir );
649 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
650 return array(); // nothing under this dir
651 } elseif ( !is_readable( $dir ) ) {
652 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
653 return null; // bad permissions?
655 return new FSFileBackendFileList( $dir, $params );
659 * @see FileBackendStore::doGetLocalReferenceMulti()
662 protected function doGetLocalReferenceMulti( array $params ) {
663 $fsFiles = array(); // (path => FSFile)
665 foreach ( $params['srcs'] as $src ) {
666 $source = $this->resolveToFSPath( $src );
667 if ( $source === null ||
!is_file( $source ) ) {
668 $fsFiles[$src] = null; // invalid path or file does not exist
670 $fsFiles[$src] = new FSFile( $source );
678 * @see FileBackendStore::doGetLocalCopyMulti()
681 protected function doGetLocalCopyMulti( array $params ) {
682 $tmpFiles = array(); // (path => TempFSFile)
684 foreach ( $params['srcs'] as $src ) {
685 $source = $this->resolveToFSPath( $src );
686 if ( $source === null ) {
687 $tmpFiles[$src] = null; // invalid path
689 // Create a new temporary file with the same extension...
690 $ext = FileBackend
::extensionFromPath( $src );
691 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
693 $tmpFiles[$src] = null;
695 $tmpPath = $tmpFile->getPath();
696 // Copy the source file over the temp file
697 wfSuppressWarnings();
698 $ok = copy( $source, $tmpPath );
701 $tmpFiles[$src] = null;
703 $this->chmod( $tmpPath );
704 $tmpFiles[$src] = $tmpFile;
714 * @see FileBackendStore::directoriesAreVirtual()
717 protected function directoriesAreVirtual() {
722 * @see FileBackendStore::doExecuteOpHandlesInternal()
723 * @return Array List of corresponding Status objects
725 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
729 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
730 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
734 foreach ( $pipes as $index => $pipe ) {
735 // Result will be empty on success in *NIX. On Windows,
736 // it may be something like " 1 file(s) [copied|moved].".
737 $errs[$index] = stream_get_contents( $pipe );
741 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
742 $status = Status
::newGood();
743 $function = '_getResponse' . $fileOpHandle->call
;
744 $this->$function( $errs[$index], $status, $fileOpHandle->params
, $fileOpHandle->cmd
);
745 $statuses[$index] = $status;
746 if ( $status->isOK() && $fileOpHandle->chmodPath
) {
747 $this->chmod( $fileOpHandle->chmodPath
);
751 clearstatcache(); // files changed
756 * Chmod a file, suppressing the warnings
758 * @param $path string Absolute file system path
759 * @return bool Success
761 protected function chmod( $path ) {
762 wfSuppressWarnings();
763 $ok = chmod( $path, $this->fileMode
);
770 * Return the text of an index.html file to hide directory listings
774 protected function indexHtmlPrivate() {
779 * Return the text of a .htaccess file to make a directory private
783 protected function htaccessPrivate() {
784 return "Deny from all\n";
788 * Clean up directory separators for the given OS
790 * @param $path string FS path
793 protected function cleanPathSlashes( $path ) {
794 return wfIsWindows() ?
strtr( $path, '/', '\\' ) : $path;
798 * Listen for E_WARNING errors and track whether any happen
802 protected function trapWarnings() {
803 $this->hadWarningErrors
[] = false; // push to stack
804 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
805 return false; // invoke normal PHP error handler
809 * Stop listening for E_WARNING errors and return true if any happened
813 protected function untrapWarnings() {
814 restore_error_handler(); // restore previous handler
815 return array_pop( $this->hadWarningErrors
); // pop from stack
821 private function handleWarning() {
822 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
823 return true; // suppress from PHP handler
828 * @see FileBackendStoreOpHandle
830 class FSFileOpHandle
extends FileBackendStoreOpHandle
{
831 public $cmd; // string; shell command
832 public $chmodPath; // string; file to chmod
836 * @param $params array
839 * @param $chmodPath null
841 public function __construct( $backend, array $params, $call, $cmd, $chmodPath = null ) {
842 $this->backend
= $backend;
843 $this->params
= $params;
846 $this->chmodPath
= $chmodPath;
851 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
852 * catches exception or does any custom behavoir that we may want.
853 * Do not use this class from places outside FSFileBackend.
855 * @ingroup FileBackend
857 abstract class FSFileBackendList
implements Iterator
{
860 protected $suffixStart; // integer
861 protected $pos = 0; // integer
863 protected $params = array();
866 * @param $dir string file system directory
867 * @param $params array
869 public function __construct( $dir, array $params ) {
870 $dir = realpath( $dir ); // normalize
871 $this->suffixStart
= strlen( $dir ) +
1; // size of "path/to/dir/"
872 $this->params
= $params;
875 $this->iter
= $this->initIterator( $dir );
876 } catch ( UnexpectedValueException
$e ) {
877 $this->iter
= null; // bad permissions? deleted?
882 * Return an appropriate iterator object to wrap
884 * @param $dir string file system directory
887 protected function initIterator( $dir ) {
888 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
889 # Get an iterator that will get direct sub-nodes
890 return new DirectoryIterator( $dir );
891 } else { // recursive
892 # Get an iterator that will return leaf nodes (non-directories)
893 # RecursiveDirectoryIterator extends FilesystemIterator.
894 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
895 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
896 return new RecursiveIteratorIterator(
897 new RecursiveDirectoryIterator( $dir, $flags ),
898 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
904 * @see Iterator::key()
907 public function key() {
912 * @see Iterator::current()
913 * @return string|bool String or false
915 public function current() {
916 return $this->getRelPath( $this->iter
->current()->getPathname() );
920 * @see Iterator::next()
923 public function next() {
926 $this->filterViaNext();
927 } catch ( UnexpectedValueException
$e ) {
934 * @see Iterator::rewind()
937 public function rewind() {
940 $this->iter
->rewind();
941 $this->filterViaNext();
942 } catch ( UnexpectedValueException
$e ) {
948 * @see Iterator::valid()
951 public function valid() {
952 return $this->iter
&& $this->iter
->valid();
956 * Filter out items by advancing to the next ones
958 protected function filterViaNext() {}
961 * Return only the relative path and normalize slashes to FileBackend-style.
962 * Uses the "real path" since the suffix is based upon that.
964 * @param $path string
967 protected function getRelPath( $path ) {
968 return strtr( substr( realpath( $path ), $this->suffixStart
), '\\', '/' );
972 class FSFileBackendDirList
extends FSFileBackendList
{
973 protected function filterViaNext() {
974 while ( $this->iter
->valid() ) {
975 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
976 $this->iter
->next(); // skip non-directories and dot files
984 class FSFileBackendFileList
extends FSFileBackendList
{
985 protected function filterViaNext() {
986 while ( $this->iter
->valid() ) {
987 if ( !$this->iter
->current()->isFile() ) {
988 $this->iter
->next(); // skip non-files and dot files