3 * @defgroup FileBackend File backend
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
11 * Base class for all file backends.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
29 * @ingroup FileBackend
30 * @author Aaron Schulz
34 * @brief Base class for all file backend classes (including multi-write backends).
36 * This class defines the methods as abstract that subclasses must implement.
37 * Outside callers can assume that all backends will have these functions.
39 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
40 * The "<path>" portion is a relative path that uses UNIX file system (FS)
41 * notation, though any particular backend may not actually be using a local
42 * filesystem. Therefore, the relative paths are only virtual.
44 * Backend contents are stored under wiki-specific container names by default.
45 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
46 * segregation must be done by setting the container paths appropriately.
48 * FS-based backends are somewhat more restrictive due to the existence of real
49 * directory files; a regular file cannot have the same name as a directory. Other
50 * backends with virtual directories may not have this limitation. Callers should
51 * store files in such a way that no files and directories are under the same path.
53 * Methods of subclasses should avoid throwing exceptions at all costs.
54 * As a corollary, external dependencies should be kept to a minimum.
56 * @ingroup FileBackend
59 abstract class FileBackend
{
60 protected $name; // string; unique backend name
61 protected $wikiId; // string; unique wiki name
62 protected $readOnly; // string; read-only explanation message
63 protected $parallelize; // string; when to do operations in parallel
64 protected $concurrency; // integer; how many operations can be done in parallel
66 /** @var LockManager */
67 protected $lockManager;
68 /** @var FileJournal */
69 protected $fileJournal;
72 * Create a new backend instance from configuration.
73 * This should only be called from within FileBackendGroup.
76 * - name : The unique name of this backend.
77 * This should consist of alphanumberic, '-', and '_' characters.
78 * This name should not be changed after use.
79 * - wikiId : Prefix to container names that is unique to this wiki.
80 * It should only consist of alphanumberic, '-', and '_' characters.
81 * - lockManager : Registered name of a file lock manager to use.
82 * - fileJournal : File journal configuration; see FileJournal::factory().
83 * Journals simply log changes to files stored in the backend.
84 * - readOnly : Write operations are disallowed if this is a non-empty string.
85 * It should be an explanation for the backend being read-only.
86 * - parallelize : When to do file operations in parallel (when possible).
87 * Allowed values are "implicit", "explicit" and "off".
88 * - concurrency : How many file operations can be done in parallel.
90 * @param $config Array
93 public function __construct( array $config ) {
94 $this->name
= $config['name'];
95 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
96 throw new MWException( "Backend name `{$this->name}` is invalid." );
98 $this->wikiId
= isset( $config['wikiId'] )
100 : wfWikiID(); // e.g. "my_wiki-en_"
101 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
102 ?
$config['lockManager']
103 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
104 $this->fileJournal
= isset( $config['fileJournal'] )
105 ?
( ( $config['fileJournal'] instanceof FileJournal
)
106 ?
$config['fileJournal']
107 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
108 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
109 $this->readOnly
= isset( $config['readOnly'] )
110 ?
(string)$config['readOnly']
112 $this->parallelize
= isset( $config['parallelize'] )
113 ?
(string)$config['parallelize']
115 $this->concurrency
= isset( $config['concurrency'] )
116 ?
(int)$config['concurrency']
121 * Get the unique backend name.
122 * We may have multiple different backends of the same type.
123 * For example, we can have two Swift backends using different proxies.
127 final public function getName() {
132 * Get the wiki identifier used for this backend (possibly empty).
133 * Note that this might *not* be in the same format as wfWikiID().
138 final public function getWikiId() {
139 return $this->wikiId
;
143 * Check if this backend is read-only
147 final public function isReadOnly() {
148 return ( $this->readOnly
!= '' );
152 * Get an explanatory message if this backend is read-only
154 * @return string|bool Returns false if the backend is not read-only
156 final public function getReadOnlyReason() {
157 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
161 * This is the main entry point into the backend for write operations.
162 * Callers supply an ordered list of operations to perform as a transaction.
163 * Files will be locked, the stat cache cleared, and then the operations attempted.
164 * If any serious errors occur, all attempted operations will be rolled back.
166 * $ops is an array of arrays. The outer array holds a list of operations.
167 * Each inner array is a set of key value pairs that specify an operation.
169 * Supported operations and their parameters. The supported actions are:
175 * - describe (since 1.21)
178 * a) Create a new file in storage with the contents of a string
182 * 'dst' => <storage path>,
183 * 'content' => <string of new file contents>,
184 * 'overwrite' => <boolean>,
185 * 'overwriteSame' => <boolean>,
186 * 'disposition' => <Content-Disposition header value>,
187 * 'headers' => <HTTP header name/value map> # since 1.21
191 * b) Copy a file system file into storage
195 * 'src' => <file system path>,
196 * 'dst' => <storage path>,
197 * 'overwrite' => <boolean>,
198 * 'overwriteSame' => <boolean>,
199 * 'disposition' => <Content-Disposition header value>,
200 * 'headers' => <HTTP header name/value map> # since 1.21
204 * c) Copy a file within storage
208 * 'src' => <storage path>,
209 * 'dst' => <storage path>,
210 * 'overwrite' => <boolean>,
211 * 'overwriteSame' => <boolean>,
212 * 'ignoreMissingSource' => <boolean>, # since 1.21
213 * 'disposition' => <Content-Disposition header value>
217 * d) Move a file within storage
221 * 'src' => <storage path>,
222 * 'dst' => <storage path>,
223 * 'overwrite' => <boolean>,
224 * 'overwriteSame' => <boolean>,
225 * 'ignoreMissingSource' => <boolean>, # since 1.21
226 * 'disposition' => <Content-Disposition header value>
230 * e) Delete a file within storage
234 * 'src' => <storage path>,
235 * 'ignoreMissingSource' => <boolean>
239 * f) Update metadata for a file within storage
242 * 'op' => 'describe',
243 * 'src' => <storage path>,
244 * 'disposition' => <Content-Disposition header value>,
245 * 'headers' => <HTTP header name/value map>
249 * g) Do nothing (no-op)
256 * Boolean flags for operations (operation-specific):
257 * - ignoreMissingSource : The operation will simply succeed and do
258 * nothing if the source file does not exist.
259 * - overwrite : Any destination file will be overwritten.
260 * - overwriteSame : An error will not be given if a file already
261 * exists at the destination that has the same
262 * contents as the new contents to be written there.
263 * - disposition : If supplied, the backend will return a Content-Disposition
264 * header when GETs/HEADs of the destination file are made.
265 * Backends that don't support metadata ignore this.
266 * See http://tools.ietf.org/html/rfc6266. (since 1.20)
267 * - headers : If supplied, the backend will return these headers when
268 * GETs/HEADs of the destination file are made. Header values
269 * should be smaller than 256 bytes, often options or numbers.
270 * Existing headers will remain, but these will replace any
271 * conflicting previous headers, and headers will be removed
272 * if they are set to an empty string.
273 * Backends that don't support metadata ignore this. (since 1.21)
275 * $opts is an associative of boolean flags, including:
276 * - force : Operation precondition errors no longer trigger an abort.
277 * Any remaining operations are still attempted. Unexpected
278 * failures may still cause remaning operations to be aborted.
279 * - nonLocking : No locks are acquired for the operations.
280 * This can increase performance for non-critical writes.
281 * This has no effect unless the 'force' flag is set.
282 * - allowStale : Don't require the latest available data.
283 * This can increase performance for non-critical writes.
284 * This has no effect unless the 'force' flag is set.
285 * - nonJournaled : Don't log this operation batch in the file journal.
286 * This limits the ability of recovery scripts.
287 * - parallelize : Try to do operations in parallel when possible.
288 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
289 * - preserveCache : Don't clear the process cache before checking files.
290 * This should only be used if all entries in the process
291 * cache were added after the files were already locked. (since 1.20)
293 * @remarks Remarks on locking:
294 * File system paths given to operations should refer to files that are
295 * already locked or otherwise safe from modification from other processes.
296 * Normally these files will be new temp files, which should be adequate.
300 * This returns a Status, which contains all warnings and fatals that occurred
301 * during the operation. The 'failCount', 'successCount', and 'success' members
302 * will reflect each operation attempted.
304 * The status will be "OK" unless:
305 * - a) unexpected operation errors occurred (network partitions, disk full...)
306 * - b) significant operation errors occurred and 'force' was not set
308 * @param $ops Array List of operations to execute in order
309 * @param $opts Array Batch operation options
312 final public function doOperations( array $ops, array $opts = array() ) {
313 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
314 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
316 if ( empty( $opts['force'] ) ) { // sanity
317 unset( $opts['nonLocking'] );
318 unset( $opts['allowStale'] );
320 return $this->doOperationsInternal( $ops, $opts );
324 * @see FileBackend::doOperations()
326 abstract protected function doOperationsInternal( array $ops, array $opts );
329 * Same as doOperations() except it takes a single operation.
330 * If you are doing a batch of operations that should either
331 * all succeed or all fail, then use that function instead.
333 * @see FileBackend::doOperations()
335 * @param $op Array Operation
336 * @param $opts Array Operation options
339 final public function doOperation( array $op, array $opts = array() ) {
340 return $this->doOperations( array( $op ), $opts );
344 * Performs a single create operation.
345 * This sets $params['op'] to 'create' and passes it to doOperation().
347 * @see FileBackend::doOperation()
349 * @param $params Array Operation parameters
350 * @param $opts Array Operation options
353 final public function create( array $params, array $opts = array() ) {
354 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
358 * Performs a single store operation.
359 * This sets $params['op'] to 'store' and passes it to doOperation().
361 * @see FileBackend::doOperation()
363 * @param $params Array Operation parameters
364 * @param $opts Array Operation options
367 final public function store( array $params, array $opts = array() ) {
368 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
372 * Performs a single copy operation.
373 * This sets $params['op'] to 'copy' and passes it to doOperation().
375 * @see FileBackend::doOperation()
377 * @param $params Array Operation parameters
378 * @param $opts Array Operation options
381 final public function copy( array $params, array $opts = array() ) {
382 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
386 * Performs a single move operation.
387 * This sets $params['op'] to 'move' and passes it to doOperation().
389 * @see FileBackend::doOperation()
391 * @param $params Array Operation parameters
392 * @param $opts Array Operation options
395 final public function move( array $params, array $opts = array() ) {
396 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
400 * Performs a single delete operation.
401 * This sets $params['op'] to 'delete' and passes it to doOperation().
403 * @see FileBackend::doOperation()
405 * @param $params Array Operation parameters
406 * @param $opts Array Operation options
409 final public function delete( array $params, array $opts = array() ) {
410 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
414 * Performs a single describe operation.
415 * This sets $params['op'] to 'describe' and passes it to doOperation().
417 * @see FileBackend::doOperation()
419 * @param $params Array Operation parameters
420 * @param $opts Array Operation options
424 final public function describe( array $params, array $opts = array() ) {
425 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
429 * Perform a set of independent file operations on some files.
431 * This does no locking, nor journaling, and possibly no stat calls.
432 * Any destination files that already exist will be overwritten.
433 * This should *only* be used on non-original files, like cache files.
435 * Supported operations and their parameters:
441 * - describe (since 1.21)
444 * a) Create a new file in storage with the contents of a string
448 * 'dst' => <storage path>,
449 * 'content' => <string of new file contents>,
450 * 'disposition' => <Content-Disposition header value>,
451 * 'headers' => <HTTP header name/value map> # since 1.21
455 * b) Copy a file system file into storage
459 * 'src' => <file system path>,
460 * 'dst' => <storage path>,
461 * 'disposition' => <Content-Disposition header value>,
462 * 'headers' => <HTTP header name/value map> # since 1.21
466 * c) Copy a file within storage
470 * 'src' => <storage path>,
471 * 'dst' => <storage path>,
472 * 'ignoreMissingSource' => <boolean>, # since 1.21
473 * 'disposition' => <Content-Disposition header value>
477 * d) Move a file within storage
481 * 'src' => <storage path>,
482 * 'dst' => <storage path>,
483 * 'ignoreMissingSource' => <boolean>, # since 1.21
484 * 'disposition' => <Content-Disposition header value>
488 * e) Delete a file within storage
492 * 'src' => <storage path>,
493 * 'ignoreMissingSource' => <boolean>
497 * f) Update metadata for a file within storage
500 * 'op' => 'describe',
501 * 'src' => <storage path>,
502 * 'disposition' => <Content-Disposition header value>,
503 * 'headers' => <HTTP header name/value map>
507 * g) Do nothing (no-op)
514 * @par Boolean flags for operations (operation-specific):
515 * - ignoreMissingSource : The operation will simply succeed and do
516 * nothing if the source file does not exist.
517 * - disposition : When supplied, the backend will add a Content-Disposition
518 * header when GETs/HEADs of the destination file are made.
519 * Backends that don't support file metadata will ignore this.
520 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
521 * - headers : If supplied, the backend will return these headers when
522 * GETs/HEADs of the destination file are made. Header values
523 * should be smaller than 256 bytes, often options or numbers.
524 * Existing headers will remain, but these will replace any
525 * conflicting previous headers, and headers will be removed
526 * if they are set to an empty string.
527 * Backends that don't support metadata ignore this. (since 1.21)
529 * $opts is an associative of boolean flags, including:
530 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
533 * This returns a Status, which contains all warnings and fatals that occurred
534 * during the operation. The 'failCount', 'successCount', and 'success' members
535 * will reflect each operation attempted for the given files. The status will be
536 * considered "OK" as long as no fatal errors occurred.
538 * @param $ops Array Set of operations to execute
539 * @param $opts Array Batch operation options
543 final public function doQuickOperations( array $ops, array $opts = array() ) {
544 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
545 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
547 foreach ( $ops as &$op ) {
548 $op['overwrite'] = true; // avoids RTTs in key/value stores
550 return $this->doQuickOperationsInternal( $ops );
554 * @see FileBackend::doQuickOperations()
557 abstract protected function doQuickOperationsInternal( array $ops );
560 * Same as doQuickOperations() except it takes a single operation.
561 * If you are doing a batch of operations, then use that function instead.
563 * @see FileBackend::doQuickOperations()
565 * @param $op Array Operation
569 final public function doQuickOperation( array $op ) {
570 return $this->doQuickOperations( array( $op ) );
574 * Performs a single quick create operation.
575 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
577 * @see FileBackend::doQuickOperation()
579 * @param $params Array Operation parameters
583 final public function quickCreate( array $params ) {
584 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
588 * Performs a single quick store operation.
589 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
591 * @see FileBackend::doQuickOperation()
593 * @param $params Array Operation parameters
597 final public function quickStore( array $params ) {
598 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
602 * Performs a single quick copy operation.
603 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
605 * @see FileBackend::doQuickOperation()
607 * @param $params Array Operation parameters
611 final public function quickCopy( array $params ) {
612 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
616 * Performs a single quick move operation.
617 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
619 * @see FileBackend::doQuickOperation()
621 * @param $params Array Operation parameters
625 final public function quickMove( array $params ) {
626 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
630 * Performs a single quick delete operation.
631 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
633 * @see FileBackend::doQuickOperation()
635 * @param $params Array Operation parameters
639 final public function quickDelete( array $params ) {
640 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
644 * Performs a single quick describe operation.
645 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
647 * @see FileBackend::doQuickOperation()
649 * @param $params Array Operation parameters
653 final public function quickDescribe( array $params ) {
654 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
658 * Concatenate a list of storage files into a single file system file.
659 * The target path should refer to a file that is already locked or
660 * otherwise safe from modification from other processes. Normally,
661 * the file will be a new temp file, which should be adequate.
663 * If a callback function is given, it will be called each time a segment is
664 * appended and when the overall concatenate operation completes or fails.
665 * The arguments passed in are:
666 * - 1) A Status object containing errors if any problems occurred.
667 * - 2) The index of the relevant segment (starting at 1) if a segment was appended
668 * (including the last one) or null in the case of overall success or failure.
669 * When a good Status is returned with a null segment, then the operation completed.
670 * Callbacks should generally avoid throwing exceptions.
672 * @param $params Array Operation parameters
674 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
675 * - dst : file system path to 0-byte temp file
676 * - parallelize : try to do operations in parallel when possible
677 * - callback : closure called when chunks are appended and on success/failure
680 abstract public function concatenate( array $params );
683 * Prepare a storage directory for usage.
684 * This will create any required containers and parent directories.
685 * Backends using key/value stores only need to create the container.
687 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
688 * except they are only applied *if* the directory/container had to be created.
689 * These flags should always be set for directories that have private files.
691 * @param $params Array
693 * - dir : storage directory
694 * - noAccess : try to deny file access (since 1.20)
695 * - noListing : try to deny file listing (since 1.20)
696 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
699 final public function prepare( array $params ) {
700 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
701 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
703 return $this->doPrepare( $params );
707 * @see FileBackend::prepare()
709 abstract protected function doPrepare( array $params );
712 * Take measures to block web access to a storage directory and
713 * the container it belongs to. FS backends might add .htaccess
714 * files whereas key/value store backends might revoke container
715 * access to the storage user representing end-users in web requests.
716 * This is not guaranteed to actually do anything.
718 * @param $params Array
720 * - dir : storage directory
721 * - noAccess : try to deny file access
722 * - noListing : try to deny file listing
723 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
726 final public function secure( array $params ) {
727 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
728 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
730 return $this->doSecure( $params );
734 * @see FileBackend::secure()
736 abstract protected function doSecure( array $params );
739 * Remove measures to block web access to a storage directory and
740 * the container it belongs to. FS backends might remove .htaccess
741 * files whereas key/value store backends might grant container
742 * access to the storage user representing end-users in web requests.
743 * This essentially can undo the result of secure() calls.
745 * @param $params Array
747 * - dir : storage directory
748 * - access : try to allow file access
749 * - listing : try to allow file listing
750 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
754 final public function publish( array $params ) {
755 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
756 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
758 return $this->doPublish( $params );
762 * @see FileBackend::publish()
764 abstract protected function doPublish( array $params );
767 * Delete a storage directory if it is empty.
768 * Backends using key/value stores may do nothing unless the directory
769 * is that of an empty container, in which case it will be deleted.
771 * @param $params Array
773 * - dir : storage directory
774 * - recursive : recursively delete empty subdirectories first (since 1.20)
775 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
778 final public function clean( array $params ) {
779 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
780 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
782 return $this->doClean( $params );
786 * @see FileBackend::clean()
788 abstract protected function doClean( array $params );
791 * Check if a file exists at a storage path in the backend.
792 * This returns false if only a directory exists at the path.
794 * @param $params Array
796 * - src : source storage path
797 * - latest : use the latest available data
798 * @return bool|null Returns null on failure
800 abstract public function fileExists( array $params );
803 * Get the last-modified timestamp of the file at a storage path.
805 * @param $params Array
807 * - src : source storage path
808 * - latest : use the latest available data
809 * @return string|bool TS_MW timestamp or false on failure
811 abstract public function getFileTimestamp( array $params );
814 * Get the contents of a file at a storage path in the backend.
815 * This should be avoided for potentially large files.
817 * @param $params Array
819 * - src : source storage path
820 * - latest : use the latest available data
821 * @return string|bool Returns false on failure
823 final public function getFileContents( array $params ) {
824 $contents = $this->getFileContentsMulti(
825 array( 'srcs' => array( $params['src'] ) ) +
$params );
827 return $contents[$params['src']];
831 * Like getFileContents() except it takes an array of storage paths
832 * and returns a map of storage paths to strings (or null on failure).
833 * The map keys (paths) are in the same order as the provided list of paths.
835 * @see FileBackend::getFileContents()
837 * @param $params Array
839 * - srcs : list of source storage paths
840 * - latest : use the latest available data
841 * - parallelize : try to do operations in parallel when possible
842 * @return Array Map of (path name => string or false on failure)
845 abstract public function getFileContentsMulti( array $params );
848 * Get the size (bytes) of a file at a storage path in the backend.
850 * @param $params Array
852 * - src : source storage path
853 * - latest : use the latest available data
854 * @return integer|bool Returns false on failure
856 abstract public function getFileSize( array $params );
859 * Get quick information about a file at a storage path in the backend.
860 * If the file does not exist, then this returns false.
861 * Otherwise, the result is an associative array that includes:
862 * - mtime : the last-modified timestamp (TS_MW)
863 * - size : the file size (bytes)
864 * Additional values may be included for internal use only.
866 * @param $params Array
868 * - src : source storage path
869 * - latest : use the latest available data
870 * @return Array|bool|null Returns null on failure
872 abstract public function getFileStat( array $params );
875 * Get a SHA-1 hash of the file at a storage path in the backend.
877 * @param $params Array
879 * - src : source storage path
880 * - latest : use the latest available data
881 * @return string|bool Hash string or false on failure
883 abstract public function getFileSha1Base36( array $params );
886 * Get the properties of the file at a storage path in the backend.
887 * Returns FSFile::placeholderProps() on failure.
889 * @param $params Array
891 * - src : source storage path
892 * - latest : use the latest available data
895 abstract public function getFileProps( array $params );
898 * Stream the file at a storage path in the backend.
899 * If the file does not exists, an HTTP 404 error will be given.
900 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
901 * will be sent if streaming began, while none will be sent otherwise.
902 * Implementations should flush the output buffer before sending data.
904 * @param $params Array
906 * - src : source storage path
907 * - headers : list of additional HTTP headers to send on success
908 * - latest : use the latest available data
911 abstract public function streamFile( array $params );
914 * Returns a file system file, identical to the file at a storage path.
915 * The file returned is either:
916 * - a) A local copy of the file at a storage path in the backend.
917 * The temporary copy will have the same extension as the source.
918 * - b) An original of the file at a storage path in the backend.
919 * Temporary files may be purged when the file object falls out of scope.
921 * Write operations should *never* be done on this file as some backends
922 * may do internal tracking or may be instances of FileBackendMultiWrite.
923 * In that later case, there are copies of the file that must stay in sync.
924 * Additionally, further calls to this function may return the same file.
926 * @param $params Array
928 * - src : source storage path
929 * - latest : use the latest available data
930 * @return FSFile|null Returns null on failure
932 final public function getLocalReference( array $params ) {
933 $fsFiles = $this->getLocalReferenceMulti(
934 array( 'srcs' => array( $params['src'] ) ) +
$params );
936 return $fsFiles[$params['src']];
940 * Like getLocalReference() except it takes an array of storage paths
941 * and returns a map of storage paths to FSFile objects (or null on failure).
942 * The map keys (paths) are in the same order as the provided list of paths.
944 * @see FileBackend::getLocalReference()
946 * @param $params Array
948 * - srcs : list of source storage paths
949 * - latest : use the latest available data
950 * - parallelize : try to do operations in parallel when possible
951 * @return Array Map of (path name => FSFile or null on failure)
954 abstract public function getLocalReferenceMulti( array $params );
957 * Get a local copy on disk of the file at a storage path in the backend.
958 * The temporary copy will have the same file extension as the source.
959 * Temporary files may be purged when the file object falls out of scope.
961 * @param $params Array
963 * - src : source storage path
964 * - latest : use the latest available data
965 * @return TempFSFile|null Returns null on failure
967 final public function getLocalCopy( array $params ) {
968 $tmpFiles = $this->getLocalCopyMulti(
969 array( 'srcs' => array( $params['src'] ) ) +
$params );
971 return $tmpFiles[$params['src']];
975 * Like getLocalCopy() except it takes an array of storage paths and
976 * returns a map of storage paths to TempFSFile objects (or null on failure).
977 * The map keys (paths) are in the same order as the provided list of paths.
979 * @see FileBackend::getLocalCopy()
981 * @param $params Array
983 * - srcs : list of source storage paths
984 * - latest : use the latest available data
985 * - parallelize : try to do operations in parallel when possible
986 * @return Array Map of (path name => TempFSFile or null on failure)
989 abstract public function getLocalCopyMulti( array $params );
992 * Return an HTTP URL to a given file that requires no authentication to use.
993 * The URL may be pre-authenticated (via some token in the URL) and temporary.
994 * This will return null if the backend cannot make an HTTP URL for the file.
996 * This is useful for key/value stores when using scripts that seek around
997 * large files and those scripts (and the backend) support HTTP Range headers.
998 * Otherwise, one would need to use getLocalReference(), which involves loading
999 * the entire file on to local disk.
1001 * @param $params Array
1003 * - src : source storage path
1004 * @return string|null
1007 abstract public function getFileHttpUrl( array $params );
1010 * Check if a directory exists at a given storage path.
1011 * Backends using key/value stores will check if the path is a
1012 * virtual directory, meaning there are files under the given directory.
1014 * Storage backends with eventual consistency might return stale data.
1016 * @param $params array
1018 * - dir : storage directory
1019 * @return bool|null Returns null on failure
1022 abstract public function directoryExists( array $params );
1025 * Get an iterator to list *all* directories under a storage directory.
1026 * If the directory is of the form "mwstore://backend/container",
1027 * then all directories in the container will be listed.
1028 * If the directory is of form "mwstore://backend/container/dir",
1029 * then all directories directly under that directory will be listed.
1030 * Results will be storage directories relative to the given directory.
1032 * Storage backends with eventual consistency might return stale data.
1034 * @param $params array
1036 * - dir : storage directory
1037 * - topOnly : only return direct child dirs of the directory
1038 * @return Traversable|Array|null Returns null on failure
1041 abstract public function getDirectoryList( array $params );
1044 * Same as FileBackend::getDirectoryList() except only lists
1045 * directories that are immediately under the given directory.
1047 * Storage backends with eventual consistency might return stale data.
1049 * @param $params array
1051 * - dir : storage directory
1052 * @return Traversable|Array|null Returns null on failure
1055 final public function getTopDirectoryList( array $params ) {
1056 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1060 * Get an iterator to list *all* stored files under a storage directory.
1061 * If the directory is of the form "mwstore://backend/container",
1062 * then all files in the container will be listed.
1063 * If the directory is of form "mwstore://backend/container/dir",
1064 * then all files under that directory will be listed.
1065 * Results will be storage paths relative to the given directory.
1067 * Storage backends with eventual consistency might return stale data.
1069 * @param $params array
1071 * - dir : storage directory
1072 * - topOnly : only return direct child files of the directory (since 1.20)
1073 * @return Traversable|Array|null Returns null on failure
1075 abstract public function getFileList( array $params );
1078 * Same as FileBackend::getFileList() except only lists
1079 * files that are immediately under the given directory.
1081 * Storage backends with eventual consistency might return stale data.
1083 * @param $params array
1085 * - dir : storage directory
1086 * @return Traversable|Array|null Returns null on failure
1089 final public function getTopFileList( array $params ) {
1090 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1094 * Preload persistent file stat and property cache into in-process cache.
1095 * This should be used when stat calls will be made on a known list of a many files.
1097 * @param $paths Array Storage paths
1100 public function preloadCache( array $paths ) {}
1103 * Invalidate any in-process file stat and property cache.
1104 * If $paths is given, then only the cache for those files will be cleared.
1106 * @param $paths Array Storage paths (optional)
1109 public function clearCache( array $paths = null ) {}
1112 * Lock the files at the given storage paths in the backend.
1113 * This will either lock all the files or none (on failure).
1115 * Callers should consider using getScopedFileLocks() instead.
1117 * @param $paths Array Storage paths
1118 * @param $type integer LockManager::LOCK_* constant
1121 final public function lockFiles( array $paths, $type ) {
1122 return $this->lockManager
->lock( $paths, $type );
1126 * Unlock the files at the given storage paths in the backend.
1128 * @param $paths Array Storage paths
1129 * @param $type integer LockManager::LOCK_* constant
1132 final public function unlockFiles( array $paths, $type ) {
1133 return $this->lockManager
->unlock( $paths, $type );
1137 * Lock the files at the given storage paths in the backend.
1138 * This will either lock all the files or none (on failure).
1139 * On failure, the status object will be updated with errors.
1141 * Once the return value goes out scope, the locks will be released and
1142 * the status updated. Unlock fatals will not change the status "OK" value.
1144 * @param $paths Array Storage paths
1145 * @param $type integer LockManager::LOCK_* constant
1146 * @param $status Status Status to update on lock/unlock
1147 * @return ScopedLock|null Returns null on failure
1149 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1150 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1154 * Get an array of scoped locks needed for a batch of file operations.
1156 * Normally, FileBackend::doOperations() handles locking, unless
1157 * the 'nonLocking' param is passed in. This function is useful if you
1158 * want the files to be locked for a broader scope than just when the
1159 * files are changing. For example, if you need to update DB metadata,
1160 * you may want to keep the files locked until finished.
1162 * @see FileBackend::doOperations()
1164 * @param $ops Array List of file operations to FileBackend::doOperations()
1165 * @param $status Status Status to update on lock/unlock
1166 * @return Array List of ScopedFileLocks or null values
1169 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1172 * Get the root storage path of this backend.
1173 * All container paths are "subdirectories" of this path.
1175 * @return string Storage path
1178 final public function getRootStoragePath() {
1179 return "mwstore://{$this->name}";
1183 * Get the storage path for the given container for this backend
1185 * @param $container string Container name
1186 * @return string Storage path
1189 final public function getContainerStoragePath( $container ) {
1190 return $this->getRootStoragePath() . "/{$container}";
1194 * Get the file journal object for this backend
1196 * @return FileJournal
1198 final public function getJournal() {
1199 return $this->fileJournal
;
1203 * Check if a given path is a "mwstore://" path.
1204 * This does not do any further validation or any existence checks.
1206 * @param $path string
1209 final public static function isStoragePath( $path ) {
1210 return ( strpos( $path, 'mwstore://' ) === 0 );
1214 * Split a storage path into a backend name, a container name,
1215 * and a relative file path. The relative path may be the empty string.
1216 * This does not do any path normalization or traversal checks.
1218 * @param $storagePath string
1219 * @return Array (backend, container, rel object) or (null, null, null)
1221 final public static function splitStoragePath( $storagePath ) {
1222 if ( self
::isStoragePath( $storagePath ) ) {
1223 // Remove the "mwstore://" prefix and split the path
1224 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1225 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1226 if ( count( $parts ) == 3 ) {
1227 return $parts; // e.g. "backend/container/path"
1229 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1233 return array( null, null, null );
1237 * Normalize a storage path by cleaning up directory separators.
1238 * Returns null if the path is not of the format of a valid storage path.
1240 * @param $storagePath string
1241 * @return string|null
1243 final public static function normalizeStoragePath( $storagePath ) {
1244 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1245 if ( $relPath !== null ) { // must be for this backend
1246 $relPath = self
::normalizeContainerPath( $relPath );
1247 if ( $relPath !== null ) {
1248 return ( $relPath != '' )
1249 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1250 : "mwstore://{$backend}/{$container}";
1257 * Get the parent storage directory of a storage path.
1258 * This returns a path like "mwstore://backend/container",
1259 * "mwstore://backend/container/...", or null if there is no parent.
1261 * @param $storagePath string
1262 * @return string|null
1264 final public static function parentStoragePath( $storagePath ) {
1265 $storagePath = dirname( $storagePath );
1266 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1267 return ( $rel === null ) ?
null : $storagePath;
1271 * Get the final extension from a storage or FS path
1273 * @param $path string
1276 final public static function extensionFromPath( $path ) {
1277 $i = strrpos( $path, '.' );
1278 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1282 * Check if a relative path has no directory traversals
1284 * @param $path string
1288 final public static function isPathTraversalFree( $path ) {
1289 return ( self
::normalizeContainerPath( $path ) !== null );
1293 * Build a Content-Disposition header value per RFC 6266.
1295 * @param $type string One of (attachment, inline)
1296 * @param $filename string Suggested file name (should not contain slashes)
1297 * @throws MWException
1301 final public static function makeContentDisposition( $type, $filename = '' ) {
1304 $type = strtolower( $type );
1305 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1306 throw new MWException( "Invalid Content-Disposition type '$type'." );
1310 if ( strlen( $filename ) ) {
1311 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1314 return implode( ';', $parts );
1318 * Validate and normalize a relative storage path.
1319 * Null is returned if the path involves directory traversal.
1320 * Traversal is insecure for FS backends and broken for others.
1322 * This uses the same traversal protection as Title::secureAndSplit().
1324 * @param $path string Storage path relative to a container
1325 * @return string|null
1327 final protected static function normalizeContainerPath( $path ) {
1328 // Normalize directory separators
1329 $path = strtr( $path, '\\', '/' );
1330 // Collapse any consecutive directory separators
1331 $path = preg_replace( '![/]{2,}!', '/', $path );
1332 // Remove any leading directory separator
1333 $path = ltrim( $path, '/' );
1334 // Use the same traversal protection as Title::secureAndSplit()
1335 if ( strpos( $path, '.' ) !== false ) {
1339 strpos( $path, './' ) === 0 ||
1340 strpos( $path, '../' ) === 0 ||
1341 strpos( $path, '/./' ) !== false ||
1342 strpos( $path, '/../' ) !== false