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
86 * @see FileBackendStore::resolveContainerPath()
87 * @param $container string
88 * @param $relStoragePath string
91 protected function resolveContainerPath( $container, $relStoragePath ) {
92 // Check that container has a root directory
93 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
94 // Check for sane relative paths (assume the base paths are OK)
95 if ( $this->isLegalRelPath( $relStoragePath ) ) {
96 return $relStoragePath;
103 * Sanity check a relative file system path for validity
105 * @param string $path Normalized relative path
108 protected function isLegalRelPath( $path ) {
109 // Check for file names longer than 255 chars
110 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
113 if ( wfIsWindows() ) { // NTFS
114 return !preg_match( '![:*?"<>|]!', $path );
121 * Given the short (unresolved) and full (resolved) name of
122 * a container, return the file system path of the container.
124 * @param $shortCont string
125 * @param $fullCont string
126 * @return string|null
128 protected function containerFSRoot( $shortCont, $fullCont ) {
129 if ( isset( $this->containerPaths
[$shortCont] ) ) {
130 return $this->containerPaths
[$shortCont];
131 } elseif ( isset( $this->basePath
) ) {
132 return "{$this->basePath}/{$fullCont}";
134 return null; // no container base path defined
138 * Get the absolute file system path for a storage path
140 * @param string $storagePath Storage path
141 * @return string|null
143 protected function resolveToFSPath( $storagePath ) {
144 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
145 if ( $relPath === null ) {
146 return null; // invalid
148 list( , $shortCont, ) = FileBackend
::splitStoragePath( $storagePath );
149 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
150 if ( $relPath != '' ) {
151 $fsPath .= "/{$relPath}";
157 * @see FileBackendStore::isPathUsableInternal()
160 public function isPathUsableInternal( $storagePath ) {
161 $fsPath = $this->resolveToFSPath( $storagePath );
162 if ( $fsPath === null ) {
163 return false; // invalid
165 $parentDir = dirname( $fsPath );
167 if ( file_exists( $fsPath ) ) {
168 $ok = is_file( $fsPath ) && is_writable( $fsPath );
170 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
173 if ( $this->fileOwner
!== null && $this->currentUser
!== $this->fileOwner
) {
175 trigger_error( __METHOD__
. ": PHP process owner is not '{$this->fileOwner}'." );
182 * @see FileBackendStore::doCreateInternal()
185 protected function doCreateInternal( array $params ) {
186 $status = Status
::newGood();
188 $dest = $this->resolveToFSPath( $params['dst'] );
189 if ( $dest === null ) {
190 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
194 if ( !empty( $params['async'] ) ) { // deferred
195 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
197 $status->fatal( 'backend-fail-create', $params['dst'] );
200 $this->trapWarnings();
201 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
202 $this->untrapWarnings();
203 if ( $bytes === false ) {
204 $status->fatal( 'backend-fail-create', $params['dst'] );
207 $cmd = implode( ' ', array(
208 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
209 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
210 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
212 $status->value
= new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
213 $tempFile->bind( $status->value
);
214 } else { // immediate write
215 $this->trapWarnings();
216 $bytes = file_put_contents( $dest, $params['content'] );
217 $this->untrapWarnings();
218 if ( $bytes === false ) {
219 $status->fatal( 'backend-fail-create', $params['dst'] );
222 $this->chmod( $dest );
229 * @see FSFileBackend::doExecuteOpHandlesInternal()
231 protected function _getResponseCreate( $errors, Status
$status, array $params, $cmd ) {
232 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
233 $status->fatal( 'backend-fail-create', $params['dst'] );
234 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
239 * @see FileBackendStore::doStoreInternal()
242 protected function doStoreInternal( array $params ) {
243 $status = Status
::newGood();
245 $dest = $this->resolveToFSPath( $params['dst'] );
246 if ( $dest === null ) {
247 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
251 if ( !empty( $params['async'] ) ) { // deferred
252 $cmd = implode( ' ', array(
253 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
254 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
255 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
257 $status->value
= new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
258 } else { // immediate write
259 $this->trapWarnings();
260 $ok = copy( $params['src'], $dest );
261 $this->untrapWarnings();
262 // In some cases (at least over NFS), copy() returns true when it fails
263 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
264 if ( $ok ) { // PHP bug
265 unlink( $dest ); // remove broken file
266 trigger_error( __METHOD__
. ": copy() failed but returned true." );
268 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
271 $this->chmod( $dest );
278 * @see FSFileBackend::doExecuteOpHandlesInternal()
280 protected function _getResponseStore( $errors, Status
$status, array $params, $cmd ) {
281 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
282 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
283 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
288 * @see FileBackendStore::doCopyInternal()
291 protected function doCopyInternal( array $params ) {
292 $status = Status
::newGood();
294 $source = $this->resolveToFSPath( $params['src'] );
295 if ( $source === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
300 $dest = $this->resolveToFSPath( $params['dst'] );
301 if ( $dest === null ) {
302 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
306 if ( !is_file( $source ) ) {
307 if ( empty( $params['ignoreMissingSource'] ) ) {
308 $status->fatal( 'backend-fail-copy', $params['src'] );
310 return $status; // do nothing; either OK or bad status
313 if ( !empty( $params['async'] ) ) { // deferred
314 $cmd = implode( ' ', array(
315 wfIsWindows() ?
'COPY /B /Y' : 'cp', // (binary, overwrite)
316 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
317 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
319 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
320 } else { // immediate write
321 $this->trapWarnings();
322 $ok = ( $source === $dest ) ?
true : copy( $source, $dest );
323 $this->untrapWarnings();
324 // In some cases (at least over NFS), copy() returns true when it fails
325 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
326 if ( $ok ) { // PHP bug
327 $this->trapWarnings();
328 unlink( $dest ); // remove broken file
329 $this->untrapWarnings();
330 trigger_error( __METHOD__
. ": copy() failed but returned true." );
332 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
335 $this->chmod( $dest );
342 * @see FSFileBackend::doExecuteOpHandlesInternal()
344 protected function _getResponseCopy( $errors, Status
$status, array $params, $cmd ) {
345 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
346 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
347 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
352 * @see FileBackendStore::doMoveInternal()
355 protected function doMoveInternal( array $params ) {
356 $status = Status
::newGood();
358 $source = $this->resolveToFSPath( $params['src'] );
359 if ( $source === null ) {
360 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
364 $dest = $this->resolveToFSPath( $params['dst'] );
365 if ( $dest === null ) {
366 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
370 if ( !is_file( $source ) ) {
371 if ( empty( $params['ignoreMissingSource'] ) ) {
372 $status->fatal( 'backend-fail-move', $params['src'] );
374 return $status; // do nothing; either OK or bad status
377 if ( !empty( $params['async'] ) ) { // deferred
378 $cmd = implode( ' ', array(
379 wfIsWindows() ?
'MOVE /Y' : 'mv', // (overwrite)
380 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
381 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
383 $status->value
= new FSFileOpHandle( $this, $params, 'Move', $cmd );
384 } else { // immediate write
385 $this->trapWarnings();
386 $ok = ( $source === $dest ) ?
true : rename( $source, $dest );
387 $this->untrapWarnings();
388 clearstatcache(); // file no longer at source
390 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
399 * @see FSFileBackend::doExecuteOpHandlesInternal()
401 protected function _getResponseMove( $errors, Status
$status, array $params, $cmd ) {
402 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
403 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
404 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
409 * @see FileBackendStore::doDeleteInternal()
412 protected function doDeleteInternal( array $params ) {
413 $status = Status
::newGood();
415 $source = $this->resolveToFSPath( $params['src'] );
416 if ( $source === null ) {
417 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
421 if ( !is_file( $source ) ) {
422 if ( empty( $params['ignoreMissingSource'] ) ) {
423 $status->fatal( 'backend-fail-delete', $params['src'] );
425 return $status; // do nothing; either OK or bad status
428 if ( !empty( $params['async'] ) ) { // deferred
429 $cmd = implode( ' ', array(
430 wfIsWindows() ?
'DEL' : 'unlink',
431 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
433 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd );
434 } else { // immediate write
435 $this->trapWarnings();
436 $ok = unlink( $source );
437 $this->untrapWarnings();
439 $status->fatal( 'backend-fail-delete', $params['src'] );
448 * @see FSFileBackend::doExecuteOpHandlesInternal()
450 protected function _getResponseDelete( $errors, Status
$status, array $params, $cmd ) {
451 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
452 $status->fatal( 'backend-fail-delete', $params['src'] );
453 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
458 * @see FileBackendStore::doPrepareInternal()
461 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
462 $status = Status
::newGood();
463 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
464 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
465 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
466 $existed = is_dir( $dir ); // already there?
467 // Create the directory and its parents as needed...
468 $this->trapWarnings();
469 if ( !wfMkdirParents( $dir ) ) {
470 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
471 } elseif ( !is_writable( $dir ) ) {
472 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
473 } elseif ( !is_readable( $dir ) ) {
474 $status->fatal( 'directorynotreadableerror', $params['dir'] );
476 $this->untrapWarnings();
477 // Respect any 'noAccess' or 'noListing' flags...
478 if ( is_dir( $dir ) && !$existed ) {
479 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
485 * @see FileBackendStore::doSecureInternal()
488 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
489 $status = Status
::newGood();
490 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
491 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
492 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
493 // Seed new directories with a blank index.html, to prevent crawling...
494 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
495 $this->trapWarnings();
496 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
497 $this->untrapWarnings();
498 if ( $bytes === false ) {
499 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
502 // Add a .htaccess file to the root of the container...
503 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
504 $this->trapWarnings();
505 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
506 $this->untrapWarnings();
507 if ( $bytes === false ) {
508 $storeDir = "mwstore://{$this->name}/{$shortCont}";
509 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
516 * @see FileBackendStore::doPublishInternal()
519 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
520 $status = Status
::newGood();
521 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
522 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
523 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
524 // Unseed new directories with a blank index.html, to allow crawling...
525 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
526 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
527 $this->trapWarnings();
528 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
529 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
531 $this->untrapWarnings();
533 // Remove the .htaccess file from the root of the container...
534 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
535 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
536 $this->trapWarnings();
537 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
538 $storeDir = "mwstore://{$this->name}/{$shortCont}";
539 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
541 $this->untrapWarnings();
547 * @see FileBackendStore::doCleanInternal()
550 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
551 $status = Status
::newGood();
552 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
553 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
554 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
555 $this->trapWarnings();
556 if ( is_dir( $dir ) ) {
557 rmdir( $dir ); // remove directory if empty
559 $this->untrapWarnings();
564 * @see FileBackendStore::doFileExists()
565 * @return array|bool|null
567 protected function doGetFileStat( array $params ) {
568 $source = $this->resolveToFSPath( $params['src'] );
569 if ( $source === null ) {
570 return false; // invalid storage path
573 $this->trapWarnings(); // don't trust 'false' if there were errors
574 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
575 $hadError = $this->untrapWarnings();
579 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
580 'size' => $stat['size']
582 } elseif ( !$hadError ) {
583 return false; // file does not exist
585 return null; // failure
590 * @see FileBackendStore::doClearCache()
592 protected function doClearCache( array $paths = null ) {
593 clearstatcache(); // clear the PHP file stat cache
597 * @see FileBackendStore::doDirectoryExists()
600 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
601 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
602 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
603 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
605 $this->trapWarnings(); // don't trust 'false' if there were errors
606 $exists = is_dir( $dir );
607 $hadError = $this->untrapWarnings();
609 return $hadError ?
null : $exists;
613 * @see FileBackendStore::getDirectoryListInternal()
616 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
617 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
618 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
619 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
620 $exists = is_dir( $dir );
622 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
623 return array(); // nothing under this dir
624 } elseif ( !is_readable( $dir ) ) {
625 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
626 return null; // bad permissions?
628 return new FSFileBackendDirList( $dir, $params );
632 * @see FileBackendStore::getFileListInternal()
633 * @return Array|FSFileBackendFileList|null
635 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
636 list( , $shortCont, ) = FileBackend
::splitStoragePath( $params['dir'] );
637 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
638 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
639 $exists = is_dir( $dir );
641 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
642 return array(); // nothing under this dir
643 } elseif ( !is_readable( $dir ) ) {
644 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
645 return null; // bad permissions?
647 return new FSFileBackendFileList( $dir, $params );
651 * @see FileBackendStore::doGetLocalReferenceMulti()
654 protected function doGetLocalReferenceMulti( array $params ) {
655 $fsFiles = array(); // (path => FSFile)
657 foreach ( $params['srcs'] as $src ) {
658 $source = $this->resolveToFSPath( $src );
659 if ( $source === null ||
!is_file( $source ) ) {
660 $fsFiles[$src] = null; // invalid path or file does not exist
662 $fsFiles[$src] = new FSFile( $source );
670 * @see FileBackendStore::doGetLocalCopyMulti()
673 protected function doGetLocalCopyMulti( array $params ) {
674 $tmpFiles = array(); // (path => TempFSFile)
676 foreach ( $params['srcs'] as $src ) {
677 $source = $this->resolveToFSPath( $src );
678 if ( $source === null ) {
679 $tmpFiles[$src] = null; // invalid path
681 // Create a new temporary file with the same extension...
682 $ext = FileBackend
::extensionFromPath( $src );
683 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
685 $tmpFiles[$src] = null;
687 $tmpPath = $tmpFile->getPath();
688 // Copy the source file over the temp file
689 $this->trapWarnings();
690 $ok = copy( $source, $tmpPath );
691 $this->untrapWarnings();
693 $tmpFiles[$src] = null;
695 $this->chmod( $tmpPath );
696 $tmpFiles[$src] = $tmpFile;
706 * @see FileBackendStore::directoriesAreVirtual()
709 protected function directoriesAreVirtual() {
714 * @see FileBackendStore::doExecuteOpHandlesInternal()
715 * @return Array List of corresponding Status objects
717 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
721 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
722 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
726 foreach ( $pipes as $index => $pipe ) {
727 // Result will be empty on success in *NIX. On Windows,
728 // it may be something like " 1 file(s) [copied|moved].".
729 $errs[$index] = stream_get_contents( $pipe );
733 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
734 $status = Status
::newGood();
735 $function = '_getResponse' . $fileOpHandle->call
;
736 $this->$function( $errs[$index], $status, $fileOpHandle->params
, $fileOpHandle->cmd
);
737 $statuses[$index] = $status;
738 if ( $status->isOK() && $fileOpHandle->chmodPath
) {
739 $this->chmod( $fileOpHandle->chmodPath
);
743 clearstatcache(); // files changed
748 * Chmod a file, suppressing the warnings
750 * @param string $path Absolute file system path
751 * @return bool Success
753 protected function chmod( $path ) {
754 $this->trapWarnings();
755 $ok = chmod( $path, $this->fileMode
);
756 $this->untrapWarnings();
762 * Return the text of an index.html file to hide directory listings
766 protected function indexHtmlPrivate() {
771 * Return the text of a .htaccess file to make a directory private
775 protected function htaccessPrivate() {
776 return "Deny from all\n";
780 * Clean up directory separators for the given OS
782 * @param string $path FS path
785 protected function cleanPathSlashes( $path ) {
786 return wfIsWindows() ?
strtr( $path, '/', '\\' ) : $path;
790 * Listen for E_WARNING errors and track whether any happen
794 protected function trapWarnings() {
795 $this->hadWarningErrors
[] = false; // push to stack
796 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
800 * Stop listening for E_WARNING errors and return true if any happened
804 protected function untrapWarnings() {
805 restore_error_handler(); // restore previous handler
806 return array_pop( $this->hadWarningErrors
); // pop from stack
810 * @param $errno integer
811 * @param $errstr string
814 private function handleWarning( $errno, $errstr ) {
815 wfDebugLog( 'FSFileBackend', $errstr ); // more detailed error logging
816 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
817 return true; // suppress from PHP handler
822 * @see FileBackendStoreOpHandle
824 class FSFileOpHandle
extends FileBackendStoreOpHandle
{
825 public $cmd; // string; shell command
826 public $chmodPath; // string; file to chmod
830 * @param $params array
833 * @param $chmodPath null
835 public function __construct( $backend, array $params, $call, $cmd, $chmodPath = null ) {
836 $this->backend
= $backend;
837 $this->params
= $params;
840 $this->chmodPath
= $chmodPath;
845 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
846 * catches exception or does any custom behavoir that we may want.
847 * Do not use this class from places outside FSFileBackend.
849 * @ingroup FileBackend
851 abstract class FSFileBackendList
implements Iterator
{
854 protected $suffixStart; // integer
855 protected $pos = 0; // integer
857 protected $params = array();
860 * @param string $dir file system directory
861 * @param $params array
863 public function __construct( $dir, array $params ) {
864 $path = realpath( $dir ); // normalize
865 if ( $path === false ) {
868 $this->suffixStart
= strlen( $path ) +
1; // size of "path/to/dir/"
869 $this->params
= $params;
872 $this->iter
= $this->initIterator( $path );
873 } catch ( UnexpectedValueException
$e ) {
874 $this->iter
= null; // bad permissions? deleted?
879 * Return an appropriate iterator object to wrap
881 * @param string $dir file system directory
884 protected function initIterator( $dir ) {
885 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
886 # Get an iterator that will get direct sub-nodes
887 return new DirectoryIterator( $dir );
888 } else { // recursive
889 # Get an iterator that will return leaf nodes (non-directories)
890 # RecursiveDirectoryIterator extends FilesystemIterator.
891 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
892 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
893 return new RecursiveIteratorIterator(
894 new RecursiveDirectoryIterator( $dir, $flags ),
895 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
901 * @see Iterator::key()
904 public function key() {
909 * @see Iterator::current()
910 * @return string|bool String or false
912 public function current() {
913 return $this->getRelPath( $this->iter
->current()->getPathname() );
917 * @see Iterator::next()
920 public function next() {
923 $this->filterViaNext();
924 } catch ( UnexpectedValueException
$e ) {
931 * @see Iterator::rewind()
934 public function rewind() {
937 $this->iter
->rewind();
938 $this->filterViaNext();
939 } catch ( UnexpectedValueException
$e ) {
945 * @see Iterator::valid()
948 public function valid() {
949 return $this->iter
&& $this->iter
->valid();
953 * Filter out items by advancing to the next ones
955 protected function filterViaNext() {}
958 * Return only the relative path and normalize slashes to FileBackend-style.
959 * Uses the "real path" since the suffix is based upon that.
961 * @param $path string
964 protected function getRelPath( $dir ) {
965 $path = realpath( $dir );
966 if ( $path === false ) {
969 return strtr( substr( $path, $this->suffixStart
), '\\', '/' );
973 class FSFileBackendDirList
extends FSFileBackendList
{
974 protected function filterViaNext() {
975 while ( $this->iter
->valid() ) {
976 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
977 $this->iter
->next(); // skip non-directories and dot files
985 class FSFileBackendFileList
extends FSFileBackendList
{
986 protected function filterViaNext() {
987 while ( $this->iter
->valid() ) {
988 if ( !$this->iter
->current()->isFile() ) {
989 $this->iter
->next(); // skip non-files and dot files