3 * @defgroup FileBackend File backend
6 * File backend is used to interact with file management systems such as SWIFT.
12 * @ingroup FileBackend
13 * @author Aaron Schulz
17 * Base class for all file backend classes (including multi-write backends).
19 * This class defines the methods as abstract that subclasses must implement.
20 * Outside callers can assume that all backends will have these functions.
22 * All "storage paths" are of the format "mwstore://backend/container/path".
23 * The paths use UNIX file system (FS) notation, though any particular backend may
24 * not actually be using a local filesystem. Therefore, the paths are only virtual.
26 * Backend contents are stored under wiki-specific container names by default.
27 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
28 * segregation must be done by setting the container paths appropriately.
30 * FS-based backends are somewhat more restrictive due to the existence of real
31 * directory files; a regular file cannot have the same name as a directory. Other
32 * backends with virtual directories may not have this limitation. Callers should
33 * store files in such a way that no files and directories are under the same path.
35 * Methods should avoid throwing exceptions at all costs.
36 * As a corollary, external dependencies should be kept to a minimum.
38 * @ingroup FileBackend
41 abstract class FileBackend
{
42 protected $name; // string; unique backend name
43 protected $wikiId; // string; unique wiki name
44 protected $readOnly; // string; read-only explanation message
45 /** @var LockManager */
46 protected $lockManager;
49 * Create a new backend instance from configuration.
50 * This should only be called from within FileBackendGroup.
53 * 'name' : The unique name of this backend.
54 * This should consist of alphanumberic, '-', and '_' characters.
55 * 'wikiId' : Prefix to container names that is unique to this wiki.
56 * This should consist of alphanumberic, '-', and '_' characters.
57 * 'lockManager' : Registered name of a file lock manager to use.
58 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
59 * It should be an explanation for the backend being read-only.
61 * @param $config Array
63 public function __construct( array $config ) {
64 $this->name
= $config['name'];
65 $this->wikiId
= isset( $config['wikiId'] )
67 : wfWikiID(); // e.g. "my_wiki-en_"
68 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
69 ?
$config['lockManager']
70 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
71 $this->readOnly
= isset( $config['readOnly'] )
72 ?
(string)$config['readOnly']
77 * Get the unique backend name.
78 * We may have multiple different backends of the same type.
79 * For example, we can have two Swift backends using different proxies.
83 final public function getName() {
88 * Check if this backend is read-only
92 final public function isReadOnly() {
93 return ( $this->readOnly
!= '' );
97 * Get an explanatory message if this backend is read-only
99 * @return string|false Returns falls if the backend is not read-only
101 final public function getReadOnlyReason() {
102 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
106 * This is the main entry point into the backend for write operations.
107 * Callers supply an ordered list of operations to perform as a transaction.
108 * Files will be locked, the stat cache cleared, and then the operations attempted.
109 * If any serious errors occur, all attempted operations will be rolled back.
111 * $ops is an array of arrays. The outer array holds a list of operations.
112 * Each inner array is a set of key value pairs that specify an operation.
114 * Supported operations and their parameters:
115 * a) Create a new file in storage with the contents of a string
118 * 'dst' => <storage path>,
119 * 'content' => <string of new file contents>,
120 * 'overwrite' => <boolean>,
121 * 'overwriteSame' => <boolean>
123 * b) Copy a file system file into storage
126 * 'src' => <file system path>,
127 * 'dst' => <storage path>,
128 * 'overwrite' => <boolean>,
129 * 'overwriteSame' => <boolean>
131 * c) Copy a file within storage
134 * 'src' => <storage path>,
135 * 'dst' => <storage path>,
136 * 'overwrite' => <boolean>,
137 * 'overwriteSame' => <boolean>
139 * d) Move a file within storage
142 * 'src' => <storage path>,
143 * 'dst' => <storage path>,
144 * 'overwrite' => <boolean>,
145 * 'overwriteSame' => <boolean>
147 * e) Delete a file within storage
150 * 'src' => <storage path>,
151 * 'ignoreMissingSource' => <boolean>
153 * f) Do nothing (no-op)
158 * Boolean flags for operations (operation-specific):
159 * 'ignoreMissingSource' : The operation will simply succeed and do
160 * nothing if the source file does not exist.
161 * 'overwrite' : Any destination file will be overwritten.
162 * 'overwriteSame' : An error will not be given if a file already
163 * exists at the destination that has the same
164 * contents as the new contents to be written there.
166 * $opts is an associative of boolean flags, including:
167 * 'force' : Errors that would normally cause a rollback do not.
168 * The remaining operations are still attempted if any fail.
169 * 'nonLocking' : No locks are acquired for the operations.
170 * This can increase performance for non-critical writes.
171 * This has no effect unless the 'force' flag is set.
172 * 'allowStale' : Don't require the latest available data.
173 * This can increase performance for non-critical writes.
174 * This has no effect unless the 'force' flag is set.
176 * Remarks on locking:
177 * File system paths given to operations should refer to files that are
178 * already locked or otherwise safe from modification from other processes.
179 * Normally these files will be new temp files, which should be adequate.
182 * This returns a Status, which contains all warnings and fatals that occured
183 * during the operation. The 'failCount', 'successCount', and 'success' members
184 * will reflect each operation attempted. The status will be "OK" unless any
185 * of the operations failed and the 'force' parameter was not set.
187 * @param $ops Array List of operations to execute in order
188 * @param $opts Array Batch operation options
191 final public function doOperations( array $ops, array $opts = array() ) {
192 if ( $this->isReadOnly() ) {
193 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
195 if ( empty( $opts['force'] ) ) { // sanity
196 unset( $opts['nonLocking'] );
197 unset( $opts['allowStale'] );
199 return $this->doOperationsInternal( $ops, $opts );
203 * @see FileBackend::doOperations()
205 abstract protected function doOperationsInternal( array $ops, array $opts );
208 * Same as doOperations() except it takes a single operation.
209 * If you are doing a batch of operations that should either
210 * all succeed or all fail, then use that function instead.
212 * @see FileBackend::doOperations()
214 * @param $op Array Operation
215 * @param $opts Array Operation options
218 final public function doOperation( array $op, array $opts = array() ) {
219 return $this->doOperations( array( $op ), $opts );
223 * Performs a single create operation.
224 * This sets $params['op'] to 'create' and passes it to doOperation().
226 * @see FileBackend::doOperation()
228 * @param $params Array Operation parameters
229 * @param $opts Array Operation options
232 final public function create( array $params, array $opts = array() ) {
233 $params['op'] = 'create';
234 return $this->doOperation( $params, $opts );
238 * Performs a single store operation.
239 * This sets $params['op'] to 'store' and passes it to doOperation().
241 * @see FileBackend::doOperation()
243 * @param $params Array Operation parameters
244 * @param $opts Array Operation options
247 final public function store( array $params, array $opts = array() ) {
248 $params['op'] = 'store';
249 return $this->doOperation( $params, $opts );
253 * Performs a single copy operation.
254 * This sets $params['op'] to 'copy' and passes it to doOperation().
256 * @see FileBackend::doOperation()
258 * @param $params Array Operation parameters
259 * @param $opts Array Operation options
262 final public function copy( array $params, array $opts = array() ) {
263 $params['op'] = 'copy';
264 return $this->doOperation( $params, $opts );
268 * Performs a single move operation.
269 * This sets $params['op'] to 'move' and passes it to doOperation().
271 * @see FileBackend::doOperation()
273 * @param $params Array Operation parameters
274 * @param $opts Array Operation options
277 final public function move( array $params, array $opts = array() ) {
278 $params['op'] = 'move';
279 return $this->doOperation( $params, $opts );
283 * Performs a single delete operation.
284 * This sets $params['op'] to 'delete' and passes it to doOperation().
286 * @see FileBackend::doOperation()
288 * @param $params Array Operation parameters
289 * @param $opts Array Operation options
292 final public function delete( array $params, array $opts = array() ) {
293 $params['op'] = 'delete';
294 return $this->doOperation( $params, $opts );
298 * Concatenate a list of storage files into a single file system file.
299 * The target path should refer to a file that is already locked or
300 * otherwise safe from modification from other processes. Normally,
301 * the file will be a new temp file, which should be adequate.
303 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
304 * dst : file system path to 0-byte temp file
306 * @param $params Array Operation parameters
309 abstract public function concatenate( array $params );
312 * Prepare a storage directory for usage.
313 * This will create any required containers and parent directories.
314 * Backends using key/value stores only need to create the container.
317 * dir : storage directory
319 * @param $params Array
322 final public function prepare( array $params ) {
323 if ( $this->isReadOnly() ) {
324 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
326 return $this->doPrepare( $params );
330 * @see FileBackend::prepare()
332 abstract protected function doPrepare( array $params );
335 * Take measures to block web access to a storage directory and
336 * the container it belongs to. FS backends might add .htaccess
337 * files whereas key/value store backends might restrict container
338 * access to the auth user that represents end-users in web request.
339 * This is not guaranteed to actually do anything.
342 * dir : storage directory
343 * noAccess : try to deny file access
344 * noListing : try to deny file listing
346 * @param $params Array
349 final public function secure( array $params ) {
350 if ( $this->isReadOnly() ) {
351 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
353 $status = $this->doPrepare( $params ); // dir must exist to restrict it
354 if ( $status->isOK() ) {
355 $status->merge( $this->doSecure( $params ) );
361 * @see FileBackend::secure()
363 abstract protected function doSecure( array $params );
366 * Delete a storage directory if it is empty.
367 * Backends using key/value stores may do nothing unless the directory
368 * is that of an empty container, in which case it should be deleted.
371 * dir : storage directory
373 * @param $params Array
376 final public function clean( array $params ) {
377 if ( $this->isReadOnly() ) {
378 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
380 return $this->doClean( $params );
384 * @see FileBackend::clean()
386 abstract protected function doClean( array $params );
389 * Check if a file exists at a storage path in the backend.
390 * This returns false if only a directory exists at the path.
393 * src : source storage path
394 * latest : use the latest available data
396 * @param $params Array
397 * @return bool|null Returns null on failure
399 abstract public function fileExists( array $params );
402 * Get the last-modified timestamp of the file at a storage path.
405 * src : source storage path
406 * latest : use the latest available data
408 * @param $params Array
409 * @return string|false TS_MW timestamp or false on failure
411 abstract public function getFileTimestamp( array $params );
414 * Get the contents of a file at a storage path in the backend.
415 * This should be avoided for potentially large files.
418 * src : source storage path
419 * latest : use the latest available data
421 * @param $params Array
422 * @return string|false Returns false on failure
424 abstract public function getFileContents( array $params );
427 * Get the size (bytes) of a file at a storage path in the backend.
430 * src : source storage path
431 * latest : use the latest available data
433 * @param $params Array
434 * @return integer|false Returns false on failure
436 abstract public function getFileSize( array $params );
439 * Get quick information about a file at a storage path in the backend.
440 * If the file does not exist, then this returns false.
441 * Otherwise, the result is an associative array that includes:
442 * mtime : the last-modified timestamp (TS_MW)
443 * size : the file size (bytes)
444 * Additional values may be included for internal use only.
447 * src : source storage path
448 * latest : use the latest available data
450 * @param $params Array
451 * @return Array|false|null Returns null on failure
453 abstract public function getFileStat( array $params );
456 * Get a SHA-1 hash of the file at a storage path in the backend.
459 * src : source storage path
460 * latest : use the latest available data
462 * @param $params Array
463 * @return string|false Hash string or false on failure
465 abstract public function getFileSha1Base36( array $params );
468 * Get the properties of the file at a storage path in the backend.
469 * Returns FSFile::placeholderProps() on failure.
472 * src : source storage path
473 * latest : use the latest available data
475 * @param $params Array
478 abstract public function getFileProps( array $params );
481 * Stream the file at a storage path in the backend.
482 * If the file does not exists, a 404 error will be given.
483 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
484 * must be sent if streaming began, while none should be sent otherwise.
485 * Implementations should flush the output buffer before sending data.
488 * src : source storage path
489 * headers : additional HTTP headers to send on success
490 * latest : use the latest available data
492 * @param $params Array
495 abstract public function streamFile( array $params );
498 * Returns a file system file, identical to the file at a storage path.
499 * The file returned is either:
500 * a) A local copy of the file at a storage path in the backend.
501 * The temporary copy will have the same extension as the source.
502 * b) An original of the file at a storage path in the backend.
503 * Temporary files may be purged when the file object falls out of scope.
505 * Write operations should *never* be done on this file as some backends
506 * may do internal tracking or may be instances of FileBackendMultiWrite.
507 * In that later case, there are copies of the file that must stay in sync.
508 * Additionally, further calls to this function may return the same file.
511 * src : source storage path
512 * latest : use the latest available data
514 * @param $params Array
515 * @return FSFile|null Returns null on failure
517 abstract public function getLocalReference( array $params );
520 * Get a local copy on disk of the file at a storage path in the backend.
521 * The temporary copy will have the same file extension as the source.
522 * Temporary files may be purged when the file object falls out of scope.
525 * src : source storage path
526 * latest : use the latest available data
528 * @param $params Array
529 * @return TempFSFile|null Returns null on failure
531 abstract public function getLocalCopy( array $params );
534 * Get an iterator to list out all stored files under a storage directory.
535 * If the directory is of the form "mwstore://backend/container",
536 * then all files in the container should be listed.
537 * If the directory is of form "mwstore://backend/container/dir",
538 * then all files under that container directory should be listed.
539 * Results should be storage paths relative to the given directory.
541 * Storage backends with eventual consistency might return stale data.
544 * dir : storage path directory
546 * @return Traversable|Array|null Returns null on failure
548 abstract public function getFileList( array $params );
551 * Invalidate any in-process file existence and property cache.
552 * If $paths is given, then only the cache for those files will be cleared.
554 * @param $paths Array Storage paths (optional)
557 public function clearCache( array $paths = null ) {}
560 * Lock the files at the given storage paths in the backend.
561 * This will either lock all the files or none (on failure).
563 * Callers should consider using getScopedFileLocks() instead.
565 * @param $paths Array Storage paths
566 * @param $type integer LockManager::LOCK_* constant
569 final public function lockFiles( array $paths, $type ) {
570 return $this->lockManager
->lock( $paths, $type );
574 * Unlock the files at the given storage paths in the backend.
576 * @param $paths Array Storage paths
577 * @param $type integer LockManager::LOCK_* constant
580 final public function unlockFiles( array $paths, $type ) {
581 return $this->lockManager
->unlock( $paths, $type );
585 * Lock the files at the given storage paths in the backend.
586 * This will either lock all the files or none (on failure).
587 * On failure, the status object will be updated with errors.
589 * Once the return value goes out scope, the locks will be released and
590 * the status updated. Unlock fatals will not change the status "OK" value.
592 * @param $paths Array Storage paths
593 * @param $type integer LockManager::LOCK_* constant
594 * @param $status Status Status to update on lock/unlock
595 * @return ScopedLock|null Returns null on failure
597 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
598 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
602 * Check if a given path is a "mwstore://" path.
603 * This does not do any further validation or any existence checks.
605 * @param $path string
608 final public static function isStoragePath( $path ) {
609 return ( strpos( $path, 'mwstore://' ) === 0 );
613 * Split a storage path into a backend name, a container name,
614 * and a relative file path. The relative path may be the empty string.
615 * This does not do any path normalization or traversal checks.
617 * @param $storagePath string
618 * @return Array (backend, container, rel object) or (null, null, null)
620 final public static function splitStoragePath( $storagePath ) {
621 if ( self
::isStoragePath( $storagePath ) ) {
622 // Remove the "mwstore://" prefix and split the path
623 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
624 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
625 if ( count( $parts ) == 3 ) {
626 return $parts; // e.g. "backend/container/path"
628 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
632 return array( null, null, null );
636 * Normalize a storage path by cleaning up directory separators.
637 * Returns null if the path is not of the format of a valid storage path.
639 * @param $storagePath string
640 * @return string|null
642 final public static function normalizeStoragePath( $storagePath ) {
643 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
644 if ( $relPath !== null ) { // must be for this backend
645 $relPath = self
::normalizeContainerPath( $relPath );
646 if ( $relPath !== null ) {
647 return ( $relPath != '' )
648 ?
"mwstore://{$backend}/{$container}/{$relPath}"
649 : "mwstore://{$backend}/{$container}";
656 * Validate and normalize a relative storage path.
657 * Null is returned if the path involves directory traversal.
658 * Traversal is insecure for FS backends and broken for others.
660 * @param $path string Storage path relative to a container
661 * @return string|null
663 final protected static function normalizeContainerPath( $path ) {
664 // Normalize directory separators
665 $path = strtr( $path, '\\', '/' );
666 // Collapse any consecutive directory separators
667 $path = preg_replace( '![/]{2,}!', '/', $path );
668 // Remove any leading directory separator
669 $path = ltrim( $path, '/' );
670 // Use the same traversal protection as Title::secureAndSplit()
671 if ( strpos( $path, '.' ) !== false ) {
675 strpos( $path, './' ) === 0 ||
676 strpos( $path, '../' ) === 0 ||
677 strpos( $path, '/./' ) !== false ||
678 strpos( $path, '/../' ) !== false
687 * Get the parent storage directory of a storage path.
688 * This returns a path like "mwstore://backend/container",
689 * "mwstore://backend/container/...", or null if there is no parent.
691 * @param $storagePath string
692 * @return string|null
694 final public static function parentStoragePath( $storagePath ) {
695 $storagePath = dirname( $storagePath );
696 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
697 return ( $rel === null ) ?
null : $storagePath;
701 * Get the final extension from a storage or FS path
703 * @param $path string
706 final public static function extensionFromPath( $path ) {
707 $i = strrpos( $path, '.' );
708 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
713 * @brief Base class for all backends associated with a particular storage medium.
715 * This class defines the methods as abstract that subclasses must implement.
716 * Outside callers should *not* use functions with "Internal" in the name.
718 * The FileBackend operations are implemented using basic functions
719 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
720 * This class is also responsible for path resolution and sanitization.
722 * @ingroup FileBackend
725 abstract class FileBackendStore
extends FileBackend
{
726 /** @var Array Map of paths to small (RAM/disk) cache items */
727 protected $cache = array(); // (storage path => key => value)
728 protected $maxCacheSize = 100; // integer; max paths with entries
729 /** @var Array Map of paths to large (RAM/disk) cache items */
730 protected $expensiveCache = array(); // (storage path => key => value)
731 protected $maxExpensiveCacheSize = 10; // integer; max paths with entries
733 /** @var Array Map of container names to sharding settings */
734 protected $shardViaHashLevels = array(); // (container name => config array)
736 protected $maxFileSize = 1000000000; // integer bytes (1GB)
739 * Get the maximum allowable file size given backend
740 * medium restrictions and basic performance constraints.
741 * Do not call this function from places outside FileBackend and FileOp.
743 * @return integer Bytes
745 final public function maxFileSizeInternal() {
746 return $this->maxFileSize
;
750 * Check if a file can be created at a given storage path.
751 * FS backends should check if the parent directory exists and the file is writable.
752 * Backends using key/value stores should check if the container exists.
754 * @param $storagePath string
757 abstract public function isPathUsableInternal( $storagePath );
760 * Create a file in the backend with the given contents.
761 * Do not call this function from places outside FileBackend and FileOp.
764 * content : the raw file contents
765 * dst : destination storage path
766 * overwrite : overwrite any file that exists at the destination
768 * @param $params Array
771 final public function createInternal( array $params ) {
772 wfProfileIn( __METHOD__
);
773 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
774 $status = Status
::newFatal( 'backend-fail-create', $params['dst'] );
776 $status = $this->doCreateInternal( $params );
777 $this->clearCache( array( $params['dst'] ) );
779 wfProfileOut( __METHOD__
);
784 * @see FileBackendStore::createInternal()
786 abstract protected function doCreateInternal( array $params );
789 * Store a file into the backend from a file on disk.
790 * Do not call this function from places outside FileBackend and FileOp.
793 * src : source path on disk
794 * dst : destination storage path
795 * overwrite : overwrite any file that exists at the destination
797 * @param $params Array
800 final public function storeInternal( array $params ) {
801 wfProfileIn( __METHOD__
);
802 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
803 $status = Status
::newFatal( 'backend-fail-store', $params['dst'] );
805 $status = $this->doStoreInternal( $params );
806 $this->clearCache( array( $params['dst'] ) );
808 wfProfileOut( __METHOD__
);
813 * @see FileBackendStore::storeInternal()
815 abstract protected function doStoreInternal( array $params );
818 * Copy a file from one storage path to another in the backend.
819 * Do not call this function from places outside FileBackend and FileOp.
822 * src : source storage path
823 * dst : destination storage path
824 * overwrite : overwrite any file that exists at the destination
826 * @param $params Array
829 final public function copyInternal( array $params ) {
830 wfProfileIn( __METHOD__
);
831 $status = $this->doCopyInternal( $params );
832 $this->clearCache( array( $params['dst'] ) );
833 wfProfileOut( __METHOD__
);
838 * @see FileBackendStore::copyInternal()
840 abstract protected function doCopyInternal( array $params );
843 * Delete a file at the storage path.
844 * Do not call this function from places outside FileBackend and FileOp.
847 * src : source storage path
848 * ignoreMissingSource : do nothing if the source file does not exist
850 * @param $params Array
853 final public function deleteInternal( array $params ) {
854 wfProfileIn( __METHOD__
);
855 $status = $this->doDeleteInternal( $params );
856 $this->clearCache( array( $params['src'] ) );
857 wfProfileOut( __METHOD__
);
862 * @see FileBackendStore::deleteInternal()
864 abstract protected function doDeleteInternal( array $params );
867 * Move a file from one storage path to another in the backend.
868 * Do not call this function from places outside FileBackend and FileOp.
871 * src : source storage path
872 * dst : destination storage path
873 * overwrite : overwrite any file that exists at the destination
875 * @param $params Array
878 final public function moveInternal( array $params ) {
879 wfProfileIn( __METHOD__
);
880 $status = $this->doMoveInternal( $params );
881 $this->clearCache( array( $params['src'], $params['dst'] ) );
882 wfProfileOut( __METHOD__
);
887 * @see FileBackendStore::moveInternal()
889 protected function doMoveInternal( array $params ) {
890 // Copy source to dest
891 $status = $this->copyInternal( $params );
892 if ( $status->isOK() ) {
893 // Delete source (only fails due to races or medium going down)
894 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
895 $status->setResult( true, $status->value
); // ignore delete() errors
901 * @see FileBackend::concatenate()
903 final public function concatenate( array $params ) {
904 wfProfileIn( __METHOD__
);
905 $status = Status
::newGood();
907 // Try to lock the source files for the scope of this function
908 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
909 if ( $status->isOK() ) {
910 // Actually do the concatenation
911 $status->merge( $this->doConcatenate( $params ) );
914 wfProfileOut( __METHOD__
);
919 * @see FileBackendStore::concatenate()
921 protected function doConcatenate( array $params ) {
922 $status = Status
::newGood();
923 $tmpPath = $params['dst']; // convenience
925 // Check that the specified temp file is valid...
926 wfSuppressWarnings();
927 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
929 if ( !$ok ) { // not present or not empty
930 $status->fatal( 'backend-fail-opentemp', $tmpPath );
934 // Build up the temp file using the source chunks (in order)...
935 $tmpHandle = fopen( $tmpPath, 'ab' );
936 if ( $tmpHandle === false ) {
937 $status->fatal( 'backend-fail-opentemp', $tmpPath );
940 foreach ( $params['srcs'] as $virtualSource ) {
941 // Get a local FS version of the chunk
942 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
944 $status->fatal( 'backend-fail-read', $virtualSource );
947 // Get a handle to the local FS version
948 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
949 if ( $sourceHandle === false ) {
950 fclose( $tmpHandle );
951 $status->fatal( 'backend-fail-read', $virtualSource );
954 // Append chunk to file (pass chunk size to avoid magic quotes)
955 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
956 fclose( $sourceHandle );
957 fclose( $tmpHandle );
958 $status->fatal( 'backend-fail-writetemp', $tmpPath );
961 fclose( $sourceHandle );
963 if ( !fclose( $tmpHandle ) ) {
964 $status->fatal( 'backend-fail-closetemp', $tmpPath );
968 clearstatcache(); // temp file changed
974 * @see FileBackend::doPrepare()
976 final protected function doPrepare( array $params ) {
977 wfProfileIn( __METHOD__
);
979 $status = Status
::newGood();
980 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
981 if ( $dir === null ) {
982 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
983 wfProfileOut( __METHOD__
);
984 return $status; // invalid storage path
987 if ( $shard !== null ) { // confined to a single container/shard
988 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
989 } else { // directory is on several shards
990 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
991 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
992 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
993 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
997 wfProfileOut( __METHOD__
);
1002 * @see FileBackendStore::doPrepare()
1004 protected function doPrepareInternal( $container, $dir, array $params ) {
1005 return Status
::newGood();
1009 * @see FileBackend::doSecure()
1011 final protected function doSecure( array $params ) {
1012 wfProfileIn( __METHOD__
);
1013 $status = Status
::newGood();
1015 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1016 if ( $dir === null ) {
1017 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
1018 wfProfileOut( __METHOD__
);
1019 return $status; // invalid storage path
1022 if ( $shard !== null ) { // confined to a single container/shard
1023 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
1024 } else { // directory is on several shards
1025 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1026 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1027 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1028 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
1032 wfProfileOut( __METHOD__
);
1037 * @see FileBackendStore::doSecure()
1039 protected function doSecureInternal( $container, $dir, array $params ) {
1040 return Status
::newGood();
1044 * @see FileBackend::doClean()
1046 final protected function doClean( array $params ) {
1047 wfProfileIn( __METHOD__
);
1048 $status = Status
::newGood();
1050 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1051 if ( $dir === null ) {
1052 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
1053 wfProfileOut( __METHOD__
);
1054 return $status; // invalid storage path
1057 // Attempt to lock this directory...
1058 $filesLockEx = array( $params['dir'] );
1059 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
1060 if ( !$status->isOK() ) {
1061 wfProfileOut( __METHOD__
);
1062 return $status; // abort
1065 if ( $shard !== null ) { // confined to a single container/shard
1066 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
1067 } else { // directory is on several shards
1068 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1069 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1070 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1071 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
1075 wfProfileOut( __METHOD__
);
1080 * @see FileBackendStore::doClean()
1082 protected function doCleanInternal( $container, $dir, array $params ) {
1083 return Status
::newGood();
1087 * @see FileBackend::fileExists()
1089 final public function fileExists( array $params ) {
1090 wfProfileIn( __METHOD__
);
1091 $stat = $this->getFileStat( $params );
1092 wfProfileOut( __METHOD__
);
1093 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
1097 * @see FileBackend::getFileTimestamp()
1099 final public function getFileTimestamp( array $params ) {
1100 wfProfileIn( __METHOD__
);
1101 $stat = $this->getFileStat( $params );
1102 wfProfileOut( __METHOD__
);
1103 return $stat ?
$stat['mtime'] : false;
1107 * @see FileBackend::getFileSize()
1109 final public function getFileSize( array $params ) {
1110 wfProfileIn( __METHOD__
);
1111 $stat = $this->getFileStat( $params );
1112 wfProfileOut( __METHOD__
);
1113 return $stat ?
$stat['size'] : false;
1117 * @see FileBackend::getFileStat()
1119 final public function getFileStat( array $params ) {
1120 wfProfileIn( __METHOD__
);
1121 $path = self
::normalizeStoragePath( $params['src'] );
1122 if ( $path === null ) {
1123 return false; // invalid storage path
1125 $latest = !empty( $params['latest'] );
1126 if ( isset( $this->cache
[$path]['stat'] ) ) {
1127 // If we want the latest data, check that this cached
1128 // value was in fact fetched with the latest available data.
1129 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
1130 wfProfileOut( __METHOD__
);
1131 return $this->cache
[$path]['stat'];
1134 $stat = $this->doGetFileStat( $params );
1135 if ( is_array( $stat ) ) { // don't cache negatives
1136 $this->trimCache(); // limit memory
1137 $this->cache
[$path]['stat'] = $stat;
1138 $this->cache
[$path]['stat']['latest'] = $latest;
1140 wfProfileOut( __METHOD__
);
1145 * @see FileBackendStore::getFileStat()
1147 abstract protected function doGetFileStat( array $params );
1150 * @see FileBackend::getFileContents()
1152 public function getFileContents( array $params ) {
1153 wfProfileIn( __METHOD__
);
1154 $tmpFile = $this->getLocalReference( $params );
1156 wfProfileOut( __METHOD__
);
1159 wfSuppressWarnings();
1160 $data = file_get_contents( $tmpFile->getPath() );
1161 wfRestoreWarnings();
1162 wfProfileOut( __METHOD__
);
1167 * @see FileBackend::getFileSha1Base36()
1169 final public function getFileSha1Base36( array $params ) {
1170 wfProfileIn( __METHOD__
);
1171 $path = $params['src'];
1172 if ( isset( $this->cache
[$path]['sha1'] ) ) {
1173 wfProfileOut( __METHOD__
);
1174 return $this->cache
[$path]['sha1'];
1176 $hash = $this->doGetFileSha1Base36( $params );
1177 if ( $hash ) { // don't cache negatives
1178 $this->trimCache(); // limit memory
1179 $this->cache
[$path]['sha1'] = $hash;
1181 wfProfileOut( __METHOD__
);
1186 * @see FileBackendStore::getFileSha1Base36()
1188 protected function doGetFileSha1Base36( array $params ) {
1189 $fsFile = $this->getLocalReference( $params );
1193 return $fsFile->getSha1Base36();
1198 * @see FileBackend::getFileProps()
1200 final public function getFileProps( array $params ) {
1201 wfProfileIn( __METHOD__
);
1202 $fsFile = $this->getLocalReference( $params );
1203 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
1204 wfProfileOut( __METHOD__
);
1209 * @see FileBackend::getLocalReference()
1211 public function getLocalReference( array $params ) {
1212 wfProfileIn( __METHOD__
);
1213 $path = $params['src'];
1214 if ( isset( $this->expensiveCache
[$path]['localRef'] ) ) {
1215 wfProfileOut( __METHOD__
);
1216 return $this->expensiveCache
[$path]['localRef'];
1218 $tmpFile = $this->getLocalCopy( $params );
1219 if ( $tmpFile ) { // don't cache negatives
1220 $this->trimExpensiveCache(); // limit memory
1221 $this->expensiveCache
[$path]['localRef'] = $tmpFile;
1223 wfProfileOut( __METHOD__
);
1228 * @see FileBackend::streamFile()
1230 final public function streamFile( array $params ) {
1231 wfProfileIn( __METHOD__
);
1232 $status = Status
::newGood();
1234 $info = $this->getFileStat( $params );
1235 if ( !$info ) { // let StreamFile handle the 404
1236 $status->fatal( 'backend-fail-notexists', $params['src'] );
1239 // Set output buffer and HTTP headers for stream
1240 $extraHeaders = $params['headers'] ?
$params['headers'] : array();
1241 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
1242 if ( $res == StreamFile
::NOT_MODIFIED
) {
1243 // do nothing; client cache is up to date
1244 } elseif ( $res == StreamFile
::READY_STREAM
) {
1245 $status = $this->doStreamFile( $params );
1247 $status->fatal( 'backend-fail-stream', $params['src'] );
1250 wfProfileOut( __METHOD__
);
1255 * @see FileBackendStore::streamFile()
1257 protected function doStreamFile( array $params ) {
1258 $status = Status
::newGood();
1260 $fsFile = $this->getLocalReference( $params );
1262 $status->fatal( 'backend-fail-stream', $params['src'] );
1263 } elseif ( !readfile( $fsFile->getPath() ) ) {
1264 $status->fatal( 'backend-fail-stream', $params['src'] );
1271 * @copydoc FileBackend::getFileList()
1273 final public function getFileList( array $params ) {
1274 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1275 if ( $dir === null ) { // invalid storage path
1278 if ( $shard !== null ) {
1279 // File listing is confined to a single container/shard
1280 return $this->getFileListInternal( $fullCont, $dir, $params );
1282 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
1283 // File listing spans multiple containers/shards
1284 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
1285 return new FileBackendStoreShardListIterator( $this,
1286 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1291 * Do not call this function from places outside FileBackend
1293 * @see FileBackendStore::getFileList()
1295 * @param $container string Resolved container name
1296 * @param $dir string Resolved path relative to container
1297 * @param $params Array
1298 * @return Traversable|Array|null
1300 abstract public function getFileListInternal( $container, $dir, array $params );
1303 * Get the list of supported operations and their corresponding FileOp classes.
1307 protected function supportedOperations() {
1309 'store' => 'StoreFileOp',
1310 'copy' => 'CopyFileOp',
1311 'move' => 'MoveFileOp',
1312 'delete' => 'DeleteFileOp',
1313 'create' => 'CreateFileOp',
1314 'null' => 'NullFileOp'
1319 * Return a list of FileOp objects from a list of operations.
1320 * Do not call this function from places outside FileBackend.
1322 * The result must have the same number of items as the input.
1323 * An exception is thrown if an unsupported operation is requested.
1325 * @param $ops Array Same format as doOperations()
1326 * @return Array List of FileOp objects
1327 * @throws MWException
1329 final public function getOperations( array $ops ) {
1330 $supportedOps = $this->supportedOperations();
1332 $performOps = array(); // array of FileOp objects
1333 // Build up ordered array of FileOps...
1334 foreach ( $ops as $operation ) {
1335 $opName = $operation['op'];
1336 if ( isset( $supportedOps[$opName] ) ) {
1337 $class = $supportedOps[$opName];
1338 // Get params for this operation
1339 $params = $operation;
1340 // Append the FileOp class
1341 $performOps[] = new $class( $this, $params );
1343 throw new MWException( "Operation `$opName` is not supported." );
1351 * @see FileBackend::doOperationsInternal()
1353 protected function doOperationsInternal( array $ops, array $opts ) {
1354 wfProfileIn( __METHOD__
);
1355 $status = Status
::newGood();
1357 // Build up a list of FileOps...
1358 $performOps = $this->getOperations( $ops );
1360 // Acquire any locks as needed...
1361 if ( empty( $opts['nonLocking'] ) ) {
1362 // Build up a list of files to lock...
1363 $filesLockEx = $filesLockSh = array();
1364 foreach ( $performOps as $fileOp ) {
1365 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
1366 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
1368 // Optimization: if doing an EX lock anyway, don't also set an SH one
1369 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
1370 // Get a shared lock on the parent directory of each path changed
1371 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
1372 // Try to lock those files for the scope of this function...
1373 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
1374 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
1375 if ( !$status->isOK() ) {
1376 wfProfileOut( __METHOD__
);
1377 return $status; // abort
1381 // Clear any cache entries (after locks acquired)
1382 $this->clearCache();
1384 // Actually attempt the operation batch...
1385 $subStatus = FileOp
::attemptBatch( $performOps, $opts );
1387 // Merge errors into status fields
1388 $status->merge( $subStatus );
1389 $status->success
= $subStatus->success
; // not done in merge()
1391 wfProfileOut( __METHOD__
);
1396 * @see FileBackend::clearCache()
1398 final public function clearCache( array $paths = null ) {
1399 if ( is_array( $paths ) ) {
1400 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1401 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1403 if ( $paths === null ) {
1404 $this->cache
= array();
1405 $this->expensiveCache
= array();
1407 foreach ( $paths as $path ) {
1408 unset( $this->cache
[$path] );
1409 unset( $this->expensiveCache
[$path] );
1412 $this->doClearCache( $paths );
1416 * Clears any additional stat caches for storage paths
1418 * @see FileBackend::clearCache()
1420 * @param $paths Array Storage paths (optional)
1423 protected function doClearCache( array $paths = null ) {}
1426 * Prune the inexpensive cache if it is too big to add an item
1430 protected function trimCache() {
1431 if ( count( $this->cache
) >= $this->maxCacheSize
) {
1432 reset( $this->cache
);
1433 unset( $this->cache
[key( $this->cache
)] );
1438 * Prune the expensive cache if it is too big to add an item
1442 protected function trimExpensiveCache() {
1443 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
1444 reset( $this->expensiveCache
);
1445 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
1450 * Check if a container name is valid.
1451 * This checks for for length and illegal characters.
1453 * @param $container string
1456 final protected static function isValidContainerName( $container ) {
1457 // This accounts for Swift and S3 restrictions while leaving room
1458 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1459 // This disallows directory separators or traversal characters.
1460 // Note that matching strings URL encode to the same string;
1461 // in Swift, the length restriction is *after* URL encoding.
1462 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1466 * Splits a storage path into an internal container name,
1467 * an internal relative file name, and a container shard suffix.
1468 * Any shard suffix is already appended to the internal container name.
1469 * This also checks that the storage path is valid and within this backend.
1471 * If the container is sharded but a suffix could not be determined,
1472 * this means that the path can only refer to a directory and can only
1473 * be scanned by looking in all the container shards.
1475 * @param $storagePath string
1476 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1478 final protected function resolveStoragePath( $storagePath ) {
1479 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1480 if ( $backend === $this->name
) { // must be for this backend
1481 $relPath = self
::normalizeContainerPath( $relPath );
1482 if ( $relPath !== null ) {
1483 // Get shard for the normalized path if this container is sharded
1484 $cShard = $this->getContainerShard( $container, $relPath );
1485 // Validate and sanitize the relative path (backend-specific)
1486 $relPath = $this->resolveContainerPath( $container, $relPath );
1487 if ( $relPath !== null ) {
1488 // Prepend any wiki ID prefix to the container name
1489 $container = $this->fullContainerName( $container );
1490 if ( self
::isValidContainerName( $container ) ) {
1491 // Validate and sanitize the container name (backend-specific)
1492 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1493 if ( $container !== null ) {
1494 return array( $container, $relPath, $cShard );
1500 return array( null, null, null );
1504 * Like resolveStoragePath() except null values are returned if
1505 * the container is sharded and the shard could not be determined.
1507 * @see FileBackendStore::resolveStoragePath()
1509 * @param $storagePath string
1510 * @return Array (container, path) or (null, null) if invalid
1512 final protected function resolveStoragePathReal( $storagePath ) {
1513 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1514 if ( $cShard !== null ) {
1515 return array( $container, $relPath );
1517 return array( null, null );
1521 * Get the container name shard suffix for a given path.
1522 * Any empty suffix means the container is not sharded.
1524 * @param $container string Container name
1525 * @param $relStoragePath string Storage path relative to the container
1526 * @return string|null Returns null if shard could not be determined
1528 final protected function getContainerShard( $container, $relPath ) {
1529 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1530 if ( $levels == 1 ||
$levels == 2 ) {
1531 // Hash characters are either base 16 or 36
1532 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1533 // Get a regex that represents the shard portion of paths.
1534 // The concatenation of the captures gives us the shard.
1535 if ( $levels === 1 ) { // 16 or 36 shards per container
1536 $hashDirRegex = '(' . $char . ')';
1537 } else { // 256 or 1296 shards per container
1538 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1539 $hashDirRegex = $char . '/(' . $char . '{2})';
1540 } else { // short hash dir format (e.g. "a/b/c")
1541 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1544 // Allow certain directories to be above the hash dirs so as
1545 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1546 // They must be 2+ chars to avoid any hash directory ambiguity.
1548 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1549 return '.' . implode( '', array_slice( $m, 1 ) );
1551 return null; // failed to match
1553 return ''; // no sharding
1557 * Get the sharding config for a container.
1558 * If greater than 0, then all file storage paths within
1559 * the container are required to be hashed accordingly.
1561 * @param $container string
1562 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1564 final protected function getContainerHashLevels( $container ) {
1565 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1566 $config = $this->shardViaHashLevels
[$container];
1567 $hashLevels = (int)$config['levels'];
1568 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1569 $hashBase = (int)$config['base'];
1570 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1571 return array( $hashLevels, $hashBase, $config['repeat'] );
1575 return array( 0, 0, false ); // no sharding
1579 * Get a list of full container shard suffixes for a container
1581 * @param $container string
1584 final protected function getContainerSuffixes( $container ) {
1586 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1587 if ( $digits > 0 ) {
1588 $numShards = pow( $base, $digits );
1589 for ( $index = 0; $index < $numShards; $index++
) {
1590 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1597 * Get the full container name, including the wiki ID prefix
1599 * @param $container string
1602 final protected function fullContainerName( $container ) {
1603 if ( $this->wikiId
!= '' ) {
1604 return "{$this->wikiId}-$container";
1611 * Resolve a container name, checking if it's allowed by the backend.
1612 * This is intended for internal use, such as encoding illegal chars.
1613 * Subclasses can override this to be more restrictive.
1615 * @param $container string
1616 * @return string|null
1618 protected function resolveContainerName( $container ) {
1623 * Resolve a relative storage path, checking if it's allowed by the backend.
1624 * This is intended for internal use, such as encoding illegal chars or perhaps
1625 * getting absolute paths (e.g. FS based backends). Note that the relative path
1626 * may be the empty string (e.g. the path is simply to the container).
1628 * @param $container string Container name
1629 * @param $relStoragePath string Storage path relative to the container
1630 * @return string|null Path or null if not valid
1632 protected function resolveContainerPath( $container, $relStoragePath ) {
1633 return $relStoragePath;
1638 * FileBackendStore helper function to handle file listings that span container shards.
1639 * Do not use this class from places outside of FileBackendStore.
1641 * @ingroup FileBackend
1643 class FileBackendStoreShardListIterator
implements Iterator
{
1644 /* @var FileBackendStore */
1649 protected $shardSuffixes;
1650 protected $container; // string
1651 protected $directory; // string
1653 /* @var Traversable */
1655 protected $curShard = 0; // integer
1656 protected $pos = 0; // integer
1659 * @param $backend FileBackendStore
1660 * @param $container string Full storage container name
1661 * @param $dir string Storage directory relative to container
1662 * @param $suffixes Array List of container shard suffixes
1663 * @param $params Array
1665 public function __construct(
1666 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1668 $this->backend
= $backend;
1669 $this->container
= $container;
1670 $this->directory
= $dir;
1671 $this->shardSuffixes
= $suffixes;
1672 $this->params
= $params;
1675 public function current() {
1676 if ( is_array( $this->iter
) ) {
1677 return current( $this->iter
);
1679 return $this->iter
->current();
1683 public function key() {
1687 public function next() {
1689 if ( is_array( $this->iter
) ) {
1690 next( $this->iter
);
1692 $this->iter
->next();
1694 // Find the next non-empty shard if no elements are left
1695 $this->nextShardIteratorIfNotValid();
1699 * If the iterator for this container shard is out of items,
1700 * then move on to the next container that has items.
1701 * If there are none, then it advances to the last container.
1703 protected function nextShardIteratorIfNotValid() {
1704 while ( !$this->valid() ) {
1705 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1706 break; // no more container shards
1708 $this->setIteratorFromCurrentShard();
1712 protected function setIteratorFromCurrentShard() {
1713 $suffix = $this->shardSuffixes
[$this->curShard
];
1714 $this->iter
= $this->backend
->getFileListInternal(
1715 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1718 public function rewind() {
1720 $this->curShard
= 0;
1721 $this->setIteratorFromCurrentShard();
1722 // Find the next non-empty shard if this one has no elements
1723 $this->nextShardIteratorIfNotValid();
1726 public function valid() {
1727 if ( $this->iter
== null ) {
1728 return false; // some failure?
1729 } elseif ( is_array( $this->iter
) ) {
1730 return ( current( $this->iter
) !== false ); // no paths can have this value
1732 return $this->iter
->valid();