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 if ( !isset( $config['wikiId'] ) ) {
114 $config['wikiId'] = wfWikiID();
115 wfDeprecated( __METHOD__
. ' called without "wikiID".', '1.23' );
117 if ( isset( $config['lockManager'] ) && !is_object( $config['lockManager'] ) ) {
118 $config['lockManager'] =
119 LockManagerGroup
::singleton( $config['wikiId'] )->get( $config['lockManager'] );
120 wfDeprecated( __METHOD__
. ' called with non-object "lockManager".', '1.23' );
122 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
123 $this->lockManager
= isset( $config['lockManager'] )
124 ?
$config['lockManager']
125 : new NullLockManager( array() );
126 $this->fileJournal
= isset( $config['fileJournal'] )
127 ?
$config['fileJournal']
128 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
129 $this->readOnly
= isset( $config['readOnly'] )
130 ?
(string)$config['readOnly']
132 $this->parallelize
= isset( $config['parallelize'] )
133 ?
(string)$config['parallelize']
135 $this->concurrency
= isset( $config['concurrency'] )
136 ?
(int)$config['concurrency']
141 * Get the unique backend name.
142 * We may have multiple different backends of the same type.
143 * For example, we can have two Swift backends using different proxies.
147 final public function getName() {
152 * Get the wiki identifier used for this backend (possibly empty).
153 * Note that this might *not* be in the same format as wfWikiID().
158 final public function getWikiId() {
159 return $this->wikiId
;
163 * Check if this backend is read-only
167 final public function isReadOnly() {
168 return ( $this->readOnly
!= '' );
172 * Get an explanatory message if this backend is read-only
174 * @return string|bool Returns false if the backend is not read-only
176 final public function getReadOnlyReason() {
177 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
181 * This is the main entry point into the backend for write operations.
182 * Callers supply an ordered list of operations to perform as a transaction.
183 * Files will be locked, the stat cache cleared, and then the operations attempted.
184 * If any serious errors occur, all attempted operations will be rolled back.
186 * $ops is an array of arrays. The outer array holds a list of operations.
187 * Each inner array is a set of key value pairs that specify an operation.
189 * Supported operations and their parameters. The supported actions are:
195 * - describe (since 1.21)
198 * a) Create a new file in storage with the contents of a string
202 * 'dst' => <storage path>,
203 * 'content' => <string of new file contents>,
204 * 'overwrite' => <boolean>,
205 * 'overwriteSame' => <boolean>,
206 * 'headers' => <HTTP header name/value map> # since 1.21
210 * b) Copy a file system file into storage
214 * 'src' => <file system path>,
215 * 'dst' => <storage path>,
216 * 'overwrite' => <boolean>,
217 * 'overwriteSame' => <boolean>,
218 * 'headers' => <HTTP header name/value map> # since 1.21
222 * c) Copy a file within storage
226 * 'src' => <storage path>,
227 * 'dst' => <storage path>,
228 * 'overwrite' => <boolean>,
229 * 'overwriteSame' => <boolean>,
230 * 'ignoreMissingSource' => <boolean>, # since 1.21
231 * 'headers' => <HTTP header name/value map> # since 1.21
235 * d) Move a file within storage
239 * 'src' => <storage path>,
240 * 'dst' => <storage path>,
241 * 'overwrite' => <boolean>,
242 * 'overwriteSame' => <boolean>,
243 * 'ignoreMissingSource' => <boolean>, # since 1.21
244 * 'headers' => <HTTP header name/value map> # since 1.21
248 * e) Delete a file within storage
252 * 'src' => <storage path>,
253 * 'ignoreMissingSource' => <boolean>
257 * f) Update metadata for a file within storage
260 * 'op' => 'describe',
261 * 'src' => <storage path>,
262 * 'headers' => <HTTP header name/value map>
266 * g) Do nothing (no-op)
273 * Boolean flags for operations (operation-specific):
274 * - ignoreMissingSource : The operation will simply succeed and do
275 * nothing if the source file does not exist.
276 * - overwrite : Any destination file will be overwritten.
277 * - overwriteSame : If a file already exists at the destination with the
278 * same contents, then do nothing to the destination file
279 * instead of giving an error. This does not compare headers.
280 * This option is ignored if 'overwrite' is already provided.
281 * - headers : If supplied, the result of merging these headers with any
282 * existing source file headers (replacing conflicting ones)
283 * will be set as the destination file headers. Headers are
284 * deleted if their value is set to the empty string. When a
285 * file has headers they are included in responses to GET and
286 * HEAD requests to the backing store for that file.
287 * Header values should be no larger than 255 bytes, except for
288 * Content-Disposition. The system might ignore or truncate any
289 * headers that are too long to store (exact limits will vary).
290 * Backends that don't support metadata ignore this. (since 1.21)
292 * $opts is an associative of boolean flags, including:
293 * - force : Operation precondition errors no longer trigger an abort.
294 * Any remaining operations are still attempted. Unexpected
295 * failures may still cause remaining operations to be aborted.
296 * - nonLocking : No locks are acquired for the operations.
297 * This can increase performance for non-critical writes.
298 * This has no effect unless the 'force' flag is set.
299 * - nonJournaled : Don't log this operation batch in the file journal.
300 * This limits the ability of recovery scripts.
301 * - parallelize : Try to do operations in parallel when possible.
302 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
303 * - preserveCache : Don't clear the process cache before checking files.
304 * This should only be used if all entries in the process
305 * cache were added after the files were already locked. (since 1.20)
307 * @remarks Remarks on locking:
308 * File system paths given to operations should refer to files that are
309 * already locked or otherwise safe from modification from other processes.
310 * Normally these files will be new temp files, which should be adequate.
314 * This returns a Status, which contains all warnings and fatals that occurred
315 * during the operation. The 'failCount', 'successCount', and 'success' members
316 * will reflect each operation attempted.
318 * The status will be "OK" unless:
319 * - a) unexpected operation errors occurred (network partitions, disk full...)
320 * - b) significant operation errors occurred and 'force' was not set
322 * @param array $ops List of operations to execute in order
323 * @param array $opts Batch operation options
326 final public function doOperations( array $ops, array $opts = array() ) {
327 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
328 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
330 if ( !count( $ops ) ) {
331 return Status
::newGood(); // nothing to do
333 if ( empty( $opts['force'] ) ) { // sanity
334 unset( $opts['nonLocking'] );
336 foreach ( $ops as &$op ) {
337 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
338 $op['headers']['Content-Disposition'] = $op['disposition'];
341 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
342 return $this->doOperationsInternal( $ops, $opts );
346 * @see FileBackend::doOperations()
348 abstract protected function doOperationsInternal( array $ops, array $opts );
351 * Same as doOperations() except it takes a single operation.
352 * If you are doing a batch of operations that should either
353 * all succeed or all fail, then use that function instead.
355 * @see FileBackend::doOperations()
357 * @param array $op Operation
358 * @param array $opts Operation options
361 final public function doOperation( array $op, array $opts = array() ) {
362 return $this->doOperations( array( $op ), $opts );
366 * Performs a single create operation.
367 * This sets $params['op'] to 'create' and passes it to doOperation().
369 * @see FileBackend::doOperation()
371 * @param array $params Operation parameters
372 * @param array $opts Operation options
375 final public function create( array $params, array $opts = array() ) {
376 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
380 * Performs a single store operation.
381 * This sets $params['op'] to 'store' and passes it to doOperation().
383 * @see FileBackend::doOperation()
385 * @param array $params Operation parameters
386 * @param array $opts Operation options
389 final public function store( array $params, array $opts = array() ) {
390 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
394 * Performs a single copy operation.
395 * This sets $params['op'] to 'copy' and passes it to doOperation().
397 * @see FileBackend::doOperation()
399 * @param array $params Operation parameters
400 * @param array $opts Operation options
403 final public function copy( array $params, array $opts = array() ) {
404 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
408 * Performs a single move operation.
409 * This sets $params['op'] to 'move' and passes it to doOperation().
411 * @see FileBackend::doOperation()
413 * @param array $params Operation parameters
414 * @param array $opts Operation options
417 final public function move( array $params, array $opts = array() ) {
418 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
422 * Performs a single delete operation.
423 * This sets $params['op'] to 'delete' and passes it to doOperation().
425 * @see FileBackend::doOperation()
427 * @param array $params Operation parameters
428 * @param array $opts Operation options
431 final public function delete( array $params, array $opts = array() ) {
432 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
436 * Performs a single describe operation.
437 * This sets $params['op'] to 'describe' and passes it to doOperation().
439 * @see FileBackend::doOperation()
441 * @param array $params Operation parameters
442 * @param array $opts Operation options
446 final public function describe( array $params, array $opts = array() ) {
447 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
451 * Perform a set of independent file operations on some files.
453 * This does no locking, nor journaling, and possibly no stat calls.
454 * Any destination files that already exist will be overwritten.
455 * This should *only* be used on non-original files, like cache files.
457 * Supported operations and their parameters:
463 * - describe (since 1.21)
466 * a) Create a new file in storage with the contents of a string
470 * 'dst' => <storage path>,
471 * 'content' => <string of new file contents>,
472 * 'headers' => <HTTP header name/value map> # since 1.21
476 * b) Copy a file system file into storage
480 * 'src' => <file system path>,
481 * 'dst' => <storage path>,
482 * 'headers' => <HTTP header name/value map> # since 1.21
486 * c) Copy a file within storage
490 * 'src' => <storage path>,
491 * 'dst' => <storage path>,
492 * 'ignoreMissingSource' => <boolean>, # since 1.21
493 * 'headers' => <HTTP header name/value map> # since 1.21
497 * d) Move a file within storage
501 * 'src' => <storage path>,
502 * 'dst' => <storage path>,
503 * 'ignoreMissingSource' => <boolean>, # since 1.21
504 * 'headers' => <HTTP header name/value map> # since 1.21
508 * e) Delete a file within storage
512 * 'src' => <storage path>,
513 * 'ignoreMissingSource' => <boolean>
517 * f) Update metadata for a file within storage
520 * 'op' => 'describe',
521 * 'src' => <storage path>,
522 * 'headers' => <HTTP header name/value map>
526 * g) Do nothing (no-op)
533 * @par Boolean flags for operations (operation-specific):
534 * - ignoreMissingSource : The operation will simply succeed and do
535 * nothing if the source file does not exist.
536 * - headers : If supplied with a header name/value map, the backend will
537 * reply with these headers when GETs/HEADs of the destination
538 * file are made. Header values should be smaller than 256 bytes.
539 * Content-Disposition headers can be longer, though the system
540 * might ignore or truncate ones that are too long to store.
541 * Existing headers will remain, but these will replace any
542 * conflicting previous headers, and headers will be removed
543 * if they are set to an empty string.
544 * Backends that don't support metadata ignore this. (since 1.21)
546 * $opts is an associative of boolean flags, including:
547 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
550 * This returns a Status, which contains all warnings and fatals that occurred
551 * during the operation. The 'failCount', 'successCount', and 'success' members
552 * will reflect each operation attempted for the given files. The status will be
553 * considered "OK" as long as no fatal errors occurred.
555 * @param array $ops Set of operations to execute
556 * @param array $opts Batch operation options
560 final public function doQuickOperations( array $ops, array $opts = array() ) {
561 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
562 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
564 if ( !count( $ops ) ) {
565 return Status
::newGood(); // nothing to do
567 foreach ( $ops as &$op ) {
568 $op['overwrite'] = true; // avoids RTTs in key/value stores
569 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
570 $op['headers']['Content-Disposition'] = $op['disposition'];
573 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
574 return $this->doQuickOperationsInternal( $ops );
578 * @see FileBackend::doQuickOperations()
581 abstract protected function doQuickOperationsInternal( array $ops );
584 * Same as doQuickOperations() except it takes a single operation.
585 * If you are doing a batch of operations, then use that function instead.
587 * @see FileBackend::doQuickOperations()
589 * @param array $op Operation
593 final public function doQuickOperation( array $op ) {
594 return $this->doQuickOperations( array( $op ) );
598 * Performs a single quick create operation.
599 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
601 * @see FileBackend::doQuickOperation()
603 * @param array $params Operation parameters
607 final public function quickCreate( array $params ) {
608 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
612 * Performs a single quick store operation.
613 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
615 * @see FileBackend::doQuickOperation()
617 * @param array $params Operation parameters
621 final public function quickStore( array $params ) {
622 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
626 * Performs a single quick copy operation.
627 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
629 * @see FileBackend::doQuickOperation()
631 * @param array $params Operation parameters
635 final public function quickCopy( array $params ) {
636 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
640 * Performs a single quick move operation.
641 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
643 * @see FileBackend::doQuickOperation()
645 * @param array $params Operation parameters
649 final public function quickMove( array $params ) {
650 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
654 * Performs a single quick delete operation.
655 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
657 * @see FileBackend::doQuickOperation()
659 * @param array $params Operation parameters
663 final public function quickDelete( array $params ) {
664 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
668 * Performs a single quick describe operation.
669 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
671 * @see FileBackend::doQuickOperation()
673 * @param array $params Operation parameters
677 final public function quickDescribe( array $params ) {
678 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
682 * Concatenate a list of storage files into a single file system file.
683 * The target path should refer to a file that is already locked or
684 * otherwise safe from modification from other processes. Normally,
685 * the file will be a new temp file, which should be adequate.
687 * @param array $params Operation parameters, include:
688 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
689 * - dst : file system path to 0-byte temp file
690 * - parallelize : try to do operations in parallel when possible
693 abstract public function concatenate( array $params );
696 * Prepare a storage directory for usage.
697 * This will create any required containers and parent directories.
698 * Backends using key/value stores only need to create the container.
700 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
701 * except they are only applied *if* the directory/container had to be created.
702 * These flags should always be set for directories that have private files.
703 * However, setting them is not guaranteed to actually do anything.
704 * Additional server configuration may be needed to achieve the desired effect.
706 * @param array $params Parameters include:
707 * - dir : storage directory
708 * - noAccess : try to deny file access (since 1.20)
709 * - noListing : try to deny file listing (since 1.20)
710 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
713 final public function prepare( array $params ) {
714 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
715 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
717 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
718 return $this->doPrepare( $params );
722 * @see FileBackend::prepare()
724 abstract protected function doPrepare( array $params );
727 * Take measures to block web access to a storage directory and
728 * the container it belongs to. FS backends might add .htaccess
729 * files whereas key/value store backends might revoke container
730 * access to the storage user representing end-users in web requests.
732 * This is not guaranteed to actually make files or listings publically hidden.
733 * Additional server configuration may be needed to achieve the desired effect.
735 * @param array $params Parameters include:
736 * - dir : storage directory
737 * - noAccess : try to deny file access
738 * - noListing : try to deny file listing
739 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
742 final public function secure( array $params ) {
743 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
744 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
746 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
747 return $this->doSecure( $params );
751 * @see FileBackend::secure()
753 abstract protected function doSecure( array $params );
756 * Remove measures to block web access to a storage directory and
757 * the container it belongs to. FS backends might remove .htaccess
758 * files whereas key/value store backends might grant container
759 * access to the storage user representing end-users in web requests.
760 * This essentially can undo the result of secure() calls.
762 * This is not guaranteed to actually make files or listings publically viewable.
763 * Additional server configuration may be needed to achieve the desired effect.
765 * @param array $params Parameters include:
766 * - dir : storage directory
767 * - access : try to allow file access
768 * - listing : try to allow file listing
769 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
773 final public function publish( array $params ) {
774 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
775 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
777 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
778 return $this->doPublish( $params );
782 * @see FileBackend::publish()
784 abstract protected function doPublish( array $params );
787 * Delete a storage directory if it is empty.
788 * Backends using key/value stores may do nothing unless the directory
789 * is that of an empty container, in which case it will be deleted.
791 * @param array $params Parameters include:
792 * - dir : storage directory
793 * - recursive : recursively delete empty subdirectories first (since 1.20)
794 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
797 final public function clean( array $params ) {
798 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
799 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
801 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
802 return $this->doClean( $params );
806 * @see FileBackend::clean()
808 abstract protected function doClean( array $params );
811 * Enter file operation scope.
812 * This just makes PHP ignore user aborts/disconnects until the return
813 * value leaves scope. This returns null and does nothing in CLI mode.
815 * @return ScopedCallback|null
817 final protected function getScopedPHPBehaviorForOps() {
818 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
819 $old = ignore_user_abort( true ); // avoid half-finished operations
820 return new ScopedCallback( function () use ( $old ) {
821 ignore_user_abort( $old );
829 * Check if a file exists at a storage path in the backend.
830 * This returns false if only a directory exists at the path.
832 * @param array $params Parameters include:
833 * - src : source storage path
834 * - latest : use the latest available data
835 * @return bool|null Returns null on failure
837 abstract public function fileExists( array $params );
840 * Get the last-modified timestamp of the file at a storage path.
842 * @param array $params Parameters include:
843 * - src : source storage path
844 * - latest : use the latest available data
845 * @return string|bool TS_MW timestamp or false on failure
847 abstract public function getFileTimestamp( array $params );
850 * Get the contents of a file at a storage path in the backend.
851 * This should be avoided for potentially large files.
853 * @param array $params Parameters include:
854 * - src : source storage path
855 * - latest : use the latest available data
856 * @return string|bool Returns false on failure
858 final public function getFileContents( array $params ) {
859 $contents = $this->getFileContentsMulti(
860 array( 'srcs' => array( $params['src'] ) ) +
$params );
862 return $contents[$params['src']];
866 * Like getFileContents() except it takes an array of storage paths
867 * and returns a map of storage paths to strings (or null on failure).
868 * The map keys (paths) are in the same order as the provided list of paths.
870 * @see FileBackend::getFileContents()
872 * @param array $params Parameters include:
873 * - srcs : list of source storage paths
874 * - latest : use the latest available data
875 * - parallelize : try to do operations in parallel when possible
876 * @return array Map of (path name => string or false on failure)
879 abstract public function getFileContentsMulti( array $params );
882 * Get the size (bytes) of a file at a storage path in the backend.
884 * @param array $params Parameters include:
885 * - src : source storage path
886 * - latest : use the latest available data
887 * @return int|bool Returns false on failure
889 abstract public function getFileSize( array $params );
892 * Get quick information about a file at a storage path in the backend.
893 * If the file does not exist, then this returns false.
894 * Otherwise, the result is an associative array that includes:
895 * - mtime : the last-modified timestamp (TS_MW)
896 * - size : the file size (bytes)
897 * Additional values may be included for internal use only.
899 * @param array $params Parameters include:
900 * - src : source storage path
901 * - latest : use the latest available data
902 * @return array|bool|null Returns null on failure
904 abstract public function getFileStat( array $params );
907 * Get a SHA-1 hash of the file at a storage path in the backend.
909 * @param array $params Parameters include:
910 * - src : source storage path
911 * - latest : use the latest available data
912 * @return string|bool Hash string or false on failure
914 abstract public function getFileSha1Base36( array $params );
917 * Get the properties of the file at a storage path in the backend.
918 * This gives the result of FSFile::getProps() on a local copy of the file.
920 * @param array $params Parameters include:
921 * - src : source storage path
922 * - latest : use the latest available data
923 * @return array Returns FSFile::placeholderProps() on failure
925 abstract public function getFileProps( array $params );
928 * Stream the file at a storage path in the backend.
929 * If the file does not exists, an HTTP 404 error will be given.
930 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
931 * will be sent if streaming began, while none will be sent otherwise.
932 * Implementations should flush the output buffer before sending data.
934 * @param array $params Parameters include:
935 * - src : source storage path
936 * - headers : list of additional HTTP headers to send on success
937 * - latest : use the latest available data
940 abstract public function streamFile( array $params );
943 * Returns a file system file, identical to the file at a storage path.
944 * The file returned is either:
945 * - a) A local copy of the file at a storage path in the backend.
946 * The temporary copy will have the same extension as the source.
947 * - b) An original of the file at a storage path in the backend.
948 * Temporary files may be purged when the file object falls out of scope.
950 * Write operations should *never* be done on this file as some backends
951 * may do internal tracking or may be instances of FileBackendMultiWrite.
952 * In that later case, there are copies of the file that must stay in sync.
953 * Additionally, further calls to this function may return the same file.
955 * @param array $params Parameters include:
956 * - src : source storage path
957 * - latest : use the latest available data
958 * @return FSFile|null Returns null on failure
960 final public function getLocalReference( array $params ) {
961 $fsFiles = $this->getLocalReferenceMulti(
962 array( 'srcs' => array( $params['src'] ) ) +
$params );
964 return $fsFiles[$params['src']];
968 * Like getLocalReference() except it takes an array of storage paths
969 * and returns a map of storage paths to FSFile objects (or null on failure).
970 * The map keys (paths) are in the same order as the provided list of paths.
972 * @see FileBackend::getLocalReference()
974 * @param array $params Parameters include:
975 * - srcs : list of source storage paths
976 * - latest : use the latest available data
977 * - parallelize : try to do operations in parallel when possible
978 * @return array Map of (path name => FSFile or null on failure)
981 abstract public function getLocalReferenceMulti( array $params );
984 * Get a local copy on disk of the file at a storage path in the backend.
985 * The temporary copy will have the same file extension as the source.
986 * Temporary files may be purged when the file object falls out of scope.
988 * @param array $params Parameters include:
989 * - src : source storage path
990 * - latest : use the latest available data
991 * @return TempFSFile|null Returns null on failure
993 final public function getLocalCopy( array $params ) {
994 $tmpFiles = $this->getLocalCopyMulti(
995 array( 'srcs' => array( $params['src'] ) ) +
$params );
997 return $tmpFiles[$params['src']];
1001 * Like getLocalCopy() except it takes an array of storage paths and
1002 * returns a map of storage paths to TempFSFile objects (or null on failure).
1003 * The map keys (paths) are in the same order as the provided list of paths.
1005 * @see FileBackend::getLocalCopy()
1007 * @param array $params Parameters include:
1008 * - srcs : list of source storage paths
1009 * - latest : use the latest available data
1010 * - parallelize : try to do operations in parallel when possible
1011 * @return array Map of (path name => TempFSFile or null on failure)
1014 abstract public function getLocalCopyMulti( array $params );
1017 * Return an HTTP URL to a given file that requires no authentication to use.
1018 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1019 * This will return null if the backend cannot make an HTTP URL for the file.
1021 * This is useful for key/value stores when using scripts that seek around
1022 * large files and those scripts (and the backend) support HTTP Range headers.
1023 * Otherwise, one would need to use getLocalReference(), which involves loading
1024 * the entire file on to local disk.
1026 * @param array $params Parameters include:
1027 * - src : source storage path
1028 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1029 * @return string|null
1032 abstract public function getFileHttpUrl( array $params );
1035 * Check if a directory exists at a given storage path.
1036 * Backends using key/value stores will check if the path is a
1037 * virtual directory, meaning there are files under the given directory.
1039 * Storage backends with eventual consistency might return stale data.
1041 * @param array $params Parameters include:
1042 * - dir : storage directory
1043 * @return bool|null Returns null on failure
1046 abstract public function directoryExists( array $params );
1049 * Get an iterator to list *all* directories under a storage directory.
1050 * If the directory is of the form "mwstore://backend/container",
1051 * then all directories in the container will be listed.
1052 * If the directory is of form "mwstore://backend/container/dir",
1053 * then all directories directly under that directory will be listed.
1054 * Results will be storage directories relative to the given directory.
1056 * Storage backends with eventual consistency might return stale data.
1058 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1060 * @param array $params Parameters include:
1061 * - dir : storage directory
1062 * - topOnly : only return direct child dirs of the directory
1063 * @return Traversable|Array|null Returns null on failure
1066 abstract public function getDirectoryList( array $params );
1069 * Same as FileBackend::getDirectoryList() except only lists
1070 * directories that are immediately under the given directory.
1072 * Storage backends with eventual consistency might return stale data.
1074 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1076 * @param array $params Parameters include:
1077 * - dir : storage directory
1078 * @return Traversable|Array|null Returns null on failure
1081 final public function getTopDirectoryList( array $params ) {
1082 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1086 * Get an iterator to list *all* stored files under a storage directory.
1087 * If the directory is of the form "mwstore://backend/container",
1088 * then all files in the container will be listed.
1089 * If the directory is of form "mwstore://backend/container/dir",
1090 * then all files under that directory will be listed.
1091 * Results will be storage paths relative to the given directory.
1093 * Storage backends with eventual consistency might return stale data.
1095 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1097 * @param array $params Parameters include:
1098 * - dir : storage directory
1099 * - topOnly : only return direct child files of the directory (since 1.20)
1100 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1101 * @return Traversable|Array|null Returns null on failure
1103 abstract public function getFileList( array $params );
1106 * Same as FileBackend::getFileList() except only lists
1107 * files that are immediately under the given directory.
1109 * Storage backends with eventual consistency might return stale data.
1111 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1113 * @param array $params Parameters include:
1114 * - dir : storage directory
1115 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1116 * @return Traversable|Array|null Returns null on failure
1119 final public function getTopFileList( array $params ) {
1120 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1124 * Preload persistent file stat and property cache into in-process cache.
1125 * This should be used when stat calls will be made on a known list of a many files.
1127 * @param array $paths Storage paths
1129 public function preloadCache( array $paths ) {
1133 * Invalidate any in-process file stat and property cache.
1134 * If $paths is given, then only the cache for those files will be cleared.
1136 * @param array $paths Storage paths (optional)
1138 public function clearCache( array $paths = null ) {
1142 * Lock the files at the given storage paths in the backend.
1143 * This will either lock all the files or none (on failure).
1145 * Callers should consider using getScopedFileLocks() instead.
1147 * @param array $paths Storage paths
1148 * @param int $type LockManager::LOCK_* constant
1151 final public function lockFiles( array $paths, $type ) {
1152 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1154 return $this->lockManager
->lock( $paths, $type );
1158 * Unlock the files at the given storage paths in the backend.
1160 * @param array $paths Storage paths
1161 * @param int $type LockManager::LOCK_* constant
1164 final public function unlockFiles( array $paths, $type ) {
1165 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1167 return $this->lockManager
->unlock( $paths, $type );
1171 * Lock the files at the given storage paths in the backend.
1172 * This will either lock all the files or none (on failure).
1173 * On failure, the status object will be updated with errors.
1175 * Once the return value goes out scope, the locks will be released and
1176 * the status updated. Unlock fatals will not change the status "OK" value.
1178 * @see ScopedLock::factory()
1180 * @param array $paths List of storage paths or map of lock types to path lists
1181 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1182 * @param Status $status Status to update on lock/unlock
1183 * @return ScopedLock|null Returns null on failure
1185 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1186 if ( $type === 'mixed' ) {
1187 foreach ( $paths as &$typePaths ) {
1188 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1191 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1194 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1198 * Get an array of scoped locks needed for a batch of file operations.
1200 * Normally, FileBackend::doOperations() handles locking, unless
1201 * the 'nonLocking' param is passed in. This function is useful if you
1202 * want the files to be locked for a broader scope than just when the
1203 * files are changing. For example, if you need to update DB metadata,
1204 * you may want to keep the files locked until finished.
1206 * @see FileBackend::doOperations()
1208 * @param array $ops List of file operations to FileBackend::doOperations()
1209 * @param Status $status Status to update on lock/unlock
1210 * @return array List of ScopedFileLocks or null values
1213 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1216 * Get the root storage path of this backend.
1217 * All container paths are "subdirectories" of this path.
1219 * @return string Storage path
1222 final public function getRootStoragePath() {
1223 return "mwstore://{$this->name}";
1227 * Get the storage path for the given container for this backend
1229 * @param string $container Container name
1230 * @return string Storage path
1233 final public function getContainerStoragePath( $container ) {
1234 return $this->getRootStoragePath() . "/{$container}";
1238 * Get the file journal object for this backend
1240 * @return FileJournal
1242 final public function getJournal() {
1243 return $this->fileJournal
;
1247 * Check if a given path is a "mwstore://" path.
1248 * This does not do any further validation or any existence checks.
1250 * @param string $path
1253 final public static function isStoragePath( $path ) {
1254 return ( strpos( $path, 'mwstore://' ) === 0 );
1258 * Split a storage path into a backend name, a container name,
1259 * and a relative file path. The relative path may be the empty string.
1260 * This does not do any path normalization or traversal checks.
1262 * @param string $storagePath
1263 * @return array (backend, container, rel object) or (null, null, null)
1265 final public static function splitStoragePath( $storagePath ) {
1266 if ( self
::isStoragePath( $storagePath ) ) {
1267 // Remove the "mwstore://" prefix and split the path
1268 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1269 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1270 if ( count( $parts ) == 3 ) {
1271 return $parts; // e.g. "backend/container/path"
1273 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1278 return array( null, null, null );
1282 * Normalize a storage path by cleaning up directory separators.
1283 * Returns null if the path is not of the format of a valid storage path.
1285 * @param string $storagePath
1286 * @return string|null
1288 final public static function normalizeStoragePath( $storagePath ) {
1289 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1290 if ( $relPath !== null ) { // must be for this backend
1291 $relPath = self
::normalizeContainerPath( $relPath );
1292 if ( $relPath !== null ) {
1293 return ( $relPath != '' )
1294 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1295 : "mwstore://{$backend}/{$container}";
1303 * Get the parent storage directory of a storage path.
1304 * This returns a path like "mwstore://backend/container",
1305 * "mwstore://backend/container/...", or null if there is no parent.
1307 * @param string $storagePath
1308 * @return string|null
1310 final public static function parentStoragePath( $storagePath ) {
1311 $storagePath = dirname( $storagePath );
1312 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1314 return ( $rel === null ) ?
null : $storagePath;
1318 * Get the final extension from a storage or FS path
1320 * @param string $path
1323 final public static function extensionFromPath( $path ) {
1324 $i = strrpos( $path, '.' );
1326 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1330 * Check if a relative path has no directory traversals
1332 * @param string $path
1336 final public static function isPathTraversalFree( $path ) {
1337 return ( self
::normalizeContainerPath( $path ) !== null );
1341 * Build a Content-Disposition header value per RFC 6266.
1343 * @param string $type One of (attachment, inline)
1344 * @param string $filename Suggested file name (should not contain slashes)
1345 * @throws MWException
1349 final public static function makeContentDisposition( $type, $filename = '' ) {
1352 $type = strtolower( $type );
1353 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1354 throw new MWException( "Invalid Content-Disposition type '$type'." );
1358 if ( strlen( $filename ) ) {
1359 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1362 return implode( ';', $parts );
1366 * Validate and normalize a relative storage path.
1367 * Null is returned if the path involves directory traversal.
1368 * Traversal is insecure for FS backends and broken for others.
1370 * This uses the same traversal protection as Title::secureAndSplit().
1372 * @param string $path Storage path relative to a container
1373 * @return string|null
1375 final protected static function normalizeContainerPath( $path ) {
1376 // Normalize directory separators
1377 $path = strtr( $path, '\\', '/' );
1378 // Collapse any consecutive directory separators
1379 $path = preg_replace( '![/]{2,}!', '/', $path );
1380 // Remove any leading directory separator
1381 $path = ltrim( $path, '/' );
1382 // Use the same traversal protection as Title::secureAndSplit()
1383 if ( strpos( $path, '.' ) !== false ) {
1387 strpos( $path, './' ) === 0 ||
1388 strpos( $path, '../' ) === 0 ||
1389 strpos( $path, '/./' ) !== false ||
1390 strpos( $path, '/../' ) !== false
1401 * @ingroup FileBackend
1404 class FileBackendError
extends MWException
{