User::isSafeToLoad() should return false if MW_NO_SESSION
[mediawiki.git] / includes / filebackend / FSFileBackend.php
blob86d146d90f2eb3310b3c85bcdc4ba3821b95c66a
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 = [];
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 = [];
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.
67 * @param array $config
69 public function __construct( array $config ) {
70 parent::__construct( $config );
72 // Remove any possible trailing slash from directories
73 if ( isset( $config['basePath'] ) ) {
74 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
75 } else {
76 $this->basePath = null; // none; containers must have explicit paths
79 if ( isset( $config['containerPaths'] ) ) {
80 $this->containerPaths = (array)$config['containerPaths'];
81 foreach ( $this->containerPaths as &$path ) {
82 $path = rtrim( $path, '/' ); // remove trailing slash
86 $this->fileMode = isset( $config['fileMode'] ) ? $config['fileMode'] : 0644;
87 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
88 $this->fileOwner = $config['fileOwner'];
89 $info = posix_getpwuid( posix_getuid() );
90 $this->currentUser = $info['name']; // cache this, assuming it doesn't change
94 public function getFeatures() {
95 return !wfIsWindows() ? FileBackend::ATTR_UNICODE_PATHS : 0;
98 protected function resolveContainerPath( $container, $relStoragePath ) {
99 // Check that container has a root directory
100 if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
101 // Check for sane relative paths (assume the base paths are OK)
102 if ( $this->isLegalRelPath( $relStoragePath ) ) {
103 return $relStoragePath;
107 return null;
111 * Sanity check a relative file system path for validity
113 * @param string $path Normalized relative path
114 * @return bool
116 protected function isLegalRelPath( $path ) {
117 // Check for file names longer than 255 chars
118 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
119 return false;
121 if ( wfIsWindows() ) { // NTFS
122 return !preg_match( '![:*?"<>|]!', $path );
123 } else {
124 return true;
129 * Given the short (unresolved) and full (resolved) name of
130 * a container, return the file system path of the container.
132 * @param string $shortCont
133 * @param string $fullCont
134 * @return string|null
136 protected function containerFSRoot( $shortCont, $fullCont ) {
137 if ( isset( $this->containerPaths[$shortCont] ) ) {
138 return $this->containerPaths[$shortCont];
139 } elseif ( isset( $this->basePath ) ) {
140 return "{$this->basePath}/{$fullCont}";
143 return null; // no container base path defined
147 * Get the absolute file system path for a storage path
149 * @param string $storagePath Storage path
150 * @return string|null
152 protected function resolveToFSPath( $storagePath ) {
153 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
154 if ( $relPath === null ) {
155 return null; // invalid
157 list( , $shortCont, ) = FileBackend::splitStoragePath( $storagePath );
158 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
159 if ( $relPath != '' ) {
160 $fsPath .= "/{$relPath}";
163 return $fsPath;
166 public function isPathUsableInternal( $storagePath ) {
167 $fsPath = $this->resolveToFSPath( $storagePath );
168 if ( $fsPath === null ) {
169 return false; // invalid
171 $parentDir = dirname( $fsPath );
173 if ( file_exists( $fsPath ) ) {
174 $ok = is_file( $fsPath ) && is_writable( $fsPath );
175 } else {
176 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
179 if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
180 $ok = false;
181 trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
184 return $ok;
187 protected function doCreateInternal( array $params ) {
188 $status = Status::newGood();
190 $dest = $this->resolveToFSPath( $params['dst'] );
191 if ( $dest === null ) {
192 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
194 return $status;
197 if ( !empty( $params['async'] ) ) { // deferred
198 $tempFile = TempFSFile::factory( 'create_', 'tmp' );
199 if ( !$tempFile ) {
200 $status->fatal( 'backend-fail-create', $params['dst'] );
202 return $status;
204 $this->trapWarnings();
205 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
206 $this->untrapWarnings();
207 if ( $bytes === false ) {
208 $status->fatal( 'backend-fail-create', $params['dst'] );
210 return $status;
212 $cmd = implode( ' ', [
213 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
214 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
215 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
216 ] );
217 $handler = function ( $errors, Status $status, array $params, $cmd ) {
218 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
219 $status->fatal( 'backend-fail-create', $params['dst'] );
220 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
223 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
224 $tempFile->bind( $status->value );
225 } else { // immediate write
226 $this->trapWarnings();
227 $bytes = file_put_contents( $dest, $params['content'] );
228 $this->untrapWarnings();
229 if ( $bytes === false ) {
230 $status->fatal( 'backend-fail-create', $params['dst'] );
232 return $status;
234 $this->chmod( $dest );
237 return $status;
240 protected function doStoreInternal( array $params ) {
241 $status = Status::newGood();
243 $dest = $this->resolveToFSPath( $params['dst'] );
244 if ( $dest === null ) {
245 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
247 return $status;
250 if ( !empty( $params['async'] ) ) { // deferred
251 $cmd = implode( ' ', [
252 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
253 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
254 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
255 ] );
256 $handler = function ( $errors, Status $status, array $params, $cmd ) {
257 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
258 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
259 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
262 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
263 } else { // immediate write
264 $this->trapWarnings();
265 $ok = copy( $params['src'], $dest );
266 $this->untrapWarnings();
267 // In some cases (at least over NFS), copy() returns true when it fails
268 if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
269 if ( $ok ) { // PHP bug
270 unlink( $dest ); // remove broken file
271 trigger_error( __METHOD__ . ": copy() failed but returned true." );
273 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
275 return $status;
277 $this->chmod( $dest );
280 return $status;
283 protected function doCopyInternal( array $params ) {
284 $status = Status::newGood();
286 $source = $this->resolveToFSPath( $params['src'] );
287 if ( $source === null ) {
288 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
290 return $status;
293 $dest = $this->resolveToFSPath( $params['dst'] );
294 if ( $dest === null ) {
295 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
297 return $status;
300 if ( !is_file( $source ) ) {
301 if ( empty( $params['ignoreMissingSource'] ) ) {
302 $status->fatal( 'backend-fail-copy', $params['src'] );
305 return $status; // do nothing; either OK or bad status
308 if ( !empty( $params['async'] ) ) { // deferred
309 $cmd = implode( ' ', [
310 wfIsWindows() ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
311 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
312 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
313 ] );
314 $handler = function ( $errors, Status $status, array $params, $cmd ) {
315 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
316 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
317 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
320 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
321 } else { // immediate write
322 $this->trapWarnings();
323 $ok = ( $source === $dest ) ? true : copy( $source, $dest );
324 $this->untrapWarnings();
325 // In some cases (at least over NFS), copy() returns true when it fails
326 if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
327 if ( $ok ) { // PHP bug
328 $this->trapWarnings();
329 unlink( $dest ); // remove broken file
330 $this->untrapWarnings();
331 trigger_error( __METHOD__ . ": copy() failed but returned true." );
333 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
335 return $status;
337 $this->chmod( $dest );
340 return $status;
343 protected function doMoveInternal( array $params ) {
344 $status = Status::newGood();
346 $source = $this->resolveToFSPath( $params['src'] );
347 if ( $source === null ) {
348 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
350 return $status;
353 $dest = $this->resolveToFSPath( $params['dst'] );
354 if ( $dest === null ) {
355 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
357 return $status;
360 if ( !is_file( $source ) ) {
361 if ( empty( $params['ignoreMissingSource'] ) ) {
362 $status->fatal( 'backend-fail-move', $params['src'] );
365 return $status; // do nothing; either OK or bad status
368 if ( !empty( $params['async'] ) ) { // deferred
369 $cmd = implode( ' ', [
370 wfIsWindows() ? 'MOVE /Y' : 'mv', // (overwrite)
371 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
372 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
373 ] );
374 $handler = function ( $errors, Status $status, array $params, $cmd ) {
375 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
376 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
377 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
380 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
381 } else { // immediate write
382 $this->trapWarnings();
383 $ok = ( $source === $dest ) ? true : rename( $source, $dest );
384 $this->untrapWarnings();
385 clearstatcache(); // file no longer at source
386 if ( !$ok ) {
387 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
389 return $status;
393 return $status;
396 protected function doDeleteInternal( array $params ) {
397 $status = Status::newGood();
399 $source = $this->resolveToFSPath( $params['src'] );
400 if ( $source === null ) {
401 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
403 return $status;
406 if ( !is_file( $source ) ) {
407 if ( empty( $params['ignoreMissingSource'] ) ) {
408 $status->fatal( 'backend-fail-delete', $params['src'] );
411 return $status; // do nothing; either OK or bad status
414 if ( !empty( $params['async'] ) ) { // deferred
415 $cmd = implode( ' ', [
416 wfIsWindows() ? 'DEL' : 'unlink',
417 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
418 ] );
419 $handler = function ( $errors, Status $status, array $params, $cmd ) {
420 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
421 $status->fatal( 'backend-fail-delete', $params['src'] );
422 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
425 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
426 } else { // immediate write
427 $this->trapWarnings();
428 $ok = unlink( $source );
429 $this->untrapWarnings();
430 if ( !$ok ) {
431 $status->fatal( 'backend-fail-delete', $params['src'] );
433 return $status;
437 return $status;
441 * @param string $fullCont
442 * @param string $dirRel
443 * @param array $params
444 * @return Status
446 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
447 $status = Status::newGood();
448 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
449 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
450 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
451 $existed = is_dir( $dir ); // already there?
452 // Create the directory and its parents as needed...
453 $this->trapWarnings();
454 if ( !wfMkdirParents( $dir ) ) {
455 wfDebugLog( 'FSFileBackend', __METHOD__ . ": cannot create directory $dir" );
456 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
457 } elseif ( !is_writable( $dir ) ) {
458 wfDebugLog( 'FSFileBackend', __METHOD__ . ": directory $dir is read-only" );
459 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
460 } elseif ( !is_readable( $dir ) ) {
461 wfDebugLog( 'FSFileBackend', __METHOD__ . ": directory $dir is not readable" );
462 $status->fatal( 'directorynotreadableerror', $params['dir'] );
464 $this->untrapWarnings();
465 // Respect any 'noAccess' or 'noListing' flags...
466 if ( is_dir( $dir ) && !$existed ) {
467 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
470 return $status;
473 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
474 $status = Status::newGood();
475 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
476 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
477 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
478 // Seed new directories with a blank index.html, to prevent crawling...
479 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
480 $this->trapWarnings();
481 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
482 $this->untrapWarnings();
483 if ( $bytes === false ) {
484 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
487 // Add a .htaccess file to the root of the container...
488 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
489 $this->trapWarnings();
490 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
491 $this->untrapWarnings();
492 if ( $bytes === false ) {
493 $storeDir = "mwstore://{$this->name}/{$shortCont}";
494 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
498 return $status;
501 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
502 $status = Status::newGood();
503 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
504 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
505 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
506 // Unseed new directories with a blank index.html, to allow crawling...
507 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
508 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
509 $this->trapWarnings();
510 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
511 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
513 $this->untrapWarnings();
515 // Remove the .htaccess file from the root of the container...
516 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
517 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
518 $this->trapWarnings();
519 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
520 $storeDir = "mwstore://{$this->name}/{$shortCont}";
521 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
523 $this->untrapWarnings();
526 return $status;
529 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
530 $status = Status::newGood();
531 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
532 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
533 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
534 $this->trapWarnings();
535 if ( is_dir( $dir ) ) {
536 rmdir( $dir ); // remove directory if empty
538 $this->untrapWarnings();
540 return $status;
543 protected function doGetFileStat( array $params ) {
544 $source = $this->resolveToFSPath( $params['src'] );
545 if ( $source === null ) {
546 return false; // invalid storage path
549 $this->trapWarnings(); // don't trust 'false' if there were errors
550 $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
551 $hadError = $this->untrapWarnings();
553 if ( $stat ) {
554 return [
555 'mtime' => wfTimestamp( TS_MW, $stat['mtime'] ),
556 'size' => $stat['size']
558 } elseif ( !$hadError ) {
559 return false; // file does not exist
560 } else {
561 return null; // failure
565 protected function doClearCache( array $paths = null ) {
566 clearstatcache(); // clear the PHP file stat cache
569 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
570 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
571 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
572 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
574 $this->trapWarnings(); // don't trust 'false' if there were errors
575 $exists = is_dir( $dir );
576 $hadError = $this->untrapWarnings();
578 return $hadError ? null : $exists;
582 * @see FileBackendStore::getDirectoryListInternal()
583 * @param string $fullCont
584 * @param string $dirRel
585 * @param array $params
586 * @return array|null
588 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
589 list( , $shortCont, ) = 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" );
596 return []; // nothing under this dir
597 } elseif ( !is_readable( $dir ) ) {
598 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
600 return null; // bad permissions?
603 return new FSFileBackendDirList( $dir, $params );
607 * @see FileBackendStore::getFileListInternal()
608 * @param string $fullCont
609 * @param string $dirRel
610 * @param array $params
611 * @return array|FSFileBackendFileList|null
613 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
614 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
615 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
616 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
617 $exists = is_dir( $dir );
618 if ( !$exists ) {
619 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
621 return []; // nothing under this dir
622 } elseif ( !is_readable( $dir ) ) {
623 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
625 return null; // bad permissions?
628 return new FSFileBackendFileList( $dir, $params );
631 protected function doGetLocalReferenceMulti( array $params ) {
632 $fsFiles = []; // (path => FSFile)
634 foreach ( $params['srcs'] as $src ) {
635 $source = $this->resolveToFSPath( $src );
636 if ( $source === null || !is_file( $source ) ) {
637 $fsFiles[$src] = null; // invalid path or file does not exist
638 } else {
639 $fsFiles[$src] = new FSFile( $source );
643 return $fsFiles;
646 protected function doGetLocalCopyMulti( array $params ) {
647 $tmpFiles = []; // (path => TempFSFile)
649 foreach ( $params['srcs'] as $src ) {
650 $source = $this->resolveToFSPath( $src );
651 if ( $source === null ) {
652 $tmpFiles[$src] = null; // invalid path
653 } else {
654 // Create a new temporary file with the same extension...
655 $ext = FileBackend::extensionFromPath( $src );
656 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
657 if ( !$tmpFile ) {
658 $tmpFiles[$src] = null;
659 } else {
660 $tmpPath = $tmpFile->getPath();
661 // Copy the source file over the temp file
662 $this->trapWarnings();
663 $ok = copy( $source, $tmpPath );
664 $this->untrapWarnings();
665 if ( !$ok ) {
666 $tmpFiles[$src] = null;
667 } else {
668 $this->chmod( $tmpPath );
669 $tmpFiles[$src] = $tmpFile;
675 return $tmpFiles;
678 protected function directoriesAreVirtual() {
679 return false;
683 * @param FSFileOpHandle[] $fileOpHandles
685 * @return Status[]
687 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
688 $statuses = [];
690 $pipes = [];
691 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
692 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
695 $errs = [];
696 foreach ( $pipes as $index => $pipe ) {
697 // Result will be empty on success in *NIX. On Windows,
698 // it may be something like " 1 file(s) [copied|moved].".
699 $errs[$index] = stream_get_contents( $pipe );
700 fclose( $pipe );
703 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
704 $status = Status::newGood();
705 $function = $fileOpHandle->call;
706 $function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
707 $statuses[$index] = $status;
708 if ( $status->isOK() && $fileOpHandle->chmodPath ) {
709 $this->chmod( $fileOpHandle->chmodPath );
713 clearstatcache(); // files changed
714 return $statuses;
718 * Chmod a file, suppressing the warnings
720 * @param string $path Absolute file system path
721 * @return bool Success
723 protected function chmod( $path ) {
724 $this->trapWarnings();
725 $ok = chmod( $path, $this->fileMode );
726 $this->untrapWarnings();
728 return $ok;
732 * Return the text of an index.html file to hide directory listings
734 * @return string
736 protected function indexHtmlPrivate() {
737 return '';
741 * Return the text of a .htaccess file to make a directory private
743 * @return string
745 protected function htaccessPrivate() {
746 return "Deny from all\n";
750 * Clean up directory separators for the given OS
752 * @param string $path FS path
753 * @return string
755 protected function cleanPathSlashes( $path ) {
756 return wfIsWindows() ? strtr( $path, '/', '\\' ) : $path;
760 * Listen for E_WARNING errors and track whether any happen
762 protected function trapWarnings() {
763 $this->hadWarningErrors[] = false; // push to stack
764 set_error_handler( [ $this, 'handleWarning' ], E_WARNING );
768 * Stop listening for E_WARNING errors and return true if any happened
770 * @return bool
772 protected function untrapWarnings() {
773 restore_error_handler(); // restore previous handler
774 return array_pop( $this->hadWarningErrors ); // pop from stack
778 * @param int $errno
779 * @param string $errstr
780 * @return bool
781 * @access private
783 public function handleWarning( $errno, $errstr ) {
784 wfDebugLog( 'FSFileBackend', $errstr ); // more detailed error logging
785 $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
787 return true; // suppress from PHP handler
792 * @see FileBackendStoreOpHandle
794 class FSFileOpHandle extends FileBackendStoreOpHandle {
795 public $cmd; // string; shell command
796 public $chmodPath; // string; file to chmod
799 * @param FSFileBackend $backend
800 * @param array $params
801 * @param callable $call
802 * @param string $cmd
803 * @param int|null $chmodPath
805 public function __construct(
806 FSFileBackend $backend, array $params, $call, $cmd, $chmodPath = null
808 $this->backend = $backend;
809 $this->params = $params;
810 $this->call = $call;
811 $this->cmd = $cmd;
812 $this->chmodPath = $chmodPath;
817 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
818 * catches exception or does any custom behavoir that we may want.
819 * Do not use this class from places outside FSFileBackend.
821 * @ingroup FileBackend
823 abstract class FSFileBackendList implements Iterator {
824 /** @var Iterator */
825 protected $iter;
827 /** @var int */
828 protected $suffixStart;
830 /** @var int */
831 protected $pos = 0;
833 /** @var array */
834 protected $params = [];
837 * @param string $dir File system directory
838 * @param array $params
840 public function __construct( $dir, array $params ) {
841 $path = realpath( $dir ); // normalize
842 if ( $path === false ) {
843 $path = $dir;
845 $this->suffixStart = strlen( $path ) + 1; // size of "path/to/dir/"
846 $this->params = $params;
848 try {
849 $this->iter = $this->initIterator( $path );
850 } catch ( UnexpectedValueException $e ) {
851 $this->iter = null; // bad permissions? deleted?
856 * Return an appropriate iterator object to wrap
858 * @param string $dir File system directory
859 * @return Iterator
861 protected function initIterator( $dir ) {
862 if ( !empty( $this->params['topOnly'] ) ) { // non-recursive
863 # Get an iterator that will get direct sub-nodes
864 return new DirectoryIterator( $dir );
865 } else { // recursive
866 # Get an iterator that will return leaf nodes (non-directories)
867 # RecursiveDirectoryIterator extends FilesystemIterator.
868 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
869 $flags = FilesystemIterator::CURRENT_AS_SELF | FilesystemIterator::SKIP_DOTS;
871 return new RecursiveIteratorIterator(
872 new RecursiveDirectoryIterator( $dir, $flags ),
873 RecursiveIteratorIterator::CHILD_FIRST // include dirs
879 * @see Iterator::key()
880 * @return int
882 public function key() {
883 return $this->pos;
887 * @see Iterator::current()
888 * @return string|bool String or false
890 public function current() {
891 return $this->getRelPath( $this->iter->current()->getPathname() );
895 * @see Iterator::next()
896 * @throws FileBackendError
898 public function next() {
899 try {
900 $this->iter->next();
901 $this->filterViaNext();
902 } catch ( UnexpectedValueException $e ) { // bad permissions? deleted?
903 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
905 ++$this->pos;
909 * @see Iterator::rewind()
910 * @throws FileBackendError
912 public function rewind() {
913 $this->pos = 0;
914 try {
915 $this->iter->rewind();
916 $this->filterViaNext();
917 } catch ( UnexpectedValueException $e ) { // bad permissions? deleted?
918 throw new FileBackendError( "File iterator gave UnexpectedValueException." );
923 * @see Iterator::valid()
924 * @return bool
926 public function valid() {
927 return $this->iter && $this->iter->valid();
931 * Filter out items by advancing to the next ones
933 protected function filterViaNext() {
937 * Return only the relative path and normalize slashes to FileBackend-style.
938 * Uses the "real path" since the suffix is based upon that.
940 * @param string $dir
941 * @return string
943 protected function getRelPath( $dir ) {
944 $path = realpath( $dir );
945 if ( $path === false ) {
946 $path = $dir;
949 return strtr( substr( $path, $this->suffixStart ), '\\', '/' );
953 class FSFileBackendDirList extends FSFileBackendList {
954 protected function filterViaNext() {
955 while ( $this->iter->valid() ) {
956 if ( $this->iter->current()->isDot() || !$this->iter->current()->isDir() ) {
957 $this->iter->next(); // skip non-directories and dot files
958 } else {
959 break;
965 class FSFileBackendFileList extends FSFileBackendList {
966 protected function filterViaNext() {
967 while ( $this->iter->valid() ) {
968 if ( !$this->iter->current()->isFile() ) {
969 $this->iter->next(); // skip non-files and dot files
970 } else {
971 break;