Fixed undefined defines warnings introduced in change 5131
[mediawiki.git] / includes / filerepo / backend / FSFileBackend.php
blob4a27ca117dd85dedd1ce5a0c8b55bff0274c64ad
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 * @author Aaron Schulz
6 */
8 /**
9 * @brief Class for a file system (FS) based file backend.
11 * All "containers" each map to a directory under the backend's base directory.
12 * For backwards-compatibility, some container paths can be set to custom paths.
13 * The wiki ID will not be used in any custom paths, so this should be avoided.
15 * Having directories with thousands of files will diminish performance.
16 * Sharding can be accomplished by using FileRepo-style hash paths.
18 * Status messages should avoid mentioning the internal FS paths.
19 * PHP warnings are assumed to be logged rather than output.
21 * @ingroup FileBackend
22 * @since 1.19
24 class FSFileBackend extends FileBackendStore {
25 protected $basePath; // string; directory holding the container directories
26 /** @var Array Map of container names to root paths */
27 protected $containerPaths = array(); // for custom container paths
28 protected $fileMode; // integer; file permission mode
30 protected $hadWarningErrors = array();
32 /**
33 * @see FileBackendStore::__construct()
34 * Additional $config params include:
35 * basePath : File system directory that holds containers.
36 * containerPaths : Map of container names to custom file system directories.
37 * This should only be used for backwards-compatibility.
38 * fileMode : Octal UNIX file permissions to use on files stored.
40 public function __construct( array $config ) {
41 parent::__construct( $config );
43 // Remove any possible trailing slash from directories
44 if ( isset( $config['basePath'] ) ) {
45 $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
46 } else {
47 $this->basePath = null; // none; containers must have explicit paths
50 if ( isset( $config['containerPaths'] ) ) {
51 $this->containerPaths = (array)$config['containerPaths'];
52 foreach ( $this->containerPaths as &$path ) {
53 $path = rtrim( $path, '/' ); // remove trailing slash
57 $this->fileMode = isset( $config['fileMode'] )
58 ? $config['fileMode']
59 : 0644;
62 /**
63 * @see FileBackendStore::resolveContainerPath()
64 * @return null|string
66 protected function resolveContainerPath( $container, $relStoragePath ) {
67 // Check that container has a root directory
68 if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
69 // Check for sane relative paths (assume the base paths are OK)
70 if ( $this->isLegalRelPath( $relStoragePath ) ) {
71 return $relStoragePath;
74 return null;
77 /**
78 * Sanity check a relative file system path for validity
80 * @param $path string Normalized relative path
81 * @return bool
83 protected function isLegalRelPath( $path ) {
84 // Check for file names longer than 255 chars
85 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
86 return false;
88 if ( wfIsWindows() ) { // NTFS
89 return !preg_match( '![:*?"<>|]!', $path );
90 } else {
91 return true;
95 /**
96 * Given the short (unresolved) and full (resolved) name of
97 * a container, return the file system path of the container.
99 * @param $shortCont string
100 * @param $fullCont string
101 * @return string|null
103 protected function containerFSRoot( $shortCont, $fullCont ) {
104 if ( isset( $this->containerPaths[$shortCont] ) ) {
105 return $this->containerPaths[$shortCont];
106 } elseif ( isset( $this->basePath ) ) {
107 return "{$this->basePath}/{$fullCont}";
109 return null; // no container base path defined
113 * Get the absolute file system path for a storage path
115 * @param $storagePath string Storage path
116 * @return string|null
118 protected function resolveToFSPath( $storagePath ) {
119 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
120 if ( $relPath === null ) {
121 return null; // invalid
123 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $storagePath );
124 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
125 if ( $relPath != '' ) {
126 $fsPath .= "/{$relPath}";
128 return $fsPath;
132 * @see FileBackendStore::isPathUsableInternal()
133 * @return bool
135 public function isPathUsableInternal( $storagePath ) {
136 $fsPath = $this->resolveToFSPath( $storagePath );
137 if ( $fsPath === null ) {
138 return false; // invalid
140 $parentDir = dirname( $fsPath );
142 if ( file_exists( $fsPath ) ) {
143 $ok = is_file( $fsPath ) && is_writable( $fsPath );
144 } else {
145 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
148 return $ok;
152 * @see FileBackendStore::doStoreInternal()
153 * @return Status
155 protected function doStoreInternal( array $params ) {
156 $status = Status::newGood();
158 $dest = $this->resolveToFSPath( $params['dst'] );
159 if ( $dest === null ) {
160 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
161 return $status;
164 if ( file_exists( $dest ) ) {
165 if ( !empty( $params['overwrite'] ) ) {
166 $ok = unlink( $dest );
167 if ( !$ok ) {
168 $status->fatal( 'backend-fail-delete', $params['dst'] );
169 return $status;
171 } else {
172 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
173 return $status;
177 $ok = copy( $params['src'], $dest );
178 if ( !$ok ) {
179 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
180 return $status;
183 $this->chmod( $dest );
185 return $status;
189 * @see FileBackendStore::doCopyInternal()
190 * @return Status
192 protected function doCopyInternal( array $params ) {
193 $status = Status::newGood();
195 $source = $this->resolveToFSPath( $params['src'] );
196 if ( $source === null ) {
197 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
198 return $status;
201 $dest = $this->resolveToFSPath( $params['dst'] );
202 if ( $dest === null ) {
203 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
204 return $status;
207 if ( file_exists( $dest ) ) {
208 if ( !empty( $params['overwrite'] ) ) {
209 $ok = unlink( $dest );
210 if ( !$ok ) {
211 $status->fatal( 'backend-fail-delete', $params['dst'] );
212 return $status;
214 } else {
215 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
216 return $status;
220 $ok = copy( $source, $dest );
221 if ( !$ok ) {
222 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
223 return $status;
226 $this->chmod( $dest );
228 return $status;
232 * @see FileBackendStore::doMoveInternal()
233 * @return Status
235 protected function doMoveInternal( array $params ) {
236 $status = Status::newGood();
238 $source = $this->resolveToFSPath( $params['src'] );
239 if ( $source === null ) {
240 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
241 return $status;
244 $dest = $this->resolveToFSPath( $params['dst'] );
245 if ( $dest === null ) {
246 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
247 return $status;
250 if ( file_exists( $dest ) ) {
251 if ( !empty( $params['overwrite'] ) ) {
252 // Windows does not support moving over existing files
253 if ( wfIsWindows() ) {
254 $ok = unlink( $dest );
255 if ( !$ok ) {
256 $status->fatal( 'backend-fail-delete', $params['dst'] );
257 return $status;
260 } else {
261 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
262 return $status;
266 $ok = rename( $source, $dest );
267 clearstatcache(); // file no longer at source
268 if ( !$ok ) {
269 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
270 return $status;
273 return $status;
277 * @see FileBackendStore::doDeleteInternal()
278 * @return Status
280 protected function doDeleteInternal( array $params ) {
281 $status = Status::newGood();
283 $source = $this->resolveToFSPath( $params['src'] );
284 if ( $source === null ) {
285 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
286 return $status;
289 if ( !is_file( $source ) ) {
290 if ( empty( $params['ignoreMissingSource'] ) ) {
291 $status->fatal( 'backend-fail-delete', $params['src'] );
293 return $status; // do nothing; either OK or bad status
296 $ok = unlink( $source );
297 if ( !$ok ) {
298 $status->fatal( 'backend-fail-delete', $params['src'] );
299 return $status;
302 return $status;
306 * @see FileBackendStore::doCreateInternal()
307 * @return Status
309 protected function doCreateInternal( array $params ) {
310 $status = Status::newGood();
312 $dest = $this->resolveToFSPath( $params['dst'] );
313 if ( $dest === null ) {
314 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
315 return $status;
318 if ( file_exists( $dest ) ) {
319 if ( !empty( $params['overwrite'] ) ) {
320 $ok = unlink( $dest );
321 if ( !$ok ) {
322 $status->fatal( 'backend-fail-delete', $params['dst'] );
323 return $status;
325 } else {
326 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
327 return $status;
331 $bytes = file_put_contents( $dest, $params['content'] );
332 if ( $bytes === false ) {
333 $status->fatal( 'backend-fail-create', $params['dst'] );
334 return $status;
337 $this->chmod( $dest );
339 return $status;
343 * @see FileBackendStore::doPrepareInternal()
344 * @return Status
346 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
347 $status = Status::newGood();
348 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
349 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
350 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
351 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
352 $status->fatal( 'directorycreateerror', $params['dir'] );
353 } elseif ( !is_writable( $dir ) ) {
354 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
355 } elseif ( !is_readable( $dir ) ) {
356 $status->fatal( 'directorynotreadableerror', $params['dir'] );
358 return $status;
362 * @see FileBackendStore::doSecureInternal()
363 * @return Status
365 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
366 $status = Status::newGood();
367 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
368 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
369 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
370 // Seed new directories with a blank index.html, to prevent crawling...
371 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
372 $bytes = file_put_contents( "{$dir}/index.html", '' );
373 if ( !$bytes ) {
374 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
375 return $status;
378 // Add a .htaccess file to the root of the container...
379 if ( !empty( $params['noAccess'] ) ) {
380 if ( !file_exists( "{$contRoot}/.htaccess" ) ) {
381 $bytes = file_put_contents( "{$contRoot}/.htaccess", "Deny from all\n" );
382 if ( !$bytes ) {
383 $storeDir = "mwstore://{$this->name}/{$shortCont}";
384 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
385 return $status;
389 return $status;
393 * @see FileBackendStore::doCleanInternal()
394 * @return Status
396 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
397 $status = Status::newGood();
398 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
399 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
400 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
401 wfSuppressWarnings();
402 if ( is_dir( $dir ) ) {
403 rmdir( $dir ); // remove directory if empty
405 wfRestoreWarnings();
406 return $status;
410 * @see FileBackendStore::doFileExists()
411 * @return array|bool|null
413 protected function doGetFileStat( array $params ) {
414 $source = $this->resolveToFSPath( $params['src'] );
415 if ( $source === null ) {
416 return false; // invalid storage path
419 $this->trapWarnings(); // don't trust 'false' if there were errors
420 $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
421 $hadError = $this->untrapWarnings();
423 if ( $stat ) {
424 return array(
425 'mtime' => wfTimestamp( TS_MW, $stat['mtime'] ),
426 'size' => $stat['size']
428 } elseif ( !$hadError ) {
429 return false; // file does not exist
430 } else {
431 return null; // failure
436 * @see FileBackendStore::doClearCache()
438 protected function doClearCache( array $paths = null ) {
439 clearstatcache(); // clear the PHP file stat cache
443 * @see FileBackendStore::getFileListInternal()
444 * @return array|FSFileBackendFileList|null
446 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
447 list( $b, $shortCont, $r ) = FileBackend::splitStoragePath( $params['dir'] );
448 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
449 $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
450 $exists = is_dir( $dir );
451 if ( !$exists ) {
452 wfDebug( __METHOD__ . "() given directory does not exist: '$dir'\n" );
453 return array(); // nothing under this dir
455 $readable = is_readable( $dir );
456 if ( !$readable ) {
457 wfDebug( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
458 return null; // bad permissions?
460 return new FSFileBackendFileList( $dir );
464 * @see FileBackendStore::getLocalReference()
465 * @return FSFile|null
467 public function getLocalReference( array $params ) {
468 $source = $this->resolveToFSPath( $params['src'] );
469 if ( $source === null ) {
470 return null;
472 return new FSFile( $source );
476 * @see FileBackendStore::getLocalCopy()
477 * @return null|TempFSFile
479 public function getLocalCopy( array $params ) {
480 $source = $this->resolveToFSPath( $params['src'] );
481 if ( $source === null ) {
482 return null;
485 // Create a new temporary file with the same extension...
486 $ext = FileBackend::extensionFromPath( $params['src'] );
487 $tmpFile = TempFSFile::factory( wfBaseName( $source ) . '_', $ext );
488 if ( !$tmpFile ) {
489 return null;
491 $tmpPath = $tmpFile->getPath();
493 // Copy the source file over the temp file
494 $ok = copy( $source, $tmpPath );
495 if ( !$ok ) {
496 return null;
499 $this->chmod( $tmpPath );
501 return $tmpFile;
505 * Chmod a file, suppressing the warnings
507 * @param $path string Absolute file system path
508 * @return bool Success
510 protected function chmod( $path ) {
511 wfSuppressWarnings();
512 $ok = chmod( $path, $this->fileMode );
513 wfRestoreWarnings();
515 return $ok;
519 * Listen for E_WARNING errors and track whether any happen
521 * @return bool
523 protected function trapWarnings() {
524 $this->hadWarningErrors[] = false; // push to stack
525 set_error_handler( array( $this, 'handleWarning' ), E_WARNING );
526 return false; // invoke normal PHP error handler
530 * Stop listening for E_WARNING errors and return true if any happened
532 * @return bool
534 protected function untrapWarnings() {
535 restore_error_handler(); // restore previous handler
536 return array_pop( $this->hadWarningErrors ); // pop from stack
539 private function handleWarning() {
540 $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
541 return true; // suppress from PHP handler
546 * Wrapper around RecursiveDirectoryIterator that catches
547 * exception or does any custom behavoir that we may want.
548 * Do not use this class from places outside FSFileBackend.
550 * @ingroup FileBackend
552 class FSFileBackendFileList implements Iterator {
553 /** @var RecursiveIteratorIterator */
554 protected $iter;
555 protected $suffixStart; // integer
556 protected $pos = 0; // integer
559 * @param $dir string file system directory
561 public function __construct( $dir ) {
562 $dir = realpath( $dir ); // normalize
563 $this->suffixStart = strlen( $dir ) + 1; // size of "path/to/dir/"
564 try {
565 # Get an iterator that will return leaf nodes (non-directories)
566 if ( MWInit::classExists( 'FilesystemIterator' ) ) { // PHP >= 5.3
567 # RecursiveDirectoryIterator extends FilesystemIterator.
568 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
569 $flags = FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS;
570 $this->iter = new RecursiveIteratorIterator(
571 new RecursiveDirectoryIterator( $dir, $flags ) );
572 } else { // PHP < 5.3
573 # RecursiveDirectoryIterator extends DirectoryIterator
574 $this->iter = new RecursiveIteratorIterator(
575 new RecursiveDirectoryIterator( $dir ) );
577 } catch ( UnexpectedValueException $e ) {
578 $this->iter = null; // bad permissions? deleted?
583 * @see Iterator::current()
584 * @return string|bool String or false
586 public function current() {
587 // Return only the relative path and normalize slashes to FileBackend-style
588 // Make sure to use the realpath since the suffix is based upon that
589 return str_replace( '\\', '/',
590 substr( realpath( $this->iter->current() ), $this->suffixStart ) );
594 * @see Iterator::key()
595 * @return integer
597 public function key() {
598 return $this->pos;
602 * @see Iterator::next()
603 * @return void
605 public function next() {
606 try {
607 $this->iter->next();
608 } catch ( UnexpectedValueException $e ) {
609 $this->iter = null;
611 ++$this->pos;
615 * @see Iterator::rewind()
616 * @return void
618 public function rewind() {
619 $this->pos = 0;
620 try {
621 $this->iter->rewind();
622 } catch ( UnexpectedValueException $e ) {
623 $this->iter = null;
628 * @see Iterator::valid()
629 * @return bool
631 public function valid() {
632 return $this->iter && $this->iter->valid();