Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / filerepo / backend / FSFileBackend.php
blob8157916f87c7fb2aa00385fb265587f3a9d0e4d3
1 <?php
2 /**
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
20 * @file
21 * @ingroup FileBackend
22 * @author Aaron Schulz
25 /**
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
39 * @since 1.19
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
47 protected $hadWarningErrors = array();
49 /**
50 * @see FileBackendStore::__construct()
51 * Additional $config params include:
52 * basePath : File system directory that holds containers.
53 * containerPaths : Map of container names to custom file system directories.
54 * This should only be used for backwards-compatibility.
55 * fileMode : Octal UNIX file permissions to use on files stored.
57 public function __construct( array $config ) {
58 parent::__construct( $config );
60 // Remove any possible trailing slash from directories
61 if ( isset( $config['basePath'] ) ) {
62 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
63 } else {
64 $this->basePath = null; // none; containers must have explicit paths
67 if ( isset( $config['containerPaths'] ) ) {
68 $this->containerPaths = (array)$config['containerPaths'];
69 foreach ( $this->containerPaths as &$path ) {
70 $path = rtrim( $path, '/' ); // remove trailing slash
74 $this->fileMode = isset( $config['fileMode'] )
75 ? $config['fileMode']
76 : 0644;
79 /**
80 * @see FileBackendStore::resolveContainerPath()
81 * @param $container string
82 * @param $relStoragePath string
83 * @return null|string
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;
93 return null;
96 /**
97 * Sanity check a relative file system path for validity
99 * @param $path string Normalized relative path
100 * @return bool
102 protected function isLegalRelPath( $path ) {
103 // Check for file names longer than 255 chars
104 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
105 return false;
107 if ( wfIsWindows() ) { // NTFS
108 return !preg_match( '![:*?"<>|]!', $path );
109 } else {
110 return true;
115 * Given the short (unresolved) and full (resolved) name of
116 * a container, return the file system path of the container.
118 * @param $shortCont string
119 * @param $fullCont string
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 $storagePath string 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( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $storagePath );
143 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
144 if ( $relPath != '' ) {
145 $fsPath .= "/{$relPath}";
147 return $fsPath;
151 * @see FileBackendStore::isPathUsableInternal()
152 * @return bool
154 public function isPathUsableInternal( $storagePath ) {
155 $fsPath = $this->resolveToFSPath( $storagePath );
156 if ( $fsPath === null ) {
157 return false; // invalid
159 $parentDir = dirname( $fsPath );
161 if ( file_exists( $fsPath ) ) {
162 $ok = is_file( $fsPath ) && is_writable( $fsPath );
163 } else {
164 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
167 return $ok;
171 * @see FileBackendStore::doStoreInternal()
172 * @return Status
174 protected function doStoreInternal( array $params ) {
175 $status = Status::newGood();
177 $dest = $this->resolveToFSPath( $params['dst'] );
178 if ( $dest === null ) {
179 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
180 return $status;
183 if ( file_exists( $dest ) ) {
184 if ( !empty( $params['overwrite'] ) ) {
185 $ok = unlink( $dest );
186 if ( !$ok ) {
187 $status->fatal( 'backend-fail-delete', $params['dst'] );
188 return $status;
190 } else {
191 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
192 return $status;
196 if ( !empty( $params['async'] ) ) { // deferred
197 $cmd = implode( ' ', array( wfIsWindows() ? 'COPY' : 'cp',
198 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
199 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
200 ) );
201 $status->value = new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
202 } else { // immediate write
203 $ok = copy( $params['src'], $dest );
204 // In some cases (at least over NFS), copy() returns true when it fails
205 if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
206 if ( $ok ) { // PHP bug
207 unlink( $dest ); // remove broken file
208 trigger_error( __METHOD__ . ": copy() failed but returned true." );
210 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
211 return $status;
213 $this->chmod( $dest );
216 return $status;
220 * @see FSFileBackend::doExecuteOpHandlesInternal()
222 protected function _getResponseStore( $errors, Status $status, array $params, $cmd ) {
223 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
224 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
225 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
230 * @see FileBackendStore::doCopyInternal()
231 * @return Status
233 protected function doCopyInternal( array $params ) {
234 $status = Status::newGood();
236 $source = $this->resolveToFSPath( $params['src'] );
237 if ( $source === null ) {
238 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
239 return $status;
242 $dest = $this->resolveToFSPath( $params['dst'] );
243 if ( $dest === null ) {
244 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
245 return $status;
248 if ( file_exists( $dest ) ) {
249 if ( !empty( $params['overwrite'] ) ) {
250 $ok = unlink( $dest );
251 if ( !$ok ) {
252 $status->fatal( 'backend-fail-delete', $params['dst'] );
253 return $status;
255 } else {
256 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
257 return $status;
261 if ( !empty( $params['async'] ) ) { // deferred
262 $cmd = implode( ' ', array( wfIsWindows() ? 'COPY' : 'cp',
263 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
264 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
265 ) );
266 $status->value = new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
267 } else { // immediate write
268 $ok = copy( $source, $dest );
269 // In some cases (at least over NFS), copy() returns true when it fails
270 if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
271 if ( $ok ) { // PHP bug
272 unlink( $dest ); // remove broken file
273 trigger_error( __METHOD__ . ": copy() failed but returned true." );
275 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
276 return $status;
278 $this->chmod( $dest );
281 return $status;
285 * @see FSFileBackend::doExecuteOpHandlesInternal()
287 protected function _getResponseCopy( $errors, Status $status, array $params, $cmd ) {
288 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
289 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
290 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
295 * @see FileBackendStore::doMoveInternal()
296 * @return Status
298 protected function doMoveInternal( array $params ) {
299 $status = Status::newGood();
301 $source = $this->resolveToFSPath( $params['src'] );
302 if ( $source === null ) {
303 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
304 return $status;
307 $dest = $this->resolveToFSPath( $params['dst'] );
308 if ( $dest === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
310 return $status;
313 if ( file_exists( $dest ) ) {
314 if ( !empty( $params['overwrite'] ) ) {
315 // Windows does not support moving over existing files
316 if ( wfIsWindows() ) {
317 $ok = unlink( $dest );
318 if ( !$ok ) {
319 $status->fatal( 'backend-fail-delete', $params['dst'] );
320 return $status;
323 } else {
324 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
325 return $status;
329 if ( !empty( $params['async'] ) ) { // deferred
330 $cmd = implode( ' ', array( wfIsWindows() ? 'MOVE' : 'mv',
331 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
332 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
333 ) );
334 $status->value = new FSFileOpHandle( $this, $params, 'Move', $cmd );
335 } else { // immediate write
336 $ok = rename( $source, $dest );
337 clearstatcache(); // file no longer at source
338 if ( !$ok ) {
339 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
340 return $status;
344 return $status;
348 * @see FSFileBackend::doExecuteOpHandlesInternal()
350 protected function _getResponseMove( $errors, Status $status, array $params, $cmd ) {
351 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
352 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
353 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
358 * @see FileBackendStore::doDeleteInternal()
359 * @return Status
361 protected function doDeleteInternal( array $params ) {
362 $status = Status::newGood();
364 $source = $this->resolveToFSPath( $params['src'] );
365 if ( $source === null ) {
366 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
367 return $status;
370 if ( !is_file( $source ) ) {
371 if ( empty( $params['ignoreMissingSource'] ) ) {
372 $status->fatal( 'backend-fail-delete', $params['src'] );
374 return $status; // do nothing; either OK or bad status
377 if ( !empty( $params['async'] ) ) { // deferred
378 $cmd = implode( ' ', array( wfIsWindows() ? 'DEL' : 'unlink',
379 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
380 ) );
381 $status->value = new FSFileOpHandle( $this, $params, 'Copy', $cmd );
382 } else { // immediate write
383 $ok = unlink( $source );
384 if ( !$ok ) {
385 $status->fatal( 'backend-fail-delete', $params['src'] );
386 return $status;
390 return $status;
394 * @see FSFileBackend::doExecuteOpHandlesInternal()
396 protected function _getResponseDelete( $errors, Status $status, array $params, $cmd ) {
397 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
398 $status->fatal( 'backend-fail-delete', $params['src'] );
399 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
404 * @see FileBackendStore::doCreateInternal()
405 * @return Status
407 protected function doCreateInternal( array $params ) {
408 $status = Status::newGood();
410 $dest = $this->resolveToFSPath( $params['dst'] );
411 if ( $dest === null ) {
412 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
413 return $status;
416 if ( file_exists( $dest ) ) {
417 if ( !empty( $params['overwrite'] ) ) {
418 $ok = unlink( $dest );
419 if ( !$ok ) {
420 $status->fatal( 'backend-fail-delete', $params['dst'] );
421 return $status;
423 } else {
424 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
425 return $status;
429 if ( !empty( $params['async'] ) ) { // deferred
430 $tempFile = TempFSFile::factory( 'create_', 'tmp' );
431 if ( !$tempFile ) {
432 $status->fatal( 'backend-fail-create', $params['dst'] );
433 return $status;
435 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
436 if ( $bytes === false ) {
437 $status->fatal( 'backend-fail-create', $params['dst'] );
438 return $status;
440 $cmd = implode( ' ', array( wfIsWindows() ? 'COPY' : 'cp',
441 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
442 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
443 ) );
444 $status->value = new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
445 $tempFile->bind( $status->value );
446 } else { // immediate write
447 $bytes = file_put_contents( $dest, $params['content'] );
448 if ( $bytes === false ) {
449 $status->fatal( 'backend-fail-create', $params['dst'] );
450 return $status;
452 $this->chmod( $dest );
455 return $status;
459 * @see FSFileBackend::doExecuteOpHandlesInternal()
461 protected function _getResponseCreate( $errors, Status $status, array $params, $cmd ) {
462 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
463 $status->fatal( 'backend-fail-create', $params['dst'] );
464 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
469 * @see FileBackendStore::doPrepareInternal()
470 * @return Status
472 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
473 $status = Status::newGood();
474 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
475 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
476 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
477 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
478 $status->fatal( 'directorycreateerror', $params['dir'] );
479 } elseif ( !is_writable( $dir ) ) {
480 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
481 } elseif ( !is_readable( $dir ) ) {
482 $status->fatal( 'directorynotreadableerror', $params['dir'] );
484 return $status;
488 * @see FileBackendStore::doSecureInternal()
489 * @return Status
491 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
492 $status = Status::newGood();
493 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
494 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
495 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
496 // Seed new directories with a blank index.html, to prevent crawling...
497 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
498 $bytes = file_put_contents( "{$dir}/index.html", '' );
499 if ( !$bytes ) {
500 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
501 return $status;
504 // Add a .htaccess file to the root of the container...
505 if ( !empty( $params['noAccess'] ) ) {
506 if ( !file_exists( "{$contRoot}/.htaccess" ) ) {
507 $bytes = file_put_contents( "{$contRoot}/.htaccess", "Deny from all\n" );
508 if ( !$bytes ) {
509 $storeDir = "mwstore://{$this->name}/{$shortCont}";
510 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
511 return $status;
515 return $status;
519 * @see FileBackendStore::doCleanInternal()
520 * @return Status
522 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
523 $status = Status::newGood();
524 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
525 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
526 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
527 wfSuppressWarnings();
528 if ( is_dir( $dir ) ) {
529 rmdir( $dir ); // remove directory if empty
531 wfRestoreWarnings();
532 return $status;
536 * @see FileBackendStore::doFileExists()
537 * @return array|bool|null
539 protected function doGetFileStat( array $params ) {
540 $source = $this->resolveToFSPath( $params['src'] );
541 if ( $source === null ) {
542 return false; // invalid storage path
545 $this->trapWarnings(); // don't trust 'false' if there were errors
546 $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
547 $hadError = $this->untrapWarnings();
549 if ( $stat ) {
550 return array(
551 'mtime' => wfTimestamp( TS_MW, $stat['mtime'] ),
552 'size' => $stat['size']
554 } elseif ( !$hadError ) {
555 return false; // file does not exist
556 } else {
557 return null; // failure
562 * @see FileBackendStore::doClearCache()
564 protected function doClearCache( array $paths = null ) {
565 clearstatcache(); // clear the PHP file stat cache
569 * @see FileBackendStore::doDirectoryExists()
570 * @return bool|null
572 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
573 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
574 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
575 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
577 $this->trapWarnings(); // don't trust 'false' if there were errors
578 $exists = is_dir( $dir );
579 $hadError = $this->untrapWarnings();
581 return $hadError ? null : $exists;
585 * @see FileBackendStore::getDirectoryListInternal()
586 * @return Array|null
588 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
589 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
590 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
591 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
592 $exists = is_dir( $dir );
593 if ( !$exists ) {
594 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
595 return array(); // nothing under this dir
596 } elseif ( !is_readable( $dir ) ) {
597 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
598 return null; // bad permissions?
600 return new FSFileBackendDirList( $dir, $params );
604 * @see FileBackendStore::getFileListInternal()
605 * @return array|FSFileBackendFileList|null
607 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
608 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
609 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
610 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
611 $exists = is_dir( $dir );
612 if ( !$exists ) {
613 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
614 return array(); // nothing under this dir
615 } elseif ( !is_readable( $dir ) ) {
616 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
617 return null; // bad permissions?
619 return new FSFileBackendFileList( $dir, $params );
623 * @see FileBackendStore::getLocalReference()
624 * @return FSFile|null
626 public function getLocalReference( array $params ) {
627 $source = $this->resolveToFSPath( $params['src'] );
628 if ( $source === null ) {
629 return null;
631 return new FSFile( $source );
635 * @see FileBackendStore::getLocalCopy()
636 * @return null|TempFSFile
638 public function getLocalCopy( array $params ) {
639 $source = $this->resolveToFSPath( $params['src'] );
640 if ( $source === null ) {
641 return null;
644 // Create a new temporary file with the same extension...
645 $ext = FileBackend::extensionFromPath( $params['src'] );
646 $tmpFile = TempFSFile::factory( wfBaseName( $source ) . '_', $ext );
647 if ( !$tmpFile ) {
648 return null;
650 $tmpPath = $tmpFile->getPath();
652 // Copy the source file over the temp file
653 $ok = copy( $source, $tmpPath );
654 if ( !$ok ) {
655 return null;
658 $this->chmod( $tmpPath );
660 return $tmpFile;
664 * @see FileBackendStore::directoriesAreVirtual()
665 * @return bool
667 protected function directoriesAreVirtual() {
668 return false;
672 * @see FileBackendStore::doExecuteOpHandlesInternal()
673 * @return Array List of corresponding Status objects
675 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
676 $statuses = array();
678 $pipes = array();
679 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
680 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
683 $errs = array();
684 foreach ( $pipes as $index => $pipe ) {
685 // Result will be empty on success in *NIX. On Windows,
686 // it may be something like " 1 file(s) [copied|moved].".
687 $errs[$index] = stream_get_contents( $pipe );
688 fclose( $pipe );
691 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
692 $status = Status::newGood();
693 $function = '_getResponse' . $fileOpHandle->call;
694 $this->$function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
695 $statuses[$index] = $status;
696 if ( $status->isOK() && $fileOpHandle->chmodPath ) {
697 $this->chmod( $fileOpHandle->chmodPath );
701 clearstatcache(); // files changed
702 return $statuses;
706 * Chmod a file, suppressing the warnings
708 * @param $path string Absolute file system path
709 * @return bool Success
711 protected function chmod( $path ) {
712 wfSuppressWarnings();
713 $ok = chmod( $path, $this->fileMode );
714 wfRestoreWarnings();
716 return $ok;
720 * Clean up directory separators for the given OS
722 * @param $path string FS path
723 * @return string
725 protected function cleanPathSlashes( $path ) {
726 return wfIsWindows() ? strtr( $path, '/', '\\' ) : $path;
730 * Listen for E_WARNING errors and track whether any happen
732 * @return bool
734 protected function trapWarnings() {
735 $this->hadWarningErrors[] = false; // push to stack
736 set_error_handler( array( $this, 'handleWarning' ), E_WARNING );
737 return false; // invoke normal PHP error handler
741 * Stop listening for E_WARNING errors and return true if any happened
743 * @return bool
745 protected function untrapWarnings() {
746 restore_error_handler(); // restore previous handler
747 return array_pop( $this->hadWarningErrors ); // pop from stack
751 * @return bool
753 private function handleWarning() {
754 $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
755 return true; // suppress from PHP handler
760 * @see FileBackendStoreOpHandle
762 class FSFileOpHandle extends FileBackendStoreOpHandle {
763 public $cmd; // string; shell command
764 public $chmodPath; // string; file to chmod
767 * @param $backend
768 * @param $params array
769 * @param $call
770 * @param $cmd
771 * @param $chmodPath null
773 public function __construct( $backend, array $params, $call, $cmd, $chmodPath = null ) {
774 $this->backend = $backend;
775 $this->params = $params;
776 $this->call = $call;
777 $this->cmd = $cmd;
778 $this->chmodPath = $chmodPath;
783 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
784 * catches exception or does any custom behavoir that we may want.
785 * Do not use this class from places outside FSFileBackend.
787 * @ingroup FileBackend
789 abstract class FSFileBackendList implements Iterator {
790 /** @var Iterator */
791 protected $iter;
792 protected $suffixStart; // integer
793 protected $pos = 0; // integer
794 /** @var Array */
795 protected $params = array();
798 * @param $dir string file system directory
799 * @param $params array
801 public function __construct( $dir, array $params ) {
802 $dir = realpath( $dir ); // normalize
803 $this->suffixStart = strlen( $dir ) + 1; // size of "path/to/dir/"
804 $this->params = $params;
806 try {
807 $this->iter = $this->initIterator( $dir );
808 } catch ( UnexpectedValueException $e ) {
809 $this->iter = null; // bad permissions? deleted?
814 * Return an appropriate iterator object to wrap
816 * @param $dir string file system directory
817 * @return Iterator
819 protected function initIterator( $dir ) {
820 if ( !empty( $this->params['topOnly'] ) ) { // non-recursive
821 # Get an iterator that will get direct sub-nodes
822 return new DirectoryIterator( $dir );
823 } else { // recursive
824 # Get an iterator that will return leaf nodes (non-directories)
825 # RecursiveDirectoryIterator extends FilesystemIterator.
826 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
827 $flags = FilesystemIterator::CURRENT_AS_SELF | FilesystemIterator::SKIP_DOTS;
828 return new RecursiveIteratorIterator(
829 new RecursiveDirectoryIterator( $dir, $flags ),
830 RecursiveIteratorIterator::CHILD_FIRST // include dirs
836 * @see Iterator::key()
837 * @return integer
839 public function key() {
840 return $this->pos;
844 * @see Iterator::current()
845 * @return string|bool String or false
847 public function current() {
848 return $this->getRelPath( $this->iter->current()->getPathname() );
852 * @see Iterator::next()
853 * @return void
855 public function next() {
856 try {
857 $this->iter->next();
858 $this->filterViaNext();
859 } catch ( UnexpectedValueException $e ) {
860 $this->iter = null;
862 ++$this->pos;
866 * @see Iterator::rewind()
867 * @return void
869 public function rewind() {
870 $this->pos = 0;
871 try {
872 $this->iter->rewind();
873 $this->filterViaNext();
874 } catch ( UnexpectedValueException $e ) {
875 $this->iter = null;
880 * @see Iterator::valid()
881 * @return bool
883 public function valid() {
884 return $this->iter && $this->iter->valid();
888 * Filter out items by advancing to the next ones
890 protected function filterViaNext() {}
893 * Return only the relative path and normalize slashes to FileBackend-style.
894 * Uses the "real path" since the suffix is based upon that.
896 * @param $path string
897 * @return string
899 protected function getRelPath( $path ) {
900 return strtr( substr( realpath( $path ), $this->suffixStart ), '\\', '/' );
904 class FSFileBackendDirList extends FSFileBackendList {
905 protected function filterViaNext() {
906 while ( $this->iter->valid() ) {
907 if ( $this->iter->current()->isDot() || !$this->iter->current()->isDir() ) {
908 $this->iter->next(); // skip non-directories and dot files
909 } else {
910 break;
916 class FSFileBackendFileList extends FSFileBackendList {
917 protected function filterViaNext() {
918 while ( $this->iter->valid() ) {
919 if ( !$this->iter->current()->isFile() ) {
920 $this->iter->next(); // skip non-files and dot files
921 } else {
922 break;