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 "backend" portion is unique name for MediaWiki to refer to a backend, while
41 * the "container" portion is a top-level directory of the backend. The "path" portion
42 * is a relative path that uses UNIX file system (FS) notation, though any particular
43 * backend may not actually be using a local filesystem. Therefore, the relative paths
46 * Backend contents are stored under wiki-specific container names by default.
47 * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
48 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
49 * containers to ones that do not respect the "wiki ID".
51 * In key/value stores, the container is the only hierarchy (the rest is emulated).
52 * FS-based backends are somewhat more restrictive due to the existence of real
53 * directory files; a regular file cannot have the same name as a directory. Other
54 * backends with virtual directories may not have this limitation. Callers should
55 * store files in such a way that no files and directories are under the same path.
57 * Methods of subclasses should avoid throwing exceptions at all costs.
58 * As a corollary, external dependencies should be kept to a minimum.
60 * @ingroup FileBackend
63 abstract class FileBackend
{
64 protected $name; // string; unique backend name
65 protected $wikiId; // string; unique wiki name
66 protected $readOnly; // string; read-only explanation message
67 protected $parallelize; // string; when to do operations in parallel
68 protected $concurrency; // integer; how many operations can be done in parallel
70 /** @var LockManager */
71 protected $lockManager;
72 /** @var FileJournal */
73 protected $fileJournal;
76 * Create a new backend instance from configuration.
77 * This should only be called from within FileBackendGroup.
80 * - name : The unique name of this backend.
81 * This should consist of alphanumberic, '-', and '_' characters.
82 * This name should not be changed after use (e.g. with journaling).
83 * Note that the name is *not* used in actual container names.
84 * - wikiId : Prefix to container names that is unique to this backend.
85 * If not provided, this defaults to the current wiki ID.
86 * It should only consist of alphanumberic, '-', and '_' characters.
87 * This ID is what avoids collisions if multiple logical backends
88 * use the same storage system, so this should be set carefully.
89 * - lockManager : Registered name of a file lock manager to use.
90 * - fileJournal : File journal configuration; see FileJournal::factory().
91 * Journals simply log changes to files stored in the backend.
92 * - readOnly : Write operations are disallowed if this is a non-empty string.
93 * It should be an explanation for the backend being read-only.
94 * - parallelize : When to do file operations in parallel (when possible).
95 * Allowed values are "implicit", "explicit" and "off".
96 * - concurrency : How many file operations can be done in parallel.
98 * @param $config Array
101 public function __construct( array $config ) {
102 $this->name
= $config['name'];
103 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
104 throw new MWException( "Backend name `{$this->name}` is invalid." );
106 $this->wikiId
= isset( $config['wikiId'] )
108 : wfWikiID(); // e.g. "my_wiki-en_"
109 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
110 ?
$config['lockManager']
111 : LockManagerGroup
::singleton( $this->wikiId
)->get( $config['lockManager'] );
112 $this->fileJournal
= isset( $config['fileJournal'] )
113 ?
( ( $config['fileJournal'] instanceof FileJournal
)
114 ?
$config['fileJournal']
115 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
116 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
117 $this->readOnly
= isset( $config['readOnly'] )
118 ?
(string)$config['readOnly']
120 $this->parallelize
= isset( $config['parallelize'] )
121 ?
(string)$config['parallelize']
123 $this->concurrency
= isset( $config['concurrency'] )
124 ?
(int)$config['concurrency']
129 * Get the unique backend name.
130 * We may have multiple different backends of the same type.
131 * For example, we can have two Swift backends using different proxies.
135 final public function getName() {
140 * Get the wiki identifier used for this backend (possibly empty).
141 * Note that this might *not* be in the same format as wfWikiID().
146 final public function getWikiId() {
147 return $this->wikiId
;
151 * Check if this backend is read-only
155 final public function isReadOnly() {
156 return ( $this->readOnly
!= '' );
160 * Get an explanatory message if this backend is read-only
162 * @return string|bool Returns false if the backend is not read-only
164 final public function getReadOnlyReason() {
165 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
169 * This is the main entry point into the backend for write operations.
170 * Callers supply an ordered list of operations to perform as a transaction.
171 * Files will be locked, the stat cache cleared, and then the operations attempted.
172 * If any serious errors occur, all attempted operations will be rolled back.
174 * $ops is an array of arrays. The outer array holds a list of operations.
175 * Each inner array is a set of key value pairs that specify an operation.
177 * Supported operations and their parameters. The supported actions are:
183 * - describe (since 1.21)
186 * a) Create a new file in storage with the contents of a string
190 * 'dst' => <storage path>,
191 * 'content' => <string of new file contents>,
192 * 'overwrite' => <boolean>,
193 * 'overwriteSame' => <boolean>,
194 * 'disposition' => <Content-Disposition header value>,
195 * 'headers' => <HTTP header name/value map> # since 1.21
199 * b) Copy a file system file into storage
203 * 'src' => <file system path>,
204 * 'dst' => <storage path>,
205 * 'overwrite' => <boolean>,
206 * 'overwriteSame' => <boolean>,
207 * 'disposition' => <Content-Disposition header value>,
208 * 'headers' => <HTTP header name/value map> # since 1.21
212 * c) Copy a file within storage
216 * 'src' => <storage path>,
217 * 'dst' => <storage path>,
218 * 'overwrite' => <boolean>,
219 * 'overwriteSame' => <boolean>,
220 * 'ignoreMissingSource' => <boolean>, # since 1.21
221 * 'disposition' => <Content-Disposition header value>
225 * d) Move a file within storage
229 * 'src' => <storage path>,
230 * 'dst' => <storage path>,
231 * 'overwrite' => <boolean>,
232 * 'overwriteSame' => <boolean>,
233 * 'ignoreMissingSource' => <boolean>, # since 1.21
234 * 'disposition' => <Content-Disposition header value>
238 * e) Delete a file within storage
242 * 'src' => <storage path>,
243 * 'ignoreMissingSource' => <boolean>
247 * f) Update metadata for a file within storage
250 * 'op' => 'describe',
251 * 'src' => <storage path>,
252 * 'disposition' => <Content-Disposition header value>,
253 * 'headers' => <HTTP header name/value map>
257 * g) Do nothing (no-op)
264 * Boolean flags for operations (operation-specific):
265 * - ignoreMissingSource : The operation will simply succeed and do
266 * nothing if the source file does not exist.
267 * - overwrite : Any destination file will be overwritten.
268 * - overwriteSame : An error will not be given if a file already
269 * exists at the destination that has the same
270 * contents as the new contents to be written there.
271 * - disposition : If supplied, the backend will return a Content-Disposition
272 * header when GETs/HEADs of the destination file are made.
273 * Backends that don't support metadata ignore this.
274 * See http://tools.ietf.org/html/rfc6266. (since 1.20)
275 * - headers : If supplied, the backend will return these headers when
276 * GETs/HEADs of the destination file are made. Header values
277 * should be smaller than 256 bytes, often options or numbers.
278 * Existing headers will remain, but these will replace any
279 * conflicting previous headers, and headers will be removed
280 * if they are set to an empty string.
281 * Backends that don't support metadata ignore this. (since 1.21)
283 * $opts is an associative of boolean flags, including:
284 * - force : Operation precondition errors no longer trigger an abort.
285 * Any remaining operations are still attempted. Unexpected
286 * failures may still cause remaining operations to be aborted.
287 * - nonLocking : No locks are acquired for the operations.
288 * This can increase performance for non-critical writes.
289 * This has no effect unless the 'force' flag is set.
290 * - nonJournaled : Don't log this operation batch in the file journal.
291 * This limits the ability of recovery scripts.
292 * - parallelize : Try to do operations in parallel when possible.
293 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
294 * - preserveCache : Don't clear the process cache before checking files.
295 * This should only be used if all entries in the process
296 * cache were added after the files were already locked. (since 1.20)
298 * @remarks Remarks on locking:
299 * File system paths given to operations should refer to files that are
300 * already locked or otherwise safe from modification from other processes.
301 * Normally these files will be new temp files, which should be adequate.
305 * This returns a Status, which contains all warnings and fatals that occurred
306 * during the operation. The 'failCount', 'successCount', and 'success' members
307 * will reflect each operation attempted.
309 * The status will be "OK" unless:
310 * - a) unexpected operation errors occurred (network partitions, disk full...)
311 * - b) significant operation errors occurred and 'force' was not set
313 * @param $ops Array List of operations to execute in order
314 * @param $opts Array Batch operation options
317 final public function doOperations( array $ops, array $opts = array() ) {
318 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
319 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
321 if ( empty( $opts['force'] ) ) { // sanity
322 unset( $opts['nonLocking'] );
324 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
325 return $this->doOperationsInternal( $ops, $opts );
329 * @see FileBackend::doOperations()
331 abstract protected function doOperationsInternal( array $ops, array $opts );
334 * Same as doOperations() except it takes a single operation.
335 * If you are doing a batch of operations that should either
336 * all succeed or all fail, then use that function instead.
338 * @see FileBackend::doOperations()
340 * @param $op Array Operation
341 * @param $opts Array Operation options
344 final public function doOperation( array $op, array $opts = array() ) {
345 return $this->doOperations( array( $op ), $opts );
349 * Performs a single create operation.
350 * This sets $params['op'] to 'create' and passes it to doOperation().
352 * @see FileBackend::doOperation()
354 * @param $params Array Operation parameters
355 * @param $opts Array Operation options
358 final public function create( array $params, array $opts = array() ) {
359 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
363 * Performs a single store operation.
364 * This sets $params['op'] to 'store' and passes it to doOperation().
366 * @see FileBackend::doOperation()
368 * @param $params Array Operation parameters
369 * @param $opts Array Operation options
372 final public function store( array $params, array $opts = array() ) {
373 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
377 * Performs a single copy operation.
378 * This sets $params['op'] to 'copy' and passes it to doOperation().
380 * @see FileBackend::doOperation()
382 * @param $params Array Operation parameters
383 * @param $opts Array Operation options
386 final public function copy( array $params, array $opts = array() ) {
387 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
391 * Performs a single move operation.
392 * This sets $params['op'] to 'move' and passes it to doOperation().
394 * @see FileBackend::doOperation()
396 * @param $params Array Operation parameters
397 * @param $opts Array Operation options
400 final public function move( array $params, array $opts = array() ) {
401 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
405 * Performs a single delete operation.
406 * This sets $params['op'] to 'delete' and passes it to doOperation().
408 * @see FileBackend::doOperation()
410 * @param $params Array Operation parameters
411 * @param $opts Array Operation options
414 final public function delete( array $params, array $opts = array() ) {
415 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
419 * Performs a single describe operation.
420 * This sets $params['op'] to 'describe' and passes it to doOperation().
422 * @see FileBackend::doOperation()
424 * @param $params Array Operation parameters
425 * @param $opts Array Operation options
429 final public function describe( array $params, array $opts = array() ) {
430 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
434 * Perform a set of independent file operations on some files.
436 * This does no locking, nor journaling, and possibly no stat calls.
437 * Any destination files that already exist will be overwritten.
438 * This should *only* be used on non-original files, like cache files.
440 * Supported operations and their parameters:
446 * - describe (since 1.21)
449 * a) Create a new file in storage with the contents of a string
453 * 'dst' => <storage path>,
454 * 'content' => <string of new file contents>,
455 * 'disposition' => <Content-Disposition header value>,
456 * 'headers' => <HTTP header name/value map> # since 1.21
460 * b) Copy a file system file into storage
464 * 'src' => <file system path>,
465 * 'dst' => <storage path>,
466 * 'disposition' => <Content-Disposition header value>,
467 * 'headers' => <HTTP header name/value map> # since 1.21
471 * c) Copy a file within storage
475 * 'src' => <storage path>,
476 * 'dst' => <storage path>,
477 * 'ignoreMissingSource' => <boolean>, # since 1.21
478 * 'disposition' => <Content-Disposition header value>
482 * d) Move a file within storage
486 * 'src' => <storage path>,
487 * 'dst' => <storage path>,
488 * 'ignoreMissingSource' => <boolean>, # since 1.21
489 * 'disposition' => <Content-Disposition header value>
493 * e) Delete a file within storage
497 * 'src' => <storage path>,
498 * 'ignoreMissingSource' => <boolean>
502 * f) Update metadata for a file within storage
505 * 'op' => 'describe',
506 * 'src' => <storage path>,
507 * 'disposition' => <Content-Disposition header value>,
508 * 'headers' => <HTTP header name/value map>
512 * g) Do nothing (no-op)
519 * @par Boolean flags for operations (operation-specific):
520 * - ignoreMissingSource : The operation will simply succeed and do
521 * nothing if the source file does not exist.
522 * - disposition : When supplied, the backend will add a Content-Disposition
523 * header when GETs/HEADs of the destination file are made.
524 * Backends that don't support file metadata will ignore this.
525 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
526 * - headers : If supplied with a header name/value map, the backend will
527 * reply with these headers when GETs/HEADs of the destination
528 * file are made. Header values should be smaller than 256 bytes.
529 * Existing headers will remain, but these will replace any
530 * conflicting previous headers, and headers will be removed
531 * if they are set to an empty string.
532 * Backends that don't support metadata ignore this. (since 1.21)
534 * $opts is an associative of boolean flags, including:
535 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
538 * This returns a Status, which contains all warnings and fatals that occurred
539 * during the operation. The 'failCount', 'successCount', and 'success' members
540 * will reflect each operation attempted for the given files. The status will be
541 * considered "OK" as long as no fatal errors occurred.
543 * @param $ops Array Set of operations to execute
544 * @param $opts Array Batch operation options
548 final public function doQuickOperations( array $ops, array $opts = array() ) {
549 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
550 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
552 foreach ( $ops as &$op ) {
553 $op['overwrite'] = true; // avoids RTTs in key/value stores
555 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
556 return $this->doQuickOperationsInternal( $ops );
560 * @see FileBackend::doQuickOperations()
563 abstract protected function doQuickOperationsInternal( array $ops );
566 * Same as doQuickOperations() except it takes a single operation.
567 * If you are doing a batch of operations, then use that function instead.
569 * @see FileBackend::doQuickOperations()
571 * @param $op Array Operation
575 final public function doQuickOperation( array $op ) {
576 return $this->doQuickOperations( array( $op ) );
580 * Performs a single quick create operation.
581 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
583 * @see FileBackend::doQuickOperation()
585 * @param $params Array Operation parameters
589 final public function quickCreate( array $params ) {
590 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
594 * Performs a single quick store operation.
595 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
597 * @see FileBackend::doQuickOperation()
599 * @param $params Array Operation parameters
603 final public function quickStore( array $params ) {
604 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
608 * Performs a single quick copy operation.
609 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
611 * @see FileBackend::doQuickOperation()
613 * @param $params Array Operation parameters
617 final public function quickCopy( array $params ) {
618 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
622 * Performs a single quick move operation.
623 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
625 * @see FileBackend::doQuickOperation()
627 * @param $params Array Operation parameters
631 final public function quickMove( array $params ) {
632 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
636 * Performs a single quick delete operation.
637 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
639 * @see FileBackend::doQuickOperation()
641 * @param $params Array Operation parameters
645 final public function quickDelete( array $params ) {
646 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
650 * Performs a single quick describe operation.
651 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
653 * @see FileBackend::doQuickOperation()
655 * @param $params Array Operation parameters
659 final public function quickDescribe( array $params ) {
660 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
664 * Concatenate a list of storage files into a single file system file.
665 * The target path should refer to a file that is already locked or
666 * otherwise safe from modification from other processes. Normally,
667 * the file will be a new temp file, which should be adequate.
669 * @param $params Array Operation parameters
671 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
672 * - dst : file system path to 0-byte temp file
673 * - parallelize : try to do operations in parallel when possible
676 abstract public function concatenate( array $params );
679 * Prepare a storage directory for usage.
680 * This will create any required containers and parent directories.
681 * Backends using key/value stores only need to create the container.
683 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
684 * except they are only applied *if* the directory/container had to be created.
685 * These flags should always be set for directories that have private files.
687 * @param $params Array
689 * - dir : storage directory
690 * - noAccess : try to deny file access (since 1.20)
691 * - noListing : try to deny file listing (since 1.20)
692 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
695 final public function prepare( array $params ) {
696 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
697 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
699 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
700 return $this->doPrepare( $params );
704 * @see FileBackend::prepare()
706 abstract protected function doPrepare( array $params );
709 * Take measures to block web access to a storage directory and
710 * the container it belongs to. FS backends might add .htaccess
711 * files whereas key/value store backends might revoke container
712 * access to the storage user representing end-users in web requests.
713 * This is not guaranteed to actually do anything.
715 * @param $params Array
717 * - dir : storage directory
718 * - noAccess : try to deny file access
719 * - noListing : try to deny file listing
720 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
723 final public function secure( array $params ) {
724 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
725 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
727 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
728 return $this->doSecure( $params );
732 * @see FileBackend::secure()
734 abstract protected function doSecure( array $params );
737 * Remove measures to block web access to a storage directory and
738 * the container it belongs to. FS backends might remove .htaccess
739 * files whereas key/value store backends might grant container
740 * access to the storage user representing end-users in web requests.
741 * This essentially can undo the result of secure() calls.
743 * @param $params Array
745 * - dir : storage directory
746 * - access : try to allow file access
747 * - listing : try to allow file listing
748 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
752 final public function publish( array $params ) {
753 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
754 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
756 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
757 return $this->doPublish( $params );
761 * @see FileBackend::publish()
763 abstract protected function doPublish( array $params );
766 * Delete a storage directory if it is empty.
767 * Backends using key/value stores may do nothing unless the directory
768 * is that of an empty container, in which case it will be deleted.
770 * @param $params Array
772 * - dir : storage directory
773 * - recursive : recursively delete empty subdirectories first (since 1.20)
774 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
777 final public function clean( array $params ) {
778 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
779 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
781 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
782 return $this->doClean( $params );
786 * @see FileBackend::clean()
788 abstract protected function doClean( array $params );
791 * Enter file operation scope.
792 * This just makes PHP ignore user aborts/disconnects until the return
793 * value leaves scope. This returns null and does nothing in CLI mode.
795 * @return ScopedCallback|null
797 final protected function getScopedPHPBehaviorForOps() {
798 if ( php_sapi_name() != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
799 $old = ignore_user_abort( true ); // avoid half-finished operations
800 return new ScopedCallback( function() use ( $old ) { ignore_user_abort( $old ); } );
806 * Check if a file exists at a storage path in the backend.
807 * This returns false if only a directory exists at the path.
809 * @param $params Array
811 * - src : source storage path
812 * - latest : use the latest available data
813 * @return bool|null Returns null on failure
815 abstract public function fileExists( array $params );
818 * Get the last-modified timestamp of the file at a storage path.
820 * @param $params Array
822 * - src : source storage path
823 * - latest : use the latest available data
824 * @return string|bool TS_MW timestamp or false on failure
826 abstract public function getFileTimestamp( array $params );
829 * Get the contents of a file at a storage path in the backend.
830 * This should be avoided for potentially large files.
832 * @param $params Array
834 * - src : source storage path
835 * - latest : use the latest available data
836 * @return string|bool Returns false on failure
838 final public function getFileContents( array $params ) {
839 $contents = $this->getFileContentsMulti(
840 array( 'srcs' => array( $params['src'] ) ) +
$params );
842 return $contents[$params['src']];
846 * Like getFileContents() except it takes an array of storage paths
847 * and returns a map of storage paths to strings (or null on failure).
848 * The map keys (paths) are in the same order as the provided list of paths.
850 * @see FileBackend::getFileContents()
852 * @param $params Array
854 * - srcs : list of source storage paths
855 * - latest : use the latest available data
856 * - parallelize : try to do operations in parallel when possible
857 * @return Array Map of (path name => string or false on failure)
860 abstract public function getFileContentsMulti( array $params );
863 * Get the size (bytes) of a file at a storage path in the backend.
865 * @param $params Array
867 * - src : source storage path
868 * - latest : use the latest available data
869 * @return integer|bool Returns false on failure
871 abstract public function getFileSize( array $params );
874 * Get quick information about a file at a storage path in the backend.
875 * If the file does not exist, then this returns false.
876 * Otherwise, the result is an associative array that includes:
877 * - mtime : the last-modified timestamp (TS_MW)
878 * - size : the file size (bytes)
879 * Additional values may be included for internal use only.
881 * @param $params Array
883 * - src : source storage path
884 * - latest : use the latest available data
885 * @return Array|bool|null Returns null on failure
887 abstract public function getFileStat( array $params );
890 * Get a SHA-1 hash of the file at a storage path in the backend.
892 * @param $params Array
894 * - src : source storage path
895 * - latest : use the latest available data
896 * @return string|bool Hash string or false on failure
898 abstract public function getFileSha1Base36( array $params );
901 * Get the properties of the file at a storage path in the backend.
902 * This gives the result of FSFile::getProps() on a local copy of the file.
904 * @param $params Array
906 * - src : source storage path
907 * - latest : use the latest available data
908 * @return Array Returns FSFile::placeholderProps() on failure
910 abstract public function getFileProps( array $params );
913 * Stream the file at a storage path in the backend.
914 * If the file does not exists, an HTTP 404 error will be given.
915 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
916 * will be sent if streaming began, while none will be sent otherwise.
917 * Implementations should flush the output buffer before sending data.
919 * @param $params Array
921 * - src : source storage path
922 * - headers : list of additional HTTP headers to send on success
923 * - latest : use the latest available data
926 abstract public function streamFile( array $params );
929 * Returns a file system file, identical to the file at a storage path.
930 * The file returned is either:
931 * - a) A local copy of the file at a storage path in the backend.
932 * The temporary copy will have the same extension as the source.
933 * - b) An original of the file at a storage path in the backend.
934 * Temporary files may be purged when the file object falls out of scope.
936 * Write operations should *never* be done on this file as some backends
937 * may do internal tracking or may be instances of FileBackendMultiWrite.
938 * In that later case, there are copies of the file that must stay in sync.
939 * Additionally, further calls to this function may return the same file.
941 * @param $params Array
943 * - src : source storage path
944 * - latest : use the latest available data
945 * @return FSFile|null Returns null on failure
947 final public function getLocalReference( array $params ) {
948 $fsFiles = $this->getLocalReferenceMulti(
949 array( 'srcs' => array( $params['src'] ) ) +
$params );
951 return $fsFiles[$params['src']];
955 * Like getLocalReference() except it takes an array of storage paths
956 * and returns a map of storage paths to FSFile objects (or null on failure).
957 * The map keys (paths) are in the same order as the provided list of paths.
959 * @see FileBackend::getLocalReference()
961 * @param $params Array
963 * - srcs : list of source storage paths
964 * - latest : use the latest available data
965 * - parallelize : try to do operations in parallel when possible
966 * @return Array Map of (path name => FSFile or null on failure)
969 abstract public function getLocalReferenceMulti( array $params );
972 * Get a local copy on disk of the file at a storage path in the backend.
973 * The temporary copy will have the same file extension as the source.
974 * Temporary files may be purged when the file object falls out of scope.
976 * @param $params Array
978 * - src : source storage path
979 * - latest : use the latest available data
980 * @return TempFSFile|null Returns null on failure
982 final public function getLocalCopy( array $params ) {
983 $tmpFiles = $this->getLocalCopyMulti(
984 array( 'srcs' => array( $params['src'] ) ) +
$params );
986 return $tmpFiles[$params['src']];
990 * Like getLocalCopy() except it takes an array of storage paths and
991 * returns a map of storage paths to TempFSFile objects (or null on failure).
992 * The map keys (paths) are in the same order as the provided list of paths.
994 * @see FileBackend::getLocalCopy()
996 * @param $params Array
998 * - srcs : list of source storage paths
999 * - latest : use the latest available data
1000 * - parallelize : try to do operations in parallel when possible
1001 * @return Array Map of (path name => TempFSFile or null on failure)
1004 abstract public function getLocalCopyMulti( array $params );
1007 * Return an HTTP URL to a given file that requires no authentication to use.
1008 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1009 * This will return null if the backend cannot make an HTTP URL for the file.
1011 * This is useful for key/value stores when using scripts that seek around
1012 * large files and those scripts (and the backend) support HTTP Range headers.
1013 * Otherwise, one would need to use getLocalReference(), which involves loading
1014 * the entire file on to local disk.
1016 * @param $params Array
1018 * - src : source storage path
1019 * @return string|null
1022 abstract public function getFileHttpUrl( array $params );
1025 * Check if a directory exists at a given storage path.
1026 * Backends using key/value stores will check if the path is a
1027 * virtual directory, meaning there are files under the given directory.
1029 * Storage backends with eventual consistency might return stale data.
1031 * @param $params array
1033 * - dir : storage directory
1034 * @return bool|null Returns null on failure
1037 abstract public function directoryExists( array $params );
1040 * Get an iterator to list *all* directories under a storage directory.
1041 * If the directory is of the form "mwstore://backend/container",
1042 * then all directories in the container will be listed.
1043 * If the directory is of form "mwstore://backend/container/dir",
1044 * then all directories directly under that directory will be listed.
1045 * Results will be storage directories relative to the given directory.
1047 * Storage backends with eventual consistency might return stale data.
1049 * @param $params array
1051 * - dir : storage directory
1052 * - topOnly : only return direct child dirs of the directory
1053 * @return Traversable|Array|null Returns null on failure
1056 abstract public function getDirectoryList( array $params );
1059 * Same as FileBackend::getDirectoryList() except only lists
1060 * directories that are immediately under the given directory.
1062 * Storage backends with eventual consistency might return stale data.
1064 * @param $params array
1066 * - dir : storage directory
1067 * @return Traversable|Array|null Returns null on failure
1070 final public function getTopDirectoryList( array $params ) {
1071 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1075 * Get an iterator to list *all* stored files under a storage directory.
1076 * If the directory is of the form "mwstore://backend/container",
1077 * then all files in the container will be listed.
1078 * If the directory is of form "mwstore://backend/container/dir",
1079 * then all files under that directory will be listed.
1080 * Results will be storage paths relative to the given directory.
1082 * Storage backends with eventual consistency might return stale data.
1084 * @param $params array
1086 * - dir : storage directory
1087 * - topOnly : only return direct child files of the directory (since 1.20)
1088 * @return Traversable|Array|null Returns null on failure
1090 abstract public function getFileList( array $params );
1093 * Same as FileBackend::getFileList() except only lists
1094 * files that are immediately under the given directory.
1096 * Storage backends with eventual consistency might return stale data.
1098 * @param $params array
1100 * - dir : storage directory
1101 * @return Traversable|Array|null Returns null on failure
1104 final public function getTopFileList( array $params ) {
1105 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1109 * Preload persistent file stat and property cache into in-process cache.
1110 * This should be used when stat calls will be made on a known list of a many files.
1112 * @param $paths Array Storage paths
1115 public function preloadCache( array $paths ) {}
1118 * Invalidate any in-process file stat and property cache.
1119 * If $paths is given, then only the cache for those files will be cleared.
1121 * @param $paths Array Storage paths (optional)
1124 public function clearCache( array $paths = null ) {}
1127 * Lock the files at the given storage paths in the backend.
1128 * This will either lock all the files or none (on failure).
1130 * Callers should consider using getScopedFileLocks() instead.
1132 * @param $paths Array Storage paths
1133 * @param $type integer LockManager::LOCK_* constant
1136 final public function lockFiles( array $paths, $type ) {
1137 return $this->lockManager
->lock( $paths, $type );
1141 * Unlock the files at the given storage paths in the backend.
1143 * @param $paths Array Storage paths
1144 * @param $type integer LockManager::LOCK_* constant
1147 final public function unlockFiles( array $paths, $type ) {
1148 return $this->lockManager
->unlock( $paths, $type );
1152 * Lock the files at the given storage paths in the backend.
1153 * This will either lock all the files or none (on failure).
1154 * On failure, the status object will be updated with errors.
1156 * Once the return value goes out scope, the locks will be released and
1157 * the status updated. Unlock fatals will not change the status "OK" value.
1159 * @param $paths Array Storage paths
1160 * @param $type integer LockManager::LOCK_* constant
1161 * @param $status Status Status to update on lock/unlock
1162 * @return ScopedLock|null Returns null on failure
1164 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1165 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1169 * Get an array of scoped locks needed for a batch of file operations.
1171 * Normally, FileBackend::doOperations() handles locking, unless
1172 * the 'nonLocking' param is passed in. This function is useful if you
1173 * want the files to be locked for a broader scope than just when the
1174 * files are changing. For example, if you need to update DB metadata,
1175 * you may want to keep the files locked until finished.
1177 * @see FileBackend::doOperations()
1179 * @param $ops Array List of file operations to FileBackend::doOperations()
1180 * @param $status Status Status to update on lock/unlock
1181 * @return Array List of ScopedFileLocks or null values
1184 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1187 * Get the root storage path of this backend.
1188 * All container paths are "subdirectories" of this path.
1190 * @return string Storage path
1193 final public function getRootStoragePath() {
1194 return "mwstore://{$this->name}";
1198 * Get the storage path for the given container for this backend
1200 * @param $container string Container name
1201 * @return string Storage path
1204 final public function getContainerStoragePath( $container ) {
1205 return $this->getRootStoragePath() . "/{$container}";
1209 * Get the file journal object for this backend
1211 * @return FileJournal
1213 final public function getJournal() {
1214 return $this->fileJournal
;
1218 * Check if a given path is a "mwstore://" path.
1219 * This does not do any further validation or any existence checks.
1221 * @param $path string
1224 final public static function isStoragePath( $path ) {
1225 return ( strpos( $path, 'mwstore://' ) === 0 );
1229 * Split a storage path into a backend name, a container name,
1230 * and a relative file path. The relative path may be the empty string.
1231 * This does not do any path normalization or traversal checks.
1233 * @param $storagePath string
1234 * @return Array (backend, container, rel object) or (null, null, null)
1236 final public static function splitStoragePath( $storagePath ) {
1237 if ( self
::isStoragePath( $storagePath ) ) {
1238 // Remove the "mwstore://" prefix and split the path
1239 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1240 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1241 if ( count( $parts ) == 3 ) {
1242 return $parts; // e.g. "backend/container/path"
1244 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1248 return array( null, null, null );
1252 * Normalize a storage path by cleaning up directory separators.
1253 * Returns null if the path is not of the format of a valid storage path.
1255 * @param $storagePath string
1256 * @return string|null
1258 final public static function normalizeStoragePath( $storagePath ) {
1259 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1260 if ( $relPath !== null ) { // must be for this backend
1261 $relPath = self
::normalizeContainerPath( $relPath );
1262 if ( $relPath !== null ) {
1263 return ( $relPath != '' )
1264 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1265 : "mwstore://{$backend}/{$container}";
1272 * Get the parent storage directory of a storage path.
1273 * This returns a path like "mwstore://backend/container",
1274 * "mwstore://backend/container/...", or null if there is no parent.
1276 * @param $storagePath string
1277 * @return string|null
1279 final public static function parentStoragePath( $storagePath ) {
1280 $storagePath = dirname( $storagePath );
1281 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1282 return ( $rel === null ) ?
null : $storagePath;
1286 * Get the final extension from a storage or FS path
1288 * @param $path string
1291 final public static function extensionFromPath( $path ) {
1292 $i = strrpos( $path, '.' );
1293 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1297 * Check if a relative path has no directory traversals
1299 * @param $path string
1303 final public static function isPathTraversalFree( $path ) {
1304 return ( self
::normalizeContainerPath( $path ) !== null );
1308 * Build a Content-Disposition header value per RFC 6266.
1310 * @param $type string One of (attachment, inline)
1311 * @param $filename string Suggested file name (should not contain slashes)
1312 * @throws MWException
1316 final public static function makeContentDisposition( $type, $filename = '' ) {
1319 $type = strtolower( $type );
1320 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1321 throw new MWException( "Invalid Content-Disposition type '$type'." );
1325 if ( strlen( $filename ) ) {
1326 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1329 return implode( ';', $parts );
1333 * Validate and normalize a relative storage path.
1334 * Null is returned if the path involves directory traversal.
1335 * Traversal is insecure for FS backends and broken for others.
1337 * This uses the same traversal protection as Title::secureAndSplit().
1339 * @param $path string Storage path relative to a container
1340 * @return string|null
1342 final protected static function normalizeContainerPath( $path ) {
1343 // Normalize directory separators
1344 $path = strtr( $path, '\\', '/' );
1345 // Collapse any consecutive directory separators
1346 $path = preg_replace( '![/]{2,}!', '/', $path );
1347 // Remove any leading directory separator
1348 $path = ltrim( $path, '/' );
1349 // Use the same traversal protection as Title::secureAndSplit()
1350 if ( strpos( $path, '.' ) !== false ) {
1354 strpos( $path, './' ) === 0 ||
1355 strpos( $path, '../' ) === 0 ||
1356 strpos( $path, '/./' ) !== false ||
1357 strpos( $path, '/../' ) !== false