ApiPageSet: Use processTitlesArray() in getRedirectTargets()
[mediawiki.git] / includes / libs / filebackend / FSFileBackend.php
blob4f0805bd2ab8b7e983ad46d0ba34d889b6df96c7
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
24 use Wikimedia\Timestamp\ConvertibleTimestamp;
26 /**
27 * @brief Class for a file system (FS) based file backend.
29 * All "containers" each map to a directory under the backend's base directory.
30 * For backwards-compatibility, some container paths can be set to custom paths.
31 * The domain ID will not be used in any custom paths, so this should be avoided.
33 * Having directories with thousands of files will diminish performance.
34 * Sharding can be accomplished by using FileRepo-style hash paths.
36 * StatusValue messages should avoid mentioning the internal FS paths.
37 * PHP warnings are assumed to be logged rather than output.
39 * @ingroup FileBackend
40 * @since 1.19
42 class FSFileBackend extends FileBackendStore {
43 /** @var string Directory holding the container directories */
44 protected $basePath;
46 /** @var array Map of container names to root paths for custom container paths */
47 protected $containerPaths = [];
49 /** @var int File permission mode */
50 protected $fileMode;
51 /** @var int File permission mode */
52 protected $dirMode;
54 /** @var string Required OS username to own files */
55 protected $fileOwner;
57 /** @var bool */
58 protected $isWindows;
59 /** @var string OS username running this script */
60 protected $currentUser;
62 /** @var array */
63 protected $hadWarningErrors = [];
65 /**
66 * @see FileBackendStore::__construct()
67 * Additional $config params include:
68 * - basePath : File system directory that holds containers.
69 * - containerPaths : Map of container names to custom file system directories.
70 * This should only be used for backwards-compatibility.
71 * - fileMode : Octal UNIX file permissions to use on files stored.
72 * - directoryMode : Octal UNIX file permissions to use on directories created.
73 * @param array $config
75 public function __construct( array $config ) {
76 parent::__construct( $config );
78 $this->isWindows = ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' );
79 // Remove any possible trailing slash from directories
80 if ( isset( $config['basePath'] ) ) {
81 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
82 } else {
83 $this->basePath = null; // none; containers must have explicit paths
86 if ( isset( $config['containerPaths'] ) ) {
87 $this->containerPaths = (array)$config['containerPaths'];
88 foreach ( $this->containerPaths as &$path ) {
89 $path = rtrim( $path, '/' ); // remove trailing slash
93 $this->fileMode = isset( $config['fileMode'] ) ? $config['fileMode'] : 0644;
94 $this->dirMode = isset( $config['directoryMode'] ) ? $config['directoryMode'] : 0777;
95 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
96 $this->fileOwner = $config['fileOwner'];
97 // cache this, assuming it doesn't change
98 $this->currentUser = posix_getpwuid( posix_getuid() )['name'];
102 public function getFeatures() {
103 return !$this->isWindows ? FileBackend::ATTR_UNICODE_PATHS : 0;
106 protected function resolveContainerPath( $container, $relStoragePath ) {
107 // Check that container has a root directory
108 if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
109 // Check for sane relative paths (assume the base paths are OK)
110 if ( $this->isLegalRelPath( $relStoragePath ) ) {
111 return $relStoragePath;
115 return null;
119 * Sanity check a relative file system path for validity
121 * @param string $path Normalized relative path
122 * @return bool
124 protected function isLegalRelPath( $path ) {
125 // Check for file names longer than 255 chars
126 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
127 return false;
129 if ( $this->isWindows ) { // NTFS
130 return !preg_match( '![:*?"<>|]!', $path );
131 } else {
132 return true;
137 * Given the short (unresolved) and full (resolved) name of
138 * a container, return the file system path of the container.
140 * @param string $shortCont
141 * @param string $fullCont
142 * @return string|null
144 protected function containerFSRoot( $shortCont, $fullCont ) {
145 if ( isset( $this->containerPaths[$shortCont] ) ) {
146 return $this->containerPaths[$shortCont];
147 } elseif ( isset( $this->basePath ) ) {
148 return "{$this->basePath}/{$fullCont}";
151 return null; // no container base path defined
155 * Get the absolute file system path for a storage path
157 * @param string $storagePath Storage path
158 * @return string|null
160 protected function resolveToFSPath( $storagePath ) {
161 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
162 if ( $relPath === null ) {
163 return null; // invalid
165 list( , $shortCont, ) = FileBackend::splitStoragePath( $storagePath );
166 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
167 if ( $relPath != '' ) {
168 $fsPath .= "/{$relPath}";
171 return $fsPath;
174 public function isPathUsableInternal( $storagePath ) {
175 $fsPath = $this->resolveToFSPath( $storagePath );
176 if ( $fsPath === null ) {
177 return false; // invalid
179 $parentDir = dirname( $fsPath );
181 if ( file_exists( $fsPath ) ) {
182 $ok = is_file( $fsPath ) && is_writable( $fsPath );
183 } else {
184 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
187 if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
188 $ok = false;
189 trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
192 return $ok;
195 protected function doCreateInternal( array $params ) {
196 $status = $this->newStatus();
198 $dest = $this->resolveToFSPath( $params['dst'] );
199 if ( $dest === null ) {
200 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
202 return $status;
205 if ( !empty( $params['async'] ) ) { // deferred
206 $tempFile = TempFSFile::factory( 'create_', 'tmp', $this->tmpDirectory );
207 if ( !$tempFile ) {
208 $status->fatal( 'backend-fail-create', $params['dst'] );
210 return $status;
212 $this->trapWarnings();
213 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
214 $this->untrapWarnings();
215 if ( $bytes === false ) {
216 $status->fatal( 'backend-fail-create', $params['dst'] );
218 return $status;
220 $cmd = implode( ' ', [
221 $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
222 escapeshellarg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
223 escapeshellarg( $this->cleanPathSlashes( $dest ) )
224 ] );
225 $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
226 if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
227 $status->fatal( 'backend-fail-create', $params['dst'] );
228 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
231 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
232 $tempFile->bind( $status->value );
233 } else { // immediate write
234 $this->trapWarnings();
235 $bytes = file_put_contents( $dest, $params['content'] );
236 $this->untrapWarnings();
237 if ( $bytes === false ) {
238 $status->fatal( 'backend-fail-create', $params['dst'] );
240 return $status;
242 $this->chmod( $dest );
245 return $status;
248 protected function doStoreInternal( array $params ) {
249 $status = $this->newStatus();
251 $dest = $this->resolveToFSPath( $params['dst'] );
252 if ( $dest === null ) {
253 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
255 return $status;
258 if ( !empty( $params['async'] ) ) { // deferred
259 $cmd = implode( ' ', [
260 $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
261 escapeshellarg( $this->cleanPathSlashes( $params['src'] ) ),
262 escapeshellarg( $this->cleanPathSlashes( $dest ) )
263 ] );
264 $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
265 if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
266 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
267 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
270 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
271 } else { // immediate write
272 $this->trapWarnings();
273 $ok = copy( $params['src'], $dest );
274 $this->untrapWarnings();
275 // In some cases (at least over NFS), copy() returns true when it fails
276 if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
277 if ( $ok ) { // PHP bug
278 unlink( $dest ); // remove broken file
279 trigger_error( __METHOD__ . ": copy() failed but returned true." );
281 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
283 return $status;
285 $this->chmod( $dest );
288 return $status;
291 protected function doCopyInternal( array $params ) {
292 $status = $this->newStatus();
294 $source = $this->resolveToFSPath( $params['src'] );
295 if ( $source === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
298 return $status;
301 $dest = $this->resolveToFSPath( $params['dst'] );
302 if ( $dest === null ) {
303 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
305 return $status;
308 if ( !is_file( $source ) ) {
309 if ( empty( $params['ignoreMissingSource'] ) ) {
310 $status->fatal( 'backend-fail-copy', $params['src'] );
313 return $status; // do nothing; either OK or bad status
316 if ( !empty( $params['async'] ) ) { // deferred
317 $cmd = implode( ' ', [
318 $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
319 escapeshellarg( $this->cleanPathSlashes( $source ) ),
320 escapeshellarg( $this->cleanPathSlashes( $dest ) )
321 ] );
322 $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
323 if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
324 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
325 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
328 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
329 } else { // immediate write
330 $this->trapWarnings();
331 $ok = ( $source === $dest ) ? true : copy( $source, $dest );
332 $this->untrapWarnings();
333 // In some cases (at least over NFS), copy() returns true when it fails
334 if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
335 if ( $ok ) { // PHP bug
336 $this->trapWarnings();
337 unlink( $dest ); // remove broken file
338 $this->untrapWarnings();
339 trigger_error( __METHOD__ . ": copy() failed but returned true." );
341 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
343 return $status;
345 $this->chmod( $dest );
348 return $status;
351 protected function doMoveInternal( array $params ) {
352 $status = $this->newStatus();
354 $source = $this->resolveToFSPath( $params['src'] );
355 if ( $source === null ) {
356 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
358 return $status;
361 $dest = $this->resolveToFSPath( $params['dst'] );
362 if ( $dest === null ) {
363 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
365 return $status;
368 if ( !is_file( $source ) ) {
369 if ( empty( $params['ignoreMissingSource'] ) ) {
370 $status->fatal( 'backend-fail-move', $params['src'] );
373 return $status; // do nothing; either OK or bad status
376 if ( !empty( $params['async'] ) ) { // deferred
377 $cmd = implode( ' ', [
378 $this->isWindows ? 'MOVE /Y' : 'mv', // (overwrite)
379 escapeshellarg( $this->cleanPathSlashes( $source ) ),
380 escapeshellarg( $this->cleanPathSlashes( $dest ) )
381 ] );
382 $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
383 if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
384 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
385 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
388 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
389 } else { // immediate write
390 $this->trapWarnings();
391 $ok = ( $source === $dest ) ? true : rename( $source, $dest );
392 $this->untrapWarnings();
393 clearstatcache(); // file no longer at source
394 if ( !$ok ) {
395 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
397 return $status;
401 return $status;
404 protected function doDeleteInternal( array $params ) {
405 $status = $this->newStatus();
407 $source = $this->resolveToFSPath( $params['src'] );
408 if ( $source === null ) {
409 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
411 return $status;
414 if ( !is_file( $source ) ) {
415 if ( empty( $params['ignoreMissingSource'] ) ) {
416 $status->fatal( 'backend-fail-delete', $params['src'] );
419 return $status; // do nothing; either OK or bad status
422 if ( !empty( $params['async'] ) ) { // deferred
423 $cmd = implode( ' ', [
424 $this->isWindows ? 'DEL' : 'unlink',
425 escapeshellarg( $this->cleanPathSlashes( $source ) )
426 ] );
427 $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
428 if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
429 $status->fatal( 'backend-fail-delete', $params['src'] );
430 trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
433 $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
434 } else { // immediate write
435 $this->trapWarnings();
436 $ok = unlink( $source );
437 $this->untrapWarnings();
438 if ( !$ok ) {
439 $status->fatal( 'backend-fail-delete', $params['src'] );
441 return $status;
445 return $status;
449 * @param string $fullCont
450 * @param string $dirRel
451 * @param array $params
452 * @return StatusValue
454 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
455 $status = $this->newStatus();
456 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
457 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
458 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
459 $existed = is_dir( $dir ); // already there?
460 // Create the directory and its parents as needed...
461 $this->trapWarnings();
462 if ( !$existed && !mkdir( $dir, $this->dirMode, true ) && !is_dir( $dir ) ) {
463 $this->logger->error( __METHOD__ . ": cannot create directory $dir" );
464 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
465 } elseif ( !is_writable( $dir ) ) {
466 $this->logger->error( __METHOD__ . ": directory $dir is read-only" );
467 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
468 } elseif ( !is_readable( $dir ) ) {
469 $this->logger->error( __METHOD__ . ": directory $dir is not readable" );
470 $status->fatal( 'directorynotreadableerror', $params['dir'] );
472 $this->untrapWarnings();
473 // Respect any 'noAccess' or 'noListing' flags...
474 if ( is_dir( $dir ) && !$existed ) {
475 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
478 return $status;
481 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
482 $status = $this->newStatus();
483 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
484 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
485 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
486 // Seed new directories with a blank index.html, to prevent crawling...
487 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
488 $this->trapWarnings();
489 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
490 $this->untrapWarnings();
491 if ( $bytes === false ) {
492 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
495 // Add a .htaccess file to the root of the container...
496 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
497 $this->trapWarnings();
498 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
499 $this->untrapWarnings();
500 if ( $bytes === false ) {
501 $storeDir = "mwstore://{$this->name}/{$shortCont}";
502 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
506 return $status;
509 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
510 $status = $this->newStatus();
511 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
512 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
513 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
514 // Unseed new directories with a blank index.html, to allow crawling...
515 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
516 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
517 $this->trapWarnings();
518 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
519 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
521 $this->untrapWarnings();
523 // Remove the .htaccess file from the root of the container...
524 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
525 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
526 $this->trapWarnings();
527 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
528 $storeDir = "mwstore://{$this->name}/{$shortCont}";
529 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
531 $this->untrapWarnings();
534 return $status;
537 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
538 $status = $this->newStatus();
539 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
540 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
541 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
542 $this->trapWarnings();
543 if ( is_dir( $dir ) ) {
544 rmdir( $dir ); // remove directory if empty
546 $this->untrapWarnings();
548 return $status;
551 protected function doGetFileStat( array $params ) {
552 $source = $this->resolveToFSPath( $params['src'] );
553 if ( $source === null ) {
554 return false; // invalid storage path
557 $this->trapWarnings(); // don't trust 'false' if there were errors
558 $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
559 $hadError = $this->untrapWarnings();
561 if ( $stat ) {
562 $ct = new ConvertibleTimestamp( $stat['mtime'] );
564 return [
565 'mtime' => $ct->getTimestamp( TS_MW ),
566 'size' => $stat['size']
568 } elseif ( !$hadError ) {
569 return false; // file does not exist
570 } else {
571 return null; // failure
575 protected function doClearCache( array $paths = null ) {
576 clearstatcache(); // clear the PHP file stat cache
579 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
580 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
581 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
582 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
584 $this->trapWarnings(); // don't trust 'false' if there were errors
585 $exists = is_dir( $dir );
586 $hadError = $this->untrapWarnings();
588 return $hadError ? null : $exists;
592 * @see FileBackendStore::getDirectoryListInternal()
593 * @param string $fullCont
594 * @param string $dirRel
595 * @param array $params
596 * @return array|FSFileBackendDirList|null
598 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
599 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
600 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
601 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
602 $exists = is_dir( $dir );
603 if ( !$exists ) {
604 $this->logger->warning( __METHOD__ . "() given directory does not exist: '$dir'\n" );
606 return []; // nothing under this dir
607 } elseif ( !is_readable( $dir ) ) {
608 $this->logger->warning( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
610 return null; // bad permissions?
613 return new FSFileBackendDirList( $dir, $params );
617 * @see FileBackendStore::getFileListInternal()
618 * @param string $fullCont
619 * @param string $dirRel
620 * @param array $params
621 * @return array|FSFileBackendFileList|null
623 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
624 list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
625 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
626 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
627 $exists = is_dir( $dir );
628 if ( !$exists ) {
629 $this->logger->warning( __METHOD__ . "() given directory does not exist: '$dir'\n" );
631 return []; // nothing under this dir
632 } elseif ( !is_readable( $dir ) ) {
633 $this->logger->warning( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
635 return null; // bad permissions?
638 return new FSFileBackendFileList( $dir, $params );
641 protected function doGetLocalReferenceMulti( array $params ) {
642 $fsFiles = []; // (path => FSFile)
644 foreach ( $params['srcs'] as $src ) {
645 $source = $this->resolveToFSPath( $src );
646 if ( $source === null || !is_file( $source ) ) {
647 $fsFiles[$src] = null; // invalid path or file does not exist
648 } else {
649 $fsFiles[$src] = new FSFile( $source );
653 return $fsFiles;
656 protected function doGetLocalCopyMulti( array $params ) {
657 $tmpFiles = []; // (path => TempFSFile)
659 foreach ( $params['srcs'] as $src ) {
660 $source = $this->resolveToFSPath( $src );
661 if ( $source === null ) {
662 $tmpFiles[$src] = null; // invalid path
663 } else {
664 // Create a new temporary file with the same extension...
665 $ext = FileBackend::extensionFromPath( $src );
666 $tmpFile = TempFSFile::factory( 'localcopy_', $ext, $this->tmpDirectory );
667 if ( !$tmpFile ) {
668 $tmpFiles[$src] = null;
669 } else {
670 $tmpPath = $tmpFile->getPath();
671 // Copy the source file over the temp file
672 $this->trapWarnings();
673 $ok = copy( $source, $tmpPath );
674 $this->untrapWarnings();
675 if ( !$ok ) {
676 $tmpFiles[$src] = null;
677 } else {
678 $this->chmod( $tmpPath );
679 $tmpFiles[$src] = $tmpFile;
685 return $tmpFiles;
688 protected function directoriesAreVirtual() {
689 return false;
693 * @param FSFileOpHandle[] $fileOpHandles
695 * @return StatusValue[]
697 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
698 $statuses = [];
700 $pipes = [];
701 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
702 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
705 $errs = [];
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 = $this->newStatus();
715 $function = $fileOpHandle->call;
716 $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 $this->isWindows ? 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( [ $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 $this->logger->error( $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 callable $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 = [];
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;