Cleaned up some docs after r111101
[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 storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
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|bool 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|bool 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|bool 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|bool 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|bool|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|bool 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 * @return Status
889 */
890 protected function doMoveInternal( array $params ) {
891 // Copy source to dest
892 $status = $this->copyInternal( $params );
893 if ( $status->isOK() ) {
894 // Delete source (only fails due to races or medium going down)
895 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
896 $status->setResult( true, $status->value ); // ignore delete() errors
897 }
898 return $status;
899 }
900
901 /**
902 * @see FileBackend::concatenate()
903 * @return Status
904 */
905 final public function concatenate( array $params ) {
906 wfProfileIn( __METHOD__ );
907 $status = Status::newGood();
908
909 // Try to lock the source files for the scope of this function
910 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
911 if ( $status->isOK() ) {
912 // Actually do the concatenation
913 $status->merge( $this->doConcatenate( $params ) );
914 }
915
916 wfProfileOut( __METHOD__ );
917 return $status;
918 }
919
920 /**
921 * @see FileBackendStore::concatenate()
922 * @return Status
923 */
924 protected function doConcatenate( array $params ) {
925 $status = Status::newGood();
926 $tmpPath = $params['dst']; // convenience
927
928 // Check that the specified temp file is valid...
929 wfSuppressWarnings();
930 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
931 wfRestoreWarnings();
932 if ( !$ok ) { // not present or not empty
933 $status->fatal( 'backend-fail-opentemp', $tmpPath );
934 return $status;
935 }
936
937 // Build up the temp file using the source chunks (in order)...
938 $tmpHandle = fopen( $tmpPath, 'ab' );
939 if ( $tmpHandle === false ) {
940 $status->fatal( 'backend-fail-opentemp', $tmpPath );
941 return $status;
942 }
943 foreach ( $params['srcs'] as $virtualSource ) {
944 // Get a local FS version of the chunk
945 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
946 if ( !$tmpFile ) {
947 $status->fatal( 'backend-fail-read', $virtualSource );
948 return $status;
949 }
950 // Get a handle to the local FS version
951 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
952 if ( $sourceHandle === false ) {
953 fclose( $tmpHandle );
954 $status->fatal( 'backend-fail-read', $virtualSource );
955 return $status;
956 }
957 // Append chunk to file (pass chunk size to avoid magic quotes)
958 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
959 fclose( $sourceHandle );
960 fclose( $tmpHandle );
961 $status->fatal( 'backend-fail-writetemp', $tmpPath );
962 return $status;
963 }
964 fclose( $sourceHandle );
965 }
966 if ( !fclose( $tmpHandle ) ) {
967 $status->fatal( 'backend-fail-closetemp', $tmpPath );
968 return $status;
969 }
970
971 clearstatcache(); // temp file changed
972
973 return $status;
974 }
975
976 /**
977 * @see FileBackend::doPrepare()
978 * @return Status
979 */
980 final protected function doPrepare( array $params ) {
981 wfProfileIn( __METHOD__ );
982
983 $status = Status::newGood();
984 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
985 if ( $dir === null ) {
986 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
987 wfProfileOut( __METHOD__ );
988 return $status; // invalid storage path
989 }
990
991 if ( $shard !== null ) { // confined to a single container/shard
992 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
993 } else { // directory is on several shards
994 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
995 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
996 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
997 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
998 }
999 }
1000
1001 wfProfileOut( __METHOD__ );
1002 return $status;
1003 }
1004
1005 /**
1006 * @see FileBackendStore::doPrepare()
1007 * @return Status
1008 */
1009 protected function doPrepareInternal( $container, $dir, array $params ) {
1010 return Status::newGood();
1011 }
1012
1013 /**
1014 * @see FileBackend::doSecure()
1015 * @return Status
1016 */
1017 final protected function doSecure( array $params ) {
1018 wfProfileIn( __METHOD__ );
1019 $status = Status::newGood();
1020
1021 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1022 if ( $dir === null ) {
1023 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
1024 wfProfileOut( __METHOD__ );
1025 return $status; // invalid storage path
1026 }
1027
1028 if ( $shard !== null ) { // confined to a single container/shard
1029 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
1030 } else { // directory is on several shards
1031 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
1032 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
1033 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1034 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
1035 }
1036 }
1037
1038 wfProfileOut( __METHOD__ );
1039 return $status;
1040 }
1041
1042 /**
1043 * @see FileBackendStore::doSecure()
1044 * @return Status
1045 */
1046 protected function doSecureInternal( $container, $dir, array $params ) {
1047 return Status::newGood();
1048 }
1049
1050 /**
1051 * @see FileBackend::doClean()
1052 * @return Status
1053 */
1054 final protected function doClean( array $params ) {
1055 wfProfileIn( __METHOD__ );
1056 $status = Status::newGood();
1057
1058 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1059 if ( $dir === null ) {
1060 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
1061 wfProfileOut( __METHOD__ );
1062 return $status; // invalid storage path
1063 }
1064
1065 // Attempt to lock this directory...
1066 $filesLockEx = array( $params['dir'] );
1067 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
1068 if ( !$status->isOK() ) {
1069 wfProfileOut( __METHOD__ );
1070 return $status; // abort
1071 }
1072
1073 if ( $shard !== null ) { // confined to a single container/shard
1074 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
1075 } else { // directory is on several shards
1076 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
1077 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
1078 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
1079 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
1080 }
1081 }
1082
1083 wfProfileOut( __METHOD__ );
1084 return $status;
1085 }
1086
1087 /**
1088 * @see FileBackendStore::doClean()
1089 * @return Status
1090 */
1091 protected function doCleanInternal( $container, $dir, array $params ) {
1092 return Status::newGood();
1093 }
1094
1095 /**
1096 * @see FileBackend::fileExists()
1097 * @return bool|null
1098 */
1099 final public function fileExists( array $params ) {
1100 wfProfileIn( __METHOD__ );
1101 $stat = $this->getFileStat( $params );
1102 wfProfileOut( __METHOD__ );
1103 return ( $stat === null ) ? null : (bool)$stat; // null => failure
1104 }
1105
1106 /**
1107 * @see FileBackend::getFileTimestamp()
1108 * @return bool
1109 */
1110 final public function getFileTimestamp( array $params ) {
1111 wfProfileIn( __METHOD__ );
1112 $stat = $this->getFileStat( $params );
1113 wfProfileOut( __METHOD__ );
1114 return $stat ? $stat['mtime'] : false;
1115 }
1116
1117 /**
1118 * @see FileBackend::getFileSize()
1119 * @return bool
1120 */
1121 final public function getFileSize( array $params ) {
1122 wfProfileIn( __METHOD__ );
1123 $stat = $this->getFileStat( $params );
1124 wfProfileOut( __METHOD__ );
1125 return $stat ? $stat['size'] : false;
1126 }
1127
1128 /**
1129 * @see FileBackend::getFileStat()
1130 * @return bool|void
1131 */
1132 final public function getFileStat( array $params ) {
1133 wfProfileIn( __METHOD__ );
1134 $path = self::normalizeStoragePath( $params['src'] );
1135 if ( $path === null ) {
1136 return false; // invalid storage path
1137 }
1138 $latest = !empty( $params['latest'] );
1139 if ( isset( $this->cache[$path]['stat'] ) ) {
1140 // If we want the latest data, check that this cached
1141 // value was in fact fetched with the latest available data.
1142 if ( !$latest || $this->cache[$path]['stat']['latest'] ) {
1143 wfProfileOut( __METHOD__ );
1144 return $this->cache[$path]['stat'];
1145 }
1146 }
1147 $stat = $this->doGetFileStat( $params );
1148 if ( is_array( $stat ) ) { // don't cache negatives
1149 $this->trimCache(); // limit memory
1150 $this->cache[$path]['stat'] = $stat;
1151 $this->cache[$path]['stat']['latest'] = $latest;
1152 }
1153 wfProfileOut( __METHOD__ );
1154 return $stat;
1155 }
1156
1157 /**
1158 * @see FileBackendStore::getFileStat()
1159 */
1160 abstract protected function doGetFileStat( array $params );
1161
1162 /**
1163 * @see FileBackend::getFileContents()
1164 * @return bool|string
1165 */
1166 public function getFileContents( array $params ) {
1167 wfProfileIn( __METHOD__ );
1168 $tmpFile = $this->getLocalReference( $params );
1169 if ( !$tmpFile ) {
1170 wfProfileOut( __METHOD__ );
1171 return false;
1172 }
1173 wfSuppressWarnings();
1174 $data = file_get_contents( $tmpFile->getPath() );
1175 wfRestoreWarnings();
1176 wfProfileOut( __METHOD__ );
1177 return $data;
1178 }
1179
1180 /**
1181 * @see FileBackend::getFileSha1Base36()
1182 * @return bool
1183 */
1184 final public function getFileSha1Base36( array $params ) {
1185 wfProfileIn( __METHOD__ );
1186 $path = $params['src'];
1187 if ( isset( $this->cache[$path]['sha1'] ) ) {
1188 wfProfileOut( __METHOD__ );
1189 return $this->cache[$path]['sha1'];
1190 }
1191 $hash = $this->doGetFileSha1Base36( $params );
1192 if ( $hash ) { // don't cache negatives
1193 $this->trimCache(); // limit memory
1194 $this->cache[$path]['sha1'] = $hash;
1195 }
1196 wfProfileOut( __METHOD__ );
1197 return $hash;
1198 }
1199
1200 /**
1201 * @see FileBackendStore::getFileSha1Base36()
1202 * @return bool
1203 */
1204 protected function doGetFileSha1Base36( array $params ) {
1205 $fsFile = $this->getLocalReference( $params );
1206 if ( !$fsFile ) {
1207 return false;
1208 } else {
1209 return $fsFile->getSha1Base36();
1210 }
1211 }
1212
1213 /**
1214 * @see FileBackend::getFileProps()
1215 * @return Array
1216 */
1217 final public function getFileProps( array $params ) {
1218 wfProfileIn( __METHOD__ );
1219 $fsFile = $this->getLocalReference( $params );
1220 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
1221 wfProfileOut( __METHOD__ );
1222 return $props;
1223 }
1224
1225 /**
1226 * @see FileBackend::getLocalReference()
1227 * @return TempFSFile|null
1228 */
1229 public function getLocalReference( array $params ) {
1230 wfProfileIn( __METHOD__ );
1231 $path = $params['src'];
1232 if ( isset( $this->expensiveCache[$path]['localRef'] ) ) {
1233 wfProfileOut( __METHOD__ );
1234 return $this->expensiveCache[$path]['localRef'];
1235 }
1236 $tmpFile = $this->getLocalCopy( $params );
1237 if ( $tmpFile ) { // don't cache negatives
1238 $this->trimExpensiveCache(); // limit memory
1239 $this->expensiveCache[$path]['localRef'] = $tmpFile;
1240 }
1241 wfProfileOut( __METHOD__ );
1242 return $tmpFile;
1243 }
1244
1245 /**
1246 * @see FileBackend::streamFile()
1247 * @return Status
1248 */
1249 final public function streamFile( array $params ) {
1250 wfProfileIn( __METHOD__ );
1251 $status = Status::newGood();
1252
1253 $info = $this->getFileStat( $params );
1254 if ( !$info ) { // let StreamFile handle the 404
1255 $status->fatal( 'backend-fail-notexists', $params['src'] );
1256 }
1257
1258 // Set output buffer and HTTP headers for stream
1259 $extraHeaders = $params['headers'] ? $params['headers'] : array();
1260 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
1261 if ( $res == StreamFile::NOT_MODIFIED ) {
1262 // do nothing; client cache is up to date
1263 } elseif ( $res == StreamFile::READY_STREAM ) {
1264 $status = $this->doStreamFile( $params );
1265 } else {
1266 $status->fatal( 'backend-fail-stream', $params['src'] );
1267 }
1268
1269 wfProfileOut( __METHOD__ );
1270 return $status;
1271 }
1272
1273 /**
1274 * @see FileBackendStore::streamFile()
1275 * @return Status
1276 */
1277 protected function doStreamFile( array $params ) {
1278 $status = Status::newGood();
1279
1280 $fsFile = $this->getLocalReference( $params );
1281 if ( !$fsFile ) {
1282 $status->fatal( 'backend-fail-stream', $params['src'] );
1283 } elseif ( !readfile( $fsFile->getPath() ) ) {
1284 $status->fatal( 'backend-fail-stream', $params['src'] );
1285 }
1286
1287 return $status;
1288 }
1289
1290 /**
1291 * @copydoc FileBackend::getFileList()
1292 * @return Array|null|Traversable
1293 */
1294 final public function getFileList( array $params ) {
1295 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
1296 if ( $dir === null ) { // invalid storage path
1297 return null;
1298 }
1299 if ( $shard !== null ) {
1300 // File listing is confined to a single container/shard
1301 return $this->getFileListInternal( $fullCont, $dir, $params );
1302 } else {
1303 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
1304 // File listing spans multiple containers/shards
1305 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
1306 return new FileBackendStoreShardListIterator( $this,
1307 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
1308 }
1309 }
1310
1311 /**
1312 * Do not call this function from places outside FileBackend
1313 *
1314 * @see FileBackendStore::getFileList()
1315 *
1316 * @param $container string Resolved container name
1317 * @param $dir string Resolved path relative to container
1318 * @param $params Array
1319 * @return Traversable|Array|null
1320 */
1321 abstract public function getFileListInternal( $container, $dir, array $params );
1322
1323 /**
1324 * Get the list of supported operations and their corresponding FileOp classes.
1325 *
1326 * @return Array
1327 */
1328 protected function supportedOperations() {
1329 return array(
1330 'store' => 'StoreFileOp',
1331 'copy' => 'CopyFileOp',
1332 'move' => 'MoveFileOp',
1333 'delete' => 'DeleteFileOp',
1334 'create' => 'CreateFileOp',
1335 'null' => 'NullFileOp'
1336 );
1337 }
1338
1339 /**
1340 * Return a list of FileOp objects from a list of operations.
1341 * Do not call this function from places outside FileBackend.
1342 *
1343 * The result must have the same number of items as the input.
1344 * An exception is thrown if an unsupported operation is requested.
1345 *
1346 * @param $ops Array Same format as doOperations()
1347 * @return Array List of FileOp objects
1348 * @throws MWException
1349 */
1350 final public function getOperations( array $ops ) {
1351 $supportedOps = $this->supportedOperations();
1352
1353 $performOps = array(); // array of FileOp objects
1354 // Build up ordered array of FileOps...
1355 foreach ( $ops as $operation ) {
1356 $opName = $operation['op'];
1357 if ( isset( $supportedOps[$opName] ) ) {
1358 $class = $supportedOps[$opName];
1359 // Get params for this operation
1360 $params = $operation;
1361 // Append the FileOp class
1362 $performOps[] = new $class( $this, $params );
1363 } else {
1364 throw new MWException( "Operation `$opName` is not supported." );
1365 }
1366 }
1367
1368 return $performOps;
1369 }
1370
1371 /**
1372 * @see FileBackend::doOperationsInternal()
1373 * @return Status
1374 */
1375 protected function doOperationsInternal( array $ops, array $opts ) {
1376 wfProfileIn( __METHOD__ );
1377 $status = Status::newGood();
1378
1379 // Build up a list of FileOps...
1380 $performOps = $this->getOperations( $ops );
1381
1382 // Acquire any locks as needed...
1383 if ( empty( $opts['nonLocking'] ) ) {
1384 // Build up a list of files to lock...
1385 $filesLockEx = $filesLockSh = array();
1386 foreach ( $performOps as $fileOp ) {
1387 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
1388 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
1389 }
1390 // Optimization: if doing an EX lock anyway, don't also set an SH one
1391 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
1392 // Get a shared lock on the parent directory of each path changed
1393 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
1394 // Try to lock those files for the scope of this function...
1395 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager::LOCK_UW, $status );
1396 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
1397 if ( !$status->isOK() ) {
1398 wfProfileOut( __METHOD__ );
1399 return $status; // abort
1400 }
1401 }
1402
1403 // Clear any cache entries (after locks acquired)
1404 $this->clearCache();
1405
1406 // Actually attempt the operation batch...
1407 $subStatus = FileOp::attemptBatch( $performOps, $opts );
1408
1409 // Merge errors into status fields
1410 $status->merge( $subStatus );
1411 $status->success = $subStatus->success; // not done in merge()
1412
1413 wfProfileOut( __METHOD__ );
1414 return $status;
1415 }
1416
1417 /**
1418 * @see FileBackend::clearCache()
1419 */
1420 final public function clearCache( array $paths = null ) {
1421 if ( is_array( $paths ) ) {
1422 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1423 $paths = array_filter( $paths, 'strlen' ); // remove nulls
1424 }
1425 if ( $paths === null ) {
1426 $this->cache = array();
1427 $this->expensiveCache = array();
1428 } else {
1429 foreach ( $paths as $path ) {
1430 unset( $this->cache[$path] );
1431 unset( $this->expensiveCache[$path] );
1432 }
1433 }
1434 $this->doClearCache( $paths );
1435 }
1436
1437 /**
1438 * Clears any additional stat caches for storage paths
1439 *
1440 * @see FileBackend::clearCache()
1441 *
1442 * @param $paths Array Storage paths (optional)
1443 * @return void
1444 */
1445 protected function doClearCache( array $paths = null ) {}
1446
1447 /**
1448 * Prune the inexpensive cache if it is too big to add an item
1449 *
1450 * @return void
1451 */
1452 protected function trimCache() {
1453 if ( count( $this->cache ) >= $this->maxCacheSize ) {
1454 reset( $this->cache );
1455 unset( $this->cache[key( $this->cache )] );
1456 }
1457 }
1458
1459 /**
1460 * Prune the expensive cache if it is too big to add an item
1461 *
1462 * @return void
1463 */
1464 protected function trimExpensiveCache() {
1465 if ( count( $this->expensiveCache ) >= $this->maxExpensiveCacheSize ) {
1466 reset( $this->expensiveCache );
1467 unset( $this->expensiveCache[key( $this->expensiveCache )] );
1468 }
1469 }
1470
1471 /**
1472 * Check if a container name is valid.
1473 * This checks for for length and illegal characters.
1474 *
1475 * @param $container string
1476 * @return bool
1477 */
1478 final protected static function isValidContainerName( $container ) {
1479 // This accounts for Swift and S3 restrictions while leaving room
1480 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1481 // This disallows directory separators or traversal characters.
1482 // Note that matching strings URL encode to the same string;
1483 // in Swift, the length restriction is *after* URL encoding.
1484 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1485 }
1486
1487 /**
1488 * Splits a storage path into an internal container name,
1489 * an internal relative file name, and a container shard suffix.
1490 * Any shard suffix is already appended to the internal container name.
1491 * This also checks that the storage path is valid and within this backend.
1492 *
1493 * If the container is sharded but a suffix could not be determined,
1494 * this means that the path can only refer to a directory and can only
1495 * be scanned by looking in all the container shards.
1496 *
1497 * @param $storagePath string
1498 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1499 */
1500 final protected function resolveStoragePath( $storagePath ) {
1501 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1502 if ( $backend === $this->name ) { // must be for this backend
1503 $relPath = self::normalizeContainerPath( $relPath );
1504 if ( $relPath !== null ) {
1505 // Get shard for the normalized path if this container is sharded
1506 $cShard = $this->getContainerShard( $container, $relPath );
1507 // Validate and sanitize the relative path (backend-specific)
1508 $relPath = $this->resolveContainerPath( $container, $relPath );
1509 if ( $relPath !== null ) {
1510 // Prepend any wiki ID prefix to the container name
1511 $container = $this->fullContainerName( $container );
1512 if ( self::isValidContainerName( $container ) ) {
1513 // Validate and sanitize the container name (backend-specific)
1514 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1515 if ( $container !== null ) {
1516 return array( $container, $relPath, $cShard );
1517 }
1518 }
1519 }
1520 }
1521 }
1522 return array( null, null, null );
1523 }
1524
1525 /**
1526 * Like resolveStoragePath() except null values are returned if
1527 * the container is sharded and the shard could not be determined.
1528 *
1529 * @see FileBackendStore::resolveStoragePath()
1530 *
1531 * @param $storagePath string
1532 * @return Array (container, path) or (null, null) if invalid
1533 */
1534 final protected function resolveStoragePathReal( $storagePath ) {
1535 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1536 if ( $cShard !== null ) {
1537 return array( $container, $relPath );
1538 }
1539 return array( null, null );
1540 }
1541
1542 /**
1543 * Get the container name shard suffix for a given path.
1544 * Any empty suffix means the container is not sharded.
1545 *
1546 * @param $container string Container name
1547 * @param $relStoragePath string Storage path relative to the container
1548 * @return string|null Returns null if shard could not be determined
1549 */
1550 final protected function getContainerShard( $container, $relPath ) {
1551 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1552 if ( $levels == 1 || $levels == 2 ) {
1553 // Hash characters are either base 16 or 36
1554 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1555 // Get a regex that represents the shard portion of paths.
1556 // The concatenation of the captures gives us the shard.
1557 if ( $levels === 1 ) { // 16 or 36 shards per container
1558 $hashDirRegex = '(' . $char . ')';
1559 } else { // 256 or 1296 shards per container
1560 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1561 $hashDirRegex = $char . '/(' . $char . '{2})';
1562 } else { // short hash dir format (e.g. "a/b/c")
1563 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1564 }
1565 }
1566 // Allow certain directories to be above the hash dirs so as
1567 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1568 // They must be 2+ chars to avoid any hash directory ambiguity.
1569 $m = array();
1570 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1571 return '.' . implode( '', array_slice( $m, 1 ) );
1572 }
1573 return null; // failed to match
1574 }
1575 return ''; // no sharding
1576 }
1577
1578 /**
1579 * Get the sharding config for a container.
1580 * If greater than 0, then all file storage paths within
1581 * the container are required to be hashed accordingly.
1582 *
1583 * @param $container string
1584 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1585 */
1586 final protected function getContainerHashLevels( $container ) {
1587 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1588 $config = $this->shardViaHashLevels[$container];
1589 $hashLevels = (int)$config['levels'];
1590 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1591 $hashBase = (int)$config['base'];
1592 if ( $hashBase == 16 || $hashBase == 36 ) {
1593 return array( $hashLevels, $hashBase, $config['repeat'] );
1594 }
1595 }
1596 }
1597 return array( 0, 0, false ); // no sharding
1598 }
1599
1600 /**
1601 * Get a list of full container shard suffixes for a container
1602 *
1603 * @param $container string
1604 * @return Array
1605 */
1606 final protected function getContainerSuffixes( $container ) {
1607 $shards = array();
1608 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1609 if ( $digits > 0 ) {
1610 $numShards = pow( $base, $digits );
1611 for ( $index = 0; $index < $numShards; $index++ ) {
1612 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1613 }
1614 }
1615 return $shards;
1616 }
1617
1618 /**
1619 * Get the full container name, including the wiki ID prefix
1620 *
1621 * @param $container string
1622 * @return string
1623 */
1624 final protected function fullContainerName( $container ) {
1625 if ( $this->wikiId != '' ) {
1626 return "{$this->wikiId}-$container";
1627 } else {
1628 return $container;
1629 }
1630 }
1631
1632 /**
1633 * Resolve a container name, checking if it's allowed by the backend.
1634 * This is intended for internal use, such as encoding illegal chars.
1635 * Subclasses can override this to be more restrictive.
1636 *
1637 * @param $container string
1638 * @return string|null
1639 */
1640 protected function resolveContainerName( $container ) {
1641 return $container;
1642 }
1643
1644 /**
1645 * Resolve a relative storage path, checking if it's allowed by the backend.
1646 * This is intended for internal use, such as encoding illegal chars or perhaps
1647 * getting absolute paths (e.g. FS based backends). Note that the relative path
1648 * may be the empty string (e.g. the path is simply to the container).
1649 *
1650 * @param $container string Container name
1651 * @param $relStoragePath string Storage path relative to the container
1652 * @return string|null Path or null if not valid
1653 */
1654 protected function resolveContainerPath( $container, $relStoragePath ) {
1655 return $relStoragePath;
1656 }
1657 }
1658
1659 /**
1660 * FileBackendStore helper function to handle file listings that span container shards.
1661 * Do not use this class from places outside of FileBackendStore.
1662 *
1663 * @ingroup FileBackend
1664 */
1665 class FileBackendStoreShardListIterator implements Iterator {
1666 /* @var FileBackendStore */
1667 protected $backend;
1668 /* @var Array */
1669 protected $params;
1670 /* @var Array */
1671 protected $shardSuffixes;
1672 protected $container; // string
1673 protected $directory; // string
1674
1675 /* @var Traversable */
1676 protected $iter;
1677 protected $curShard = 0; // integer
1678 protected $pos = 0; // integer
1679
1680 /**
1681 * @param $backend FileBackendStore
1682 * @param $container string Full storage container name
1683 * @param $dir string Storage directory relative to container
1684 * @param $suffixes Array List of container shard suffixes
1685 * @param $params Array
1686 */
1687 public function __construct(
1688 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1689 ) {
1690 $this->backend = $backend;
1691 $this->container = $container;
1692 $this->directory = $dir;
1693 $this->shardSuffixes = $suffixes;
1694 $this->params = $params;
1695 }
1696
1697 public function current() {
1698 if ( is_array( $this->iter ) ) {
1699 return current( $this->iter );
1700 } else {
1701 return $this->iter->current();
1702 }
1703 }
1704
1705 public function key() {
1706 return $this->pos;
1707 }
1708
1709 public function next() {
1710 ++$this->pos;
1711 if ( is_array( $this->iter ) ) {
1712 next( $this->iter );
1713 } else {
1714 $this->iter->next();
1715 }
1716 // Find the next non-empty shard if no elements are left
1717 $this->nextShardIteratorIfNotValid();
1718 }
1719
1720 /**
1721 * If the iterator for this container shard is out of items,
1722 * then move on to the next container that has items.
1723 * If there are none, then it advances to the last container.
1724 */
1725 protected function nextShardIteratorIfNotValid() {
1726 while ( !$this->valid() ) {
1727 if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
1728 break; // no more container shards
1729 }
1730 $this->setIteratorFromCurrentShard();
1731 }
1732 }
1733
1734 protected function setIteratorFromCurrentShard() {
1735 $suffix = $this->shardSuffixes[$this->curShard];
1736 $this->iter = $this->backend->getFileListInternal(
1737 "{$this->container}{$suffix}", $this->directory, $this->params );
1738 }
1739
1740 public function rewind() {
1741 $this->pos = 0;
1742 $this->curShard = 0;
1743 $this->setIteratorFromCurrentShard();
1744 // Find the next non-empty shard if this one has no elements
1745 $this->nextShardIteratorIfNotValid();
1746 }
1747
1748 public function valid() {
1749 if ( $this->iter == null ) {
1750 return false; // some failure?
1751 } elseif ( is_array( $this->iter ) ) {
1752 return ( current( $this->iter ) !== false ); // no paths can have this value
1753 } else {
1754 return $this->iter->valid();
1755 }
1756 }
1757 }