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