Merge "filebackend: cleaned up the FileBackend constructor"
[mediawiki.git] / includes / filebackend / FSFileBackend.php
blob8438919a04f34b511957344a0b890e7ce06fb067
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 /** @var string Directory holding the container directories */
43 protected $basePath;
45 /** @var array Map of container names to root paths for custom container paths */
46 protected $containerPaths = array();
48 /** @var int File permission mode */
49 protected $fileMode;
51 /** @var string Required OS username to own files */
52 protected $fileOwner;
54 /** @var string OS username running this script */
55 protected $currentUser;
57 /** @var array */
58 protected $hadWarningErrors = array();
60 /**
61 * @see FileBackendStore::__construct()
62 * Additional $config params include:
63 * - basePath : File system directory that holds containers.
64 * - containerPaths : Map of container names to custom file system directories.
65 * This should only be used for backwards-compatibility.
66 * - fileMode : Octal UNIX file permissions to use on files stored.
68 public function __construct( array $config ) {
69 parent::__construct( $config );
71 // Remove any possible trailing slash from directories
72 if ( isset( $config['basePath'] ) ) {
73 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
74 } else {
75 $this->basePath = null; // none; containers must have explicit paths
78 if ( isset( $config['containerPaths'] ) ) {
79 $this->containerPaths = (array)$config['containerPaths'];
80 foreach ( $this->containerPaths as &$path ) {
81 $path = rtrim( $path, '/' ); // remove trailing slash
85 $this->fileMode = isset( $config['fileMode'] ) ? $config['fileMode'] : 0644;
86 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
87 $this->fileOwner = $config['fileOwner'];
88 $info = posix_getpwuid( posix_getuid() );
89 $this->currentUser = $info['name']; // cache this, assuming it doesn't change
93 protected function resolveContainerPath( $container, $relStoragePath ) {
94 // Check that container has a root directory
95 if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
96 // Check for sane relative paths (assume the base paths are OK)
97 if ( $this->isLegalRelPath( $relStoragePath ) ) {
98 return $relStoragePath;
102 return null;
106 * Sanity check a relative file system path for validity
108 * @param string $path Normalized relative path
109 * @return bool
111 protected function isLegalRelPath( $path ) {
112 // Check for file names longer than 255 chars
113 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
114 return false;
116 if ( wfIsWindows() ) { // NTFS
117 return !preg_match( '![:*?"<>|]!', $path );
118 } else {
119 return true;
124 * Given the short (unresolved) and full (resolved) name of
125 * a container, return the file system path of the container.
127 * @param string $shortCont
128 * @param string $fullCont
129 * @return string|null
131 protected function containerFSRoot( $shortCont, $fullCont ) {
132 if ( isset( $this->containerPaths[$shortCont] ) ) {
133 return $this->containerPaths[$shortCont];
134 } elseif ( isset( $this->basePath ) ) {
135 return "{$this->basePath}/{$fullCont}";
138 return null; // no container base path defined
142 * Get the absolute file system path for a storage path
144 * @param string $storagePath Storage path
145 * @return string|null
147 protected function resolveToFSPath( $storagePath ) {
148 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
149 if ( $relPath === null ) {
150 return null; // invalid
152 list( , $shortCont, ) = FileBackend::splitStoragePath( $storagePath );
153 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
154 if ( $relPath != '' ) {
155 $fsPath .= "/{$relPath}";
158 return $fsPath;
161 public function isPathUsableInternal( $storagePath ) {
162 $fsPath = $this->resolveToFSPath( $storagePath );
163 if ( $fsPath === null ) {
164 return false; // invalid
166 $parentDir = dirname( $fsPath );
168 if ( file_exists( $fsPath ) ) {
169 $ok = is_file( $fsPath ) && is_writable( $fsPath );
170 } else {
171 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
174 if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
175 $ok = false;
176 trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
179 return $ok;
182 protected function doCreateInternal( array $params ) {
183 $status = Status::newGood();
185 $dest = $this->resolveToFSPath( $params['dst'] );
186 if ( $dest === null ) {
187 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
189 return $status;
192 if ( !empty( $params['async'] ) ) { // deferred
193 $tempFile = TempFSFile::factory( 'create_', 'tmp' );
194 if ( !$tempFile ) {
195 $status->fatal( 'backend-fail-create', $params['dst'] );
197 return $status;
199 $this->trapWarnings();
200 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
201 $this->untrapWarnings();
202 if ( $bytes === false ) {
203 $status->fatal( 'backend-fail-create', $params['dst'] );
205 return $status;
207 $cmd = implode( ' ', array(
208 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
209 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
210 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
211 ) );
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'] );
221 return $status;
223 $this->chmod( $dest );
226 return $status;
230 * @see FSFileBackend::doExecuteOpHandlesInternal()
232 protected function getResponseCreate( $errors, Status $status, array $params, $cmd ) {
233 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
234 $status->fatal( 'backend-fail-create', $params['dst'] );
235 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
239 protected function doStoreInternal( array $params ) {
240 $status = Status::newGood();
242 $dest = $this->resolveToFSPath( $params['dst'] );
243 if ( $dest === null ) {
244 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
246 return $status;
249 if ( !empty( $params['async'] ) ) { // deferred
250 $cmd = implode( ' ', array(
251 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
252 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
253 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
254 ) );
255 $status->value = new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
256 } else { // immediate write
257 $this->trapWarnings();
258 $ok = copy( $params['src'], $dest );
259 $this->untrapWarnings();
260 // In some cases (at least over NFS), copy() returns true when it fails
261 if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
262 if ( $ok ) { // PHP bug
263 unlink( $dest ); // remove broken file
264 trigger_error( __METHOD__ . ": copy() failed but returned true." );
266 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
268 return $status;
270 $this->chmod( $dest );
273 return $status;
277 * @see FSFileBackend::doExecuteOpHandlesInternal()
279 protected function getResponseStore( $errors, Status $status, array $params, $cmd ) {
280 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
281 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
282 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
286 protected function doCopyInternal( array $params ) {
287 $status = Status::newGood();
289 $source = $this->resolveToFSPath( $params['src'] );
290 if ( $source === null ) {
291 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
293 return $status;
296 $dest = $this->resolveToFSPath( $params['dst'] );
297 if ( $dest === null ) {
298 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
300 return $status;
303 if ( !is_file( $source ) ) {
304 if ( empty( $params['ignoreMissingSource'] ) ) {
305 $status->fatal( 'backend-fail-copy', $params['src'] );
308 return $status; // do nothing; either OK or bad status
311 if ( !empty( $params['async'] ) ) { // deferred
312 $cmd = implode( ' ', array(
313 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
314 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
315 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
316 ) );
317 $status->value = new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
318 } else { // immediate write
319 $this->trapWarnings();
320 $ok = ( $source === $dest ) ? true : copy( $source, $dest );
321 $this->untrapWarnings();
322 // In some cases (at least over NFS), copy() returns true when it fails
323 if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
324 if ( $ok ) { // PHP bug
325 $this->trapWarnings();
326 unlink( $dest ); // remove broken file
327 $this->untrapWarnings();
328 trigger_error( __METHOD__ . ": copy() failed but returned true." );
330 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
332 return $status;
334 $this->chmod( $dest );
337 return $status;
341 * @see FSFileBackend::doExecuteOpHandlesInternal()
343 protected function getResponseCopy( $errors, Status $status, array $params, $cmd ) {
344 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
345 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
346 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
350 protected function doMoveInternal( array $params ) {
351 $status = Status::newGood();
353 $source = $this->resolveToFSPath( $params['src'] );
354 if ( $source === null ) {
355 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
357 return $status;
360 $dest = $this->resolveToFSPath( $params['dst'] );
361 if ( $dest === null ) {
362 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
364 return $status;
367 if ( !is_file( $source ) ) {
368 if ( empty( $params['ignoreMissingSource'] ) ) {
369 $status->fatal( 'backend-fail-move', $params['src'] );
372 return $status; // do nothing; either OK or bad status
375 if ( !empty( $params['async'] ) ) { // deferred
376 $cmd = implode( ' ', array(
377 wfIsWindows() ? 'MOVE /Y' : 'mv', // (overwrite)
378 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
379 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
380 ) );
381 $status->value = new FSFileOpHandle( $this, $params, 'Move', $cmd );
382 } else { // immediate write
383 $this->trapWarnings();
384 $ok = ( $source === $dest ) ? true : rename( $source, $dest );
385 $this->untrapWarnings();
386 clearstatcache(); // file no longer at source
387 if ( !$ok ) {
388 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
390 return $status;
394 return $status;
398 * @see FSFileBackend::doExecuteOpHandlesInternal()
400 protected function getResponseMove( $errors, Status $status, array $params, $cmd ) {
401 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
402 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
403 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
407 protected function doDeleteInternal( array $params ) {
408 $status = Status::newGood();
410 $source = $this->resolveToFSPath( $params['src'] );
411 if ( $source === null ) {
412 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
414 return $status;
417 if ( !is_file( $source ) ) {
418 if ( empty( $params['ignoreMissingSource'] ) ) {
419 $status->fatal( 'backend-fail-delete', $params['src'] );
422 return $status; // do nothing; either OK or bad status
425 if ( !empty( $params['async'] ) ) { // deferred
426 $cmd = implode( ' ', array(
427 wfIsWindows() ? 'DEL' : 'unlink',
428 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
429 ) );
430 $status->value = new FSFileOpHandle( $this, $params, 'Copy', $cmd );
431 } else { // immediate write
432 $this->trapWarnings();
433 $ok = unlink( $source );
434 $this->untrapWarnings();
435 if ( !$ok ) {
436 $status->fatal( 'backend-fail-delete', $params['src'] );
438 return $status;
442 return $status;
446 * @see FSFileBackend::doExecuteOpHandlesInternal()
448 protected function getResponseDelete( $errors, Status $status, array $params, $cmd ) {
449 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
450 $status->fatal( 'backend-fail-delete', $params['src'] );
451 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
456 * @param string $fullCont
457 * @param $dirRel
458 * @param array $params
459 * @return Status
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 ) );
482 return $status;
485 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
486 $status = Status::newGood();
487 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
488 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
489 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
490 // Seed new directories with a blank index.html, to prevent crawling...
491 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
492 $this->trapWarnings();
493 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
494 $this->untrapWarnings();
495 if ( $bytes === false ) {
496 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
499 // Add a .htaccess file to the root of the container...
500 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
501 $this->trapWarnings();
502 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
503 $this->untrapWarnings();
504 if ( $bytes === false ) {
505 $storeDir = "mwstore://{$this->name}/{$shortCont}";
506 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
510 return $status;
513 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
514 $status = Status::newGood();
515 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
516 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
517 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
518 // Unseed new directories with a blank index.html, to allow crawling...
519 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
520 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
521 $this->trapWarnings();
522 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
523 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
525 $this->untrapWarnings();
527 // Remove the .htaccess file from the root of the container...
528 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
529 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
530 $this->trapWarnings();
531 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
532 $storeDir = "mwstore://{$this->name}/{$shortCont}";
533 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
535 $this->untrapWarnings();
538 return $status;
541 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
542 $status = Status::newGood();
543 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
544 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
545 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
546 $this->trapWarnings();
547 if ( is_dir( $dir ) ) {
548 rmdir( $dir ); // remove directory if empty
550 $this->untrapWarnings();
552 return $status;
555 protected function doGetFileStat( array $params ) {
556 $source = $this->resolveToFSPath( $params['src'] );
557 if ( $source === null ) {
558 return false; // invalid storage path
561 $this->trapWarnings(); // don't trust 'false' if there were errors
562 $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
563 $hadError = $this->untrapWarnings();
565 if ( $stat ) {
566 return array(
567 'mtime' => wfTimestamp( TS_MW, $stat['mtime'] ),
568 'size' => $stat['size']
570 } elseif ( !$hadError ) {
571 return false; // file does not exist
572 } else {
573 return null; // failure
578 * @see FileBackendStore::doClearCache()
580 protected function doClearCache( array $paths = null ) {
581 clearstatcache(); // clear the PHP file stat cache
584 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
585 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
586 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
587 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
589 $this->trapWarnings(); // don't trust 'false' if there were errors
590 $exists = is_dir( $dir );
591 $hadError = $this->untrapWarnings();
593 return $hadError ? null : $exists;
597 * @see FileBackendStore::getDirectoryListInternal()
598 * @param string $fullCont
599 * @param string $dirRel
600 * @param array $params
601 * @return array|null
603 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
604 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
605 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
606 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
607 $exists = is_dir( $dir );
608 if ( !$exists ) {
609 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
611 return array(); // nothing under this dir
612 } elseif ( !is_readable( $dir ) ) {
613 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
615 return null; // bad permissions?
618 return new FSFileBackendDirList( $dir, $params );
622 * @see FileBackendStore::getFileListInternal()
623 * @param string $fullCont
624 * @param string $dirRel
625 * @param array $params
626 * @return array|FSFileBackendFileList|null
628 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
629 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
630 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
631 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
632 $exists = is_dir( $dir );
633 if ( !$exists ) {
634 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
636 return array(); // nothing under this dir
637 } elseif ( !is_readable( $dir ) ) {
638 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
640 return null; // bad permissions?
643 return new FSFileBackendFileList( $dir, $params );
646 protected function doGetLocalReferenceMulti( array $params ) {
647 $fsFiles = array(); // (path => FSFile)
649 foreach ( $params['srcs'] as $src ) {
650 $source = $this->resolveToFSPath( $src );
651 if ( $source === null || !is_file( $source ) ) {
652 $fsFiles[$src] = null; // invalid path or file does not exist
653 } else {
654 $fsFiles[$src] = new FSFile( $source );
658 return $fsFiles;
661 protected function doGetLocalCopyMulti( array $params ) {
662 $tmpFiles = array(); // (path => TempFSFile)
664 foreach ( $params['srcs'] as $src ) {
665 $source = $this->resolveToFSPath( $src );
666 if ( $source === null ) {
667 $tmpFiles[$src] = null; // invalid path
668 } else {
669 // Create a new temporary file with the same extension...
670 $ext = FileBackend::extensionFromPath( $src );
671 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
672 if ( !$tmpFile ) {
673 $tmpFiles[$src] = null;
674 } else {
675 $tmpPath = $tmpFile->getPath();
676 // Copy the source file over the temp file
677 $this->trapWarnings();
678 $ok = copy( $source, $tmpPath );
679 $this->untrapWarnings();
680 if ( !$ok ) {
681 $tmpFiles[$src] = null;
682 } else {
683 $this->chmod( $tmpPath );
684 $tmpFiles[$src] = $tmpFile;
690 return $tmpFiles;
693 protected function directoriesAreVirtual() {
694 return false;
697 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
698 $statuses = array();
700 $pipes = array();
701 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
702 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
705 $errs = array();
706 foreach ( $pipes as $index => $pipe ) {
707 // Result will be empty on success in *NIX. On Windows,
708 // it may be something like " 1 file(s) [copied|moved].".
709 $errs[$index] = stream_get_contents( $pipe );
710 fclose( $pipe );
713 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
714 $status = Status::newGood();
715 $function = 'getResponse' . $fileOpHandle->call;
716 $this->$function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
717 $statuses[$index] = $status;
718 if ( $status->isOK() && $fileOpHandle->chmodPath ) {
719 $this->chmod( $fileOpHandle->chmodPath );
723 clearstatcache(); // files changed
724 return $statuses;
728 * Chmod a file, suppressing the warnings
730 * @param string $path Absolute file system path
731 * @return bool Success
733 protected function chmod( $path ) {
734 $this->trapWarnings();
735 $ok = chmod( $path, $this->fileMode );
736 $this->untrapWarnings();
738 return $ok;
742 * Return the text of an index.html file to hide directory listings
744 * @return string
746 protected function indexHtmlPrivate() {
747 return '';
751 * Return the text of a .htaccess file to make a directory private
753 * @return string
755 protected function htaccessPrivate() {
756 return "Deny from all\n";
760 * Clean up directory separators for the given OS
762 * @param string $path FS path
763 * @return string
765 protected function cleanPathSlashes( $path ) {
766 return wfIsWindows() ? strtr( $path, '/', '\\' ) : $path;
770 * Listen for E_WARNING errors and track whether any happen
772 protected function trapWarnings() {
773 $this->hadWarningErrors[] = false; // push to stack
774 set_error_handler( array( $this, 'handleWarning' ), E_WARNING );
778 * Stop listening for E_WARNING errors and return true if any happened
780 * @return bool
782 protected function untrapWarnings() {
783 restore_error_handler(); // restore previous handler
784 return array_pop( $this->hadWarningErrors ); // pop from stack
788 * @param int $errno
789 * @param string $errstr
790 * @return bool
791 * @access private
793 public function handleWarning( $errno, $errstr ) {
794 wfDebugLog( 'FSFileBackend', $errstr ); // more detailed error logging
795 $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
797 return true; // suppress from PHP handler
802 * @see FileBackendStoreOpHandle
804 class FSFileOpHandle extends FileBackendStoreOpHandle {
805 public $cmd; // string; shell command
806 public $chmodPath; // string; file to chmod
809 * @param FSFileBackend $backend
810 * @param array $params
811 * @param string $call
812 * @param string $cmd
813 * @param int|null $chmodPath
815 public function __construct(
816 FSFileBackend $backend, array $params, $call, $cmd, $chmodPath = null
818 $this->backend = $backend;
819 $this->params = $params;
820 $this->call = $call;
821 $this->cmd = $cmd;
822 $this->chmodPath = $chmodPath;
827 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
828 * catches exception or does any custom behavoir that we may want.
829 * Do not use this class from places outside FSFileBackend.
831 * @ingroup FileBackend
833 abstract class FSFileBackendList implements Iterator {
834 /** @var Iterator */
835 protected $iter;
837 /** @var int */
838 protected $suffixStart;
840 /** @var int */
841 protected $pos = 0;
843 /** @var array */
844 protected $params = array();
847 * @param string $dir file system directory
848 * @param array $params
850 public function __construct( $dir, array $params ) {
851 $path = realpath( $dir ); // normalize
852 if ( $path === false ) {
853 $path = $dir;
855 $this->suffixStart = strlen( $path ) + 1; // size of "path/to/dir/"
856 $this->params = $params;
858 try {
859 $this->iter = $this->initIterator( $path );
860 } catch ( UnexpectedValueException $e ) {
861 $this->iter = null; // bad permissions? deleted?
866 * Return an appropriate iterator object to wrap
868 * @param string $dir file system directory
869 * @return Iterator
871 protected function initIterator( $dir ) {
872 if ( !empty( $this->params['topOnly'] ) ) { // non-recursive
873 # Get an iterator that will get direct sub-nodes
874 return new DirectoryIterator( $dir );
875 } else { // recursive
876 # Get an iterator that will return leaf nodes (non-directories)
877 # RecursiveDirectoryIterator extends FilesystemIterator.
878 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
879 $flags = FilesystemIterator::CURRENT_AS_SELF | FilesystemIterator::SKIP_DOTS;
881 return new RecursiveIteratorIterator(
882 new RecursiveDirectoryIterator( $dir, $flags ),
883 RecursiveIteratorIterator::CHILD_FIRST // include dirs
889 * @see Iterator::key()
890 * @return int
892 public function key() {
893 return $this->pos;
897 * @see Iterator::current()
898 * @return string|bool String or false
900 public function current() {
901 return $this->getRelPath( $this->iter->current()->getPathname() );
905 * @see Iterator::next()
906 * @throws FileBackendError
908 public function next() {
909 try {
910 $this->iter->next();
911 $this->filterViaNext();
912 } catch ( UnexpectedValueException $e ) { // bad permissions? deleted?
913 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
915 ++$this->pos;
919 * @see Iterator::rewind()
920 * @throws FileBackendError
922 public function rewind() {
923 $this->pos = 0;
924 try {
925 $this->iter->rewind();
926 $this->filterViaNext();
927 } catch ( UnexpectedValueException $e ) { // bad permissions? deleted?
928 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
933 * @see Iterator::valid()
934 * @return bool
936 public function valid() {
937 return $this->iter && $this->iter->valid();
941 * Filter out items by advancing to the next ones
943 protected function filterViaNext() {
947 * Return only the relative path and normalize slashes to FileBackend-style.
948 * Uses the "real path" since the suffix is based upon that.
950 * @param string $dir
951 * @return string
953 protected function getRelPath( $dir ) {
954 $path = realpath( $dir );
955 if ( $path === false ) {
956 $path = $dir;
959 return strtr( substr( $path, $this->suffixStart ), '\\', '/' );
963 class FSFileBackendDirList extends FSFileBackendList {
964 protected function filterViaNext() {
965 while ( $this->iter->valid() ) {
966 if ( $this->iter->current()->isDot() || !$this->iter->current()->isDir() ) {
967 $this->iter->next(); // skip non-directories and dot files
968 } else {
969 break;
975 class FSFileBackendFileList extends FSFileBackendList {
976 protected function filterViaNext() {
977 while ( $this->iter->valid() ) {
978 if ( !$this->iter->current()->isFile() ) {
979 $this->iter->next(); // skip non-files and dot files
980 } else {
981 break;