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 * If not provided, this defaults to the current wiki ID.
81 * It should only consist of alphanumberic, '-', and '_' characters.
82 * - lockManager : Registered name of a file lock manager to use.
83 * - fileJournal : File journal configuration; see FileJournal::factory().
84 * Journals simply log changes to files stored in the backend.
85 * - readOnly : Write operations are disallowed if this is a non-empty string.
86 * It should be an explanation for the backend being read-only.
87 * - parallelize : When to do file operations in parallel (when possible).
88 * Allowed values are "implicit", "explicit" and "off".
89 * - concurrency : How many file operations can be done in parallel.
91 * @param $config Array
94 public function __construct( array $config ) {
95 $this->name
= $config['name'];
96 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
97 throw new MWException( "Backend name `{$this->name}` is invalid." );
99 $this->wikiId
= isset( $config['wikiId'] )
101 : wfWikiID(); // e.g. "my_wiki-en_"
102 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
103 ?
$config['lockManager']
104 : LockManagerGroup
::singleton( $this->wikiId
)->get( $config['lockManager'] );
105 $this->fileJournal
= isset( $config['fileJournal'] )
106 ?
( ( $config['fileJournal'] instanceof FileJournal
)
107 ?
$config['fileJournal']
108 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
109 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
110 $this->readOnly
= isset( $config['readOnly'] )
111 ?
(string)$config['readOnly']
113 $this->parallelize
= isset( $config['parallelize'] )
114 ?
(string)$config['parallelize']
116 $this->concurrency
= isset( $config['concurrency'] )
117 ?
(int)$config['concurrency']
122 * Get the unique backend name.
123 * We may have multiple different backends of the same type.
124 * For example, we can have two Swift backends using different proxies.
128 final public function getName() {
133 * Get the wiki identifier used for this backend (possibly empty).
134 * Note that this might *not* be in the same format as wfWikiID().
139 final public function getWikiId() {
140 return $this->wikiId
;
144 * Check if this backend is read-only
148 final public function isReadOnly() {
149 return ( $this->readOnly
!= '' );
153 * Get an explanatory message if this backend is read-only
155 * @return string|bool Returns false if the backend is not read-only
157 final public function getReadOnlyReason() {
158 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
162 * This is the main entry point into the backend for write operations.
163 * Callers supply an ordered list of operations to perform as a transaction.
164 * Files will be locked, the stat cache cleared, and then the operations attempted.
165 * If any serious errors occur, all attempted operations will be rolled back.
167 * $ops is an array of arrays. The outer array holds a list of operations.
168 * Each inner array is a set of key value pairs that specify an operation.
170 * Supported operations and their parameters. The supported actions are:
176 * - describe (since 1.21)
179 * a) Create a new file in storage with the contents of a string
183 * 'dst' => <storage path>,
184 * 'content' => <string of new file contents>,
185 * 'overwrite' => <boolean>,
186 * 'overwriteSame' => <boolean>,
187 * 'disposition' => <Content-Disposition header value>,
188 * 'headers' => <HTTP header name/value map> # since 1.21
192 * b) Copy a file system file into storage
196 * 'src' => <file system path>,
197 * 'dst' => <storage path>,
198 * 'overwrite' => <boolean>,
199 * 'overwriteSame' => <boolean>,
200 * 'disposition' => <Content-Disposition header value>,
201 * 'headers' => <HTTP header name/value map> # since 1.21
205 * c) Copy a file within storage
209 * 'src' => <storage path>,
210 * 'dst' => <storage path>,
211 * 'overwrite' => <boolean>,
212 * 'overwriteSame' => <boolean>,
213 * 'ignoreMissingSource' => <boolean>, # since 1.21
214 * 'disposition' => <Content-Disposition header value>
218 * d) Move a file within storage
222 * 'src' => <storage path>,
223 * 'dst' => <storage path>,
224 * 'overwrite' => <boolean>,
225 * 'overwriteSame' => <boolean>,
226 * 'ignoreMissingSource' => <boolean>, # since 1.21
227 * 'disposition' => <Content-Disposition header value>
231 * e) Delete a file within storage
235 * 'src' => <storage path>,
236 * 'ignoreMissingSource' => <boolean>
240 * f) Update metadata for a file within storage
243 * 'op' => 'describe',
244 * 'src' => <storage path>,
245 * 'disposition' => <Content-Disposition header value>,
246 * 'headers' => <HTTP header name/value map>
250 * g) Do nothing (no-op)
257 * Boolean flags for operations (operation-specific):
258 * - ignoreMissingSource : The operation will simply succeed and do
259 * nothing if the source file does not exist.
260 * - overwrite : Any destination file will be overwritten.
261 * - overwriteSame : An error will not be given if a file already
262 * exists at the destination that has the same
263 * contents as the new contents to be written there.
264 * - disposition : If supplied, the backend will return a Content-Disposition
265 * header when GETs/HEADs of the destination file are made.
266 * Backends that don't support metadata ignore this.
267 * See http://tools.ietf.org/html/rfc6266. (since 1.20)
268 * - headers : If supplied, the backend will return these headers when
269 * GETs/HEADs of the destination file are made. Header values
270 * should be smaller than 256 bytes, often options or numbers.
271 * Existing headers will remain, but these will replace any
272 * conflicting previous headers, and headers will be removed
273 * if they are set to an empty string.
274 * Backends that don't support metadata ignore this. (since 1.21)
276 * $opts is an associative of boolean flags, including:
277 * - force : Operation precondition errors no longer trigger an abort.
278 * Any remaining operations are still attempted. Unexpected
279 * failures may still cause remaning operations to be aborted.
280 * - nonLocking : No locks are acquired for the operations.
281 * This can increase performance for non-critical writes.
282 * This has no effect unless the 'force' flag is set.
283 * - nonJournaled : Don't log this operation batch in the file journal.
284 * This limits the ability of recovery scripts.
285 * - parallelize : Try to do operations in parallel when possible.
286 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
287 * - preserveCache : Don't clear the process cache before checking files.
288 * This should only be used if all entries in the process
289 * cache were added after the files were already locked. (since 1.20)
291 * @remarks Remarks on locking:
292 * File system paths given to operations should refer to files that are
293 * already locked or otherwise safe from modification from other processes.
294 * Normally these files will be new temp files, which should be adequate.
298 * This returns a Status, which contains all warnings and fatals that occurred
299 * during the operation. The 'failCount', 'successCount', and 'success' members
300 * will reflect each operation attempted.
302 * The status will be "OK" unless:
303 * - a) unexpected operation errors occurred (network partitions, disk full...)
304 * - b) significant operation errors occurred and 'force' was not set
306 * @param $ops Array List of operations to execute in order
307 * @param $opts Array Batch operation options
310 final public function doOperations( array $ops, array $opts = array() ) {
311 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
312 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
314 if ( empty( $opts['force'] ) ) { // sanity
315 unset( $opts['nonLocking'] );
317 return $this->doOperationsInternal( $ops, $opts );
321 * @see FileBackend::doOperations()
323 abstract protected function doOperationsInternal( array $ops, array $opts );
326 * Same as doOperations() except it takes a single operation.
327 * If you are doing a batch of operations that should either
328 * all succeed or all fail, then use that function instead.
330 * @see FileBackend::doOperations()
332 * @param $op Array Operation
333 * @param $opts Array Operation options
336 final public function doOperation( array $op, array $opts = array() ) {
337 return $this->doOperations( array( $op ), $opts );
341 * Performs a single create operation.
342 * This sets $params['op'] to 'create' and passes it to doOperation().
344 * @see FileBackend::doOperation()
346 * @param $params Array Operation parameters
347 * @param $opts Array Operation options
350 final public function create( array $params, array $opts = array() ) {
351 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
355 * Performs a single store operation.
356 * This sets $params['op'] to 'store' and passes it to doOperation().
358 * @see FileBackend::doOperation()
360 * @param $params Array Operation parameters
361 * @param $opts Array Operation options
364 final public function store( array $params, array $opts = array() ) {
365 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
369 * Performs a single copy operation.
370 * This sets $params['op'] to 'copy' and passes it to doOperation().
372 * @see FileBackend::doOperation()
374 * @param $params Array Operation parameters
375 * @param $opts Array Operation options
378 final public function copy( array $params, array $opts = array() ) {
379 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
383 * Performs a single move operation.
384 * This sets $params['op'] to 'move' and passes it to doOperation().
386 * @see FileBackend::doOperation()
388 * @param $params Array Operation parameters
389 * @param $opts Array Operation options
392 final public function move( array $params, array $opts = array() ) {
393 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
397 * Performs a single delete operation.
398 * This sets $params['op'] to 'delete' and passes it to doOperation().
400 * @see FileBackend::doOperation()
402 * @param $params Array Operation parameters
403 * @param $opts Array Operation options
406 final public function delete( array $params, array $opts = array() ) {
407 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
411 * Performs a single describe operation.
412 * This sets $params['op'] to 'describe' and passes it to doOperation().
414 * @see FileBackend::doOperation()
416 * @param $params Array Operation parameters
417 * @param $opts Array Operation options
421 final public function describe( array $params, array $opts = array() ) {
422 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
426 * Perform a set of independent file operations on some files.
428 * This does no locking, nor journaling, and possibly no stat calls.
429 * Any destination files that already exist will be overwritten.
430 * This should *only* be used on non-original files, like cache files.
432 * Supported operations and their parameters:
438 * - describe (since 1.21)
441 * a) Create a new file in storage with the contents of a string
445 * 'dst' => <storage path>,
446 * 'content' => <string of new file contents>,
447 * 'disposition' => <Content-Disposition header value>,
448 * 'headers' => <HTTP header name/value map> # since 1.21
452 * b) Copy a file system file into storage
456 * 'src' => <file system path>,
457 * 'dst' => <storage path>,
458 * 'disposition' => <Content-Disposition header value>,
459 * 'headers' => <HTTP header name/value map> # since 1.21
463 * c) Copy a file within storage
467 * 'src' => <storage path>,
468 * 'dst' => <storage path>,
469 * 'ignoreMissingSource' => <boolean>, # since 1.21
470 * 'disposition' => <Content-Disposition header value>
474 * d) Move a file within storage
478 * 'src' => <storage path>,
479 * 'dst' => <storage path>,
480 * 'ignoreMissingSource' => <boolean>, # since 1.21
481 * 'disposition' => <Content-Disposition header value>
485 * e) Delete a file within storage
489 * 'src' => <storage path>,
490 * 'ignoreMissingSource' => <boolean>
494 * f) Update metadata for a file within storage
497 * 'op' => 'describe',
498 * 'src' => <storage path>,
499 * 'disposition' => <Content-Disposition header value>,
500 * 'headers' => <HTTP header name/value map>
504 * g) Do nothing (no-op)
511 * @par Boolean flags for operations (operation-specific):
512 * - ignoreMissingSource : The operation will simply succeed and do
513 * nothing if the source file does not exist.
514 * - disposition : When supplied, the backend will add a Content-Disposition
515 * header when GETs/HEADs of the destination file are made.
516 * Backends that don't support file metadata will ignore this.
517 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
518 * - headers : If supplied with a header name/value map, the backend will
519 * reply with these headers when GETs/HEADs of the destination
520 * file are made. Header values should be smaller than 256 bytes.
521 * Existing headers will remain, but these will replace any
522 * conflicting previous headers, and headers will be removed
523 * if they are set to an empty string.
524 * Backends that don't support metadata ignore this. (since 1.21)
526 * $opts is an associative of boolean flags, including:
527 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
530 * This returns a Status, which contains all warnings and fatals that occurred
531 * during the operation. The 'failCount', 'successCount', and 'success' members
532 * will reflect each operation attempted for the given files. The status will be
533 * considered "OK" as long as no fatal errors occurred.
535 * @param $ops Array Set of operations to execute
536 * @param $opts Array Batch operation options
540 final public function doQuickOperations( array $ops, array $opts = array() ) {
541 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
542 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
544 foreach ( $ops as &$op ) {
545 $op['overwrite'] = true; // avoids RTTs in key/value stores
547 return $this->doQuickOperationsInternal( $ops );
551 * @see FileBackend::doQuickOperations()
554 abstract protected function doQuickOperationsInternal( array $ops );
557 * Same as doQuickOperations() except it takes a single operation.
558 * If you are doing a batch of operations, then use that function instead.
560 * @see FileBackend::doQuickOperations()
562 * @param $op Array Operation
566 final public function doQuickOperation( array $op ) {
567 return $this->doQuickOperations( array( $op ) );
571 * Performs a single quick create operation.
572 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
574 * @see FileBackend::doQuickOperation()
576 * @param $params Array Operation parameters
580 final public function quickCreate( array $params ) {
581 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
585 * Performs a single quick store operation.
586 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
588 * @see FileBackend::doQuickOperation()
590 * @param $params Array Operation parameters
594 final public function quickStore( array $params ) {
595 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
599 * Performs a single quick copy operation.
600 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
602 * @see FileBackend::doQuickOperation()
604 * @param $params Array Operation parameters
608 final public function quickCopy( array $params ) {
609 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
613 * Performs a single quick move operation.
614 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
616 * @see FileBackend::doQuickOperation()
618 * @param $params Array Operation parameters
622 final public function quickMove( array $params ) {
623 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
627 * Performs a single quick delete operation.
628 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
630 * @see FileBackend::doQuickOperation()
632 * @param $params Array Operation parameters
636 final public function quickDelete( array $params ) {
637 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
641 * Performs a single quick describe operation.
642 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
644 * @see FileBackend::doQuickOperation()
646 * @param $params Array Operation parameters
650 final public function quickDescribe( array $params ) {
651 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
655 * Concatenate a list of storage files into a single file system file.
656 * The target path should refer to a file that is already locked or
657 * otherwise safe from modification from other processes. Normally,
658 * the file will be a new temp file, which should be adequate.
660 * @param $params Array Operation parameters
662 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
663 * - dst : file system path to 0-byte temp file
664 * - parallelize : try to do operations in parallel when possible
667 abstract public function concatenate( array $params );
670 * Prepare a storage directory for usage.
671 * This will create any required containers and parent directories.
672 * Backends using key/value stores only need to create the container.
674 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
675 * except they are only applied *if* the directory/container had to be created.
676 * These flags should always be set for directories that have private files.
678 * @param $params Array
680 * - dir : storage directory
681 * - noAccess : try to deny file access (since 1.20)
682 * - noListing : try to deny file listing (since 1.20)
683 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
686 final public function prepare( array $params ) {
687 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
688 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
690 return $this->doPrepare( $params );
694 * @see FileBackend::prepare()
696 abstract protected function doPrepare( array $params );
699 * Take measures to block web access to a storage directory and
700 * the container it belongs to. FS backends might add .htaccess
701 * files whereas key/value store backends might revoke container
702 * access to the storage user representing end-users in web requests.
703 * This is not guaranteed to actually do anything.
705 * @param $params Array
707 * - dir : storage directory
708 * - noAccess : try to deny file access
709 * - noListing : try to deny file listing
710 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
713 final public function secure( array $params ) {
714 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
715 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
717 return $this->doSecure( $params );
721 * @see FileBackend::secure()
723 abstract protected function doSecure( array $params );
726 * Remove measures to block web access to a storage directory and
727 * the container it belongs to. FS backends might remove .htaccess
728 * files whereas key/value store backends might grant container
729 * access to the storage user representing end-users in web requests.
730 * This essentially can undo the result of secure() calls.
732 * @param $params Array
734 * - dir : storage directory
735 * - access : try to allow file access
736 * - listing : try to allow file listing
737 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
741 final public function publish( array $params ) {
742 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
743 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
745 return $this->doPublish( $params );
749 * @see FileBackend::publish()
751 abstract protected function doPublish( array $params );
754 * Delete a storage directory if it is empty.
755 * Backends using key/value stores may do nothing unless the directory
756 * is that of an empty container, in which case it will be deleted.
758 * @param $params Array
760 * - dir : storage directory
761 * - recursive : recursively delete empty subdirectories first (since 1.20)
762 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
765 final public function clean( array $params ) {
766 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
767 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
769 return $this->doClean( $params );
773 * @see FileBackend::clean()
775 abstract protected function doClean( array $params );
778 * Check if a file exists at a storage path in the backend.
779 * This returns false if only a directory exists at the path.
781 * @param $params Array
783 * - src : source storage path
784 * - latest : use the latest available data
785 * @return bool|null Returns null on failure
787 abstract public function fileExists( array $params );
790 * Get the last-modified timestamp of the file at a storage path.
792 * @param $params Array
794 * - src : source storage path
795 * - latest : use the latest available data
796 * @return string|bool TS_MW timestamp or false on failure
798 abstract public function getFileTimestamp( array $params );
801 * Get the contents of a file at a storage path in the backend.
802 * This should be avoided for potentially large files.
804 * @param $params Array
806 * - src : source storage path
807 * - latest : use the latest available data
808 * @return string|bool Returns false on failure
810 final public function getFileContents( array $params ) {
811 $contents = $this->getFileContentsMulti(
812 array( 'srcs' => array( $params['src'] ) ) +
$params );
814 return $contents[$params['src']];
818 * Like getFileContents() except it takes an array of storage paths
819 * and returns a map of storage paths to strings (or null on failure).
820 * The map keys (paths) are in the same order as the provided list of paths.
822 * @see FileBackend::getFileContents()
824 * @param $params Array
826 * - srcs : list of source storage paths
827 * - latest : use the latest available data
828 * - parallelize : try to do operations in parallel when possible
829 * @return Array Map of (path name => string or false on failure)
832 abstract public function getFileContentsMulti( array $params );
835 * Get the size (bytes) of a file at a storage path in the backend.
837 * @param $params Array
839 * - src : source storage path
840 * - latest : use the latest available data
841 * @return integer|bool Returns false on failure
843 abstract public function getFileSize( array $params );
846 * Get quick information about a file at a storage path in the backend.
847 * If the file does not exist, then this returns false.
848 * Otherwise, the result is an associative array that includes:
849 * - mtime : the last-modified timestamp (TS_MW)
850 * - size : the file size (bytes)
851 * Additional values may be included for internal use only.
853 * @param $params Array
855 * - src : source storage path
856 * - latest : use the latest available data
857 * @return Array|bool|null Returns null on failure
859 abstract public function getFileStat( array $params );
862 * Get a SHA-1 hash of the file at a storage path in the backend.
864 * @param $params Array
866 * - src : source storage path
867 * - latest : use the latest available data
868 * @return string|bool Hash string or false on failure
870 abstract public function getFileSha1Base36( array $params );
873 * Get the properties of the file at a storage path in the backend.
874 * This gives the result of FSFile::getProps() on a local copy of the file.
876 * @param $params Array
878 * - src : source storage path
879 * - latest : use the latest available data
880 * @return Array Returns FSFile::placeholderProps() on failure
882 abstract public function getFileProps( array $params );
885 * Stream the file at a storage path in the backend.
886 * If the file does not exists, an HTTP 404 error will be given.
887 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
888 * will be sent if streaming began, while none will be sent otherwise.
889 * Implementations should flush the output buffer before sending data.
891 * @param $params Array
893 * - src : source storage path
894 * - headers : list of additional HTTP headers to send on success
895 * - latest : use the latest available data
898 abstract public function streamFile( array $params );
901 * Returns a file system file, identical to the file at a storage path.
902 * The file returned is either:
903 * - a) A local copy of the file at a storage path in the backend.
904 * The temporary copy will have the same extension as the source.
905 * - b) An original of the file at a storage path in the backend.
906 * Temporary files may be purged when the file object falls out of scope.
908 * Write operations should *never* be done on this file as some backends
909 * may do internal tracking or may be instances of FileBackendMultiWrite.
910 * In that later case, there are copies of the file that must stay in sync.
911 * Additionally, further calls to this function may return the same file.
913 * @param $params Array
915 * - src : source storage path
916 * - latest : use the latest available data
917 * @return FSFile|null Returns null on failure
919 final public function getLocalReference( array $params ) {
920 $fsFiles = $this->getLocalReferenceMulti(
921 array( 'srcs' => array( $params['src'] ) ) +
$params );
923 return $fsFiles[$params['src']];
927 * Like getLocalReference() except it takes an array of storage paths
928 * and returns a map of storage paths to FSFile objects (or null on failure).
929 * The map keys (paths) are in the same order as the provided list of paths.
931 * @see FileBackend::getLocalReference()
933 * @param $params Array
935 * - srcs : list of source storage paths
936 * - latest : use the latest available data
937 * - parallelize : try to do operations in parallel when possible
938 * @return Array Map of (path name => FSFile or null on failure)
941 abstract public function getLocalReferenceMulti( array $params );
944 * Get a local copy on disk of the file at a storage path in the backend.
945 * The temporary copy will have the same file extension as the source.
946 * Temporary files may be purged when the file object falls out of scope.
948 * @param $params Array
950 * - src : source storage path
951 * - latest : use the latest available data
952 * @return TempFSFile|null Returns null on failure
954 final public function getLocalCopy( array $params ) {
955 $tmpFiles = $this->getLocalCopyMulti(
956 array( 'srcs' => array( $params['src'] ) ) +
$params );
958 return $tmpFiles[$params['src']];
962 * Like getLocalCopy() except it takes an array of storage paths and
963 * returns a map of storage paths to TempFSFile objects (or null on failure).
964 * The map keys (paths) are in the same order as the provided list of paths.
966 * @see FileBackend::getLocalCopy()
968 * @param $params Array
970 * - srcs : list of source storage paths
971 * - latest : use the latest available data
972 * - parallelize : try to do operations in parallel when possible
973 * @return Array Map of (path name => TempFSFile or null on failure)
976 abstract public function getLocalCopyMulti( array $params );
979 * Return an HTTP URL to a given file that requires no authentication to use.
980 * The URL may be pre-authenticated (via some token in the URL) and temporary.
981 * This will return null if the backend cannot make an HTTP URL for the file.
983 * This is useful for key/value stores when using scripts that seek around
984 * large files and those scripts (and the backend) support HTTP Range headers.
985 * Otherwise, one would need to use getLocalReference(), which involves loading
986 * the entire file on to local disk.
988 * @param $params Array
990 * - src : source storage path
991 * @return string|null
994 abstract public function getFileHttpUrl( array $params );
997 * Check if a directory exists at a given storage path.
998 * Backends using key/value stores will check if the path is a
999 * virtual directory, meaning there are files under the given directory.
1001 * Storage backends with eventual consistency might return stale data.
1003 * @param $params array
1005 * - dir : storage directory
1006 * @return bool|null Returns null on failure
1009 abstract public function directoryExists( array $params );
1012 * Get an iterator to list *all* directories under a storage directory.
1013 * If the directory is of the form "mwstore://backend/container",
1014 * then all directories in the container will be listed.
1015 * If the directory is of form "mwstore://backend/container/dir",
1016 * then all directories directly under that directory will be listed.
1017 * Results will be storage directories relative to the given directory.
1019 * Storage backends with eventual consistency might return stale data.
1021 * @param $params array
1023 * - dir : storage directory
1024 * - topOnly : only return direct child dirs of the directory
1025 * @return Traversable|Array|null Returns null on failure
1028 abstract public function getDirectoryList( array $params );
1031 * Same as FileBackend::getDirectoryList() except only lists
1032 * directories that are immediately under the given directory.
1034 * Storage backends with eventual consistency might return stale data.
1036 * @param $params array
1038 * - dir : storage directory
1039 * @return Traversable|Array|null Returns null on failure
1042 final public function getTopDirectoryList( array $params ) {
1043 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1047 * Get an iterator to list *all* stored files under a storage directory.
1048 * If the directory is of the form "mwstore://backend/container",
1049 * then all files in the container will be listed.
1050 * If the directory is of form "mwstore://backend/container/dir",
1051 * then all files under that directory will be listed.
1052 * Results will be storage paths relative to the given directory.
1054 * Storage backends with eventual consistency might return stale data.
1056 * @param $params array
1058 * - dir : storage directory
1059 * - topOnly : only return direct child files of the directory (since 1.20)
1060 * @return Traversable|Array|null Returns null on failure
1062 abstract public function getFileList( array $params );
1065 * Same as FileBackend::getFileList() except only lists
1066 * files that are immediately under the given directory.
1068 * Storage backends with eventual consistency might return stale data.
1070 * @param $params array
1072 * - dir : storage directory
1073 * @return Traversable|Array|null Returns null on failure
1076 final public function getTopFileList( array $params ) {
1077 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1081 * Preload persistent file stat and property cache into in-process cache.
1082 * This should be used when stat calls will be made on a known list of a many files.
1084 * @param $paths Array Storage paths
1087 public function preloadCache( array $paths ) {}
1090 * Invalidate any in-process file stat and property cache.
1091 * If $paths is given, then only the cache for those files will be cleared.
1093 * @param $paths Array Storage paths (optional)
1096 public function clearCache( array $paths = null ) {}
1099 * Lock the files at the given storage paths in the backend.
1100 * This will either lock all the files or none (on failure).
1102 * Callers should consider using getScopedFileLocks() instead.
1104 * @param $paths Array Storage paths
1105 * @param $type integer LockManager::LOCK_* constant
1108 final public function lockFiles( array $paths, $type ) {
1109 return $this->lockManager
->lock( $paths, $type );
1113 * Unlock the files at the given storage paths in the backend.
1115 * @param $paths Array Storage paths
1116 * @param $type integer LockManager::LOCK_* constant
1119 final public function unlockFiles( array $paths, $type ) {
1120 return $this->lockManager
->unlock( $paths, $type );
1124 * Lock the files at the given storage paths in the backend.
1125 * This will either lock all the files or none (on failure).
1126 * On failure, the status object will be updated with errors.
1128 * Once the return value goes out scope, the locks will be released and
1129 * the status updated. Unlock fatals will not change the status "OK" value.
1131 * @param $paths Array Storage paths
1132 * @param $type integer LockManager::LOCK_* constant
1133 * @param $status Status Status to update on lock/unlock
1134 * @return ScopedLock|null Returns null on failure
1136 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1137 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1141 * Get an array of scoped locks needed for a batch of file operations.
1143 * Normally, FileBackend::doOperations() handles locking, unless
1144 * the 'nonLocking' param is passed in. This function is useful if you
1145 * want the files to be locked for a broader scope than just when the
1146 * files are changing. For example, if you need to update DB metadata,
1147 * you may want to keep the files locked until finished.
1149 * @see FileBackend::doOperations()
1151 * @param $ops Array List of file operations to FileBackend::doOperations()
1152 * @param $status Status Status to update on lock/unlock
1153 * @return Array List of ScopedFileLocks or null values
1156 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1159 * Get the root storage path of this backend.
1160 * All container paths are "subdirectories" of this path.
1162 * @return string Storage path
1165 final public function getRootStoragePath() {
1166 return "mwstore://{$this->name}";
1170 * Get the storage path for the given container for this backend
1172 * @param $container string Container name
1173 * @return string Storage path
1176 final public function getContainerStoragePath( $container ) {
1177 return $this->getRootStoragePath() . "/{$container}";
1181 * Get the file journal object for this backend
1183 * @return FileJournal
1185 final public function getJournal() {
1186 return $this->fileJournal
;
1190 * Check if a given path is a "mwstore://" path.
1191 * This does not do any further validation or any existence checks.
1193 * @param $path string
1196 final public static function isStoragePath( $path ) {
1197 return ( strpos( $path, 'mwstore://' ) === 0 );
1201 * Split a storage path into a backend name, a container name,
1202 * and a relative file path. The relative path may be the empty string.
1203 * This does not do any path normalization or traversal checks.
1205 * @param $storagePath string
1206 * @return Array (backend, container, rel object) or (null, null, null)
1208 final public static function splitStoragePath( $storagePath ) {
1209 if ( self
::isStoragePath( $storagePath ) ) {
1210 // Remove the "mwstore://" prefix and split the path
1211 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1212 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1213 if ( count( $parts ) == 3 ) {
1214 return $parts; // e.g. "backend/container/path"
1216 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1220 return array( null, null, null );
1224 * Normalize a storage path by cleaning up directory separators.
1225 * Returns null if the path is not of the format of a valid storage path.
1227 * @param $storagePath string
1228 * @return string|null
1230 final public static function normalizeStoragePath( $storagePath ) {
1231 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1232 if ( $relPath !== null ) { // must be for this backend
1233 $relPath = self
::normalizeContainerPath( $relPath );
1234 if ( $relPath !== null ) {
1235 return ( $relPath != '' )
1236 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1237 : "mwstore://{$backend}/{$container}";
1244 * Get the parent storage directory of a storage path.
1245 * This returns a path like "mwstore://backend/container",
1246 * "mwstore://backend/container/...", or null if there is no parent.
1248 * @param $storagePath string
1249 * @return string|null
1251 final public static function parentStoragePath( $storagePath ) {
1252 $storagePath = dirname( $storagePath );
1253 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1254 return ( $rel === null ) ?
null : $storagePath;
1258 * Get the final extension from a storage or FS path
1260 * @param $path string
1263 final public static function extensionFromPath( $path ) {
1264 $i = strrpos( $path, '.' );
1265 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1269 * Check if a relative path has no directory traversals
1271 * @param $path string
1275 final public static function isPathTraversalFree( $path ) {
1276 return ( self
::normalizeContainerPath( $path ) !== null );
1280 * Build a Content-Disposition header value per RFC 6266.
1282 * @param $type string One of (attachment, inline)
1283 * @param $filename string Suggested file name (should not contain slashes)
1284 * @throws MWException
1288 final public static function makeContentDisposition( $type, $filename = '' ) {
1291 $type = strtolower( $type );
1292 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1293 throw new MWException( "Invalid Content-Disposition type '$type'." );
1297 if ( strlen( $filename ) ) {
1298 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1301 return implode( ';', $parts );
1305 * Validate and normalize a relative storage path.
1306 * Null is returned if the path involves directory traversal.
1307 * Traversal is insecure for FS backends and broken for others.
1309 * This uses the same traversal protection as Title::secureAndSplit().
1311 * @param $path string Storage path relative to a container
1312 * @return string|null
1314 final protected static function normalizeContainerPath( $path ) {
1315 // Normalize directory separators
1316 $path = strtr( $path, '\\', '/' );
1317 // Collapse any consecutive directory separators
1318 $path = preg_replace( '![/]{2,}!', '/', $path );
1319 // Remove any leading directory separator
1320 $path = ltrim( $path, '/' );
1321 // Use the same traversal protection as Title::secureAndSplit()
1322 if ( strpos( $path, '.' ) !== false ) {
1326 strpos( $path, './' ) === 0 ||
1327 strpos( $path, '../' ) === 0 ||
1328 strpos( $path, '/./' ) !== false ||
1329 strpos( $path, '/../' ) !== false