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 * @param $params Array Operation parameters
665 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
666 * - dst : file system path to 0-byte temp file
667 * - parallelize : try to do operations in parallel when possible
670 abstract public function concatenate( array $params );
673 * Prepare a storage directory for usage.
674 * This will create any required containers and parent directories.
675 * Backends using key/value stores only need to create the container.
677 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
678 * except they are only applied *if* the directory/container had to be created.
679 * These flags should always be set for directories that have private files.
681 * @param $params Array
683 * - dir : storage directory
684 * - noAccess : try to deny file access (since 1.20)
685 * - noListing : try to deny file listing (since 1.20)
686 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
689 final public function prepare( array $params ) {
690 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
691 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
693 return $this->doPrepare( $params );
697 * @see FileBackend::prepare()
699 abstract protected function doPrepare( array $params );
702 * Take measures to block web access to a storage directory and
703 * the container it belongs to. FS backends might add .htaccess
704 * files whereas key/value store backends might revoke container
705 * access to the storage user representing end-users in web requests.
706 * This is not guaranteed to actually do anything.
708 * @param $params Array
710 * - dir : storage directory
711 * - noAccess : try to deny file access
712 * - noListing : try to deny file listing
713 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
716 final public function secure( array $params ) {
717 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
718 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
720 return $this->doSecure( $params );
724 * @see FileBackend::secure()
726 abstract protected function doSecure( array $params );
729 * Remove measures to block web access to a storage directory and
730 * the container it belongs to. FS backends might remove .htaccess
731 * files whereas key/value store backends might grant container
732 * access to the storage user representing end-users in web requests.
733 * This essentially can undo the result of secure() calls.
735 * @param $params Array
737 * - dir : storage directory
738 * - access : try to allow file access
739 * - listing : try to allow file listing
740 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
744 final public function publish( array $params ) {
745 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
746 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
748 return $this->doPublish( $params );
752 * @see FileBackend::publish()
754 abstract protected function doPublish( array $params );
757 * Delete a storage directory if it is empty.
758 * Backends using key/value stores may do nothing unless the directory
759 * is that of an empty container, in which case it will be deleted.
761 * @param $params Array
763 * - dir : storage directory
764 * - recursive : recursively delete empty subdirectories first (since 1.20)
765 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
768 final public function clean( array $params ) {
769 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
770 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
772 return $this->doClean( $params );
776 * @see FileBackend::clean()
778 abstract protected function doClean( array $params );
781 * Check if a file exists at a storage path in the backend.
782 * This returns false if only a directory exists at the path.
784 * @param $params Array
786 * - src : source storage path
787 * - latest : use the latest available data
788 * @return bool|null Returns null on failure
790 abstract public function fileExists( array $params );
793 * Get the last-modified timestamp of the file at a storage path.
795 * @param $params Array
797 * - src : source storage path
798 * - latest : use the latest available data
799 * @return string|bool TS_MW timestamp or false on failure
801 abstract public function getFileTimestamp( array $params );
804 * Get the contents of a file at a storage path in the backend.
805 * This should be avoided for potentially large files.
807 * @param $params Array
809 * - src : source storage path
810 * - latest : use the latest available data
811 * @return string|bool Returns false on failure
813 final public function getFileContents( array $params ) {
814 $contents = $this->getFileContentsMulti(
815 array( 'srcs' => array( $params['src'] ) ) +
$params );
817 return $contents[$params['src']];
821 * Like getFileContents() except it takes an array of storage paths
822 * and returns a map of storage paths to strings (or null on failure).
823 * The map keys (paths) are in the same order as the provided list of paths.
825 * @see FileBackend::getFileContents()
827 * @param $params Array
829 * - srcs : list of source storage paths
830 * - latest : use the latest available data
831 * - parallelize : try to do operations in parallel when possible
832 * @return Array Map of (path name => string or false on failure)
835 abstract public function getFileContentsMulti( array $params );
838 * Get the size (bytes) of a file at a storage path in the backend.
840 * @param $params Array
842 * - src : source storage path
843 * - latest : use the latest available data
844 * @return integer|bool Returns false on failure
846 abstract public function getFileSize( array $params );
849 * Get quick information about a file at a storage path in the backend.
850 * If the file does not exist, then this returns false.
851 * Otherwise, the result is an associative array that includes:
852 * - mtime : the last-modified timestamp (TS_MW)
853 * - size : the file size (bytes)
854 * Additional values may be included for internal use only.
856 * @param $params Array
858 * - src : source storage path
859 * - latest : use the latest available data
860 * @return Array|bool|null Returns null on failure
862 abstract public function getFileStat( array $params );
865 * Get a SHA-1 hash of the file at a storage path in the backend.
867 * @param $params Array
869 * - src : source storage path
870 * - latest : use the latest available data
871 * @return string|bool Hash string or false on failure
873 abstract public function getFileSha1Base36( array $params );
876 * Get the properties of the file at a storage path in the backend.
877 * Returns FSFile::placeholderProps() on failure.
879 * @param $params Array
881 * - src : source storage path
882 * - latest : use the latest available data
885 abstract public function getFileProps( array $params );
888 * Stream the file at a storage path in the backend.
889 * If the file does not exists, an HTTP 404 error will be given.
890 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
891 * will be sent if streaming began, while none will be sent otherwise.
892 * Implementations should flush the output buffer before sending data.
894 * @param $params Array
896 * - src : source storage path
897 * - headers : list of additional HTTP headers to send on success
898 * - latest : use the latest available data
901 abstract public function streamFile( array $params );
904 * Returns a file system file, identical to the file at a storage path.
905 * The file returned is either:
906 * - a) A local copy of the file at a storage path in the backend.
907 * The temporary copy will have the same extension as the source.
908 * - b) An original of the file at a storage path in the backend.
909 * Temporary files may be purged when the file object falls out of scope.
911 * Write operations should *never* be done on this file as some backends
912 * may do internal tracking or may be instances of FileBackendMultiWrite.
913 * In that later case, there are copies of the file that must stay in sync.
914 * Additionally, further calls to this function may return the same file.
916 * @param $params Array
918 * - src : source storage path
919 * - latest : use the latest available data
920 * @return FSFile|null Returns null on failure
922 final public function getLocalReference( array $params ) {
923 $fsFiles = $this->getLocalReferenceMulti(
924 array( 'srcs' => array( $params['src'] ) ) +
$params );
926 return $fsFiles[$params['src']];
930 * Like getLocalReference() except it takes an array of storage paths
931 * and returns a map of storage paths to FSFile objects (or null on failure).
932 * The map keys (paths) are in the same order as the provided list of paths.
934 * @see FileBackend::getLocalReference()
936 * @param $params Array
938 * - srcs : list of source storage paths
939 * - latest : use the latest available data
940 * - parallelize : try to do operations in parallel when possible
941 * @return Array Map of (path name => FSFile or null on failure)
944 abstract public function getLocalReferenceMulti( array $params );
947 * Get a local copy on disk of the file at a storage path in the backend.
948 * The temporary copy will have the same file extension as the source.
949 * Temporary files may be purged when the file object falls out of scope.
951 * @param $params Array
953 * - src : source storage path
954 * - latest : use the latest available data
955 * @return TempFSFile|null Returns null on failure
957 final public function getLocalCopy( array $params ) {
958 $tmpFiles = $this->getLocalCopyMulti(
959 array( 'srcs' => array( $params['src'] ) ) +
$params );
961 return $tmpFiles[$params['src']];
965 * Like getLocalCopy() except it takes an array of storage paths and
966 * returns a map of storage paths to TempFSFile objects (or null on failure).
967 * The map keys (paths) are in the same order as the provided list of paths.
969 * @see FileBackend::getLocalCopy()
971 * @param $params Array
973 * - srcs : list of source storage paths
974 * - latest : use the latest available data
975 * - parallelize : try to do operations in parallel when possible
976 * @return Array Map of (path name => TempFSFile or null on failure)
979 abstract public function getLocalCopyMulti( array $params );
982 * Return an HTTP URL to a given file that requires no authentication to use.
983 * The URL may be pre-authenticated (via some token in the URL) and temporary.
984 * This will return null if the backend cannot make an HTTP URL for the file.
986 * This is useful for key/value stores when using scripts that seek around
987 * large files and those scripts (and the backend) support HTTP Range headers.
988 * Otherwise, one would need to use getLocalReference(), which involves loading
989 * the entire file on to local disk.
991 * @param $params Array
993 * - src : source storage path
994 * @return string|null
997 abstract public function getFileHttpUrl( array $params );
1000 * Check if a directory exists at a given storage path.
1001 * Backends using key/value stores will check if the path is a
1002 * virtual directory, meaning there are files under the given directory.
1004 * Storage backends with eventual consistency might return stale data.
1006 * @param $params array
1008 * - dir : storage directory
1009 * @return bool|null Returns null on failure
1012 abstract public function directoryExists( array $params );
1015 * Get an iterator to list *all* directories under a storage directory.
1016 * If the directory is of the form "mwstore://backend/container",
1017 * then all directories in the container will be listed.
1018 * If the directory is of form "mwstore://backend/container/dir",
1019 * then all directories directly under that directory will be listed.
1020 * Results will be storage directories relative to the given directory.
1022 * Storage backends with eventual consistency might return stale data.
1024 * @param $params array
1026 * - dir : storage directory
1027 * - topOnly : only return direct child dirs of the directory
1028 * @return Traversable|Array|null Returns null on failure
1031 abstract public function getDirectoryList( array $params );
1034 * Same as FileBackend::getDirectoryList() except only lists
1035 * directories that are immediately under the given directory.
1037 * Storage backends with eventual consistency might return stale data.
1039 * @param $params array
1041 * - dir : storage directory
1042 * @return Traversable|Array|null Returns null on failure
1045 final public function getTopDirectoryList( array $params ) {
1046 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1050 * Get an iterator to list *all* stored files under a storage directory.
1051 * If the directory is of the form "mwstore://backend/container",
1052 * then all files in the container will be listed.
1053 * If the directory is of form "mwstore://backend/container/dir",
1054 * then all files under that directory will be listed.
1055 * Results will be storage paths relative to the given directory.
1057 * Storage backends with eventual consistency might return stale data.
1059 * @param $params array
1061 * - dir : storage directory
1062 * - topOnly : only return direct child files of the directory (since 1.20)
1063 * @return Traversable|Array|null Returns null on failure
1065 abstract public function getFileList( array $params );
1068 * Same as FileBackend::getFileList() except only lists
1069 * files that are immediately under the given directory.
1071 * Storage backends with eventual consistency might return stale data.
1073 * @param $params array
1075 * - dir : storage directory
1076 * @return Traversable|Array|null Returns null on failure
1079 final public function getTopFileList( array $params ) {
1080 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1084 * Preload persistent file stat and property cache into in-process cache.
1085 * This should be used when stat calls will be made on a known list of a many files.
1087 * @param $paths Array Storage paths
1090 public function preloadCache( array $paths ) {}
1093 * Invalidate any in-process file stat and property cache.
1094 * If $paths is given, then only the cache for those files will be cleared.
1096 * @param $paths Array Storage paths (optional)
1099 public function clearCache( array $paths = null ) {}
1102 * Lock the files at the given storage paths in the backend.
1103 * This will either lock all the files or none (on failure).
1105 * Callers should consider using getScopedFileLocks() instead.
1107 * @param $paths Array Storage paths
1108 * @param $type integer LockManager::LOCK_* constant
1111 final public function lockFiles( array $paths, $type ) {
1112 return $this->lockManager
->lock( $paths, $type );
1116 * Unlock the files at the given storage paths in the backend.
1118 * @param $paths Array Storage paths
1119 * @param $type integer LockManager::LOCK_* constant
1122 final public function unlockFiles( array $paths, $type ) {
1123 return $this->lockManager
->unlock( $paths, $type );
1127 * Lock the files at the given storage paths in the backend.
1128 * This will either lock all the files or none (on failure).
1129 * On failure, the status object will be updated with errors.
1131 * Once the return value goes out scope, the locks will be released and
1132 * the status updated. Unlock fatals will not change the status "OK" value.
1134 * @param $paths Array Storage paths
1135 * @param $type integer LockManager::LOCK_* constant
1136 * @param $status Status Status to update on lock/unlock
1137 * @return ScopedLock|null Returns null on failure
1139 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1140 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1144 * Get an array of scoped locks needed for a batch of file operations.
1146 * Normally, FileBackend::doOperations() handles locking, unless
1147 * the 'nonLocking' param is passed in. This function is useful if you
1148 * want the files to be locked for a broader scope than just when the
1149 * files are changing. For example, if you need to update DB metadata,
1150 * you may want to keep the files locked until finished.
1152 * @see FileBackend::doOperations()
1154 * @param $ops Array List of file operations to FileBackend::doOperations()
1155 * @param $status Status Status to update on lock/unlock
1156 * @return Array List of ScopedFileLocks or null values
1159 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1162 * Get the root storage path of this backend.
1163 * All container paths are "subdirectories" of this path.
1165 * @return string Storage path
1168 final public function getRootStoragePath() {
1169 return "mwstore://{$this->name}";
1173 * Get the storage path for the given container for this backend
1175 * @param $container string Container name
1176 * @return string Storage path
1179 final public function getContainerStoragePath( $container ) {
1180 return $this->getRootStoragePath() . "/{$container}";
1184 * Get the file journal object for this backend
1186 * @return FileJournal
1188 final public function getJournal() {
1189 return $this->fileJournal
;
1193 * Check if a given path is a "mwstore://" path.
1194 * This does not do any further validation or any existence checks.
1196 * @param $path string
1199 final public static function isStoragePath( $path ) {
1200 return ( strpos( $path, 'mwstore://' ) === 0 );
1204 * Split a storage path into a backend name, a container name,
1205 * and a relative file path. The relative path may be the empty string.
1206 * This does not do any path normalization or traversal checks.
1208 * @param $storagePath string
1209 * @return Array (backend, container, rel object) or (null, null, null)
1211 final public static function splitStoragePath( $storagePath ) {
1212 if ( self
::isStoragePath( $storagePath ) ) {
1213 // Remove the "mwstore://" prefix and split the path
1214 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1215 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1216 if ( count( $parts ) == 3 ) {
1217 return $parts; // e.g. "backend/container/path"
1219 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1223 return array( null, null, null );
1227 * Normalize a storage path by cleaning up directory separators.
1228 * Returns null if the path is not of the format of a valid storage path.
1230 * @param $storagePath string
1231 * @return string|null
1233 final public static function normalizeStoragePath( $storagePath ) {
1234 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1235 if ( $relPath !== null ) { // must be for this backend
1236 $relPath = self
::normalizeContainerPath( $relPath );
1237 if ( $relPath !== null ) {
1238 return ( $relPath != '' )
1239 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1240 : "mwstore://{$backend}/{$container}";
1247 * Get the parent storage directory of a storage path.
1248 * This returns a path like "mwstore://backend/container",
1249 * "mwstore://backend/container/...", or null if there is no parent.
1251 * @param $storagePath string
1252 * @return string|null
1254 final public static function parentStoragePath( $storagePath ) {
1255 $storagePath = dirname( $storagePath );
1256 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1257 return ( $rel === null ) ?
null : $storagePath;
1261 * Get the final extension from a storage or FS path
1263 * @param $path string
1266 final public static function extensionFromPath( $path ) {
1267 $i = strrpos( $path, '.' );
1268 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1272 * Check if a relative path has no directory traversals
1274 * @param $path string
1278 final public static function isPathTraversalFree( $path ) {
1279 return ( self
::normalizeContainerPath( $path ) !== null );
1283 * Build a Content-Disposition header value per RFC 6266.
1285 * @param $type string One of (attachment, inline)
1286 * @param $filename string Suggested file name (should not contain slashes)
1287 * @throws MWException
1291 final public static function makeContentDisposition( $type, $filename = '' ) {
1294 $type = strtolower( $type );
1295 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1296 throw new MWException( "Invalid Content-Disposition type '$type'." );
1300 if ( strlen( $filename ) ) {
1301 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1304 return implode( ';', $parts );
1308 * Validate and normalize a relative storage path.
1309 * Null is returned if the path involves directory traversal.
1310 * Traversal is insecure for FS backends and broken for others.
1312 * This uses the same traversal protection as Title::secureAndSplit().
1314 * @param $path string Storage path relative to a container
1315 * @return string|null
1317 final protected static function normalizeContainerPath( $path ) {
1318 // Normalize directory separators
1319 $path = strtr( $path, '\\', '/' );
1320 // Collapse any consecutive directory separators
1321 $path = preg_replace( '![/]{2,}!', '/', $path );
1322 // Remove any leading directory separator
1323 $path = ltrim( $path, '/' );
1324 // Use the same traversal protection as Title::secureAndSplit()
1325 if ( strpos( $path, '.' ) !== false ) {
1329 strpos( $path, './' ) === 0 ||
1330 strpos( $path, '../' ) === 0 ||
1331 strpos( $path, '/./' ) !== false ||
1332 strpos( $path, '/../' ) !== false