77018ab7650b894ba891470a28dd1415d9becc09
[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 * We may have multiple different backends of the same type.
79 * For example, we can have two Swift backends using different proxies.
80 *
81 * @return string
82 */
83 final public function getName() {
84 return $this->name;
85 }
86
87 /**
88 * This is the main entry point into the backend for write operations.
89 * Callers supply an ordered list of operations to perform as a transaction.
90 * If any serious errors occur, all attempted operations will be rolled back.
91 *
92 * $ops is an array of arrays. The outer array holds a list of operations.
93 * Each inner array is a set of key value pairs that specify an operation.
94 *
95 * Supported operations and their parameters:
96 * a) Create a new file in storage with the contents of a string
97 * array(
98 * 'op' => 'create',
99 * 'dst' => <storage path>,
100 * 'content' => <string of new file contents>,
101 * 'overwrite' => <boolean>,
102 * 'overwriteSame' => <boolean>
103 * )
104 * b) Copy a file system file into storage
105 * array(
106 * 'op' => 'store',
107 * 'src' => <file system path>,
108 * 'dst' => <storage path>,
109 * 'overwrite' => <boolean>,
110 * 'overwriteSame' => <boolean>
111 * )
112 * c) Copy a file within storage
113 * array(
114 * 'op' => 'copy',
115 * 'src' => <storage path>,
116 * 'dst' => <storage path>,
117 * 'overwrite' => <boolean>,
118 * 'overwriteSame' => <boolean>
119 * )
120 * d) Move a file within storage
121 * array(
122 * 'op' => 'move',
123 * 'src' => <storage path>,
124 * 'dst' => <storage path>,
125 * 'overwrite' => <boolean>,
126 * 'overwriteSame' => <boolean>
127 * )
128 * e) Delete a file within storage
129 * array(
130 * 'op' => 'delete',
131 * 'src' => <storage path>,
132 * 'ignoreMissingSource' => <boolean>
133 * )
134 * f) Do nothing (no-op)
135 * array(
136 * 'op' => 'null',
137 * )
138 *
139 * Boolean flags for operations (operation-specific):
140 * 'ignoreMissingSource' : The operation will simply succeed and do
141 * nothing if the source file does not exist.
142 * 'overwrite' : Any destination file will be overwritten.
143 * 'overwriteSame' : An error will not be given if a file already
144 * exists at the destination that has the same
145 * contents as the new contents to be written there.
146 *
147 * $opts is an associative of boolean flags, including:
148 * 'force' : Errors that would normally cause a rollback do not.
149 * The remaining operations are still attempted if any fail.
150 * 'nonLocking' : No locks are acquired for the operations.
151 * This can increase performance for non-critical writes.
152 * This has no effect unless the 'force' flag is set.
153 * 'allowStale' : Don't require the latest available data.
154 * This can increase performance for non-critical writes.
155 * This has no effect unless the 'force' flag is set.
156 *
157 * Remarks:
158 * File system paths given to operations should refer to files that are
159 * either locked or otherwise safe from modification from other processes.
160 * Normally these files will be new temp files, which should be adequate.
161 *
162 * Return value:
163 * This returns a Status, which contains all warnings and fatals that occured
164 * during the operation. The 'failCount', 'successCount', and 'success' members
165 * will reflect each operation attempted. The status will be "OK" unless any
166 * of the operations failed and the 'force' parameter was not set.
167 *
168 * @param $ops Array List of operations to execute in order
169 * @param $opts Array Batch operation options
170 * @return Status
171 */
172 final public function doOperations( array $ops, array $opts = array() ) {
173 if ( $this->readOnly != '' ) {
174 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
175 }
176 if ( empty( $opts['force'] ) ) { // sanity
177 unset( $opts['nonLocking'] );
178 unset( $opts['allowStale'] );
179 }
180 return $this->doOperationsInternal( $ops, $opts );
181 }
182
183 /**
184 * @see FileBackendBase::doOperations()
185 */
186 abstract protected function doOperationsInternal( array $ops, array $opts );
187
188 /**
189 * Same as doOperations() except it takes a single operation.
190 * If you are doing a batch of operations that should either
191 * all succeed or all fail, then use that function instead.
192 *
193 * @see FileBackendBase::doOperations()
194 *
195 * @param $op Array Operation
196 * @param $opts Array Operation options
197 * @return Status
198 */
199 final public function doOperation( array $op, array $opts = array() ) {
200 return $this->doOperations( array( $op ), $opts );
201 }
202
203 /**
204 * Performs a single create operation.
205 * This sets $params['op'] to 'create' and passes it to doOperation().
206 *
207 * @see FileBackendBase::doOperation()
208 *
209 * @param $params Array Operation parameters
210 * @param $opts Array Operation options
211 * @return Status
212 */
213 final public function create( array $params, array $opts = array() ) {
214 $params['op'] = 'create';
215 return $this->doOperation( $params, $opts );
216 }
217
218 /**
219 * Performs a single store operation.
220 * This sets $params['op'] to 'store' and passes it to doOperation().
221 *
222 * @see FileBackendBase::doOperation()
223 *
224 * @param $params Array Operation parameters
225 * @param $opts Array Operation options
226 * @return Status
227 */
228 final public function store( array $params, array $opts = array() ) {
229 $params['op'] = 'store';
230 return $this->doOperation( $params, $opts );
231 }
232
233 /**
234 * Performs a single copy operation.
235 * This sets $params['op'] to 'copy' and passes it to doOperation().
236 *
237 * @see FileBackendBase::doOperation()
238 *
239 * @param $params Array Operation parameters
240 * @param $opts Array Operation options
241 * @return Status
242 */
243 final public function copy( array $params, array $opts = array() ) {
244 $params['op'] = 'copy';
245 return $this->doOperation( $params, $opts );
246 }
247
248 /**
249 * Performs a single move operation.
250 * This sets $params['op'] to 'move' and passes it to doOperation().
251 *
252 * @see FileBackendBase::doOperation()
253 *
254 * @param $params Array Operation parameters
255 * @param $opts Array Operation options
256 * @return Status
257 */
258 final public function move( array $params, array $opts = array() ) {
259 $params['op'] = 'move';
260 return $this->doOperation( $params, $opts );
261 }
262
263 /**
264 * Performs a single delete operation.
265 * This sets $params['op'] to 'delete' and passes it to doOperation().
266 *
267 * @see FileBackendBase::doOperation()
268 *
269 * @param $params Array Operation parameters
270 * @param $opts Array Operation options
271 * @return Status
272 */
273 final public function delete( array $params, array $opts = array() ) {
274 $params['op'] = 'delete';
275 return $this->doOperation( $params, $opts );
276 }
277
278 /**
279 * Concatenate a list of storage files into a single file on the file system
280 * $params include:
281 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
282 * dst : file system path to 0-byte temp file
283 *
284 * @param $params Array Operation parameters
285 * @return Status
286 */
287 abstract public function concatenate( array $params );
288
289 /**
290 * Prepare a storage directory for usage.
291 * This will create any required containers and parent directories.
292 * Backends using key/value stores only need to create the container.
293 *
294 * $params include:
295 * dir : storage directory
296 *
297 * @param $params Array
298 * @return Status
299 */
300 final public function prepare( array $params ) {
301 if ( $this->readOnly != '' ) {
302 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
303 }
304 return $this->doPrepare( $params );
305 }
306
307 /**
308 * @see FileBackendBase::prepare()
309 */
310 abstract protected function doPrepare( array $params );
311
312 /**
313 * Take measures to block web access to a storage directory and
314 * the container it belongs to. FS backends might add .htaccess
315 * files whereas key/value store backends might restrict container
316 * access to the auth user that represents end-users in web request.
317 * This is not guaranteed to actually do anything.
318 *
319 * $params include:
320 * dir : storage directory
321 * noAccess : try to deny file access
322 * noListing : try to deny file listing
323 *
324 * @param $params Array
325 * @return Status
326 */
327 final public function secure( array $params ) {
328 if ( $this->readOnly != '' ) {
329 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
330 }
331 $status = $this->doPrepare( $params ); // dir must exist to restrict it
332 if ( $status->isOK() ) {
333 $status->merge( $this->doSecure( $params ) );
334 }
335 return $status;
336 }
337
338 /**
339 * @see FileBackendBase::secure()
340 */
341 abstract protected function doSecure( array $params );
342
343 /**
344 * Delete a storage directory if it is empty.
345 * Backends using key/value stores may do nothing unless the directory
346 * is that of an empty container, in which case it should be deleted.
347 *
348 * $params include:
349 * dir : storage directory
350 *
351 * @param $params Array
352 * @return Status
353 */
354 final public function clean( array $params ) {
355 if ( $this->readOnly != '' ) {
356 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
357 }
358 return $this->doClean( $params );
359 }
360
361 /**
362 * @see FileBackendBase::clean()
363 */
364 abstract protected function doClean( array $params );
365
366 /**
367 * Check if a file exists at a storage path in the backend.
368 * This returns false if only a directory exists at the path.
369 *
370 * $params include:
371 * src : source storage path
372 * latest : use the latest available data
373 *
374 * @param $params Array
375 * @return bool|null Returns null on failure
376 */
377 abstract public function fileExists( array $params );
378
379 /**
380 * Get the last-modified timestamp of the file at a storage path.
381 *
382 * $params include:
383 * src : source storage path
384 * latest : use the latest available data
385 *
386 * @param $params Array
387 * @return string|false TS_MW timestamp or false on failure
388 */
389 abstract public function getFileTimestamp( array $params );
390
391 /**
392 * Get the contents of a file at a storage path in the backend.
393 * This should be avoided for potentially large files.
394 *
395 * $params include:
396 * src : source storage path
397 * latest : use the latest available data
398 *
399 * @param $params Array
400 * @return string|false Returns false on failure
401 */
402 abstract public function getFileContents( array $params );
403
404 /**
405 * Get the size (bytes) of a file at a storage path in the backend.
406 *
407 * $params include:
408 * src : source storage path
409 * latest : use the latest available data
410 *
411 * @param $params Array
412 * @return integer|false Returns false on failure
413 */
414 abstract public function getFileSize( array $params );
415
416 /**
417 * Get quick information about a file at a storage path in the backend.
418 * If the file does not exist, then this returns false.
419 * Otherwise, the result is an associative array that includes:
420 * mtime : the last-modified timestamp (TS_MW)
421 * size : the file size (bytes)
422 * Additional values may be included for internal use only.
423 *
424 * $params include:
425 * src : source storage path
426 * latest : use the latest available data
427 *
428 * @param $params Array
429 * @return Array|false|null Returns null on failure
430 */
431 abstract public function getFileStat( array $params );
432
433 /**
434 * Get a SHA-1 hash of the file at a storage path in the backend.
435 *
436 * $params include:
437 * src : source storage path
438 * latest : use the latest available data
439 *
440 * @param $params Array
441 * @return string|false Hash string or false on failure
442 */
443 abstract public function getFileSha1Base36( array $params );
444
445 /**
446 * Get the properties of the file at a storage path in the backend.
447 * Returns FSFile::placeholderProps() on failure.
448 *
449 * $params include:
450 * src : source storage path
451 * latest : use the latest available data
452 *
453 * @param $params Array
454 * @return Array
455 */
456 abstract public function getFileProps( array $params );
457
458 /**
459 * Stream the file at a storage path in the backend.
460 * If the file does not exists, a 404 error will be given.
461 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
462 * must be sent if streaming began, while none should be sent otherwise.
463 * Implementations should flush the output buffer before sending data.
464 *
465 * $params include:
466 * src : source storage path
467 * headers : additional HTTP headers to send on success
468 * latest : use the latest available data
469 *
470 * @param $params Array
471 * @return Status
472 */
473 abstract public function streamFile( array $params );
474
475 /**
476 * Returns a file system file, identical to the file at a storage path.
477 * The file returned is either:
478 * a) A local copy of the file at a storage path in the backend.
479 * The temporary copy will have the same extension as the source.
480 * b) An original of the file at a storage path in the backend.
481 * Temporary files may be purged when the file object falls out of scope.
482 *
483 * Write operations should *never* be done on this file as some backends
484 * may do internal tracking or may be instances of FileBackendMultiWrite.
485 * In that later case, there are copies of the file that must stay in sync.
486 *
487 * $params include:
488 * src : source storage path
489 * latest : use the latest available data
490 *
491 * @param $params Array
492 * @return FSFile|null Returns null on failure
493 */
494 abstract public function getLocalReference( array $params );
495
496 /**
497 * Get a local copy on disk of the file at a storage path in the backend.
498 * The temporary copy will have the same file extension as the source.
499 * Temporary files may be purged when the file object falls out of scope.
500 *
501 * $params include:
502 * src : source storage path
503 * latest : use the latest available data
504 *
505 * @param $params Array
506 * @return TempFSFile|null Returns null on failure
507 */
508 abstract public function getLocalCopy( array $params );
509
510 /**
511 * Get an iterator to list out all stored files under a storage directory.
512 * If the directory is of the form "mwstore://container", then all items in
513 * the container should be listed. If of the form "mwstore://container/dir",
514 * then all items under that container directory should be listed.
515 * Results should be storage paths relative to the given directory.
516 *
517 * $params include:
518 * dir : storage path directory
519 *
520 * @return Traversable|Array|null Returns null on failure
521 */
522 abstract public function getFileList( array $params );
523
524 /**
525 * Invalidate any in-process file existence and property cache.
526 * If $paths is given, then only the cache for those files will be cleared.
527 *
528 * @param $paths Array Storage paths (optional)
529 * @return void
530 */
531 abstract public function clearCache( array $paths = null );
532
533 /**
534 * Lock the files at the given storage paths in the backend.
535 * This will either lock all the files or none (on failure).
536 *
537 * Callers should consider using getScopedFileLocks() instead.
538 *
539 * @param $paths Array Storage paths
540 * @param $type integer LockManager::LOCK_* constant
541 * @return Status
542 */
543 final public function lockFiles( array $paths, $type ) {
544 return $this->lockManager->lock( $paths, $type );
545 }
546
547 /**
548 * Unlock the files at the given storage paths in the backend.
549 *
550 * @param $paths Array Storage paths
551 * @param $type integer LockManager::LOCK_* constant
552 * @return Status
553 */
554 final public function unlockFiles( array $paths, $type ) {
555 return $this->lockManager->unlock( $paths, $type );
556 }
557
558 /**
559 * Lock the files at the given storage paths in the backend.
560 * This will either lock all the files or none (on failure).
561 * On failure, the status object will be updated with errors.
562 *
563 * Once the return value goes out scope, the locks will be released and
564 * the status updated. Unlock fatals will not change the status "OK" value.
565 *
566 * @param $paths Array Storage paths
567 * @param $type integer LockManager::LOCK_* constant
568 * @param $status Status Status to update on lock/unlock
569 * @return ScopedLock|null Returns null on failure
570 */
571 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
572 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
573 }
574 }
575
576 /**
577 * Base class for all single-write backends.
578 * This class defines the methods as abstract that subclasses must implement.
579 * Callers outside of FileBackend and its helper classes, such as FileOp,
580 * should only call functions that are present in FileBackendBase.
581 *
582 * The FileBackendBase operations are implemented using primitive functions
583 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
584 * This class is also responsible for path resolution and sanitization.
585 *
586 * @ingroup FileBackend
587 * @since 1.19
588 */
589 abstract class FileBackend extends FileBackendBase {
590 /** @var Array */
591 protected $cache = array(); // (storage path => key => value)
592 protected $maxCacheSize = 75; // integer; max paths with entries
593 /** @var Array */
594 protected $shardViaHashLevels = array(); // (container name => integer)
595
596 protected $maxFileSize = 1000000000; // integer bytes (1GB)
597
598 /**
599 * Get the maximum allowable file size given backend
600 * medium restrictions and basic performance constraints.
601 * Do not call this function from places outside FileBackend and FileOp.
602 *
603 * @return integer Bytes
604 */
605 final public function maxFileSizeInternal() {
606 return $this->maxFileSize;
607 }
608
609 /**
610 * Check if a file can be created at a given storage path.
611 * FS backends should check if the parent directory exists and the file is writable.
612 * Backends using key/value stores should check if the container exists.
613 *
614 * @param $storagePath string
615 * @return bool
616 */
617 abstract public function isPathUsableInternal( $storagePath );
618
619 /**
620 * Create a file in the backend with the given contents.
621 * Do not call this function from places outside FileBackend and FileOp.
622 *
623 * $params include:
624 * content : the raw file contents
625 * dst : destination storage path
626 * overwrite : overwrite any file that exists at the destination
627 *
628 * @param $params Array
629 * @return Status
630 */
631 final public function createInternal( array $params ) {
632 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
633 $status = Status::newFatal( 'backend-fail-create', $params['dst'] );
634 } else {
635 $status = $this->doCreateInternal( $params );
636 $this->clearCache( array( $params['dst'] ) );
637 }
638 return $status;
639 }
640
641 /**
642 * @see FileBackend::createInternal()
643 */
644 abstract protected function doCreateInternal( array $params );
645
646 /**
647 * Store a file into the backend from a file on disk.
648 * Do not call this function from places outside FileBackend and FileOp.
649 *
650 * $params include:
651 * src : source path on disk
652 * dst : destination storage path
653 * overwrite : overwrite any file that exists at the destination
654 *
655 * @param $params Array
656 * @return Status
657 */
658 final public function storeInternal( array $params ) {
659 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
660 $status = Status::newFatal( 'backend-fail-store', $params['dst'] );
661 } else {
662 $status = $this->doStoreInternal( $params );
663 $this->clearCache( array( $params['dst'] ) );
664 }
665 return $status;
666 }
667
668 /**
669 * @see FileBackend::storeInternal()
670 */
671 abstract protected function doStoreInternal( array $params );
672
673 /**
674 * Copy a file from one storage path to another in the backend.
675 * Do not call this function from places outside FileBackend and FileOp.
676 *
677 * $params include:
678 * src : source storage path
679 * dst : destination storage path
680 * overwrite : overwrite any file that exists at the destination
681 *
682 * @param $params Array
683 * @return Status
684 */
685 final public function copyInternal( array $params ) {
686 $status = $this->doCopyInternal( $params );
687 $this->clearCache( array( $params['dst'] ) );
688 return $status;
689 }
690
691 /**
692 * @see FileBackend::copyInternal()
693 */
694 abstract protected function doCopyInternal( array $params );
695
696 /**
697 * Delete a file at the storage path.
698 * Do not call this function from places outside FileBackend and FileOp.
699 *
700 * $params include:
701 * src : source storage path
702 * ignoreMissingSource : do nothing if the source file does not exist
703 *
704 * @param $params Array
705 * @return Status
706 */
707 final public function deleteInternal( array $params ) {
708 $status = $this->doDeleteInternal( $params );
709 $this->clearCache( array( $params['src'] ) );
710 return $status;
711 }
712
713 /**
714 * @see FileBackend::deleteInternal()
715 */
716 abstract protected function doDeleteInternal( array $params );
717
718 /**
719 * Move a file from one storage path to another in the backend.
720 * Do not call this function from places outside FileBackend and FileOp.
721 *
722 * $params include:
723 * src : source storage path
724 * dst : destination storage path
725 * overwrite : overwrite any file that exists at the destination
726 *
727 * @param $params Array
728 * @return Status
729 */
730 final public function moveInternal( array $params ) {
731 $status = $this->doMoveInternal( $params );
732 $this->clearCache( array( $params['src'], $params['dst'] ) );
733 return $status;
734 }
735
736 /**
737 * @see FileBackend::moveInternal()
738 */
739 protected function doMoveInternal( array $params ) {
740 // Copy source to dest
741 $status = $this->copyInternal( $params );
742 if ( !$status->isOK() ) {
743 return $status;
744 }
745 // Delete source (only fails due to races or medium going down)
746 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
747 $status->setResult( true, $status->value ); // ignore delete() errors
748 return $status;
749 }
750
751 /**
752 * @see FileBackendBase::concatenate()
753 */
754 final public function concatenate( array $params ) {
755 $status = Status::newGood();
756
757 // Try to lock the source files for the scope of this function
758 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
759 if ( !$status->isOK() ) {
760 return $status; // abort
761 }
762
763 // Actually do the concatenation
764 $status->merge( $this->doConcatenate( $params ) );
765
766 return $status;
767 }
768
769 /**
770 * @see FileBackend::concatenate()
771 */
772 protected function doConcatenate( array $params ) {
773 $status = Status::newGood();
774 $tmpPath = $params['dst']; // convenience
775
776 // Check that the specified temp file is valid...
777 wfSuppressWarnings();
778 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
779 wfRestoreWarnings();
780 if ( !$ok ) { // not present or not empty
781 $status->fatal( 'backend-fail-opentemp', $tmpPath );
782 return $status;
783 }
784
785 // Build up the temp file using the source chunks (in order)...
786 $tmpHandle = fopen( $tmpPath, 'a' );
787 if ( $tmpHandle === false ) {
788 $status->fatal( 'backend-fail-opentemp', $tmpPath );
789 return $status;
790 }
791 foreach ( $params['srcs'] as $virtualSource ) {
792 // Get a local FS version of the chunk
793 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
794 if ( !$tmpFile ) {
795 $status->fatal( 'backend-fail-read', $virtualSource );
796 return $status;
797 }
798 // Get a handle to the local FS version
799 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
800 if ( $sourceHandle === false ) {
801 fclose( $tmpHandle );
802 $status->fatal( 'backend-fail-read', $virtualSource );
803 return $status;
804 }
805 // Append chunk to file (pass chunk size to avoid magic quotes)
806 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
807 fclose( $sourceHandle );
808 fclose( $tmpHandle );
809 $status->fatal( 'backend-fail-writetemp', $tmpPath );
810 return $status;
811 }
812 fclose( $sourceHandle );
813 }
814 if ( !fclose( $tmpHandle ) ) {
815 $status->fatal( 'backend-fail-closetemp', $tmpPath );
816 return $status;
817 }
818
819 clearstatcache(); // temp file changed
820
821 return $status;
822 }
823
824 /**
825 * @see FileBackendBase::doPrepare()
826 */
827 final protected function doPrepare( array $params ) {
828 $status = Status::newGood();
829 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
830 if ( $dir === null ) {
831 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
832 return $status; // invalid storage path
833 }
834 if ( $shard !== null ) { // confined to a single container/shard
835 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
836 } else { // directory is on several shards
837 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
838 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
839 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
840 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
841 }
842 }
843 return $status;
844 }
845
846 /**
847 * @see FileBackend::doPrepare()
848 */
849 protected function doPrepareInternal( $container, $dir, array $params ) {
850 return Status::newGood();
851 }
852
853 /**
854 * @see FileBackendBase::doSecure()
855 */
856 final protected function doSecure( array $params ) {
857 $status = Status::newGood();
858 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
859 if ( $dir === null ) {
860 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
861 return $status; // invalid storage path
862 }
863 if ( $shard !== null ) { // confined to a single container/shard
864 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
865 } else { // directory is on several shards
866 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
867 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
868 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
869 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
870 }
871 }
872 return $status;
873 }
874
875 /**
876 * @see FileBackend::doSecure()
877 */
878 protected function doSecureInternal( $container, $dir, array $params ) {
879 return Status::newGood();
880 }
881
882 /**
883 * @see FileBackendBase::doClean()
884 */
885 final protected function doClean( array $params ) {
886 $status = Status::newGood();
887 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
888 if ( $dir === null ) {
889 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
890 return $status; // invalid storage path
891 }
892 // Attempt to lock this directory...
893 $filesLockEx = array( $params['dir'] );
894 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
895 if ( !$status->isOK() ) {
896 return $status; // abort
897 }
898 if ( $shard !== null ) { // confined to a single container/shard
899 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
900 } else { // directory is on several shards
901 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
902 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
903 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
904 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
905 }
906 }
907 return $status;
908 }
909
910 /**
911 * @see FileBackend::doClean()
912 */
913 protected function doCleanInternal( $container, $dir, array $params ) {
914 return Status::newGood();
915 }
916
917 /**
918 * @see FileBackendBase::fileExists()
919 */
920 final public function fileExists( array $params ) {
921 $stat = $this->getFileStat( $params );
922 if ( $stat === null ) {
923 return null; // failure
924 }
925 return (bool)$stat;
926 }
927
928 /**
929 * @see FileBackendBase::getFileTimestamp()
930 */
931 final public function getFileTimestamp( array $params ) {
932 $stat = $this->getFileStat( $params );
933 if ( $stat ) {
934 return $stat['mtime'];
935 } else {
936 return false;
937 }
938 }
939
940 /**
941 * @see FileBackendBase::getFileSize()
942 */
943 final public function getFileSize( array $params ) {
944 $stat = $this->getFileStat( $params );
945 if ( $stat ) {
946 return $stat['size'];
947 } else {
948 return false;
949 }
950 }
951
952 /**
953 * @see FileBackendBase::getFileStat()
954 */
955 final public function getFileStat( array $params ) {
956 $path = $params['src'];
957 $latest = !empty( $params['latest'] );
958 if ( isset( $this->cache[$path]['stat'] ) ) {
959 // If we want the latest data, check that this cached
960 // value was in fact fetched with the latest available data.
961 if ( !$latest || $this->cache[$path]['stat']['latest'] ) {
962 return $this->cache[$path]['stat'];
963 }
964 }
965 $stat = $this->doGetFileStat( $params );
966 if ( is_array( $stat ) ) { // don't cache negatives
967 $this->trimCache(); // limit memory
968 $this->cache[$path]['stat'] = $stat;
969 $this->cache[$path]['stat']['latest'] = $latest;
970 }
971 return $stat;
972 }
973
974 /**
975 * @see FileBackend::getFileStat()
976 */
977 abstract protected function doGetFileStat( array $params );
978
979 /**
980 * @see FileBackendBase::getFileContents()
981 */
982 public function getFileContents( array $params ) {
983 $tmpFile = $this->getLocalReference( $params );
984 if ( !$tmpFile ) {
985 return false;
986 }
987 wfSuppressWarnings();
988 $data = file_get_contents( $tmpFile->getPath() );
989 wfRestoreWarnings();
990 return $data;
991 }
992
993 /**
994 * @see FileBackendBase::getFileSha1Base36()
995 */
996 final public function getFileSha1Base36( array $params ) {
997 $path = $params['src'];
998 if ( isset( $this->cache[$path]['sha1'] ) ) {
999 return $this->cache[$path]['sha1'];
1000 }
1001 $hash = $this->doGetFileSha1Base36( $params );
1002 if ( $hash ) { // don't cache negatives
1003 $this->trimCache(); // limit memory
1004 $this->cache[$path]['sha1'] = $hash;
1005 }
1006 return $hash;
1007 }
1008
1009 /**
1010 * @see FileBackend::getFileSha1Base36()
1011 */
1012 protected function doGetFileSha1Base36( array $params ) {
1013 $fsFile = $this->getLocalReference( $params );
1014 if ( !$fsFile ) {
1015 return false;
1016 } else {
1017 return $fsFile->getSha1Base36();
1018 }
1019 }
1020
1021 /**
1022 * @see FileBackendBase::getFileProps()
1023 */
1024 public function getFileProps( array $params ) {
1025 $fsFile = $this->getLocalReference( $params );
1026 if ( !$fsFile ) {
1027 return FSFile::placeholderProps();
1028 } else {
1029 return $fsFile->getProps();
1030 }
1031 }
1032
1033 /**
1034 * @see FileBackendBase::getLocalReference()
1035 */
1036 public function getLocalReference( array $params ) {
1037 $path = $params['src'];
1038 if ( isset( $this->cache[$path]['localRef'] ) ) {
1039 return $this->cache[$path]['localRef'];
1040 }
1041 $tmpFile = $this->getLocalCopy( $params );
1042 if ( $tmpFile ) { // don't cache negatives
1043 $this->trimCache(); // limit memory
1044 $this->cache[$path]['localRef'] = $tmpFile;
1045 }
1046 return $tmpFile;
1047 }
1048
1049 /**
1050 * @see FileBackendBase::streamFile()
1051 */
1052 final public function streamFile( array $params ) {
1053 $status = Status::newGood();
1054
1055 $info = $this->getFileStat( $params );
1056 if ( !$info ) { // let StreamFile handle the 404
1057 $status->fatal( 'backend-fail-notexists', $params['src'] );
1058 }
1059
1060 // Set output buffer and HTTP headers for stream
1061 $extraHeaders = $params['headers'] ? $params['headers'] : array();
1062 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
1063 if ( $res == StreamFile::NOT_MODIFIED ) {
1064 // do nothing; client cache is up to date
1065 } elseif ( $res == StreamFile::READY_STREAM ) {
1066 $status = $this->doStreamFile( $params );
1067 } else {
1068 $status->fatal( 'backend-fail-stream', $params['src'] );
1069 }
1070
1071 return $status;
1072 }
1073
1074 /**
1075 * @see FileBackend::streamFile()
1076 */
1077 protected function doStreamFile( array $params ) {
1078 $status = Status::newGood();
1079
1080 $fsFile = $this->getLocalReference( $params );
1081 if ( !$fsFile ) {
1082 $status->fatal( 'backend-fail-stream', $params['src'] );
1083 } elseif ( !readfile( $fsFile->getPath() ) ) {
1084 $status->fatal( 'backend-fail-stream', $params['src'] );
1085 }
1086
1087 return $status;
1088 }
1089
1090 /**
1091 * @see FileBackendBase::getFileList()
1092 */
1093 final public function getFileList( array $params ) {
1094 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1095 if ( $dir === null ) { // invalid storage path
1096 return null;
1097 }
1098 if ( $shard !== null ) {
1099 // File listing is confined to a single container/shard
1100 return $this->getFileListInternal( $fullCont, $dir, $params );
1101 } else {
1102 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
1103 // File listing spans multiple containers/shards
1104 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
1105 return new FileBackendShardListIterator( $this,
1106 $fullCont, $this->getContainerSuffixes( $shortCont ), $params );
1107 }
1108 }
1109
1110 /**
1111 * Do not call this function from places outside FileBackend and ContainerFileListIterator
1112 *
1113 * @param $container string Resolved container name
1114 * @param $dir string Resolved path relative to container
1115 * @param $params Array
1116 * @see FileBackend::getFileList()
1117 */
1118 abstract public function getFileListInternal( $container, $dir, array $params );
1119
1120 /**
1121 * Get the list of supported operations and their corresponding FileOp classes.
1122 *
1123 * @return Array
1124 */
1125 protected function supportedOperations() {
1126 return array(
1127 'store' => 'StoreFileOp',
1128 'copy' => 'CopyFileOp',
1129 'move' => 'MoveFileOp',
1130 'delete' => 'DeleteFileOp',
1131 'create' => 'CreateFileOp',
1132 'null' => 'NullFileOp'
1133 );
1134 }
1135
1136 /**
1137 * Return a list of FileOp objects from a list of operations.
1138 * Do not call this function from places outside FileBackend.
1139 *
1140 * The result must have the same number of items as the input.
1141 * An exception is thrown if an unsupported operation is requested.
1142 *
1143 * @param $ops Array Same format as doOperations()
1144 * @return Array List of FileOp objects
1145 * @throws MWException
1146 */
1147 final public function getOperations( array $ops ) {
1148 $supportedOps = $this->supportedOperations();
1149
1150 $performOps = array(); // array of FileOp objects
1151 // Build up ordered array of FileOps...
1152 foreach ( $ops as $operation ) {
1153 $opName = $operation['op'];
1154 if ( isset( $supportedOps[$opName] ) ) {
1155 $class = $supportedOps[$opName];
1156 // Get params for this operation
1157 $params = $operation;
1158 // Append the FileOp class
1159 $performOps[] = new $class( $this, $params );
1160 } else {
1161 throw new MWException( "Operation `$opName` is not supported." );
1162 }
1163 }
1164
1165 return $performOps;
1166 }
1167
1168 /**
1169 * @see FileBackendBase::doOperationsInternal()
1170 */
1171 protected function doOperationsInternal( array $ops, array $opts ) {
1172 $status = Status::newGood();
1173
1174 // Build up a list of FileOps...
1175 $performOps = $this->getOperations( $ops );
1176
1177 // Acquire any locks as needed...
1178 if ( empty( $opts['nonLocking'] ) ) {
1179 // Build up a list of files to lock...
1180 $filesLockEx = $filesLockSh = array();
1181 foreach ( $performOps as $fileOp ) {
1182 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
1183 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
1184 }
1185 // Optimization: if doing an EX lock anyway, don't also set an SH one
1186 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
1187 // Get a shared lock on the parent directory of each path changed
1188 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
1189 // Try to lock those files for the scope of this function...
1190 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager::LOCK_UW, $status );
1191 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
1192 if ( !$status->isOK() ) {
1193 return $status; // abort
1194 }
1195 }
1196
1197 // Clear any cache entries (after locks acquired)
1198 $this->clearCache();
1199
1200 // Actually attempt the operation batch...
1201 $subStatus = FileOp::attemptBatch( $performOps, $opts );
1202
1203 // Merge errors into status fields
1204 $status->merge( $subStatus );
1205 $status->success = $subStatus->success; // not done in merge()
1206
1207 return $status;
1208 }
1209
1210 /**
1211 * @see FileBackendBase::clearCache()
1212 */
1213 final public function clearCache( array $paths = null ) {
1214 if ( $paths === null ) {
1215 $this->cache = array();
1216 } else {
1217 foreach ( $paths as $path ) {
1218 unset( $this->cache[$path] );
1219 }
1220 }
1221 $this->doClearCache( $paths );
1222 }
1223
1224 /**
1225 * Clears any additional stat caches for storage paths
1226 *
1227 * @see FileBackendBase::clearCache()
1228 *
1229 * @param $paths Array Storage paths (optional)
1230 * @return void
1231 */
1232 protected function doClearCache( array $paths = null ) {}
1233
1234 /**
1235 * Prune the cache if it is too big to add an item
1236 *
1237 * @return void
1238 */
1239 protected function trimCache() {
1240 if ( count( $this->cache ) >= $this->maxCacheSize ) {
1241 reset( $this->cache );
1242 $key = key( $this->cache );
1243 unset( $this->cache[$key] );
1244 }
1245 }
1246
1247 /**
1248 * Check if a given path is a mwstore:// path.
1249 * This does not do any actual validation or existence checks.
1250 *
1251 * @param $path string
1252 * @return bool
1253 */
1254 final public static function isStoragePath( $path ) {
1255 return ( strpos( $path, 'mwstore://' ) === 0 );
1256 }
1257
1258 /**
1259 * Split a storage path (e.g. "mwstore://backend/container/path/to/object")
1260 * into a backend name, a container name, and a relative object path.
1261 *
1262 * @param $storagePath string
1263 * @return Array (backend, container, rel object) or (null, null, null)
1264 */
1265 final public static function splitStoragePath( $storagePath ) {
1266 if ( self::isStoragePath( $storagePath ) ) {
1267 // Note: strlen( 'mwstore://' ) = 10
1268 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1269 if ( count( $parts ) == 3 ) {
1270 return $parts; // e.g. "backend/container/path"
1271 } elseif ( count( $parts ) == 2 ) {
1272 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1273 }
1274 }
1275 return array( null, null, null );
1276 }
1277
1278 /**
1279 * Check if a container name is valid.
1280 * This checks for for length and illegal characters.
1281 *
1282 * @param $container string
1283 * @return bool
1284 */
1285 final protected static function isValidContainerName( $container ) {
1286 // This accounts for Swift and S3 restrictions while leaving room
1287 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1288 // Note that matching strings URL encode to the same string;
1289 // in Swift, the length resriction is *after* URL encoding.
1290 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1291 }
1292
1293 /**
1294 * Validate and normalize a relative storage path.
1295 * Null is returned if the path involves directory traversal.
1296 * Traversal is insecure for FS backends and broken for others.
1297 *
1298 * @param $path string Storage path relative to a container
1299 * @return string|null
1300 */
1301 final protected static function normalizeContainerPath( $path ) {
1302 // Normalize directory separators
1303 $path = strtr( $path, '\\', '/' );
1304 // Collapse consecutive directory separators
1305 $path = preg_replace( '![/]{2,}!', '/', $path );
1306 // Use the same traversal protection as Title::secureAndSplit()
1307 if ( strpos( $path, '.' ) !== false ) {
1308 if (
1309 $path === '.' ||
1310 $path === '..' ||
1311 strpos( $path, './' ) === 0 ||
1312 strpos( $path, '../' ) === 0 ||
1313 strpos( $path, '/./' ) !== false ||
1314 strpos( $path, '/../' ) !== false
1315 ) {
1316 return null;
1317 }
1318 }
1319 return $path;
1320 }
1321
1322 /**
1323 * Splits a storage path into an internal container name,
1324 * an internal relative file name, and a container shard suffix.
1325 * Any shard suffix is already appended to the internal container name.
1326 * This also checks that the storage path is valid and within this backend.
1327 *
1328 * If the container is sharded but a suffix could not be determined,
1329 * this means that the path can only refer to a directory and can only
1330 * be scanned by looking in all the container shards.
1331 *
1332 * @param $storagePath string
1333 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1334 */
1335 final protected function resolveStoragePath( $storagePath ) {
1336 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1337 if ( $backend === $this->name ) { // must be for this backend
1338 $relPath = self::normalizeContainerPath( $relPath );
1339 if ( $relPath !== null ) {
1340 // Get shard for the normalized path if this container is sharded
1341 $cShard = $this->getContainerShard( $container, $relPath );
1342 // Validate and sanitize the relative path (backend-specific)
1343 $relPath = $this->resolveContainerPath( $container, $relPath );
1344 if ( $relPath !== null ) {
1345 // Prepend any wiki ID prefix to the container name
1346 $container = $this->fullContainerName( $container );
1347 if ( self::isValidContainerName( $container ) ) {
1348 // Validate and sanitize the container name (backend-specific)
1349 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1350 if ( $container !== null ) {
1351 return array( $container, $relPath, $cShard );
1352 }
1353 }
1354 }
1355 }
1356 }
1357 return array( null, null, null );
1358 }
1359
1360 /**
1361 * Like resolveStoragePath() except null values are returned if
1362 * the container is sharded and the shard could not be determined.
1363 *
1364 * @see FileBackend::resolveStoragePath()
1365 *
1366 * @param $storagePath string
1367 * @return Array (container, path) or (null, null) if invalid
1368 */
1369 final protected function resolveStoragePathReal( $storagePath ) {
1370 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1371 if ( $cShard !== null ) {
1372 return array( $container, $relPath );
1373 }
1374 return array( null, null );
1375 }
1376
1377 /**
1378 * Get the container name shard suffix for a given path.
1379 * Any empty suffix means the container is not sharded.
1380 *
1381 * @param $container string Container name
1382 * @param $relStoragePath string Storage path relative to the container
1383 * @return string|null Returns null if shard could not be determined
1384 */
1385 final protected function getContainerShard( $container, $relPath ) {
1386 $hashLevels = $this->getContainerHashLevels( $container );
1387 if ( $hashLevels === 1 ) { // 16 shards per container
1388 $hashDirRegex = '(?P<shard>[0-9a-f])';
1389 } elseif ( $hashLevels === 2 ) { // 256 shards per container
1390 $hashDirRegex = '[0-9a-f]/(?P<shard>[0-9a-f]{2})';
1391 } else {
1392 return ''; // no sharding
1393 }
1394 // Allow certain directories to be above the hash dirs so as
1395 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1396 // They must be 2+ chars to avoid any hash directory ambiguity.
1397 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1398 return '.' . str_pad( $m['shard'], $hashLevels, '0', STR_PAD_LEFT );
1399 }
1400 return null; // failed to match
1401 }
1402
1403 /**
1404 * Get the number of hash levels for a container.
1405 * If greater than 0, then all file storage paths within
1406 * the container are required to be hashed accordingly.
1407 *
1408 * @param $container string
1409 * @return integer
1410 */
1411 final protected function getContainerHashLevels( $container ) {
1412 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1413 $hashLevels = (int)$this->shardViaHashLevels[$container];
1414 if ( $hashLevels >= 0 && $hashLevels <= 2 ) {
1415 return $hashLevels;
1416 }
1417 }
1418 return 0; // no sharding
1419 }
1420
1421 /**
1422 * Get a list of full container shard suffixes for a container
1423 *
1424 * @param $container string
1425 * @return Array
1426 */
1427 final protected function getContainerSuffixes( $container ) {
1428 $shards = array();
1429 $digits = $this->getContainerHashLevels( $container );
1430 if ( $digits > 0 ) {
1431 $numShards = 1 << ( $digits * 4 );
1432 for ( $index = 0; $index < $numShards; $index++ ) {
1433 $shards[] = '.' . str_pad( dechex( $index ), $digits, '0', STR_PAD_LEFT );
1434 }
1435 }
1436 return $shards;
1437 }
1438
1439 /**
1440 * Get the full container name, including the wiki ID prefix
1441 *
1442 * @param $container string
1443 * @return string
1444 */
1445 final protected function fullContainerName( $container ) {
1446 if ( $this->wikiId != '' ) {
1447 return "{$this->wikiId}-$container";
1448 } else {
1449 return $container;
1450 }
1451 }
1452
1453 /**
1454 * Resolve a container name, checking if it's allowed by the backend.
1455 * This is intended for internal use, such as encoding illegal chars.
1456 * Subclasses can override this to be more restrictive.
1457 *
1458 * @param $container string
1459 * @return string|null
1460 */
1461 protected function resolveContainerName( $container ) {
1462 return $container;
1463 }
1464
1465 /**
1466 * Resolve a relative storage path, checking if it's allowed by the backend.
1467 * This is intended for internal use, such as encoding illegal chars or perhaps
1468 * getting absolute paths (e.g. FS based backends). Note that the relative path
1469 * may be the empty string (e.g. the path is simply to the container).
1470 *
1471 * @param $container string Container name
1472 * @param $relStoragePath string Storage path relative to the container
1473 * @return string|null Path or null if not valid
1474 */
1475 protected function resolveContainerPath( $container, $relStoragePath ) {
1476 return $relStoragePath;
1477 }
1478
1479 /**
1480 * Get the final extension from a storage or FS path
1481 *
1482 * @param $path string
1483 * @return string
1484 */
1485 final public static function extensionFromPath( $path ) {
1486 $i = strrpos( $path, '.' );
1487 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1488 }
1489 }
1490
1491 /**
1492 * FileBackend helper function to handle file listings that span container shards.
1493 * Do not use this class from places outside of FileBackend.
1494 *
1495 * @ingroup FileBackend
1496 */
1497 class FileBackendShardListIterator implements Iterator {
1498 /* @var FileBackend */
1499 protected $backend;
1500 /* @var Array */
1501 protected $params;
1502 /* @var Array */
1503 protected $shardSuffixes;
1504 protected $container; // string
1505 protected $directory; // string
1506
1507 /* @var Traversable */
1508 protected $iter;
1509 protected $curShard = 0; // integer
1510 protected $pos = 0; // integer
1511
1512 /**
1513 * @param $backend FileBackend
1514 * @param $container string Full storage container name
1515 * @param $dir string Storage directory relative to container
1516 * @param $suffixes Array List of container shard suffixes
1517 * @param $params Array
1518 */
1519 public function __construct(
1520 FileBackend $backend, $container, $dir, array $suffixes, array $params
1521 ) {
1522 $this->backend = $backend;
1523 $this->container = $container;
1524 $this->directory = $dir;
1525 $this->shardSuffixes = $suffixes;
1526 $this->params = $params;
1527 }
1528
1529 public function current() {
1530 if ( is_array( $this->iter ) ) {
1531 return current( $this->iter );
1532 } else {
1533 return $this->iter->current();
1534 }
1535 }
1536
1537 public function key() {
1538 return $this->pos;
1539 }
1540
1541 public function next() {
1542 ++$this->pos;
1543 if ( is_array( $this->iter ) ) {
1544 next( $this->iter );
1545 } else {
1546 $this->iter->next();
1547 }
1548 // Find the next non-empty shard if no elements are left
1549 $this->nextShardIteratorIfNotValid();
1550 }
1551
1552 /**
1553 * If the iterator for this container shard is out of items,
1554 * then move on to the next container that has items.
1555 * If there are none, then it advances to the last container.
1556 */
1557 protected function nextShardIteratorIfNotValid() {
1558 while ( !$this->valid() ) {
1559 if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
1560 break; // no more container shards
1561 }
1562 $this->setIteratorFromCurrentShard();
1563 }
1564 }
1565
1566 protected function setIteratorFromCurrentShard() {
1567 $suffix = $this->shardSuffixes[$this->curShard];
1568 $this->iter = $this->backend->getFileListInternal(
1569 "{$this->container}{$suffix}", $this->directory, $this->params );
1570 }
1571
1572 public function rewind() {
1573 $this->pos = 0;
1574 $this->curShard = 0;
1575 $this->setIteratorFromCurrentShard();
1576 // Find the next non-empty shard if this one has no elements
1577 $this->nextShardIteratorIfNotValid();
1578 }
1579
1580 public function valid() {
1581 if ( $this->iter == null ) {
1582 return false; // some failure?
1583 } elseif ( is_array( $this->iter ) ) {
1584 return ( current( $this->iter ) !== false ); // no paths can have this value
1585 } else {
1586 return $this->iter->valid();
1587 }
1588 }
1589 }