r108353: Distinguish null/false in FileBackend::fileExists(). This is intended for...
[lhc/web/wiklou.git] / includes / filerepo / backend / FileBackend.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 * @author Aaron Schulz
6 */
7
8 /**
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.
12 *
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.
16 *
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.
20 *
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.
25 *
26 * Methods should avoid throwing exceptions at all costs.
27 * As a corollary, external dependencies should be kept to a minimum.
28 *
29 * @ingroup FileBackend
30 * @since 1.19
31 */
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;
38
39 /**
40 * Create a new backend instance from configuration.
41 * This should only be called from within FileBackendGroup.
42 *
43 * $config includes:
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.
50 *
51 * @param $config Array
52 */
53 public function __construct( array $config ) {
54 $this->name = $config['name'];
55 $this->wikiId = isset( $config['wikiId'] )
56 ? $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']
62 : '';
63 }
64
65 /**
66 * Normalize a wiki ID by replacing characters that are
67 * not supported by the backend as part of container names.
68 *
69 * @param $wikiId string
70 * @return string
71 */
72 protected function resolveWikiId( $wikiId ) {
73 return $wikiId;
74 }
75
76 /**
77 * Get the unique backend name.
78 *
79 * We may have multiple different backends of the same type.
80 * For example, we can have two Swift backends using different proxies.
81 *
82 * @return string
83 */
84 final public function getName() {
85 return $this->name;
86 }
87
88 /**
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.
92 *
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.
95 *
96 * Supported operations and their parameters:
97 * a) Create a new file in storage with the contents of a string
98 * array(
99 * 'op' => 'create',
100 * 'dst' => <storage path>,
101 * 'content' => <string of new file contents>,
102 * 'overwriteDest' => <boolean>,
103 * 'overwriteSame' => <boolean>
104 * )
105 * b) Copy a file system file into storage
106 * array(
107 * 'op' => 'store',
108 * 'src' => <file system path>,
109 * 'dst' => <storage path>,
110 * 'overwriteDest' => <boolean>,
111 * 'overwriteSame' => <boolean>
112 * )
113 * c) Copy a file within storage
114 * array(
115 * 'op' => 'copy',
116 * 'src' => <storage path>,
117 * 'dst' => <storage path>,
118 * 'overwriteDest' => <boolean>,
119 * 'overwriteSame' => <boolean>
120 * )
121 * d) Move a file within storage
122 * array(
123 * 'op' => 'move',
124 * 'src' => <storage path>,
125 * 'dst' => <storage path>,
126 * 'overwriteDest' => <boolean>,
127 * 'overwriteSame' => <boolean>
128 * )
129 * e) Delete a file within storage
130 * array(
131 * 'op' => 'delete',
132 * 'src' => <storage path>,
133 * 'ignoreMissingSource' => <boolean>
134 * )
135 * f) Do nothing (no-op)
136 * array(
137 * 'op' => 'null',
138 * )
139 *
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.
147 *
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.
157 *
158 * Return value:
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.
163 *
164 * @param $ops Array List of operations to execute in order
165 * @param $opts Array Batch operation options
166 * @return Status
167 */
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 );
171 }
172 if ( empty( $opts['force'] ) ) { // sanity
173 unset( $opts['nonLocking'] );
174 unset( $opts['allowStale'] );
175 }
176 return $this->doOperationsInternal( $ops, $opts );
177 }
178
179 /**
180 * @see FileBackendBase::doOperations()
181 */
182 abstract protected function doOperationsInternal( array $ops, array $opts );
183
184 /**
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.
188 *
189 * @see FileBackendBase::doOperations()
190 *
191 * @param $op Array Operation
192 * @param $opts Array Operation options
193 * @return Status
194 */
195 final public function doOperation( array $op, array $opts = array() ) {
196 return $this->doOperations( array( $op ), $opts );
197 }
198
199 /**
200 * Performs a single create operation.
201 * This sets $params['op'] to 'create' and passes it to doOperation().
202 *
203 * @see FileBackendBase::doOperation()
204 *
205 * @param $params Array Operation parameters
206 * @param $opts Array Operation options
207 * @return Status
208 */
209 final public function create( array $params, array $opts = array() ) {
210 $params['op'] = 'create';
211 return $this->doOperation( $params, $opts );
212 }
213
214 /**
215 * Performs a single store operation.
216 * This sets $params['op'] to 'store' and passes it to doOperation().
217 *
218 * @see FileBackendBase::doOperation()
219 *
220 * @param $params Array Operation parameters
221 * @param $opts Array Operation options
222 * @return Status
223 */
224 final public function store( array $params, array $opts = array() ) {
225 $params['op'] = 'store';
226 return $this->doOperation( $params, $opts );
227 }
228
229 /**
230 * Performs a single copy operation.
231 * This sets $params['op'] to 'copy' and passes it to doOperation().
232 *
233 * @see FileBackendBase::doOperation()
234 *
235 * @param $params Array Operation parameters
236 * @param $opts Array Operation options
237 * @return Status
238 */
239 final public function copy( array $params, array $opts = array() ) {
240 $params['op'] = 'copy';
241 return $this->doOperation( $params, $opts );
242 }
243
244 /**
245 * Performs a single move operation.
246 * This sets $params['op'] to 'move' and passes it to doOperation().
247 *
248 * @see FileBackendBase::doOperation()
249 *
250 * @param $params Array Operation parameters
251 * @param $opts Array Operation options
252 * @return Status
253 */
254 final public function move( array $params, array $opts = array() ) {
255 $params['op'] = 'move';
256 return $this->doOperation( $params, $opts );
257 }
258
259 /**
260 * Performs a single delete operation.
261 * This sets $params['op'] to 'delete' and passes it to doOperation().
262 *
263 * @see FileBackendBase::doOperation()
264 *
265 * @param $params Array Operation parameters
266 * @param $opts Array Operation options
267 * @return Status
268 */
269 final public function delete( array $params, array $opts = array() ) {
270 $params['op'] = 'delete';
271 return $this->doOperation( $params, $opts );
272 }
273
274 /**
275 * Concatenate a list of storage files into a single file on the file system
276 * $params include:
277 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
278 * dst : file system path to 0-byte temp file
279 *
280 * @param $params Array Operation parameters
281 * @return Status
282 */
283 abstract public function concatenate( array $params );
284
285 /**
286 * Prepare a storage path for usage. This will create containers
287 * that don't yet exist or, on FS backends, create parent directories.
288 *
289 * $params include:
290 * dir : storage directory
291 *
292 * @param $params Array
293 * @return Status
294 */
295 final public function prepare( array $params ) {
296 if ( $this->readOnly != '' ) {
297 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
298 }
299 return $this->doPrepare( $params );
300 }
301
302 /**
303 * @see FileBackendBase::prepare()
304 */
305 abstract protected function doPrepare( array $params );
306
307 /**
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.
313 *
314 * $params include:
315 * dir : storage directory
316 * noAccess : try to deny file access
317 * noListing : try to deny file listing
318 *
319 * @param $params Array
320 * @return Status
321 */
322 final public function secure( array $params ) {
323 if ( $this->readOnly != '' ) {
324 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
325 }
326 return $this->doSecure( $params );
327 }
328
329 /**
330 * @see FileBackendBase::secure()
331 */
332 abstract protected function doSecure( array $params );
333
334 /**
335 * Clean up an empty storage directory.
336 * On FS backends, the directory will be deleted. Others may do nothing.
337 *
338 * $params include:
339 * dir : storage directory
340 *
341 * @param $params Array
342 * @return Status
343 */
344 final public function clean( array $params ) {
345 if ( $this->readOnly != '' ) {
346 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
347 }
348 return $this->doClean( $params );
349 }
350
351 /**
352 * @see FileBackendBase::clean()
353 */
354 abstract protected function doClean( array $params );
355
356 /**
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.
359 *
360 * $params include:
361 * src : source storage path
362 * latest : use the latest available data
363 *
364 * @param $params Array
365 * @return bool|null Returns null on failure
366 */
367 abstract public function fileExists( array $params );
368
369 /**
370 * Get the last-modified timestamp of the file at a storage path.
371 *
372 * $params include:
373 * src : source storage path
374 * latest : use the latest available data
375 *
376 * @param $params Array
377 * @return string|false TS_MW timestamp or false on failure
378 */
379 abstract public function getFileTimestamp( array $params );
380
381 /**
382 * Get the contents of a file at a storage path in the backend.
383 * This should be avoided for potentially large files.
384 *
385 * $params include:
386 * src : source storage path
387 * latest : use the latest available data
388 *
389 * @param $params Array
390 * @return string|false Returns false on failure
391 */
392 abstract public function getFileContents( array $params );
393
394 /**
395 * Get the size (bytes) of a file at a storage path in the backend.
396 *
397 * $params include:
398 * src : source storage path
399 * latest : use the latest available data
400 *
401 * @param $params Array
402 * @return integer|false Returns false on failure
403 */
404 abstract public function getFileSize( array $params );
405
406 /**
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)
412 *
413 * $params include:
414 * src : source storage path
415 * latest : use the latest available data
416 *
417 * @param $params Array
418 * @return Array|false|null Returns null on failure
419 */
420 abstract public function getFileStat( array $params );
421
422 /**
423 * Get a SHA-1 hash of the file at a storage path in the backend.
424 *
425 * $params include:
426 * src : source storage path
427 * latest : use the latest available data
428 *
429 * @param $params Array
430 * @return string|false Hash string or false on failure
431 */
432 abstract public function getFileSha1Base36( array $params );
433
434 /**
435 * Get the properties of the file at a storage path in the backend.
436 * Returns FSFile::placeholderProps() on failure.
437 *
438 * $params include:
439 * src : source storage path
440 * latest : use the latest available data
441 *
442 * @param $params Array
443 * @return Array
444 */
445 abstract public function getFileProps( array $params );
446
447 /**
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.
453 *
454 * $params include:
455 * src : source storage path
456 * headers : additional HTTP headers to send on success
457 * latest : use the latest available data
458 *
459 * @param $params Array
460 * @return Status
461 */
462 abstract public function streamFile( array $params );
463
464 /**
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.
471 *
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.
475 *
476 * $params include:
477 * src : source storage path
478 * latest : use the latest available data
479 *
480 * @param $params Array
481 * @return FSFile|null Returns null on failure
482 */
483 abstract public function getLocalReference( array $params );
484
485 /**
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.
489 *
490 * $params include:
491 * src : source storage path
492 * latest : use the latest available data
493 *
494 * @param $params Array
495 * @return TempFSFile|null Returns null on failure
496 */
497 abstract public function getLocalCopy( array $params );
498
499 /**
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.
505 *
506 * $params include:
507 * dir : storage path directory
508 *
509 * @return Traversable|Array|null Returns null on failure
510 */
511 abstract public function getFileList( array $params );
512
513 /**
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.
516 *
517 * @param $paths Array Storage paths
518 * @return void
519 */
520 abstract public function clearCache( array $paths = null );
521
522 /**
523 * Lock the files at the given storage paths in the backend.
524 * This will either lock all the files or none (on failure).
525 *
526 * Callers should consider using getScopedFileLocks() instead.
527 *
528 * @param $paths Array Storage paths
529 * @param $type integer LockManager::LOCK_* constant
530 * @return Status
531 */
532 final public function lockFiles( array $paths, $type ) {
533 return $this->lockManager->lock( $paths, $type );
534 }
535
536 /**
537 * Unlock the files at the given storage paths in the backend.
538 *
539 * @param $paths Array Storage paths
540 * @param $type integer LockManager::LOCK_* constant
541 * @return Status
542 */
543 final public function unlockFiles( array $paths, $type ) {
544 return $this->lockManager->unlock( $paths, $type );
545 }
546
547 /**
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.
551 *
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.
554 *
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
559 */
560 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
561 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
562 }
563 }
564
565 /**
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.
570 *
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.
574 *
575 * @ingroup FileBackend
576 * @since 1.19
577 */
578 abstract class FileBackend extends FileBackendBase {
579 /** @var Array */
580 protected $cache = array(); // (storage path => key => value)
581 protected $maxCacheSize = 75; // integer; max paths with entries
582 /** @var Array */
583 protected $shardViaHashLevels = array(); // (container name => integer)
584
585 /**
586 * Create a file in the backend with the given contents.
587 * Do not call this function from places outside FileBackend and FileOp.
588 *
589 * $params include:
590 * content : the raw file contents
591 * dst : destination storage path
592 * overwriteDest : overwrite any file that exists at the destination
593 *
594 * @param $params Array
595 * @return Status
596 */
597 final public function createInternal( array $params ) {
598 $status = $this->doCreateInternal( $params );
599 $this->clearCache( array( $params['dst'] ) );
600 return $status;
601 }
602
603 /**
604 * @see FileBackend::createInternal()
605 */
606 abstract protected function doCreateInternal( array $params );
607
608 /**
609 * Store a file into the backend from a file on disk.
610 * Do not call this function from places outside FileBackend and FileOp.
611 *
612 * $params include:
613 * src : source path on disk
614 * dst : destination storage path
615 * overwriteDest : overwrite any file that exists at the destination
616 *
617 * @param $params Array
618 * @return Status
619 */
620 final public function storeInternal( array $params ) {
621 $status = $this->doStoreInternal( $params );
622 $this->clearCache( array( $params['dst'] ) );
623 return $status;
624 }
625
626 /**
627 * @see FileBackend::storeInternal()
628 */
629 abstract protected function doStoreInternal( array $params );
630
631 /**
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.
634 *
635 * $params include:
636 * src : source storage path
637 * dst : destination storage path
638 * overwriteDest : overwrite any file that exists at the destination
639 *
640 * @param $params Array
641 * @return Status
642 */
643 final public function copyInternal( array $params ) {
644 $status = $this->doCopyInternal( $params );
645 $this->clearCache( array( $params['dst'] ) );
646 return $status;
647 }
648
649 /**
650 * @see FileBackend::copyInternal()
651 */
652 abstract protected function doCopyInternal( array $params );
653
654 /**
655 * Delete a file at the storage path.
656 * Do not call this function from places outside FileBackend and FileOp.
657 *
658 * $params include:
659 * src : source storage path
660 * ignoreMissingSource : do nothing if the source file does not exist
661 *
662 * @param $params Array
663 * @return Status
664 */
665 final public function deleteInternal( array $params ) {
666 $status = $this->doDeleteInternal( $params );
667 $this->clearCache( array( $params['src'] ) );
668 return $status;
669 }
670
671 /**
672 * @see FileBackend::deleteInternal()
673 */
674 abstract protected function doDeleteInternal( array $params );
675
676 /**
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.
679 *
680 * $params include:
681 * src : source storage path
682 * dst : destination storage path
683 * overwriteDest : overwrite any file that exists at the destination
684 *
685 * @param $params Array
686 * @return Status
687 */
688 final public function moveInternal( array $params ) {
689 $status = $this->doMoveInternal( $params );
690 $this->clearCache( array( $params['src'], $params['dst'] ) );
691 return $status;
692 }
693
694 /**
695 * @see FileBackend::moveInternal()
696 */
697 protected function doMoveInternal( array $params ) {
698 // Copy source to dest
699 $status = $this->copyInternal( $params );
700 if ( !$status->isOK() ) {
701 return $status;
702 }
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
706 return $status;
707 }
708
709 /**
710 * @see FileBackendBase::concatenate()
711 */
712 final public function concatenate( array $params ) {
713 $status = Status::newGood();
714
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
719 }
720
721 // Actually do the concatenation
722 $status->merge( $this->doConcatenate( $params ) );
723
724 return $status;
725 }
726
727 /**
728 * @see FileBackend::concatenate()
729 */
730 protected function doConcatenate( array $params ) {
731 $status = Status::newGood();
732 $tmpPath = $params['dst']; // convenience
733
734 // Check that the specified temp file is valid...
735 wfSuppressWarnings();
736 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
737 wfRestoreWarnings();
738 if ( !$ok ) { // not present or not empty
739 $status->fatal( 'backend-fail-opentemp', $tmpPath );
740 return $status;
741 }
742
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 );
747 return $status;
748 }
749 foreach ( $params['srcs'] as $virtualSource ) {
750 // Get a local FS version of the chunk
751 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
752 if ( !$tmpFile ) {
753 $status->fatal( 'backend-fail-read', $virtualSource );
754 return $status;
755 }
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 );
761 return $status;
762 }
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 );
768 return $status;
769 }
770 fclose( $sourceHandle );
771 }
772 if ( !fclose( $tmpHandle ) ) {
773 $status->fatal( 'backend-fail-closetemp', $tmpPath );
774 return $status;
775 }
776
777 return $status;
778 }
779
780 /**
781 * @see FileBackendBase::doPrepare()
782 */
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
789 }
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 ) );
797 }
798 }
799 return $status;
800 }
801
802 /**
803 * @see FileBackend::doPrepare()
804 */
805 protected function doPrepareInternal( $container, $dir, array $params ) {
806 return Status::newGood();
807 }
808
809 /**
810 * @see FileBackendBase::doSecure()
811 */
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
818 }
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 ) );
826 }
827 }
828 return $status;
829 }
830
831 /**
832 * @see FileBackend::doSecure()
833 */
834 protected function doSecureInternal( $container, $dir, array $params ) {
835 return Status::newGood();
836 }
837
838 /**
839 * @see FileBackendBase::doClean()
840 */
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
847 }
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 ) );
855 }
856 }
857 return $status;
858 }
859
860 /**
861 * @see FileBackend::doClean()
862 */
863 protected function doCleanInternal( $container, $dir, array $params ) {
864 return Status::newGood();
865 }
866
867 /**
868 * @see FileBackendBase::fileExists()
869 */
870 final public function fileExists( array $params ) {
871 $stat = $this->getFileStat( $params );
872 if ( $stat === null ) {
873 return null; // failure
874 }
875 return (bool)$stat;
876 }
877
878 /**
879 * @see FileBackendBase::getFileTimestamp()
880 */
881 final public function getFileTimestamp( array $params ) {
882 $stat = $this->getFileStat( $params );
883 if ( $stat ) {
884 return $stat['mtime'];
885 } else {
886 return false;
887 }
888 }
889
890 /**
891 * @see FileBackendBase::getFileSize()
892 */
893 final public function getFileSize( array $params ) {
894 $stat = $this->getFileStat( $params );
895 if ( $stat ) {
896 return $stat['size'];
897 } else {
898 return false;
899 }
900 }
901
902 /**
903 * @see FileBackendBase::getFileStat()
904 */
905 final public function getFileStat( array $params ) {
906 $path = $params['src'];
907 if ( isset( $this->cache[$path]['stat'] ) ) {
908 return $this->cache[$path]['stat'];
909 }
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;
914 }
915 return $stat;
916 }
917
918 /**
919 * @see FileBackend::getFileStat()
920 */
921 abstract protected function doGetFileStat( array $params );
922
923 /**
924 * @see FileBackendBase::getFileContents()
925 */
926 public function getFileContents( array $params ) {
927 $tmpFile = $this->getLocalReference( $params );
928 if ( !$tmpFile ) {
929 return false;
930 }
931 wfSuppressWarnings();
932 $data = file_get_contents( $tmpFile->getPath() );
933 wfRestoreWarnings();
934 return $data;
935 }
936
937 /**
938 * @see FileBackendBase::getFileSha1Base36()
939 */
940 final public function getFileSha1Base36( array $params ) {
941 $path = $params['src'];
942 if ( isset( $this->cache[$path]['sha1'] ) ) {
943 return $this->cache[$path]['sha1'];
944 }
945 $hash = $this->doGetFileSha1Base36( $params );
946 if ( $hash ) { // don't cache negatives
947 $this->trimCache(); // limit memory
948 $this->cache[$path]['sha1'] = $hash;
949 }
950 return $hash;
951 }
952
953 /**
954 * @see FileBackend::getFileSha1Base36()
955 */
956 protected function doGetFileSha1Base36( array $params ) {
957 $fsFile = $this->getLocalReference( $params );
958 if ( !$fsFile ) {
959 return false;
960 } else {
961 return $fsFile->getSha1Base36();
962 }
963 }
964
965 /**
966 * @see FileBackendBase::getFileProps()
967 */
968 public function getFileProps( array $params ) {
969 $fsFile = $this->getLocalReference( $params );
970 if ( !$fsFile ) {
971 return FSFile::placeholderProps();
972 } else {
973 return $fsFile->getProps();
974 }
975 }
976
977 /**
978 * @see FileBackendBase::getLocalReference()
979 */
980 public function getLocalReference( array $params ) {
981 $path = $params['src'];
982 if ( isset( $this->cache[$path]['localRef'] ) ) {
983 return $this->cache[$path]['localRef'];
984 }
985 $tmpFile = $this->getLocalCopy( $params );
986 if ( $tmpFile ) { // don't cache negatives
987 $this->trimCache(); // limit memory
988 $this->cache[$path]['localRef'] = $tmpFile;
989 }
990 return $tmpFile;
991 }
992
993 /**
994 * @see FileBackendBase::streamFile()
995 */
996 final public function streamFile( array $params ) {
997 $status = Status::newGood();
998
999 $info = $this->getFileStat( $params );
1000 if ( !$info ) { // let StreamFile handle the 404
1001 $status->fatal( 'backend-fail-notexists', $params['src'] );
1002 }
1003
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 );
1011 } else {
1012 $status->fatal( 'backend-fail-stream', $params['src'] );
1013 }
1014
1015 return $status;
1016 }
1017
1018 /**
1019 * @see FileBackend::streamFile()
1020 */
1021 protected function doStreamFile( array $params ) {
1022 $status = Status::newGood();
1023
1024 $fsFile = $this->getLocalReference( $params );
1025 if ( !$fsFile ) {
1026 $status->fatal( 'backend-fail-stream', $params['src'] );
1027 } elseif ( !readfile( $fsFile->getPath() ) ) {
1028 $status->fatal( 'backend-fail-stream', $params['src'] );
1029 }
1030
1031 return $status;
1032 }
1033
1034 /**
1035 * @see FileBackendBase::getFileList()
1036 */
1037 final public function getFileList( array $params ) {
1038 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1039 if ( $dir === null ) { // invalid storage path
1040 return null;
1041 }
1042 if ( $shard !== null ) {
1043 // File listing is confined to a single container/shard
1044 return $this->getFileListInternal( $fullCont, $dir, $params );
1045 } else {
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 );
1051 }
1052 }
1053
1054 /**
1055 * Do not call this function from places outside FileBackend and ContainerFileListIterator
1056 *
1057 * @param $container string Resolved container name
1058 * @param $dir string Resolved path relative to container
1059 * @param $params Array
1060 * @see FileBackend::getFileList()
1061 */
1062 abstract public function getFileListInternal( $container, $dir, array $params );
1063
1064 /**
1065 * Get the list of supported operations and their corresponding FileOp classes.
1066 *
1067 * @return Array
1068 */
1069 protected function supportedOperations() {
1070 return array(
1071 'store' => 'StoreFileOp',
1072 'copy' => 'CopyFileOp',
1073 'move' => 'MoveFileOp',
1074 'delete' => 'DeleteFileOp',
1075 'create' => 'CreateFileOp',
1076 'null' => 'NullFileOp'
1077 );
1078 }
1079
1080 /**
1081 * Return a list of FileOp objects from a list of operations.
1082 * Do not call this function from places outside FileBackend.
1083 *
1084 * The result must have the same number of items as the input.
1085 * An exception is thrown if an unsupported operation is requested.
1086 *
1087 * @param $ops Array Same format as doOperations()
1088 * @return Array List of FileOp objects
1089 * @throws MWException
1090 */
1091 final public function getOperations( array $ops ) {
1092 $supportedOps = $this->supportedOperations();
1093
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 );
1104 } else {
1105 throw new MWException( "Operation `$opName` is not supported." );
1106 }
1107 }
1108
1109 return $performOps;
1110 }
1111
1112 /**
1113 * @see FileBackendBase::doOperationsInternal()
1114 */
1115 protected function doOperationsInternal( array $ops, array $opts ) {
1116 $status = Status::newGood();
1117
1118 // Build up a list of FileOps...
1119 $performOps = $this->getOperations( $ops );
1120
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() );
1128 }
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
1136 }
1137 }
1138
1139 // Clear any cache entries (after locks acquired)
1140 $this->clearCache();
1141
1142 // Actually attempt the operation batch...
1143 $subStatus = FileOp::attemptBatch( $performOps, $opts );
1144
1145 // Merge errors into status fields
1146 $status->merge( $subStatus );
1147 $status->success = $subStatus->success; // not done in merge()
1148
1149 return $status;
1150 }
1151
1152 /**
1153 * @see FileBackendBase::clearCache()
1154 */
1155 final public function clearCache( array $paths = null ) {
1156 if ( $paths === null ) {
1157 $this->cache = array();
1158 } else {
1159 foreach ( $paths as $path ) {
1160 unset( $this->cache[$path] );
1161 }
1162 }
1163 }
1164
1165 /**
1166 * Prune the cache if it is too big to add an item
1167 *
1168 * @return void
1169 */
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] );
1175 }
1176 }
1177
1178 /**
1179 * Check if a given path is a mwstore:// path.
1180 * This does not do any actual validation or existence checks.
1181 *
1182 * @param $path string
1183 * @return bool
1184 */
1185 final public static function isStoragePath( $path ) {
1186 return ( strpos( $path, 'mwstore://' ) === 0 );
1187 }
1188
1189 /**
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.
1192 *
1193 * @param $storagePath string
1194 * @return Array (backend, container, rel object) or (null, null, null)
1195 */
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"
1204 }
1205 }
1206 return array( null, null, null );
1207 }
1208
1209 /**
1210 * Check if a container name is valid.
1211 * This checks for for length and illegal characters.
1212 *
1213 * @param $container string
1214 * @return bool
1215 */
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 );
1222 }
1223
1224 /**
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.
1228 *
1229 * @param $path string
1230 * @return string|null
1231 */
1232 final protected static function normalizeStoragePath( $path ) {
1233 // Normalize directory separators
1234 $path = strtr( $path, '\\', '/' );
1235 // Use the same traversal protection as Title::secureAndSplit()
1236 if ( strpos( $path, '.' ) !== false ) {
1237 if (
1238 $path === '.' ||
1239 $path === '..' ||
1240 strpos( $path, './' ) === 0 ||
1241 strpos( $path, '../' ) === 0 ||
1242 strpos( $path, '/./' ) !== false ||
1243 strpos( $path, '/../' ) !== false
1244 ) {
1245 return null;
1246 }
1247 }
1248 return $path;
1249 }
1250
1251 /**
1252 * Splits a storage path into an internal container name,
1253 * an internal relative file name, and a container shard suffix.
1254 * Any shard suffix is already appended to the internal container name.
1255 * This also checks that the storage path is valid and within this backend.
1256 *
1257 * If the container is sharded but a suffix could not be determined,
1258 * this means that the path can only refer to a directory and can only
1259 * be scanned by looking in all the container shards.
1260 *
1261 * @param $storagePath string
1262 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1263 */
1264 final protected function resolveStoragePath( $storagePath ) {
1265 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1266 if ( $backend === $this->name ) { // must be for this backend
1267 $relPath = self::normalizeStoragePath( $relPath );
1268 if ( $relPath !== null ) {
1269 // Get shard for the normalized path if this container is sharded
1270 $cShard = $this->getContainerShard( $container, $relPath );
1271 // Validate and sanitize the relative path (backend-specific)
1272 $relPath = $this->resolveContainerPath( $container, $relPath );
1273 if ( $relPath !== null ) {
1274 // Prepend any wiki ID prefix to the container name
1275 $container = $this->fullContainerName( $container );
1276 if ( self::isValidContainerName( $container ) ) {
1277 // Validate and sanitize the container name (backend-specific)
1278 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1279 if ( $container !== null ) {
1280 return array( $container, $relPath, $cShard );
1281 }
1282 }
1283 }
1284 }
1285 }
1286 return array( null, null, null );
1287 }
1288
1289 /**
1290 * Like resolveStoragePath() except null values are returned if
1291 * the container is sharded and the shard could not be determined.
1292 *
1293 * @see FileBackend::resolveStoragePath()
1294 *
1295 * @param $storagePath string
1296 * @return Array (container, path) or (null, null) if invalid
1297 */
1298 final protected function resolveStoragePathReal( $storagePath ) {
1299 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1300 if ( $cShard !== null ) {
1301 return array( $container, $relPath );
1302 }
1303 return array( null, null );
1304 }
1305
1306 /**
1307 * Get the container name shard suffix for a given path.
1308 * Any empty suffix means the container is not sharded.
1309 *
1310 * @param $container string Container name
1311 * @param $relStoragePath string Storage path relative to the container
1312 * @return string|null Returns null if shard could not be determined
1313 */
1314 final protected function getContainerShard( $container, $relPath ) {
1315 $hashLevels = $this->getContainerHashLevels( $container );
1316 if ( $hashLevels === 1 ) { // 16 shards per container
1317 $hashDirRegex = '(?P<shard>[0-9a-f])';
1318 } elseif ( $hashLevels === 2 ) { // 256 shards per container
1319 $hashDirRegex = '[0-9a-f]/(?P<shard>[0-9a-f]{2})';
1320 } else {
1321 return ''; // no sharding
1322 }
1323 // Allow certain directories to be above the hash dirs so as
1324 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1325 // They must be 2+ chars to avoid any hash directory ambiguity.
1326 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1327 return '.' . str_pad( $m['shard'], $hashLevels, '0', STR_PAD_LEFT );
1328 }
1329 return null; // failed to match
1330 }
1331
1332 /**
1333 * Get the number of hash levels for a container.
1334 * If greater than 0, then all file storage paths within
1335 * the container are required to be hashed accordingly.
1336 *
1337 * @param $container string
1338 * @return integer
1339 */
1340 final protected function getContainerHashLevels( $container ) {
1341 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1342 $hashLevels = (int)$this->shardViaHashLevels[$container];
1343 if ( $hashLevels >= 0 && $hashLevels <= 2 ) {
1344 return $hashLevels;
1345 }
1346 }
1347 return 0; // no sharding
1348 }
1349
1350 /**
1351 * Get a list of full container shard suffixes for a container
1352 *
1353 * @param $container string
1354 * @return Array
1355 */
1356 final protected function getContainerSuffixes( $container ) {
1357 $shards = array();
1358 $digits = $this->getContainerHashLevels( $container );
1359 if ( $digits > 0 ) {
1360 $numShards = 1 << ( $digits * 4 );
1361 for ( $index = 0; $index < $numShards; $index++ ) {
1362 $shards[] = '.' . str_pad( dechex( $index ), $digits, '0', STR_PAD_LEFT );
1363 }
1364 }
1365 return $shards;
1366 }
1367
1368 /**
1369 * Get the full container name, including the wiki ID prefix
1370 *
1371 * @param $container string
1372 * @return string
1373 */
1374 final protected function fullContainerName( $container ) {
1375 if ( $this->wikiId != '' ) {
1376 return "{$this->wikiId}-$container";
1377 } else {
1378 return $container;
1379 }
1380 }
1381
1382 /**
1383 * Resolve a container name, checking if it's allowed by the backend.
1384 * This is intended for internal use, such as encoding illegal chars.
1385 * Subclasses can override this to be more restrictive.
1386 *
1387 * @param $container string
1388 * @return string|null
1389 */
1390 protected function resolveContainerName( $container ) {
1391 return $container;
1392 }
1393
1394 /**
1395 * Resolve a relative storage path, checking if it's allowed by the backend.
1396 * This is intended for internal use, such as encoding illegal chars or perhaps
1397 * getting absolute paths (e.g. FS based backends). Note that the relative path
1398 * may be the empty string (e.g. the path is simply to the container).
1399 *
1400 * @param $container string Container name
1401 * @param $relStoragePath string Storage path relative to the container
1402 * @return string|null Path or null if not valid
1403 */
1404 protected function resolveContainerPath( $container, $relStoragePath ) {
1405 return $relStoragePath;
1406 }
1407
1408 /**
1409 * Get the final extension from a storage or FS path
1410 *
1411 * @param $path string
1412 * @return string
1413 */
1414 final public static function extensionFromPath( $path ) {
1415 $i = strrpos( $path, '.' );
1416 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1417 }
1418 }
1419
1420 /**
1421 * FileBackend helper function to handle file listings that span container shards.
1422 * Do not use this class from places outside of FileBackend.
1423 *
1424 * @ingroup FileBackend
1425 */
1426 class ContainerShardListIterator implements Iterator {
1427 /* @var FileBackend */
1428 protected $backend;
1429 /* @var Array */
1430 protected $params;
1431 /* @var Array */
1432 protected $shardSuffixes;
1433 protected $container; // string
1434 protected $directory; // string
1435
1436 /* @var Traversable */
1437 protected $iter;
1438 protected $curShard = 0; // integer
1439 protected $pos = 0; // integer
1440
1441 /**
1442 * @param $backend FileBackend
1443 * @param $container string Full storage container name
1444 * @param $dir string Storage directory relative to container
1445 * @param $suffixes Array List of container shard suffixes
1446 * @param $params Array
1447 */
1448 public function __construct(
1449 FileBackend $backend, $container, $dir, array $suffixes, array $params
1450 ) {
1451 $this->backend = $backend;
1452 $this->container = $container;
1453 $this->directory = $dir;
1454 $this->shardSuffixes = $suffixes;
1455 $this->params = $params;
1456 }
1457
1458 public function current() {
1459 if ( is_array( $this->iter ) ) {
1460 return current( $this->iter );
1461 } else {
1462 return $this->iter->current();
1463 }
1464 }
1465
1466 public function key() {
1467 return $this->pos;
1468 }
1469
1470 public function next() {
1471 ++$this->pos;
1472 if ( is_array( $this->iter ) ) {
1473 next( $this->iter );
1474 } else {
1475 $this->iter->next();
1476 }
1477 // Find the next non-empty shard if no elements are left
1478 $this->nextShardIteratorIfNotValid();
1479 }
1480
1481 /**
1482 * If the iterator for this container shard is out of items,
1483 * then move on to the next container that has items.
1484 * If there are none, then it advances to the last container.
1485 */
1486 protected function nextShardIteratorIfNotValid() {
1487 while ( !$this->valid() ) {
1488 if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
1489 break; // no more container shards
1490 }
1491 $this->setIteratorFromCurrentShard();
1492 }
1493 }
1494
1495 protected function setIteratorFromCurrentShard() {
1496 $suffix = $this->shardSuffixes[$this->curShard];
1497 $this->iter = $this->backend->getFileListInternal(
1498 "{$this->container}{$suffix}", $this->directory, $this->params );
1499 }
1500
1501 public function rewind() {
1502 $this->pos = 0;
1503 $this->curShard = 0;
1504 $this->setIteratorFromCurrentShard();
1505 // Find the next non-empty shard if this one has no elements
1506 $this->nextShardIteratorIfNotValid();
1507 }
1508
1509 public function valid() {
1510 if ( $this->iter == null ) {
1511 return false; // some failure?
1512 } elseif ( is_array( $this->iter ) ) {
1513 return ( current( $this->iter ) !== false ); // no paths can have this value
1514 } else {
1515 return $this->iter->valid();
1516 }
1517 }
1518 }