9 * Base class for all file backend classes (including multi-write backends).
10 * This class defines the methods as abstract that subclasses must implement.
11 * Outside callers can assume that all backends will have these functions.
13 * All "storage paths" are of the format "mwstore://backend/container/path".
14 * The paths use UNIX file system (FS) notation, though any particular backend may
15 * not actually be using a local filesystem. Therefore, the paths are only virtual.
17 * Backend contents are stored under wiki-specific container names by default.
18 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
19 * segregation must be done by setting the container paths appropriately.
21 * FS-based backends are somewhat more restrictive due to the existence of real
22 * directory files; a regular file cannot have the same name as a directory. Other
23 * backends with virtual directories may not have this limitation. Callers should
24 * store files in such a way that no files and directories are under the same path.
26 * Methods should avoid throwing exceptions at all costs.
27 * As a corollary, external dependencies should be kept to a minimum.
29 * @ingroup FileBackend
32 abstract class FileBackendBase
{
33 protected $name; // unique backend name
34 protected $wikiId; // unique wiki name
35 protected $readOnly; // string
36 /** @var LockManager */
37 protected $lockManager;
40 * Create a new backend instance from configuration.
41 * This should only be called from within FileBackendGroup.
44 * 'name' : The unique name of this backend.
45 * 'wikiId' : Prefix to container names that is unique to this wiki.
46 * This should consist of alphanumberic, '-', and '_' chars.
47 * 'lockManager' : Registered name of a file lock manager to use.
48 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
49 * It should be an explanation for the backend being read-only.
51 * @param $config Array
53 public function __construct( array $config ) {
54 $this->name
= $config['name'];
55 $this->wikiId
= isset( $config['wikiId'] )
57 : wfWikiID(); // e.g. "my_wiki-en_"
58 $this->wikiId
= $this->resolveWikiId( $this->wikiId
);
59 $this->lockManager
= LockManagerGroup
::singleton()->get( $config['lockManager'] );
60 $this->readOnly
= isset( $config['readOnly'] )
61 ?
(string)$config['readOnly']
66 * Normalize a wiki ID by replacing characters that are
67 * not supported by the backend as part of container names.
69 * @param $wikiId string
72 protected function resolveWikiId( $wikiId ) {
77 * Get the unique backend name.
79 * We may have multiple different backends of the same type.
80 * For example, we can have two Swift backends using different proxies.
84 final public function getName() {
89 * This is the main entry point into the backend for write operations.
90 * Callers supply an ordered list of operations to perform as a transaction.
91 * If any serious errors occur, all attempted operations will be rolled back.
93 * $ops is an array of arrays. The outer array holds a list of operations.
94 * Each inner array is a set of key value pairs that specify an operation.
96 * Supported operations and their parameters:
97 * a) Create a new file in storage with the contents of a string
100 * 'dst' => <storage path>,
101 * 'content' => <string of new file contents>,
102 * 'overwriteDest' => <boolean>,
103 * 'overwriteSame' => <boolean>
105 * b) Copy a file system file into storage
108 * 'src' => <file system path>,
109 * 'dst' => <storage path>,
110 * 'overwriteDest' => <boolean>,
111 * 'overwriteSame' => <boolean>
113 * c) Copy a file within storage
116 * 'src' => <storage path>,
117 * 'dst' => <storage path>,
118 * 'overwriteDest' => <boolean>,
119 * 'overwriteSame' => <boolean>
121 * d) Move a file within storage
124 * 'src' => <storage path>,
125 * 'dst' => <storage path>,
126 * 'overwriteDest' => <boolean>,
127 * 'overwriteSame' => <boolean>
129 * e) Delete a file within storage
132 * 'src' => <storage path>,
133 * 'ignoreMissingSource' => <boolean>
135 * f) Do nothing (no-op)
140 * Boolean flags for operations (operation-specific):
141 * 'ignoreMissingSource' : The operation will simply succeed and do
142 * nothing if the source file does not exist.
143 * 'overwriteDest' : Any destination file will be overwritten.
144 * 'overwriteSame' : An error will not be given if a file already
145 * exists at the destination that has the same
146 * contents as the new contents to be written there.
148 * $opts is an associative of boolean flags, including:
149 * 'force' : Errors that would normally cause a rollback do not.
150 * The remaining operations are still attempted if any fail.
151 * 'nonLocking' : No locks are acquired for the operations.
152 * This can increase performance for non-critical writes.
153 * This has no effect unless the 'force' flag is set.
154 * 'allowStale' : Don't require the latest available data.
155 * This can increase performance for non-critical writes.
156 * This has no effect unless the 'force' flag is set.
159 * This returns a Status, which contains all warnings and fatals that occured
160 * during the operation. The 'failCount', 'successCount', and 'success' members
161 * will reflect each operation attempted. The status will be "OK" unless any
162 * of the operations failed and the 'force' parameter was not set.
164 * @param $ops Array List of operations to execute in order
165 * @param $opts Array Batch operation options
168 final public function doOperations( array $ops, array $opts = array() ) {
169 if ( $this->readOnly
!= '' ) {
170 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
172 if ( empty( $opts['force'] ) ) { // sanity
173 unset( $opts['nonLocking'] );
174 unset( $opts['allowStale'] );
176 return $this->doOperationsInternal( $ops, $opts );
180 * @see FileBackendBase::doOperations()
182 abstract protected function doOperationsInternal( array $ops, array $opts );
185 * Same as doOperations() except it takes a single operation.
186 * If you are doing a batch of operations that should either
187 * all succeed or all fail, then use that function instead.
189 * @see FileBackendBase::doOperations()
191 * @param $op Array Operation
192 * @param $opts Array Operation options
195 final public function doOperation( array $op, array $opts = array() ) {
196 return $this->doOperations( array( $op ), $opts );
200 * Performs a single create operation.
201 * This sets $params['op'] to 'create' and passes it to doOperation().
203 * @see FileBackendBase::doOperation()
205 * @param $params Array Operation parameters
206 * @param $opts Array Operation options
209 final public function create( array $params, array $opts = array() ) {
210 $params['op'] = 'create';
211 return $this->doOperation( $params, $opts );
215 * Performs a single store operation.
216 * This sets $params['op'] to 'store' and passes it to doOperation().
218 * @see FileBackendBase::doOperation()
220 * @param $params Array Operation parameters
221 * @param $opts Array Operation options
224 final public function store( array $params, array $opts = array() ) {
225 $params['op'] = 'store';
226 return $this->doOperation( $params, $opts );
230 * Performs a single copy operation.
231 * This sets $params['op'] to 'copy' and passes it to doOperation().
233 * @see FileBackendBase::doOperation()
235 * @param $params Array Operation parameters
236 * @param $opts Array Operation options
239 final public function copy( array $params, array $opts = array() ) {
240 $params['op'] = 'copy';
241 return $this->doOperation( $params, $opts );
245 * Performs a single move operation.
246 * This sets $params['op'] to 'move' and passes it to doOperation().
248 * @see FileBackendBase::doOperation()
250 * @param $params Array Operation parameters
251 * @param $opts Array Operation options
254 final public function move( array $params, array $opts = array() ) {
255 $params['op'] = 'move';
256 return $this->doOperation( $params, $opts );
260 * Performs a single delete operation.
261 * This sets $params['op'] to 'delete' and passes it to doOperation().
263 * @see FileBackendBase::doOperation()
265 * @param $params Array Operation parameters
266 * @param $opts Array Operation options
269 final public function delete( array $params, array $opts = array() ) {
270 $params['op'] = 'delete';
271 return $this->doOperation( $params, $opts );
275 * Concatenate a list of storage files into a single file on the file system
277 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
278 * dst : file system path to 0-byte temp file
280 * @param $params Array Operation parameters
283 abstract public function concatenate( array $params );
286 * Prepare a storage path for usage. This will create containers
287 * that don't yet exist or, on FS backends, create parent directories.
290 * dir : storage directory
292 * @param $params Array
295 final public function prepare( array $params ) {
296 if ( $this->readOnly
!= '' ) {
297 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
299 return $this->doPrepare( $params );
303 * @see FileBackendBase::prepare()
305 abstract protected function doPrepare( array $params );
308 * Take measures to block web access to a directory and
309 * the container it belongs to. FS backends might add .htaccess
310 * files wheras backends like Swift this might restrict container
311 * access to backend user that represents end-users in web request.
312 * This is not guaranteed to actually do anything.
315 * dir : storage directory
316 * noAccess : try to deny file access
317 * noListing : try to deny file listing
319 * @param $params Array
322 final public function secure( array $params ) {
323 if ( $this->readOnly
!= '' ) {
324 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
326 return $this->doSecure( $params );
330 * @see FileBackendBase::secure()
332 abstract protected function doSecure( array $params );
335 * Clean up an empty storage directory.
336 * On FS backends, the directory will be deleted. Others may do nothing.
339 * dir : storage directory
341 * @param $params Array
344 final public function clean( array $params ) {
345 if ( $this->readOnly
!= '' ) {
346 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
348 return $this->doClean( $params );
352 * @see FileBackendBase::clean()
354 abstract protected function doClean( array $params );
357 * Check if a file exists at a storage path in the backend.
358 * This returns false if only a directory exists at the path.
361 * src : source storage path
362 * latest : use the latest available data
364 * @param $params Array
365 * @return bool|null Returns null on failure
367 abstract public function fileExists( array $params );
370 * Get the last-modified timestamp of the file at a storage path.
373 * src : source storage path
374 * latest : use the latest available data
376 * @param $params Array
377 * @return string|false TS_MW timestamp or false on failure
379 abstract public function getFileTimestamp( array $params );
382 * Get the contents of a file at a storage path in the backend.
383 * This should be avoided for potentially large files.
386 * src : source storage path
387 * latest : use the latest available data
389 * @param $params Array
390 * @return string|false Returns false on failure
392 abstract public function getFileContents( array $params );
395 * Get the size (bytes) of a file at a storage path in the backend.
398 * src : source storage path
399 * latest : use the latest available data
401 * @param $params Array
402 * @return integer|false Returns false on failure
404 abstract public function getFileSize( array $params );
407 * Get quick information about a file at a storage path in the backend.
408 * If the file does not exist, then this returns false.
409 * Otherwise, the result is an associative array that includes:
410 * mtime : the last-modified timestamp (TS_MW)
411 * size : the file size (bytes)
414 * src : source storage path
415 * latest : use the latest available data
417 * @param $params Array
418 * @return Array|false|null Returns null on failure
420 abstract public function getFileStat( array $params );
423 * Get a SHA-1 hash of the file at a storage path in the backend.
426 * src : source storage path
427 * latest : use the latest available data
429 * @param $params Array
430 * @return string|false Hash string or false on failure
432 abstract public function getFileSha1Base36( array $params );
435 * Get the properties of the file at a storage path in the backend.
436 * Returns FSFile::placeholderProps() on failure.
439 * src : source storage path
440 * latest : use the latest available data
442 * @param $params Array
445 abstract public function getFileProps( array $params );
448 * Stream the file at a storage path in the backend.
449 * If the file does not exists, a 404 error will be given.
450 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
451 * must be sent if streaming began, while none should be sent otherwise.
452 * Implementations should flush the output buffer before sending data.
455 * src : source storage path
456 * headers : additional HTTP headers to send on success
457 * latest : use the latest available data
459 * @param $params Array
462 abstract public function streamFile( array $params );
465 * Returns a file system file, identical to the file at a storage path.
466 * The file returned is either:
467 * a) A local copy of the file at a storage path in the backend.
468 * The temporary copy will have the same extension as the source.
469 * b) An original of the file at a storage path in the backend.
470 * Temporary files may be purged when the file object falls out of scope.
472 * Write operations should *never* be done on this file as some backends
473 * may do internal tracking or may be instances of FileBackendMultiWrite.
474 * In that later case, there are copies of the file that must stay in sync.
477 * src : source storage path
478 * latest : use the latest available data
480 * @param $params Array
481 * @return FSFile|null Returns null on failure
483 abstract public function getLocalReference( array $params );
486 * Get a local copy on disk of the file at a storage path in the backend.
487 * The temporary copy will have the same file extension as the source.
488 * Temporary files may be purged when the file object falls out of scope.
491 * src : source storage path
492 * latest : use the latest available data
494 * @param $params Array
495 * @return TempFSFile|null Returns null on failure
497 abstract public function getLocalCopy( array $params );
500 * Get an iterator to list out all stored files under a storage directory.
501 * If the directory is of the form "mwstore://container", then all items in
502 * the container should be listed. If of the form "mwstore://container/dir",
503 * then all items under that container directory should be listed.
504 * Results should be storage paths relative to the given directory.
507 * dir : storage path directory
509 * @return Traversable|Array|null Returns null on failure
511 abstract public function getFileList( array $params );
514 * Invalidate any in-process file existence and property cache.
515 * If $paths is given, then only the cache for those files will be cleared.
517 * @param $paths Array Storage paths
520 abstract public function clearCache( array $paths = null );
523 * Lock the files at the given storage paths in the backend.
524 * This will either lock all the files or none (on failure).
526 * Callers should consider using getScopedFileLocks() instead.
528 * @param $paths Array Storage paths
529 * @param $type integer LockManager::LOCK_* constant
532 final public function lockFiles( array $paths, $type ) {
533 return $this->lockManager
->lock( $paths, $type );
537 * Unlock the files at the given storage paths in the backend.
539 * @param $paths Array Storage paths
540 * @param $type integer LockManager::LOCK_* constant
543 final public function unlockFiles( array $paths, $type ) {
544 return $this->lockManager
->unlock( $paths, $type );
548 * Lock the files at the given storage paths in the backend.
549 * This will either lock all the files or none (on failure).
550 * On failure, the status object will be updated with errors.
552 * Once the return value goes out scope, the locks will be released and
553 * the status updated. Unlock fatals will not change the status "OK" value.
555 * @param $paths Array Storage paths
556 * @param $type integer LockManager::LOCK_* constant
557 * @param $status Status Status to update on lock/unlock
558 * @return ScopedLock|null Returns null on failure
560 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
561 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
566 * Base class for all single-write backends.
567 * This class defines the methods as abstract that subclasses must implement.
568 * Callers outside of FileBackend and its helper classes, such as FileOp,
569 * should only call functions that are present in FileBackendBase.
571 * The FileBackendBase operations are implemented using primitive functions
572 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
573 * This class is also responsible for path resolution and sanitization.
575 * @ingroup FileBackend
578 abstract class FileBackend
extends FileBackendBase
{
580 protected $cache = array(); // (storage path => key => value)
581 protected $maxCacheSize = 75; // integer; max paths with entries
583 protected $shardViaHashLevels = array(); // (container name => integer)
586 * Create a file in the backend with the given contents.
587 * Do not call this function from places outside FileBackend and FileOp.
590 * content : the raw file contents
591 * dst : destination storage path
592 * overwriteDest : overwrite any file that exists at the destination
594 * @param $params Array
597 final public function createInternal( array $params ) {
598 $status = $this->doCreateInternal( $params );
599 $this->clearCache( array( $params['dst'] ) );
604 * @see FileBackend::createInternal()
606 abstract protected function doCreateInternal( array $params );
609 * Store a file into the backend from a file on disk.
610 * Do not call this function from places outside FileBackend and FileOp.
613 * src : source path on disk
614 * dst : destination storage path
615 * overwriteDest : overwrite any file that exists at the destination
617 * @param $params Array
620 final public function storeInternal( array $params ) {
621 $status = $this->doStoreInternal( $params );
622 $this->clearCache( array( $params['dst'] ) );
627 * @see FileBackend::storeInternal()
629 abstract protected function doStoreInternal( array $params );
632 * Copy a file from one storage path to another in the backend.
633 * Do not call this function from places outside FileBackend and FileOp.
636 * src : source storage path
637 * dst : destination storage path
638 * overwriteDest : overwrite any file that exists at the destination
640 * @param $params Array
643 final public function copyInternal( array $params ) {
644 $status = $this->doCopyInternal( $params );
645 $this->clearCache( array( $params['dst'] ) );
650 * @see FileBackend::copyInternal()
652 abstract protected function doCopyInternal( array $params );
655 * Delete a file at the storage path.
656 * Do not call this function from places outside FileBackend and FileOp.
659 * src : source storage path
660 * ignoreMissingSource : do nothing if the source file does not exist
662 * @param $params Array
665 final public function deleteInternal( array $params ) {
666 $status = $this->doDeleteInternal( $params );
667 $this->clearCache( array( $params['src'] ) );
672 * @see FileBackend::deleteInternal()
674 abstract protected function doDeleteInternal( array $params );
677 * Move a file from one storage path to another in the backend.
678 * Do not call this function from places outside FileBackend and FileOp.
681 * src : source storage path
682 * dst : destination storage path
683 * overwriteDest : overwrite any file that exists at the destination
685 * @param $params Array
688 final public function moveInternal( array $params ) {
689 $status = $this->doMoveInternal( $params );
690 $this->clearCache( array( $params['src'], $params['dst'] ) );
695 * @see FileBackend::moveInternal()
697 protected function doMoveInternal( array $params ) {
698 // Copy source to dest
699 $status = $this->copyInternal( $params );
700 if ( !$status->isOK() ) {
703 // Delete source (only fails due to races or medium going down)
704 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
705 $status->setResult( true, $status->value
); // ignore delete() errors
710 * @see FileBackendBase::concatenate()
712 final public function concatenate( array $params ) {
713 $status = Status
::newGood();
715 // Try to lock the source files for the scope of this function
716 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
717 if ( !$status->isOK() ) {
718 return $status; // abort
721 // Actually do the concatenation
722 $status->merge( $this->doConcatenate( $params ) );
728 * @see FileBackend::concatenate()
730 protected function doConcatenate( array $params ) {
731 $status = Status
::newGood();
732 $tmpPath = $params['dst']; // convenience
734 // Check that the specified temp file is valid...
735 wfSuppressWarnings();
736 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
738 if ( !$ok ) { // not present or not empty
739 $status->fatal( 'backend-fail-opentemp', $tmpPath );
743 // Build up the temp file using the source chunks (in order)...
744 $tmpHandle = fopen( $tmpPath, 'a' );
745 if ( $tmpHandle === false ) {
746 $status->fatal( 'backend-fail-opentemp', $tmpPath );
749 foreach ( $params['srcs'] as $virtualSource ) {
750 // Get a local FS version of the chunk
751 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
753 $status->fatal( 'backend-fail-read', $virtualSource );
756 // Get a handle to the local FS version
757 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
758 if ( $sourceHandle === false ) {
759 fclose( $tmpHandle );
760 $status->fatal( 'backend-fail-read', $virtualSource );
763 // Append chunk to file (pass chunk size to avoid magic quotes)
764 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
765 fclose( $sourceHandle );
766 fclose( $tmpHandle );
767 $status->fatal( 'backend-fail-writetemp', $tmpPath );
770 fclose( $sourceHandle );
772 if ( !fclose( $tmpHandle ) ) {
773 $status->fatal( 'backend-fail-closetemp', $tmpPath );
781 * @see FileBackendBase::doPrepare()
783 final protected function doPrepare( array $params ) {
784 $status = Status
::newGood();
785 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
786 if ( $dir === null ) {
787 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
788 return $status; // invalid storage path
790 if ( $shard !== null ) { // confined to a single container/shard
791 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
792 } else { // directory is on several shards
793 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
794 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
795 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
796 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
803 * @see FileBackend::doPrepare()
805 protected function doPrepareInternal( $container, $dir, array $params ) {
806 return Status
::newGood();
810 * @see FileBackendBase::doSecure()
812 final protected function doSecure( array $params ) {
813 $status = Status
::newGood();
814 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
815 if ( $dir === null ) {
816 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
817 return $status; // invalid storage path
819 if ( $shard !== null ) { // confined to a single container/shard
820 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
821 } else { // directory is on several shards
822 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
823 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
824 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
825 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
832 * @see FileBackend::doSecure()
834 protected function doSecureInternal( $container, $dir, array $params ) {
835 return Status
::newGood();
839 * @see FileBackendBase::doClean()
841 final protected function doClean( array $params ) {
842 $status = Status
::newGood();
843 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
844 if ( $dir === null ) {
845 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
846 return $status; // invalid storage path
848 if ( $shard !== null ) { // confined to a single container/shard
849 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
850 } else { // directory is on several shards
851 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
852 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
853 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
854 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
861 * @see FileBackend::doClean()
863 protected function doCleanInternal( $container, $dir, array $params ) {
864 return Status
::newGood();
868 * @see FileBackendBase::fileExists()
870 final public function fileExists( array $params ) {
871 $stat = $this->getFileStat( $params );
872 if ( $stat === null ) {
873 return null; // failure
879 * @see FileBackendBase::getFileTimestamp()
881 final public function getFileTimestamp( array $params ) {
882 $stat = $this->getFileStat( $params );
884 return $stat['mtime'];
891 * @see FileBackendBase::getFileSize()
893 final public function getFileSize( array $params ) {
894 $stat = $this->getFileStat( $params );
896 return $stat['size'];
903 * @see FileBackendBase::getFileStat()
905 final public function getFileStat( array $params ) {
906 $path = $params['src'];
907 if ( isset( $this->cache
[$path]['stat'] ) ) {
908 return $this->cache
[$path]['stat'];
910 $stat = $this->doGetFileStat( $params );
911 if ( is_array( $stat ) ) { // don't cache negatives
912 $this->trimCache(); // limit memory
913 $this->cache
[$path]['stat'] = $stat;
919 * @see FileBackend::getFileStat()
921 abstract protected function doGetFileStat( array $params );
924 * @see FileBackendBase::getFileContents()
926 public function getFileContents( array $params ) {
927 $tmpFile = $this->getLocalReference( $params );
931 wfSuppressWarnings();
932 $data = file_get_contents( $tmpFile->getPath() );
938 * @see FileBackendBase::getFileSha1Base36()
940 final public function getFileSha1Base36( array $params ) {
941 $path = $params['src'];
942 if ( isset( $this->cache
[$path]['sha1'] ) ) {
943 return $this->cache
[$path]['sha1'];
945 $hash = $this->doGetFileSha1Base36( $params );
946 if ( $hash ) { // don't cache negatives
947 $this->trimCache(); // limit memory
948 $this->cache
[$path]['sha1'] = $hash;
954 * @see FileBackend::getFileSha1Base36()
956 protected function doGetFileSha1Base36( array $params ) {
957 $fsFile = $this->getLocalReference( $params );
961 return $fsFile->getSha1Base36();
966 * @see FileBackendBase::getFileProps()
968 public function getFileProps( array $params ) {
969 $fsFile = $this->getLocalReference( $params );
971 return FSFile
::placeholderProps();
973 return $fsFile->getProps();
978 * @see FileBackendBase::getLocalReference()
980 public function getLocalReference( array $params ) {
981 $path = $params['src'];
982 if ( isset( $this->cache
[$path]['localRef'] ) ) {
983 return $this->cache
[$path]['localRef'];
985 $tmpFile = $this->getLocalCopy( $params );
986 if ( $tmpFile ) { // don't cache negatives
987 $this->trimCache(); // limit memory
988 $this->cache
[$path]['localRef'] = $tmpFile;
994 * @see FileBackendBase::streamFile()
996 final public function streamFile( array $params ) {
997 $status = Status
::newGood();
999 $info = $this->getFileStat( $params );
1000 if ( !$info ) { // let StreamFile handle the 404
1001 $status->fatal( 'backend-fail-notexists', $params['src'] );
1004 // Set output buffer and HTTP headers for stream
1005 $extraHeaders = $params['headers'] ?
$params['headers'] : array();
1006 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
1007 if ( $res == StreamFile
::NOT_MODIFIED
) {
1008 // do nothing; client cache is up to date
1009 } elseif ( $res == StreamFile
::READY_STREAM
) {
1010 $status = $this->doStreamFile( $params );
1012 $status->fatal( 'backend-fail-stream', $params['src'] );
1019 * @see FileBackend::streamFile()
1021 protected function doStreamFile( array $params ) {
1022 $status = Status
::newGood();
1024 $fsFile = $this->getLocalReference( $params );
1026 $status->fatal( 'backend-fail-stream', $params['src'] );
1027 } elseif ( !readfile( $fsFile->getPath() ) ) {
1028 $status->fatal( 'backend-fail-stream', $params['src'] );
1035 * @see FileBackendBase::getFileList()
1037 final public function getFileList( array $params ) {
1038 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1039 if ( $dir === null ) { // invalid storage path
1042 if ( $shard !== null ) {
1043 // File listing is confined to a single container/shard
1044 return $this->getFileListInternal( $fullCont, $dir, $params );
1046 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1047 // File listing spans multiple containers/shards
1048 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1049 return new ContainerShardListIterator( $this,
1050 $fullCont, $this->getContainerSuffixes( $shortCont ), $params );
1055 * Do not call this function from places outside FileBackend and ContainerFileListIterator
1057 * @param $container string Resolved container name
1058 * @param $dir string Resolved path relative to container
1059 * @param $params Array
1060 * @see FileBackend::getFileList()
1062 abstract public function getFileListInternal( $container, $dir, array $params );
1065 * Get the list of supported operations and their corresponding FileOp classes.
1069 protected function supportedOperations() {
1071 'store' => 'StoreFileOp',
1072 'copy' => 'CopyFileOp',
1073 'move' => 'MoveFileOp',
1074 'delete' => 'DeleteFileOp',
1075 'create' => 'CreateFileOp',
1076 'null' => 'NullFileOp'
1081 * Return a list of FileOp objects from a list of operations.
1082 * Do not call this function from places outside FileBackend.
1084 * The result must have the same number of items as the input.
1085 * An exception is thrown if an unsupported operation is requested.
1087 * @param $ops Array Same format as doOperations()
1088 * @return Array List of FileOp objects
1089 * @throws MWException
1091 final public function getOperations( array $ops ) {
1092 $supportedOps = $this->supportedOperations();
1094 $performOps = array(); // array of FileOp objects
1095 // Build up ordered array of FileOps...
1096 foreach ( $ops as $operation ) {
1097 $opName = $operation['op'];
1098 if ( isset( $supportedOps[$opName] ) ) {
1099 $class = $supportedOps[$opName];
1100 // Get params for this operation
1101 $params = $operation;
1102 // Append the FileOp class
1103 $performOps[] = new $class( $this, $params );
1105 throw new MWException( "Operation `$opName` is not supported." );
1113 * @see FileBackendBase::doOperationsInternal()
1115 protected function doOperationsInternal( array $ops, array $opts ) {
1116 $status = Status
::newGood();
1118 // Build up a list of FileOps...
1119 $performOps = $this->getOperations( $ops );
1121 // Acquire any locks as needed...
1122 if ( empty( $opts['nonLocking'] ) ) {
1123 // Build up a list of files to lock...
1124 $filesLockEx = $filesLockSh = array();
1125 foreach ( $performOps as $fileOp ) {
1126 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
1127 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
1129 // Optimization: if doing an EX lock anyway, don't also set an SH one
1130 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
1131 // Try to lock those files for the scope of this function...
1132 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
1133 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
1134 if ( !$status->isOK() ) {
1135 return $status; // abort
1139 // Clear any cache entries (after locks acquired)
1140 $this->clearCache();
1142 // Actually attempt the operation batch...
1143 $subStatus = FileOp
::attemptBatch( $performOps, $opts );
1145 // Merge errors into status fields
1146 $status->merge( $subStatus );
1147 $status->success
= $subStatus->success
; // not done in merge()
1153 * @see FileBackendBase::clearCache()
1155 final public function clearCache( array $paths = null ) {
1156 if ( $paths === null ) {
1157 $this->cache
= array();
1159 foreach ( $paths as $path ) {
1160 unset( $this->cache
[$path] );
1166 * Prune the cache if it is too big to add an item
1170 protected function trimCache() {
1171 if ( count( $this->cache
) >= $this->maxCacheSize
) {
1172 reset( $this->cache
);
1173 $key = key( $this->cache
);
1174 unset( $this->cache
[$key] );
1179 * Check if a given path is a mwstore:// path.
1180 * This does not do any actual validation or existence checks.
1182 * @param $path string
1185 final public static function isStoragePath( $path ) {
1186 return ( strpos( $path, 'mwstore://' ) === 0 );
1190 * Split a storage path (e.g. "mwstore://backend/container/path/to/object")
1191 * into a backend name, a container name, and a relative object path.
1193 * @param $storagePath string
1194 * @return Array (backend, container, rel object) or (null, null, null)
1196 final public static function splitStoragePath( $storagePath ) {
1197 if ( self
::isStoragePath( $storagePath ) ) {
1198 // Note: strlen( 'mwstore://' ) = 10
1199 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1200 if ( count( $parts ) == 3 ) {
1201 return $parts; // e.g. "backend/container/path"
1202 } elseif ( count( $parts ) == 2 ) {
1203 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1206 return array( null, null, null );
1210 * Check if a container name is valid.
1211 * This checks for for length and illegal characters.
1213 * @param $container string
1216 final protected static function isValidContainerName( $container ) {
1217 // This accounts for Swift and S3 restrictions while leaving room
1218 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1219 // Note that matching strings URL encode to the same string;
1220 // in Swift, the length resriction is *after* URL encoding.
1221 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1225 * Validate and normalize a relative storage path.
1226 * Null is returned if the path involves directory traversal.
1227 * Traversal is insecure for FS backends and broken for others.
1229 * @param $path string Storage path relative to a container
1230 * @return string|null
1232 final protected static function normalizeContainerPath( $path ) {
1233 // Normalize directory separators
1234 $path = strtr( $path, '\\', '/' );
1235 // Collapse consecutive directory separators
1236 $path = preg_replace( '![/]{2,}!', '/', $path );
1237 // Use the same traversal protection as Title::secureAndSplit()
1238 if ( strpos( $path, '.' ) !== false ) {
1242 strpos( $path, './' ) === 0 ||
1243 strpos( $path, '../' ) === 0 ||
1244 strpos( $path, '/./' ) !== false ||
1245 strpos( $path, '/../' ) !== false
1254 * Splits a storage path into an internal container name,
1255 * an internal relative file name, and a container shard suffix.
1256 * Any shard suffix is already appended to the internal container name.
1257 * This also checks that the storage path is valid and within this backend.
1259 * If the container is sharded but a suffix could not be determined,
1260 * this means that the path can only refer to a directory and can only
1261 * be scanned by looking in all the container shards.
1263 * @param $storagePath string
1264 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1266 final protected function resolveStoragePath( $storagePath ) {
1267 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1268 if ( $backend === $this->name
) { // must be for this backend
1269 $relPath = self
::normalizeContainerPath( $relPath );
1270 if ( $relPath !== null ) {
1271 // Get shard for the normalized path if this container is sharded
1272 $cShard = $this->getContainerShard( $container, $relPath );
1273 // Validate and sanitize the relative path (backend-specific)
1274 $relPath = $this->resolveContainerPath( $container, $relPath );
1275 if ( $relPath !== null ) {
1276 // Prepend any wiki ID prefix to the container name
1277 $container = $this->fullContainerName( $container );
1278 if ( self
::isValidContainerName( $container ) ) {
1279 // Validate and sanitize the container name (backend-specific)
1280 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1281 if ( $container !== null ) {
1282 return array( $container, $relPath, $cShard );
1288 return array( null, null, null );
1292 * Like resolveStoragePath() except null values are returned if
1293 * the container is sharded and the shard could not be determined.
1295 * @see FileBackend::resolveStoragePath()
1297 * @param $storagePath string
1298 * @return Array (container, path) or (null, null) if invalid
1300 final protected function resolveStoragePathReal( $storagePath ) {
1301 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1302 if ( $cShard !== null ) {
1303 return array( $container, $relPath );
1305 return array( null, null );
1309 * Get the container name shard suffix for a given path.
1310 * Any empty suffix means the container is not sharded.
1312 * @param $container string Container name
1313 * @param $relStoragePath string Storage path relative to the container
1314 * @return string|null Returns null if shard could not be determined
1316 final protected function getContainerShard( $container, $relPath ) {
1317 $hashLevels = $this->getContainerHashLevels( $container );
1318 if ( $hashLevels === 1 ) { // 16 shards per container
1319 $hashDirRegex = '(?P<shard>[0-9a-f])';
1320 } elseif ( $hashLevels === 2 ) { // 256 shards per container
1321 $hashDirRegex = '[0-9a-f]/(?P<shard>[0-9a-f]{2})';
1323 return ''; // no sharding
1325 // Allow certain directories to be above the hash dirs so as
1326 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1327 // They must be 2+ chars to avoid any hash directory ambiguity.
1328 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1329 return '.' . str_pad( $m['shard'], $hashLevels, '0', STR_PAD_LEFT
);
1331 return null; // failed to match
1335 * Get the number of hash levels for a container.
1336 * If greater than 0, then all file storage paths within
1337 * the container are required to be hashed accordingly.
1339 * @param $container string
1342 final protected function getContainerHashLevels( $container ) {
1343 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1344 $hashLevels = (int)$this->shardViaHashLevels
[$container];
1345 if ( $hashLevels >= 0 && $hashLevels <= 2 ) {
1349 return 0; // no sharding
1353 * Get a list of full container shard suffixes for a container
1355 * @param $container string
1358 final protected function getContainerSuffixes( $container ) {
1360 $digits = $this->getContainerHashLevels( $container );
1361 if ( $digits > 0 ) {
1362 $numShards = 1 << ( $digits * 4 );
1363 for ( $index = 0; $index < $numShards; $index++
) {
1364 $shards[] = '.' . str_pad( dechex( $index ), $digits, '0', STR_PAD_LEFT
);
1371 * Get the full container name, including the wiki ID prefix
1373 * @param $container string
1376 final protected function fullContainerName( $container ) {
1377 if ( $this->wikiId
!= '' ) {
1378 return "{$this->wikiId}-$container";
1385 * Resolve a container name, checking if it's allowed by the backend.
1386 * This is intended for internal use, such as encoding illegal chars.
1387 * Subclasses can override this to be more restrictive.
1389 * @param $container string
1390 * @return string|null
1392 protected function resolveContainerName( $container ) {
1397 * Resolve a relative storage path, checking if it's allowed by the backend.
1398 * This is intended for internal use, such as encoding illegal chars or perhaps
1399 * getting absolute paths (e.g. FS based backends). Note that the relative path
1400 * may be the empty string (e.g. the path is simply to the container).
1402 * @param $container string Container name
1403 * @param $relStoragePath string Storage path relative to the container
1404 * @return string|null Path or null if not valid
1406 protected function resolveContainerPath( $container, $relStoragePath ) {
1407 return $relStoragePath;
1411 * Get the final extension from a storage or FS path
1413 * @param $path string
1416 final public static function extensionFromPath( $path ) {
1417 $i = strrpos( $path, '.' );
1418 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1423 * FileBackend helper function to handle file listings that span container shards.
1424 * Do not use this class from places outside of FileBackend.
1426 * @ingroup FileBackend
1428 class ContainerShardListIterator
implements Iterator
{
1429 /* @var FileBackend */
1434 protected $shardSuffixes;
1435 protected $container; // string
1436 protected $directory; // string
1438 /* @var Traversable */
1440 protected $curShard = 0; // integer
1441 protected $pos = 0; // integer
1444 * @param $backend FileBackend
1445 * @param $container string Full storage container name
1446 * @param $dir string Storage directory relative to container
1447 * @param $suffixes Array List of container shard suffixes
1448 * @param $params Array
1450 public function __construct(
1451 FileBackend
$backend, $container, $dir, array $suffixes, array $params
1453 $this->backend
= $backend;
1454 $this->container
= $container;
1455 $this->directory
= $dir;
1456 $this->shardSuffixes
= $suffixes;
1457 $this->params
= $params;
1460 public function current() {
1461 if ( is_array( $this->iter
) ) {
1462 return current( $this->iter
);
1464 return $this->iter
->current();
1468 public function key() {
1472 public function next() {
1474 if ( is_array( $this->iter
) ) {
1475 next( $this->iter
);
1477 $this->iter
->next();
1479 // Find the next non-empty shard if no elements are left
1480 $this->nextShardIteratorIfNotValid();
1484 * If the iterator for this container shard is out of items,
1485 * then move on to the next container that has items.
1486 * If there are none, then it advances to the last container.
1488 protected function nextShardIteratorIfNotValid() {
1489 while ( !$this->valid() ) {
1490 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1491 break; // no more container shards
1493 $this->setIteratorFromCurrentShard();
1497 protected function setIteratorFromCurrentShard() {
1498 $suffix = $this->shardSuffixes
[$this->curShard
];
1499 $this->iter
= $this->backend
->getFileListInternal(
1500 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1503 public function rewind() {
1505 $this->curShard
= 0;
1506 $this->setIteratorFromCurrentShard();
1507 // Find the next non-empty shard if this one has no elements
1508 $this->nextShardIteratorIfNotValid();
1511 public function valid() {
1512 if ( $this->iter
== null ) {
1513 return false; // some failure?
1514 } elseif ( is_array( $this->iter
) ) {
1515 return ( current( $this->iter
) !== false ); // no paths can have this value
1517 return $this->iter
->valid();