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 * - nonJournaled : Don't log this operation batch in the file journal.
283 * This limits the ability of recovery scripts.
284 * - parallelize : Try to do operations in parallel when possible.
285 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
286 * - preserveCache : Don't clear the process cache before checking files.
287 * This should only be used if all entries in the process
288 * cache were added after the files were already locked. (since 1.20)
290 * @remarks Remarks on locking:
291 * File system paths given to operations should refer to files that are
292 * already locked or otherwise safe from modification from other processes.
293 * Normally these files will be new temp files, which should be adequate.
297 * This returns a Status, which contains all warnings and fatals that occurred
298 * during the operation. The 'failCount', 'successCount', and 'success' members
299 * will reflect each operation attempted.
301 * The status will be "OK" unless:
302 * - a) unexpected operation errors occurred (network partitions, disk full...)
303 * - b) significant operation errors occurred and 'force' was not set
305 * @param $ops Array List of operations to execute in order
306 * @param $opts Array Batch operation options
309 final public function doOperations( array $ops, array $opts = array() ) {
310 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
311 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
313 if ( empty( $opts['force'] ) ) { // sanity
314 unset( $opts['nonLocking'] );
316 return $this->doOperationsInternal( $ops, $opts );
320 * @see FileBackend::doOperations()
322 abstract protected function doOperationsInternal( array $ops, array $opts );
325 * Same as doOperations() except it takes a single operation.
326 * If you are doing a batch of operations that should either
327 * all succeed or all fail, then use that function instead.
329 * @see FileBackend::doOperations()
331 * @param $op Array Operation
332 * @param $opts Array Operation options
335 final public function doOperation( array $op, array $opts = array() ) {
336 return $this->doOperations( array( $op ), $opts );
340 * Performs a single create operation.
341 * This sets $params['op'] to 'create' and passes it to doOperation().
343 * @see FileBackend::doOperation()
345 * @param $params Array Operation parameters
346 * @param $opts Array Operation options
349 final public function create( array $params, array $opts = array() ) {
350 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
354 * Performs a single store operation.
355 * This sets $params['op'] to 'store' and passes it to doOperation().
357 * @see FileBackend::doOperation()
359 * @param $params Array Operation parameters
360 * @param $opts Array Operation options
363 final public function store( array $params, array $opts = array() ) {
364 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
368 * Performs a single copy operation.
369 * This sets $params['op'] to 'copy' and passes it to doOperation().
371 * @see FileBackend::doOperation()
373 * @param $params Array Operation parameters
374 * @param $opts Array Operation options
377 final public function copy( array $params, array $opts = array() ) {
378 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
382 * Performs a single move operation.
383 * This sets $params['op'] to 'move' and passes it to doOperation().
385 * @see FileBackend::doOperation()
387 * @param $params Array Operation parameters
388 * @param $opts Array Operation options
391 final public function move( array $params, array $opts = array() ) {
392 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
396 * Performs a single delete operation.
397 * This sets $params['op'] to 'delete' and passes it to doOperation().
399 * @see FileBackend::doOperation()
401 * @param $params Array Operation parameters
402 * @param $opts Array Operation options
405 final public function delete( array $params, array $opts = array() ) {
406 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
410 * Performs a single describe operation.
411 * This sets $params['op'] to 'describe' and passes it to doOperation().
413 * @see FileBackend::doOperation()
415 * @param $params Array Operation parameters
416 * @param $opts Array Operation options
420 final public function describe( array $params, array $opts = array() ) {
421 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
425 * Perform a set of independent file operations on some files.
427 * This does no locking, nor journaling, and possibly no stat calls.
428 * Any destination files that already exist will be overwritten.
429 * This should *only* be used on non-original files, like cache files.
431 * Supported operations and their parameters:
437 * - describe (since 1.21)
440 * a) Create a new file in storage with the contents of a string
444 * 'dst' => <storage path>,
445 * 'content' => <string of new file contents>,
446 * 'disposition' => <Content-Disposition header value>,
447 * 'headers' => <HTTP header name/value map> # since 1.21
451 * b) Copy a file system file into storage
455 * 'src' => <file system path>,
456 * 'dst' => <storage path>,
457 * 'disposition' => <Content-Disposition header value>,
458 * 'headers' => <HTTP header name/value map> # since 1.21
462 * c) Copy a file within storage
466 * 'src' => <storage path>,
467 * 'dst' => <storage path>,
468 * 'ignoreMissingSource' => <boolean>, # since 1.21
469 * 'disposition' => <Content-Disposition header value>
473 * d) Move a file within storage
477 * 'src' => <storage path>,
478 * 'dst' => <storage path>,
479 * 'ignoreMissingSource' => <boolean>, # since 1.21
480 * 'disposition' => <Content-Disposition header value>
484 * e) Delete a file within storage
488 * 'src' => <storage path>,
489 * 'ignoreMissingSource' => <boolean>
493 * f) Update metadata for a file within storage
496 * 'op' => 'describe',
497 * 'src' => <storage path>,
498 * 'disposition' => <Content-Disposition header value>,
499 * 'headers' => <HTTP header name/value map>
503 * g) Do nothing (no-op)
510 * @par Boolean flags for operations (operation-specific):
511 * - ignoreMissingSource : The operation will simply succeed and do
512 * nothing if the source file does not exist.
513 * - disposition : When supplied, the backend will add a Content-Disposition
514 * header when GETs/HEADs of the destination file are made.
515 * Backends that don't support file metadata will ignore this.
516 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
517 * - headers : If supplied with a header name/value map, the backend will
518 * reply with these headers when GETs/HEADs of the destination
519 * file are made. Header values should be smaller than 256 bytes.
520 * Existing headers will remain, but these will replace any
521 * conflicting previous headers, and headers will be removed
522 * if they are set to an empty string.
523 * Backends that don't support metadata ignore this. (since 1.21)
525 * $opts is an associative of boolean flags, including:
526 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
529 * This returns a Status, which contains all warnings and fatals that occurred
530 * during the operation. The 'failCount', 'successCount', and 'success' members
531 * will reflect each operation attempted for the given files. The status will be
532 * considered "OK" as long as no fatal errors occurred.
534 * @param $ops Array Set of operations to execute
535 * @param $opts Array Batch operation options
539 final public function doQuickOperations( array $ops, array $opts = array() ) {
540 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
541 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
543 foreach ( $ops as &$op ) {
544 $op['overwrite'] = true; // avoids RTTs in key/value stores
546 return $this->doQuickOperationsInternal( $ops );
550 * @see FileBackend::doQuickOperations()
553 abstract protected function doQuickOperationsInternal( array $ops );
556 * Same as doQuickOperations() except it takes a single operation.
557 * If you are doing a batch of operations, then use that function instead.
559 * @see FileBackend::doQuickOperations()
561 * @param $op Array Operation
565 final public function doQuickOperation( array $op ) {
566 return $this->doQuickOperations( array( $op ) );
570 * Performs a single quick create operation.
571 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
573 * @see FileBackend::doQuickOperation()
575 * @param $params Array Operation parameters
579 final public function quickCreate( array $params ) {
580 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
584 * Performs a single quick store operation.
585 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
587 * @see FileBackend::doQuickOperation()
589 * @param $params Array Operation parameters
593 final public function quickStore( array $params ) {
594 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
598 * Performs a single quick copy operation.
599 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
601 * @see FileBackend::doQuickOperation()
603 * @param $params Array Operation parameters
607 final public function quickCopy( array $params ) {
608 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
612 * Performs a single quick move operation.
613 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
615 * @see FileBackend::doQuickOperation()
617 * @param $params Array Operation parameters
621 final public function quickMove( array $params ) {
622 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
626 * Performs a single quick delete operation.
627 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
629 * @see FileBackend::doQuickOperation()
631 * @param $params Array Operation parameters
635 final public function quickDelete( array $params ) {
636 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
640 * Performs a single quick describe operation.
641 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
643 * @see FileBackend::doQuickOperation()
645 * @param $params Array Operation parameters
649 final public function quickDescribe( array $params ) {
650 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
654 * Concatenate a list of storage files into a single file system file.
655 * The target path should refer to a file that is already locked or
656 * otherwise safe from modification from other processes. Normally,
657 * the file will be a new temp file, which should be adequate.
659 * @param $params Array Operation parameters
661 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
662 * - dst : file system path to 0-byte temp file
663 * - parallelize : try to do operations in parallel when possible
666 abstract public function concatenate( array $params );
669 * Prepare a storage directory for usage.
670 * This will create any required containers and parent directories.
671 * Backends using key/value stores only need to create the container.
673 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
674 * except they are only applied *if* the directory/container had to be created.
675 * These flags should always be set for directories that have private files.
677 * @param $params Array
679 * - dir : storage directory
680 * - noAccess : try to deny file access (since 1.20)
681 * - noListing : try to deny file listing (since 1.20)
682 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
685 final public function prepare( array $params ) {
686 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
687 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
689 return $this->doPrepare( $params );
693 * @see FileBackend::prepare()
695 abstract protected function doPrepare( array $params );
698 * Take measures to block web access to a storage directory and
699 * the container it belongs to. FS backends might add .htaccess
700 * files whereas key/value store backends might revoke container
701 * access to the storage user representing end-users in web requests.
702 * This is not guaranteed to actually do anything.
704 * @param $params Array
706 * - dir : storage directory
707 * - noAccess : try to deny file access
708 * - noListing : try to deny file listing
709 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
712 final public function secure( array $params ) {
713 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
714 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
716 return $this->doSecure( $params );
720 * @see FileBackend::secure()
722 abstract protected function doSecure( array $params );
725 * Remove measures to block web access to a storage directory and
726 * the container it belongs to. FS backends might remove .htaccess
727 * files whereas key/value store backends might grant container
728 * access to the storage user representing end-users in web requests.
729 * This essentially can undo the result of secure() calls.
731 * @param $params Array
733 * - dir : storage directory
734 * - access : try to allow file access
735 * - listing : try to allow file listing
736 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
740 final public function publish( array $params ) {
741 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
742 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
744 return $this->doPublish( $params );
748 * @see FileBackend::publish()
750 abstract protected function doPublish( array $params );
753 * Delete a storage directory if it is empty.
754 * Backends using key/value stores may do nothing unless the directory
755 * is that of an empty container, in which case it will be deleted.
757 * @param $params Array
759 * - dir : storage directory
760 * - recursive : recursively delete empty subdirectories first (since 1.20)
761 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
764 final public function clean( array $params ) {
765 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
766 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
768 return $this->doClean( $params );
772 * @see FileBackend::clean()
774 abstract protected function doClean( array $params );
777 * Check if a file exists at a storage path in the backend.
778 * This returns false if only a directory exists at the path.
780 * @param $params Array
782 * - src : source storage path
783 * - latest : use the latest available data
784 * @return bool|null Returns null on failure
786 abstract public function fileExists( array $params );
789 * Get the last-modified timestamp of the file at a storage path.
791 * @param $params Array
793 * - src : source storage path
794 * - latest : use the latest available data
795 * @return string|bool TS_MW timestamp or false on failure
797 abstract public function getFileTimestamp( array $params );
800 * Get the contents of a file at a storage path in the backend.
801 * This should be avoided for potentially large files.
803 * @param $params Array
805 * - src : source storage path
806 * - latest : use the latest available data
807 * @return string|bool Returns false on failure
809 final public function getFileContents( array $params ) {
810 $contents = $this->getFileContentsMulti(
811 array( 'srcs' => array( $params['src'] ) ) +
$params );
813 return $contents[$params['src']];
817 * Like getFileContents() except it takes an array of storage paths
818 * and returns a map of storage paths to strings (or null on failure).
819 * The map keys (paths) are in the same order as the provided list of paths.
821 * @see FileBackend::getFileContents()
823 * @param $params Array
825 * - srcs : list of source storage paths
826 * - latest : use the latest available data
827 * - parallelize : try to do operations in parallel when possible
828 * @return Array Map of (path name => string or false on failure)
831 abstract public function getFileContentsMulti( array $params );
834 * Get the size (bytes) of a file at a storage path in the backend.
836 * @param $params Array
838 * - src : source storage path
839 * - latest : use the latest available data
840 * @return integer|bool Returns false on failure
842 abstract public function getFileSize( array $params );
845 * Get quick information about a file at a storage path in the backend.
846 * If the file does not exist, then this returns false.
847 * Otherwise, the result is an associative array that includes:
848 * - mtime : the last-modified timestamp (TS_MW)
849 * - size : the file size (bytes)
850 * Additional values may be included for internal use only.
852 * @param $params Array
854 * - src : source storage path
855 * - latest : use the latest available data
856 * @return Array|bool|null Returns null on failure
858 abstract public function getFileStat( array $params );
861 * Get a SHA-1 hash of the file at a storage path in the backend.
863 * @param $params Array
865 * - src : source storage path
866 * - latest : use the latest available data
867 * @return string|bool Hash string or false on failure
869 abstract public function getFileSha1Base36( array $params );
872 * Get the properties of the file at a storage path in the backend.
873 * This gives the result of FSFile::getProps() on a local copy of the file.
875 * @param $params Array
877 * - src : source storage path
878 * - latest : use the latest available data
879 * @return Array Returns FSFile::placeholderProps() on failure
881 abstract public function getFileProps( array $params );
884 * Stream the file at a storage path in the backend.
885 * If the file does not exists, an HTTP 404 error will be given.
886 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
887 * will be sent if streaming began, while none will be sent otherwise.
888 * Implementations should flush the output buffer before sending data.
890 * @param $params Array
892 * - src : source storage path
893 * - headers : list of additional HTTP headers to send on success
894 * - latest : use the latest available data
897 abstract public function streamFile( array $params );
900 * Returns a file system file, identical to the file at a storage path.
901 * The file returned is either:
902 * - a) A local copy of the file at a storage path in the backend.
903 * The temporary copy will have the same extension as the source.
904 * - b) An original of the file at a storage path in the backend.
905 * Temporary files may be purged when the file object falls out of scope.
907 * Write operations should *never* be done on this file as some backends
908 * may do internal tracking or may be instances of FileBackendMultiWrite.
909 * In that later case, there are copies of the file that must stay in sync.
910 * Additionally, further calls to this function may return the same file.
912 * @param $params Array
914 * - src : source storage path
915 * - latest : use the latest available data
916 * @return FSFile|null Returns null on failure
918 final public function getLocalReference( array $params ) {
919 $fsFiles = $this->getLocalReferenceMulti(
920 array( 'srcs' => array( $params['src'] ) ) +
$params );
922 return $fsFiles[$params['src']];
926 * Like getLocalReference() except it takes an array of storage paths
927 * and returns a map of storage paths to FSFile objects (or null on failure).
928 * The map keys (paths) are in the same order as the provided list of paths.
930 * @see FileBackend::getLocalReference()
932 * @param $params Array
934 * - srcs : list of source storage paths
935 * - latest : use the latest available data
936 * - parallelize : try to do operations in parallel when possible
937 * @return Array Map of (path name => FSFile or null on failure)
940 abstract public function getLocalReferenceMulti( array $params );
943 * Get a local copy on disk of the file at a storage path in the backend.
944 * The temporary copy will have the same file extension as the source.
945 * Temporary files may be purged when the file object falls out of scope.
947 * @param $params Array
949 * - src : source storage path
950 * - latest : use the latest available data
951 * @return TempFSFile|null Returns null on failure
953 final public function getLocalCopy( array $params ) {
954 $tmpFiles = $this->getLocalCopyMulti(
955 array( 'srcs' => array( $params['src'] ) ) +
$params );
957 return $tmpFiles[$params['src']];
961 * Like getLocalCopy() except it takes an array of storage paths and
962 * returns a map of storage paths to TempFSFile objects (or null on failure).
963 * The map keys (paths) are in the same order as the provided list of paths.
965 * @see FileBackend::getLocalCopy()
967 * @param $params Array
969 * - srcs : list of source storage paths
970 * - latest : use the latest available data
971 * - parallelize : try to do operations in parallel when possible
972 * @return Array Map of (path name => TempFSFile or null on failure)
975 abstract public function getLocalCopyMulti( array $params );
978 * Return an HTTP URL to a given file that requires no authentication to use.
979 * The URL may be pre-authenticated (via some token in the URL) and temporary.
980 * This will return null if the backend cannot make an HTTP URL for the file.
982 * This is useful for key/value stores when using scripts that seek around
983 * large files and those scripts (and the backend) support HTTP Range headers.
984 * Otherwise, one would need to use getLocalReference(), which involves loading
985 * the entire file on to local disk.
987 * @param $params Array
989 * - src : source storage path
990 * @return string|null
993 abstract public function getFileHttpUrl( array $params );
996 * Check if a directory exists at a given storage path.
997 * Backends using key/value stores will check if the path is a
998 * virtual directory, meaning there are files under the given directory.
1000 * Storage backends with eventual consistency might return stale data.
1002 * @param $params array
1004 * - dir : storage directory
1005 * @return bool|null Returns null on failure
1008 abstract public function directoryExists( array $params );
1011 * Get an iterator to list *all* directories under a storage directory.
1012 * If the directory is of the form "mwstore://backend/container",
1013 * then all directories in the container will be listed.
1014 * If the directory is of form "mwstore://backend/container/dir",
1015 * then all directories directly under that directory will be listed.
1016 * Results will be storage directories relative to the given directory.
1018 * Storage backends with eventual consistency might return stale data.
1020 * @param $params array
1022 * - dir : storage directory
1023 * - topOnly : only return direct child dirs of the directory
1024 * @return Traversable|Array|null Returns null on failure
1027 abstract public function getDirectoryList( array $params );
1030 * Same as FileBackend::getDirectoryList() except only lists
1031 * directories that are immediately under the given directory.
1033 * Storage backends with eventual consistency might return stale data.
1035 * @param $params array
1037 * - dir : storage directory
1038 * @return Traversable|Array|null Returns null on failure
1041 final public function getTopDirectoryList( array $params ) {
1042 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1046 * Get an iterator to list *all* stored files under a storage directory.
1047 * If the directory is of the form "mwstore://backend/container",
1048 * then all files in the container will be listed.
1049 * If the directory is of form "mwstore://backend/container/dir",
1050 * then all files under that directory will be listed.
1051 * Results will be storage paths relative to the given directory.
1053 * Storage backends with eventual consistency might return stale data.
1055 * @param $params array
1057 * - dir : storage directory
1058 * - topOnly : only return direct child files of the directory (since 1.20)
1059 * @return Traversable|Array|null Returns null on failure
1061 abstract public function getFileList( array $params );
1064 * Same as FileBackend::getFileList() except only lists
1065 * files that are immediately under the given directory.
1067 * Storage backends with eventual consistency might return stale data.
1069 * @param $params array
1071 * - dir : storage directory
1072 * @return Traversable|Array|null Returns null on failure
1075 final public function getTopFileList( array $params ) {
1076 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1080 * Preload persistent file stat and property cache into in-process cache.
1081 * This should be used when stat calls will be made on a known list of a many files.
1083 * @param $paths Array Storage paths
1086 public function preloadCache( array $paths ) {}
1089 * Invalidate any in-process file stat and property cache.
1090 * If $paths is given, then only the cache for those files will be cleared.
1092 * @param $paths Array Storage paths (optional)
1095 public function clearCache( array $paths = null ) {}
1098 * Lock the files at the given storage paths in the backend.
1099 * This will either lock all the files or none (on failure).
1101 * Callers should consider using getScopedFileLocks() instead.
1103 * @param $paths Array Storage paths
1104 * @param $type integer LockManager::LOCK_* constant
1107 final public function lockFiles( array $paths, $type ) {
1108 return $this->lockManager
->lock( $paths, $type );
1112 * Unlock the files at the given storage paths in the backend.
1114 * @param $paths Array Storage paths
1115 * @param $type integer LockManager::LOCK_* constant
1118 final public function unlockFiles( array $paths, $type ) {
1119 return $this->lockManager
->unlock( $paths, $type );
1123 * Lock the files at the given storage paths in the backend.
1124 * This will either lock all the files or none (on failure).
1125 * On failure, the status object will be updated with errors.
1127 * Once the return value goes out scope, the locks will be released and
1128 * the status updated. Unlock fatals will not change the status "OK" value.
1130 * @param $paths Array Storage paths
1131 * @param $type integer LockManager::LOCK_* constant
1132 * @param $status Status Status to update on lock/unlock
1133 * @return ScopedLock|null Returns null on failure
1135 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1136 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1140 * Get an array of scoped locks needed for a batch of file operations.
1142 * Normally, FileBackend::doOperations() handles locking, unless
1143 * the 'nonLocking' param is passed in. This function is useful if you
1144 * want the files to be locked for a broader scope than just when the
1145 * files are changing. For example, if you need to update DB metadata,
1146 * you may want to keep the files locked until finished.
1148 * @see FileBackend::doOperations()
1150 * @param $ops Array List of file operations to FileBackend::doOperations()
1151 * @param $status Status Status to update on lock/unlock
1152 * @return Array List of ScopedFileLocks or null values
1155 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1158 * Get the root storage path of this backend.
1159 * All container paths are "subdirectories" of this path.
1161 * @return string Storage path
1164 final public function getRootStoragePath() {
1165 return "mwstore://{$this->name}";
1169 * Get the storage path for the given container for this backend
1171 * @param $container string Container name
1172 * @return string Storage path
1175 final public function getContainerStoragePath( $container ) {
1176 return $this->getRootStoragePath() . "/{$container}";
1180 * Get the file journal object for this backend
1182 * @return FileJournal
1184 final public function getJournal() {
1185 return $this->fileJournal
;
1189 * Check if a given path is a "mwstore://" path.
1190 * This does not do any further validation or any existence checks.
1192 * @param $path string
1195 final public static function isStoragePath( $path ) {
1196 return ( strpos( $path, 'mwstore://' ) === 0 );
1200 * Split a storage path into a backend name, a container name,
1201 * and a relative file path. The relative path may be the empty string.
1202 * This does not do any path normalization or traversal checks.
1204 * @param $storagePath string
1205 * @return Array (backend, container, rel object) or (null, null, null)
1207 final public static function splitStoragePath( $storagePath ) {
1208 if ( self
::isStoragePath( $storagePath ) ) {
1209 // Remove the "mwstore://" prefix and split the path
1210 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1211 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1212 if ( count( $parts ) == 3 ) {
1213 return $parts; // e.g. "backend/container/path"
1215 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1219 return array( null, null, null );
1223 * Normalize a storage path by cleaning up directory separators.
1224 * Returns null if the path is not of the format of a valid storage path.
1226 * @param $storagePath string
1227 * @return string|null
1229 final public static function normalizeStoragePath( $storagePath ) {
1230 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1231 if ( $relPath !== null ) { // must be for this backend
1232 $relPath = self
::normalizeContainerPath( $relPath );
1233 if ( $relPath !== null ) {
1234 return ( $relPath != '' )
1235 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1236 : "mwstore://{$backend}/{$container}";
1243 * Get the parent storage directory of a storage path.
1244 * This returns a path like "mwstore://backend/container",
1245 * "mwstore://backend/container/...", or null if there is no parent.
1247 * @param $storagePath string
1248 * @return string|null
1250 final public static function parentStoragePath( $storagePath ) {
1251 $storagePath = dirname( $storagePath );
1252 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1253 return ( $rel === null ) ?
null : $storagePath;
1257 * Get the final extension from a storage or FS path
1259 * @param $path string
1262 final public static function extensionFromPath( $path ) {
1263 $i = strrpos( $path, '.' );
1264 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1268 * Check if a relative path has no directory traversals
1270 * @param $path string
1274 final public static function isPathTraversalFree( $path ) {
1275 return ( self
::normalizeContainerPath( $path ) !== null );
1279 * Build a Content-Disposition header value per RFC 6266.
1281 * @param $type string One of (attachment, inline)
1282 * @param $filename string Suggested file name (should not contain slashes)
1283 * @throws MWException
1287 final public static function makeContentDisposition( $type, $filename = '' ) {
1290 $type = strtolower( $type );
1291 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1292 throw new MWException( "Invalid Content-Disposition type '$type'." );
1296 if ( strlen( $filename ) ) {
1297 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1300 return implode( ';', $parts );
1304 * Validate and normalize a relative storage path.
1305 * Null is returned if the path involves directory traversal.
1306 * Traversal is insecure for FS backends and broken for others.
1308 * This uses the same traversal protection as Title::secureAndSplit().
1310 * @param $path string Storage path relative to a container
1311 * @return string|null
1313 final protected static function normalizeContainerPath( $path ) {
1314 // Normalize directory separators
1315 $path = strtr( $path, '\\', '/' );
1316 // Collapse any consecutive directory separators
1317 $path = preg_replace( '![/]{2,}!', '/', $path );
1318 // Remove any leading directory separator
1319 $path = ltrim( $path, '/' );
1320 // Use the same traversal protection as Title::secureAndSplit()
1321 if ( strpos( $path, '.' ) !== false ) {
1325 strpos( $path, './' ) === 0 ||
1326 strpos( $path, '../' ) === 0 ||
1327 strpos( $path, '/./' ) !== false ||
1328 strpos( $path, '/../' ) !== false