3 * @defgroup FileBackend File backend
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
10 * Base class for all file backends.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
28 * @ingroup FileBackend
29 * @author Aaron Schulz
33 * @brief Base class for all file backend classes (including multi-write backends).
35 * This class defines the methods as abstract that subclasses must implement.
36 * Outside callers can assume that all backends will have these functions.
38 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
39 * The "backend" portion is unique name for MediaWiki to refer to a backend, while
40 * the "container" portion is a top-level directory of the backend. The "path" portion
41 * is a relative path that uses UNIX file system (FS) notation, though any particular
42 * backend may not actually be using a local filesystem. Therefore, the relative paths
45 * Backend contents are stored under wiki-specific container names by default.
46 * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
47 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
48 * containers to ones that do not respect the "wiki ID".
50 * In key/value stores, the container is the only hierarchy (the rest is emulated).
51 * FS-based backends are somewhat more restrictive due to the existence of real
52 * directory files; a regular file cannot have the same name as a directory. Other
53 * backends with virtual directories may not have this limitation. Callers should
54 * store files in such a way that no files and directories are under the same path.
56 * Methods of subclasses should avoid throwing exceptions at all costs.
57 * As a corollary, external dependencies should be kept to a minimum.
59 * @ingroup FileBackend
62 abstract class FileBackend
{
63 /** @var string Unique backend name */
66 /** @var string Unique wiki name */
69 /** @var string Read-only explanation message */
72 /** @var string When to do operations in parallel */
73 protected $parallelize;
75 /** @var int How many operations can be done in parallel */
76 protected $concurrency;
78 /** @var LockManager */
79 protected $lockManager;
81 /** @var FileJournal */
82 protected $fileJournal;
85 * Create a new backend instance from configuration.
86 * This should only be called from within FileBackendGroup.
88 * @param array $config Parameters include:
89 * - name : The unique name of this backend.
90 * This should consist of alphanumberic, '-', and '_' characters.
91 * This name should not be changed after use (e.g. with journaling).
92 * Note that the name is *not* used in actual container names.
93 * - wikiId : Prefix to container names that is unique to this backend.
94 * It should only consist of alphanumberic, '-', and '_' characters.
95 * This ID is what avoids collisions if multiple logical backends
96 * use the same storage system, so this should be set carefully.
97 * - lockManager : LockManager object to use for any file locking.
98 * If not provided, then no file locking will be enforced.
99 * - fileJournal : FileJournal object to use for logging changes to files.
100 * If not provided, then change journaling will be disabled.
101 * - readOnly : Write operations are disallowed if this is a non-empty string.
102 * It should be an explanation for the backend being read-only.
103 * - parallelize : When to do file operations in parallel (when possible).
104 * Allowed values are "implicit", "explicit" and "off".
105 * - concurrency : How many file operations can be done in parallel.
106 * @throws MWException
108 public function __construct( array $config ) {
109 $this->name
= $config['name'];
110 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
111 throw new MWException( "Backend name `{$this->name}` is invalid." );
113 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
114 $this->lockManager
= isset( $config['lockManager'] )
115 ?
$config['lockManager']
116 : new NullLockManager( array() );
117 $this->fileJournal
= isset( $config['fileJournal'] )
118 ?
$config['fileJournal']
119 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
120 $this->readOnly
= isset( $config['readOnly'] )
121 ?
(string)$config['readOnly']
123 $this->parallelize
= isset( $config['parallelize'] )
124 ?
(string)$config['parallelize']
126 $this->concurrency
= isset( $config['concurrency'] )
127 ?
(int)$config['concurrency']
132 * Get the unique backend name.
133 * We may have multiple different backends of the same type.
134 * For example, we can have two Swift backends using different proxies.
138 final public function getName() {
143 * Get the wiki identifier used for this backend (possibly empty).
144 * Note that this might *not* be in the same format as wfWikiID().
149 final public function getWikiId() {
150 return $this->wikiId
;
154 * Check if this backend is read-only
158 final public function isReadOnly() {
159 return ( $this->readOnly
!= '' );
163 * Get an explanatory message if this backend is read-only
165 * @return string|bool Returns false if the backend is not read-only
167 final public function getReadOnlyReason() {
168 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
172 * This is the main entry point into the backend for write operations.
173 * Callers supply an ordered list of operations to perform as a transaction.
174 * Files will be locked, the stat cache cleared, and then the operations attempted.
175 * If any serious errors occur, all attempted operations will be rolled back.
177 * $ops is an array of arrays. The outer array holds a list of operations.
178 * Each inner array is a set of key value pairs that specify an operation.
180 * Supported operations and their parameters. The supported actions are:
186 * - describe (since 1.21)
189 * a) Create a new file in storage with the contents of a string
193 * 'dst' => <storage path>,
194 * 'content' => <string of new file contents>,
195 * 'overwrite' => <boolean>,
196 * 'overwriteSame' => <boolean>,
197 * 'headers' => <HTTP header name/value map> # since 1.21
201 * b) Copy a file system file into storage
205 * 'src' => <file system path>,
206 * 'dst' => <storage path>,
207 * 'overwrite' => <boolean>,
208 * 'overwriteSame' => <boolean>,
209 * 'headers' => <HTTP header name/value map> # since 1.21
213 * c) Copy a file within storage
217 * 'src' => <storage path>,
218 * 'dst' => <storage path>,
219 * 'overwrite' => <boolean>,
220 * 'overwriteSame' => <boolean>,
221 * 'ignoreMissingSource' => <boolean>, # since 1.21
222 * 'headers' => <HTTP header name/value map> # since 1.21
226 * d) Move a file within storage
230 * 'src' => <storage path>,
231 * 'dst' => <storage path>,
232 * 'overwrite' => <boolean>,
233 * 'overwriteSame' => <boolean>,
234 * 'ignoreMissingSource' => <boolean>, # since 1.21
235 * 'headers' => <HTTP header name/value map> # since 1.21
239 * e) Delete a file within storage
243 * 'src' => <storage path>,
244 * 'ignoreMissingSource' => <boolean>
248 * f) Update metadata for a file within storage
251 * 'op' => 'describe',
252 * 'src' => <storage path>,
253 * 'headers' => <HTTP header name/value map>
257 * g) Do nothing (no-op)
264 * Boolean flags for operations (operation-specific):
265 * - ignoreMissingSource : The operation will simply succeed and do
266 * nothing if the source file does not exist.
267 * - overwrite : Any destination file will be overwritten.
268 * - overwriteSame : If a file already exists at the destination with the
269 * same contents, then do nothing to the destination file
270 * instead of giving an error. This does not compare headers.
271 * This option is ignored if 'overwrite' is already provided.
272 * - headers : If supplied, the result of merging these headers with any
273 * existing source file headers (replacing conflicting ones)
274 * will be set as the destination file headers. Headers are
275 * deleted if their value is set to the empty string. When a
276 * file has headers they are included in responses to GET and
277 * HEAD requests to the backing store for that file.
278 * Header values should be no larger than 255 bytes, except for
279 * Content-Disposition. The system might ignore or truncate any
280 * headers that are too long to store (exact limits will vary).
281 * Backends that don't support metadata ignore this. (since 1.21)
283 * $opts is an associative of boolean flags, including:
284 * - force : Operation precondition errors no longer trigger an abort.
285 * Any remaining operations are still attempted. Unexpected
286 * failures may still cause remaining operations to be aborted.
287 * - nonLocking : No locks are acquired for the operations.
288 * This can increase performance for non-critical writes.
289 * This has no effect unless the 'force' flag is set.
290 * - nonJournaled : Don't log this operation batch in the file journal.
291 * This limits the ability of recovery scripts.
292 * - parallelize : Try to do operations in parallel when possible.
293 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
294 * - preserveCache : Don't clear the process cache before checking files.
295 * This should only be used if all entries in the process
296 * cache were added after the files were already locked. (since 1.20)
298 * @remarks Remarks on locking:
299 * File system paths given to operations should refer to files that are
300 * already locked or otherwise safe from modification from other processes.
301 * Normally these files will be new temp files, which should be adequate.
305 * This returns a Status, which contains all warnings and fatals that occurred
306 * during the operation. The 'failCount', 'successCount', and 'success' members
307 * will reflect each operation attempted.
309 * The status will be "OK" unless:
310 * - a) unexpected operation errors occurred (network partitions, disk full...)
311 * - b) significant operation errors occurred and 'force' was not set
313 * @param array $ops List of operations to execute in order
314 * @param array $opts Batch operation options
317 final public function doOperations( array $ops, array $opts = array() ) {
318 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
319 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
321 if ( !count( $ops ) ) {
322 return Status
::newGood(); // nothing to do
324 if ( empty( $opts['force'] ) ) { // sanity
325 unset( $opts['nonLocking'] );
327 foreach ( $ops as &$op ) {
328 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
329 $op['headers']['Content-Disposition'] = $op['disposition'];
332 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
333 return $this->doOperationsInternal( $ops, $opts );
337 * @see FileBackend::doOperations()
339 abstract protected function doOperationsInternal( array $ops, array $opts );
342 * Same as doOperations() except it takes a single operation.
343 * If you are doing a batch of operations that should either
344 * all succeed or all fail, then use that function instead.
346 * @see FileBackend::doOperations()
348 * @param array $op Operation
349 * @param array $opts Operation options
352 final public function doOperation( array $op, array $opts = array() ) {
353 return $this->doOperations( array( $op ), $opts );
357 * Performs a single create operation.
358 * This sets $params['op'] to 'create' and passes it to doOperation().
360 * @see FileBackend::doOperation()
362 * @param array $params Operation parameters
363 * @param array $opts Operation options
366 final public function create( array $params, array $opts = array() ) {
367 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
371 * Performs a single store operation.
372 * This sets $params['op'] to 'store' and passes it to doOperation().
374 * @see FileBackend::doOperation()
376 * @param array $params Operation parameters
377 * @param array $opts Operation options
380 final public function store( array $params, array $opts = array() ) {
381 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
385 * Performs a single copy operation.
386 * This sets $params['op'] to 'copy' and passes it to doOperation().
388 * @see FileBackend::doOperation()
390 * @param array $params Operation parameters
391 * @param array $opts Operation options
394 final public function copy( array $params, array $opts = array() ) {
395 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
399 * Performs a single move operation.
400 * This sets $params['op'] to 'move' and passes it to doOperation().
402 * @see FileBackend::doOperation()
404 * @param array $params Operation parameters
405 * @param array $opts Operation options
408 final public function move( array $params, array $opts = array() ) {
409 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
413 * Performs a single delete operation.
414 * This sets $params['op'] to 'delete' and passes it to doOperation().
416 * @see FileBackend::doOperation()
418 * @param array $params Operation parameters
419 * @param array $opts Operation options
422 final public function delete( array $params, array $opts = array() ) {
423 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
427 * Performs a single describe operation.
428 * This sets $params['op'] to 'describe' and passes it to doOperation().
430 * @see FileBackend::doOperation()
432 * @param array $params Operation parameters
433 * @param array $opts Operation options
437 final public function describe( array $params, array $opts = array() ) {
438 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
442 * Perform a set of independent file operations on some files.
444 * This does no locking, nor journaling, and possibly no stat calls.
445 * Any destination files that already exist will be overwritten.
446 * This should *only* be used on non-original files, like cache files.
448 * Supported operations and their parameters:
454 * - describe (since 1.21)
457 * a) Create a new file in storage with the contents of a string
461 * 'dst' => <storage path>,
462 * 'content' => <string of new file contents>,
463 * 'headers' => <HTTP header name/value map> # since 1.21
467 * b) Copy a file system file into storage
471 * 'src' => <file system path>,
472 * 'dst' => <storage path>,
473 * 'headers' => <HTTP header name/value map> # since 1.21
477 * c) Copy a file within storage
481 * 'src' => <storage path>,
482 * 'dst' => <storage path>,
483 * 'ignoreMissingSource' => <boolean>, # since 1.21
484 * 'headers' => <HTTP header name/value map> # since 1.21
488 * d) Move a file within storage
492 * 'src' => <storage path>,
493 * 'dst' => <storage path>,
494 * 'ignoreMissingSource' => <boolean>, # since 1.21
495 * 'headers' => <HTTP header name/value map> # since 1.21
499 * e) Delete a file within storage
503 * 'src' => <storage path>,
504 * 'ignoreMissingSource' => <boolean>
508 * f) Update metadata for a file within storage
511 * 'op' => 'describe',
512 * 'src' => <storage path>,
513 * 'headers' => <HTTP header name/value map>
517 * g) Do nothing (no-op)
524 * @par Boolean flags for operations (operation-specific):
525 * - ignoreMissingSource : The operation will simply succeed and do
526 * nothing if the source file does not exist.
527 * - headers : If supplied with a header name/value map, the backend will
528 * reply with these headers when GETs/HEADs of the destination
529 * file are made. Header values should be smaller than 256 bytes.
530 * Content-Disposition headers can be longer, though the system
531 * might ignore or truncate ones that are too long to store.
532 * Existing headers will remain, but these will replace any
533 * conflicting previous headers, and headers will be removed
534 * if they are set to an empty string.
535 * Backends that don't support metadata ignore this. (since 1.21)
537 * $opts is an associative of boolean flags, including:
538 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
541 * This returns a Status, which contains all warnings and fatals that occurred
542 * during the operation. The 'failCount', 'successCount', and 'success' members
543 * will reflect each operation attempted for the given files. The status will be
544 * considered "OK" as long as no fatal errors occurred.
546 * @param array $ops Set of operations to execute
547 * @param array $opts Batch operation options
551 final public function doQuickOperations( array $ops, array $opts = array() ) {
552 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
553 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
555 if ( !count( $ops ) ) {
556 return Status
::newGood(); // nothing to do
558 foreach ( $ops as &$op ) {
559 $op['overwrite'] = true; // avoids RTTs in key/value stores
560 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
561 $op['headers']['Content-Disposition'] = $op['disposition'];
564 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
565 return $this->doQuickOperationsInternal( $ops );
569 * @see FileBackend::doQuickOperations()
572 abstract protected function doQuickOperationsInternal( array $ops );
575 * Same as doQuickOperations() except it takes a single operation.
576 * If you are doing a batch of operations, then use that function instead.
578 * @see FileBackend::doQuickOperations()
580 * @param array $op Operation
584 final public function doQuickOperation( array $op ) {
585 return $this->doQuickOperations( array( $op ) );
589 * Performs a single quick create operation.
590 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
592 * @see FileBackend::doQuickOperation()
594 * @param array $params Operation parameters
598 final public function quickCreate( array $params ) {
599 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
603 * Performs a single quick store operation.
604 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
606 * @see FileBackend::doQuickOperation()
608 * @param array $params Operation parameters
612 final public function quickStore( array $params ) {
613 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
617 * Performs a single quick copy operation.
618 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
620 * @see FileBackend::doQuickOperation()
622 * @param array $params Operation parameters
626 final public function quickCopy( array $params ) {
627 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
631 * Performs a single quick move operation.
632 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
634 * @see FileBackend::doQuickOperation()
636 * @param array $params Operation parameters
640 final public function quickMove( array $params ) {
641 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
645 * Performs a single quick delete operation.
646 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
648 * @see FileBackend::doQuickOperation()
650 * @param array $params Operation parameters
654 final public function quickDelete( array $params ) {
655 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
659 * Performs a single quick describe operation.
660 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
662 * @see FileBackend::doQuickOperation()
664 * @param array $params Operation parameters
668 final public function quickDescribe( array $params ) {
669 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
673 * Concatenate a list of storage files into a single file system file.
674 * The target path should refer to a file that is already locked or
675 * otherwise safe from modification from other processes. Normally,
676 * the file will be a new temp file, which should be adequate.
678 * @param array $params Operation parameters, include:
679 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
680 * - dst : file system path to 0-byte temp file
681 * - parallelize : try to do operations in parallel when possible
684 abstract public function concatenate( array $params );
687 * Prepare a storage directory for usage.
688 * This will create any required containers and parent directories.
689 * Backends using key/value stores only need to create the container.
691 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
692 * except they are only applied *if* the directory/container had to be created.
693 * These flags should always be set for directories that have private files.
694 * However, setting them is not guaranteed to actually do anything.
695 * Additional server configuration may be needed to achieve the desired effect.
697 * @param array $params Parameters include:
698 * - dir : storage directory
699 * - noAccess : try to deny file access (since 1.20)
700 * - noListing : try to deny file listing (since 1.20)
701 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
704 final public function prepare( array $params ) {
705 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
706 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
708 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
709 return $this->doPrepare( $params );
713 * @see FileBackend::prepare()
715 abstract protected function doPrepare( array $params );
718 * Take measures to block web access to a storage directory and
719 * the container it belongs to. FS backends might add .htaccess
720 * files whereas key/value store backends might revoke container
721 * access to the storage user representing end-users in web requests.
723 * This is not guaranteed to actually make files or listings publically hidden.
724 * Additional server configuration may be needed to achieve the desired effect.
726 * @param array $params Parameters include:
727 * - dir : storage directory
728 * - noAccess : try to deny file access
729 * - noListing : try to deny file listing
730 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
733 final public function secure( array $params ) {
734 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
735 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
737 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
738 return $this->doSecure( $params );
742 * @see FileBackend::secure()
744 abstract protected function doSecure( array $params );
747 * Remove measures to block web access to a storage directory and
748 * the container it belongs to. FS backends might remove .htaccess
749 * files whereas key/value store backends might grant container
750 * access to the storage user representing end-users in web requests.
751 * This essentially can undo the result of secure() calls.
753 * This is not guaranteed to actually make files or listings publically viewable.
754 * Additional server configuration may be needed to achieve the desired effect.
756 * @param array $params Parameters include:
757 * - dir : storage directory
758 * - access : try to allow file access
759 * - listing : try to allow file listing
760 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
764 final public function publish( array $params ) {
765 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
766 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
768 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
769 return $this->doPublish( $params );
773 * @see FileBackend::publish()
775 abstract protected function doPublish( array $params );
778 * Delete a storage directory if it is empty.
779 * Backends using key/value stores may do nothing unless the directory
780 * is that of an empty container, in which case it will be deleted.
782 * @param array $params Parameters include:
783 * - dir : storage directory
784 * - recursive : recursively delete empty subdirectories first (since 1.20)
785 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
788 final public function clean( array $params ) {
789 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
790 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
792 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
793 return $this->doClean( $params );
797 * @see FileBackend::clean()
799 abstract protected function doClean( array $params );
802 * Enter file operation scope.
803 * This just makes PHP ignore user aborts/disconnects until the return
804 * value leaves scope. This returns null and does nothing in CLI mode.
806 * @return ScopedCallback|null
808 final protected function getScopedPHPBehaviorForOps() {
809 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
810 $old = ignore_user_abort( true ); // avoid half-finished operations
811 return new ScopedCallback( function () use ( $old ) {
812 ignore_user_abort( $old );
820 * Check if a file exists at a storage path in the backend.
821 * This returns false if only a directory exists at the path.
823 * @param array $params Parameters include:
824 * - src : source storage path
825 * - latest : use the latest available data
826 * @return bool|null Returns null on failure
828 abstract public function fileExists( array $params );
831 * Get the last-modified timestamp of the file at a storage path.
833 * @param array $params Parameters include:
834 * - src : source storage path
835 * - latest : use the latest available data
836 * @return string|bool TS_MW timestamp or false on failure
838 abstract public function getFileTimestamp( array $params );
841 * Get the contents of a file at a storage path in the backend.
842 * This should be avoided for potentially large files.
844 * @param array $params Parameters include:
845 * - src : source storage path
846 * - latest : use the latest available data
847 * @return string|bool Returns false on failure
849 final public function getFileContents( array $params ) {
850 $contents = $this->getFileContentsMulti(
851 array( 'srcs' => array( $params['src'] ) ) +
$params );
853 return $contents[$params['src']];
857 * Like getFileContents() except it takes an array of storage paths
858 * and returns a map of storage paths to strings (or null on failure).
859 * The map keys (paths) are in the same order as the provided list of paths.
861 * @see FileBackend::getFileContents()
863 * @param array $params Parameters include:
864 * - srcs : list of source storage paths
865 * - latest : use the latest available data
866 * - parallelize : try to do operations in parallel when possible
867 * @return array Map of (path name => string or false on failure)
870 abstract public function getFileContentsMulti( array $params );
873 * Get the size (bytes) of a file at a storage path in the backend.
875 * @param array $params Parameters include:
876 * - src : source storage path
877 * - latest : use the latest available data
878 * @return int|bool Returns false on failure
880 abstract public function getFileSize( array $params );
883 * Get quick information about a file at a storage path in the backend.
884 * If the file does not exist, then this returns false.
885 * Otherwise, the result is an associative array that includes:
886 * - mtime : the last-modified timestamp (TS_MW)
887 * - size : the file size (bytes)
888 * Additional values may be included for internal use only.
890 * @param array $params Parameters include:
891 * - src : source storage path
892 * - latest : use the latest available data
893 * @return array|bool|null Returns null on failure
895 abstract public function getFileStat( array $params );
898 * Get a SHA-1 hash of the file at a storage path in the backend.
900 * @param array $params Parameters include:
901 * - src : source storage path
902 * - latest : use the latest available data
903 * @return string|bool Hash string or false on failure
905 abstract public function getFileSha1Base36( array $params );
908 * Get the properties of the file at a storage path in the backend.
909 * This gives the result of FSFile::getProps() on a local copy of the file.
911 * @param array $params Parameters include:
912 * - src : source storage path
913 * - latest : use the latest available data
914 * @return array Returns FSFile::placeholderProps() on failure
916 abstract public function getFileProps( array $params );
919 * Stream the file at a storage path in the backend.
920 * If the file does not exists, an HTTP 404 error will be given.
921 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
922 * will be sent if streaming began, while none will be sent otherwise.
923 * Implementations should flush the output buffer before sending data.
925 * @param array $params Parameters include:
926 * - src : source storage path
927 * - headers : list of additional HTTP headers to send on success
928 * - latest : use the latest available data
931 abstract public function streamFile( array $params );
934 * Returns a file system file, identical to the file at a storage path.
935 * The file returned is either:
936 * - a) A local copy of the file at a storage path in the backend.
937 * The temporary copy will have the same extension as the source.
938 * - b) An original of the file at a storage path in the backend.
939 * Temporary files may be purged when the file object falls out of scope.
941 * Write operations should *never* be done on this file as some backends
942 * may do internal tracking or may be instances of FileBackendMultiWrite.
943 * In that later case, there are copies of the file that must stay in sync.
944 * Additionally, further calls to this function may return the same file.
946 * @param array $params Parameters include:
947 * - src : source storage path
948 * - latest : use the latest available data
949 * @return FSFile|null Returns null on failure
951 final public function getLocalReference( array $params ) {
952 $fsFiles = $this->getLocalReferenceMulti(
953 array( 'srcs' => array( $params['src'] ) ) +
$params );
955 return $fsFiles[$params['src']];
959 * Like getLocalReference() except it takes an array of storage paths
960 * and returns a map of storage paths to FSFile objects (or null on failure).
961 * The map keys (paths) are in the same order as the provided list of paths.
963 * @see FileBackend::getLocalReference()
965 * @param array $params Parameters include:
966 * - srcs : list of source storage paths
967 * - latest : use the latest available data
968 * - parallelize : try to do operations in parallel when possible
969 * @return array Map of (path name => FSFile or null on failure)
972 abstract public function getLocalReferenceMulti( array $params );
975 * Get a local copy on disk of the file at a storage path in the backend.
976 * The temporary copy will have the same file extension as the source.
977 * Temporary files may be purged when the file object falls out of scope.
979 * @param array $params Parameters include:
980 * - src : source storage path
981 * - latest : use the latest available data
982 * @return TempFSFile|null Returns null on failure
984 final public function getLocalCopy( array $params ) {
985 $tmpFiles = $this->getLocalCopyMulti(
986 array( 'srcs' => array( $params['src'] ) ) +
$params );
988 return $tmpFiles[$params['src']];
992 * Like getLocalCopy() except it takes an array of storage paths and
993 * returns a map of storage paths to TempFSFile objects (or null on failure).
994 * The map keys (paths) are in the same order as the provided list of paths.
996 * @see FileBackend::getLocalCopy()
998 * @param array $params Parameters include:
999 * - srcs : list of source storage paths
1000 * - latest : use the latest available data
1001 * - parallelize : try to do operations in parallel when possible
1002 * @return array Map of (path name => TempFSFile or null on failure)
1005 abstract public function getLocalCopyMulti( array $params );
1008 * Return an HTTP URL to a given file that requires no authentication to use.
1009 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1010 * This will return null if the backend cannot make an HTTP URL for the file.
1012 * This is useful for key/value stores when using scripts that seek around
1013 * large files and those scripts (and the backend) support HTTP Range headers.
1014 * Otherwise, one would need to use getLocalReference(), which involves loading
1015 * the entire file on to local disk.
1017 * @param array $params Parameters include:
1018 * - src : source storage path
1019 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1020 * @return string|null
1023 abstract public function getFileHttpUrl( array $params );
1026 * Check if a directory exists at a given storage path.
1027 * Backends using key/value stores will check if the path is a
1028 * virtual directory, meaning there are files under the given directory.
1030 * Storage backends with eventual consistency might return stale data.
1032 * @param array $params Parameters include:
1033 * - dir : storage directory
1034 * @return bool|null Returns null on failure
1037 abstract public function directoryExists( array $params );
1040 * Get an iterator to list *all* directories under a storage directory.
1041 * If the directory is of the form "mwstore://backend/container",
1042 * then all directories in the container will be listed.
1043 * If the directory is of form "mwstore://backend/container/dir",
1044 * then all directories directly under that directory will be listed.
1045 * Results will be storage directories relative to the given directory.
1047 * Storage backends with eventual consistency might return stale data.
1049 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1051 * @param array $params Parameters include:
1052 * - dir : storage directory
1053 * - topOnly : only return direct child dirs of the directory
1054 * @return Traversable|Array|null Returns null on failure
1057 abstract public function getDirectoryList( array $params );
1060 * Same as FileBackend::getDirectoryList() except only lists
1061 * directories that are immediately under the given directory.
1063 * Storage backends with eventual consistency might return stale data.
1065 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1067 * @param array $params Parameters include:
1068 * - dir : storage directory
1069 * @return Traversable|Array|null Returns null on failure
1072 final public function getTopDirectoryList( array $params ) {
1073 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1077 * Get an iterator to list *all* stored files under a storage directory.
1078 * If the directory is of the form "mwstore://backend/container",
1079 * then all files in the container will be listed.
1080 * If the directory is of form "mwstore://backend/container/dir",
1081 * then all files under that directory will be listed.
1082 * Results will be storage paths relative to the given directory.
1084 * Storage backends with eventual consistency might return stale data.
1086 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1088 * @param array $params Parameters include:
1089 * - dir : storage directory
1090 * - topOnly : only return direct child files of the directory (since 1.20)
1091 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1092 * @return Traversable|Array|null Returns null on failure
1094 abstract public function getFileList( array $params );
1097 * Same as FileBackend::getFileList() except only lists
1098 * files that are immediately under the given directory.
1100 * Storage backends with eventual consistency might return stale data.
1102 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1104 * @param array $params Parameters include:
1105 * - dir : storage directory
1106 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1107 * @return Traversable|Array|null Returns null on failure
1110 final public function getTopFileList( array $params ) {
1111 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1115 * Preload persistent file stat and property cache into in-process cache.
1116 * This should be used when stat calls will be made on a known list of a many files.
1118 * @param array $paths Storage paths
1120 public function preloadCache( array $paths ) {
1124 * Invalidate any in-process file stat and property cache.
1125 * If $paths is given, then only the cache for those files will be cleared.
1127 * @param array $paths Storage paths (optional)
1129 public function clearCache( array $paths = null ) {
1133 * Lock the files at the given storage paths in the backend.
1134 * This will either lock all the files or none (on failure).
1136 * Callers should consider using getScopedFileLocks() instead.
1138 * @param array $paths Storage paths
1139 * @param int $type LockManager::LOCK_* constant
1142 final public function lockFiles( array $paths, $type ) {
1143 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1145 return $this->lockManager
->lock( $paths, $type );
1149 * Unlock the files at the given storage paths in the backend.
1151 * @param array $paths Storage paths
1152 * @param int $type LockManager::LOCK_* constant
1155 final public function unlockFiles( array $paths, $type ) {
1156 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1158 return $this->lockManager
->unlock( $paths, $type );
1162 * Lock the files at the given storage paths in the backend.
1163 * This will either lock all the files or none (on failure).
1164 * On failure, the status object will be updated with errors.
1166 * Once the return value goes out scope, the locks will be released and
1167 * the status updated. Unlock fatals will not change the status "OK" value.
1169 * @see ScopedLock::factory()
1171 * @param array $paths List of storage paths or map of lock types to path lists
1172 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1173 * @param Status $status Status to update on lock/unlock
1174 * @return ScopedLock|null Returns null on failure
1176 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1177 if ( $type === 'mixed' ) {
1178 foreach ( $paths as &$typePaths ) {
1179 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1182 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1185 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1189 * Get an array of scoped locks needed for a batch of file operations.
1191 * Normally, FileBackend::doOperations() handles locking, unless
1192 * the 'nonLocking' param is passed in. This function is useful if you
1193 * want the files to be locked for a broader scope than just when the
1194 * files are changing. For example, if you need to update DB metadata,
1195 * you may want to keep the files locked until finished.
1197 * @see FileBackend::doOperations()
1199 * @param array $ops List of file operations to FileBackend::doOperations()
1200 * @param Status $status Status to update on lock/unlock
1201 * @return array List of ScopedFileLocks or null values
1204 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1207 * Get the root storage path of this backend.
1208 * All container paths are "subdirectories" of this path.
1210 * @return string Storage path
1213 final public function getRootStoragePath() {
1214 return "mwstore://{$this->name}";
1218 * Get the storage path for the given container for this backend
1220 * @param string $container Container name
1221 * @return string Storage path
1224 final public function getContainerStoragePath( $container ) {
1225 return $this->getRootStoragePath() . "/{$container}";
1229 * Get the file journal object for this backend
1231 * @return FileJournal
1233 final public function getJournal() {
1234 return $this->fileJournal
;
1238 * Check if a given path is a "mwstore://" path.
1239 * This does not do any further validation or any existence checks.
1241 * @param string $path
1244 final public static function isStoragePath( $path ) {
1245 return ( strpos( $path, 'mwstore://' ) === 0 );
1249 * Split a storage path into a backend name, a container name,
1250 * and a relative file path. The relative path may be the empty string.
1251 * This does not do any path normalization or traversal checks.
1253 * @param string $storagePath
1254 * @return array (backend, container, rel object) or (null, null, null)
1256 final public static function splitStoragePath( $storagePath ) {
1257 if ( self
::isStoragePath( $storagePath ) ) {
1258 // Remove the "mwstore://" prefix and split the path
1259 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1260 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1261 if ( count( $parts ) == 3 ) {
1262 return $parts; // e.g. "backend/container/path"
1264 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1269 return array( null, null, null );
1273 * Normalize a storage path by cleaning up directory separators.
1274 * Returns null if the path is not of the format of a valid storage path.
1276 * @param string $storagePath
1277 * @return string|null
1279 final public static function normalizeStoragePath( $storagePath ) {
1280 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1281 if ( $relPath !== null ) { // must be for this backend
1282 $relPath = self
::normalizeContainerPath( $relPath );
1283 if ( $relPath !== null ) {
1284 return ( $relPath != '' )
1285 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1286 : "mwstore://{$backend}/{$container}";
1294 * Get the parent storage directory of a storage path.
1295 * This returns a path like "mwstore://backend/container",
1296 * "mwstore://backend/container/...", or null if there is no parent.
1298 * @param string $storagePath
1299 * @return string|null
1301 final public static function parentStoragePath( $storagePath ) {
1302 $storagePath = dirname( $storagePath );
1303 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1305 return ( $rel === null ) ?
null : $storagePath;
1309 * Get the final extension from a storage or FS path
1311 * @param string $path
1314 final public static function extensionFromPath( $path ) {
1315 $i = strrpos( $path, '.' );
1317 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1321 * Check if a relative path has no directory traversals
1323 * @param string $path
1327 final public static function isPathTraversalFree( $path ) {
1328 return ( self
::normalizeContainerPath( $path ) !== null );
1332 * Build a Content-Disposition header value per RFC 6266.
1334 * @param string $type One of (attachment, inline)
1335 * @param string $filename Suggested file name (should not contain slashes)
1336 * @throws MWException
1340 final public static function makeContentDisposition( $type, $filename = '' ) {
1343 $type = strtolower( $type );
1344 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1345 throw new MWException( "Invalid Content-Disposition type '$type'." );
1349 if ( strlen( $filename ) ) {
1350 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1353 return implode( ';', $parts );
1357 * Validate and normalize a relative storage path.
1358 * Null is returned if the path involves directory traversal.
1359 * Traversal is insecure for FS backends and broken for others.
1361 * This uses the same traversal protection as Title::secureAndSplit().
1363 * @param string $path Storage path relative to a container
1364 * @return string|null
1366 final protected static function normalizeContainerPath( $path ) {
1367 // Normalize directory separators
1368 $path = strtr( $path, '\\', '/' );
1369 // Collapse any consecutive directory separators
1370 $path = preg_replace( '![/]{2,}!', '/', $path );
1371 // Remove any leading directory separator
1372 $path = ltrim( $path, '/' );
1373 // Use the same traversal protection as Title::secureAndSplit()
1374 if ( strpos( $path, '.' ) !== false ) {
1378 strpos( $path, './' ) === 0 ||
1379 strpos( $path, '../' ) === 0 ||
1380 strpos( $path, '/./' ) !== false ||
1381 strpos( $path, '/../' ) !== false
1392 * @ingroup FileBackend
1395 class FileBackendError
extends MWException
{