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 * 'headers' => <HTTP header name/value map> # since 1.21
198 * b) Copy a file system file into storage
202 * 'src' => <file system path>,
203 * 'dst' => <storage path>,
204 * 'overwrite' => <boolean>,
205 * 'overwriteSame' => <boolean>,
206 * 'headers' => <HTTP header name/value map> # since 1.21
210 * c) Copy a file within storage
214 * 'src' => <storage path>,
215 * 'dst' => <storage path>,
216 * 'overwrite' => <boolean>,
217 * 'overwriteSame' => <boolean>,
218 * 'ignoreMissingSource' => <boolean>, # since 1.21
219 * 'headers' => <HTTP header name/value map> # since 1.21
223 * d) Move a file within storage
227 * 'src' => <storage path>,
228 * 'dst' => <storage path>,
229 * 'overwrite' => <boolean>,
230 * 'overwriteSame' => <boolean>,
231 * 'ignoreMissingSource' => <boolean>, # since 1.21
232 * 'headers' => <HTTP header name/value map> # since 1.21
236 * e) Delete a file within storage
240 * 'src' => <storage path>,
241 * 'ignoreMissingSource' => <boolean>
245 * f) Update metadata for a file within storage
248 * 'op' => 'describe',
249 * 'src' => <storage path>,
250 * 'headers' => <HTTP header name/value map>
254 * g) Do nothing (no-op)
261 * Boolean flags for operations (operation-specific):
262 * - ignoreMissingSource : The operation will simply succeed and do
263 * nothing if the source file does not exist.
264 * - overwrite : Any destination file will be overwritten.
265 * - overwriteSame : An error will not be given if a file already
266 * exists at the destination that has the same
267 * contents as the new contents to be written there.
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 * Content-Disposition headers can be longer, though the system
272 * might ignore or truncate ones that are too long to store.
273 * Existing headers will remain, but these will replace any
274 * conflicting previous headers, and headers will be removed
275 * if they are set to an empty string.
276 * Backends that don't support metadata ignore this. (since 1.21)
278 * $opts is an associative of boolean flags, including:
279 * - force : Operation precondition errors no longer trigger an abort.
280 * Any remaining operations are still attempted. Unexpected
281 * failures may still cause remaining operations to be aborted.
282 * - nonLocking : No locks are acquired for the operations.
283 * This can increase performance for non-critical writes.
284 * This has no effect unless the 'force' flag is set.
285 * - nonJournaled : Don't log this operation batch in the file journal.
286 * This limits the ability of recovery scripts.
287 * - parallelize : Try to do operations in parallel when possible.
288 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
289 * - preserveCache : Don't clear the process cache before checking files.
290 * This should only be used if all entries in the process
291 * cache were added after the files were already locked. (since 1.20)
293 * @remarks Remarks on locking:
294 * File system paths given to operations should refer to files that are
295 * already locked or otherwise safe from modification from other processes.
296 * Normally these files will be new temp files, which should be adequate.
300 * This returns a Status, which contains all warnings and fatals that occurred
301 * during the operation. The 'failCount', 'successCount', and 'success' members
302 * will reflect each operation attempted.
304 * The status will be "OK" unless:
305 * - a) unexpected operation errors occurred (network partitions, disk full...)
306 * - b) significant operation errors occurred and 'force' was not set
308 * @param array $ops List of operations to execute in order
309 * @param array $opts Batch operation options
312 final public function doOperations( array $ops, array $opts = array() ) {
313 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
314 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
316 if ( empty( $opts['force'] ) ) { // sanity
317 unset( $opts['nonLocking'] );
319 foreach ( $ops as &$op ) {
320 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
321 $op['headers']['Content-Disposition'] = $op['disposition'];
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 array $op Operation
341 * @param array $opts 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 array $params Operation parameters
355 * @param array $opts 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 array $params Operation parameters
369 * @param array $opts 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 array $params Operation parameters
383 * @param array $opts 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 array $params Operation parameters
397 * @param array $opts 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 array $params Operation parameters
411 * @param array $opts 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 array $params Operation parameters
425 * @param array $opts 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 * 'headers' => <HTTP header name/value map> # since 1.21
459 * b) Copy a file system file into storage
463 * 'src' => <file system path>,
464 * 'dst' => <storage path>,
465 * 'headers' => <HTTP header name/value map> # since 1.21
469 * c) Copy a file within storage
473 * 'src' => <storage path>,
474 * 'dst' => <storage path>,
475 * 'ignoreMissingSource' => <boolean>, # since 1.21
476 * 'headers' => <HTTP header name/value map> # since 1.21
480 * d) Move a file within storage
484 * 'src' => <storage path>,
485 * 'dst' => <storage path>,
486 * 'ignoreMissingSource' => <boolean>, # since 1.21
487 * 'headers' => <HTTP header name/value map> # since 1.21
491 * e) Delete a file within storage
495 * 'src' => <storage path>,
496 * 'ignoreMissingSource' => <boolean>
500 * f) Update metadata for a file within storage
503 * 'op' => 'describe',
504 * 'src' => <storage path>,
505 * 'headers' => <HTTP header name/value map>
509 * g) Do nothing (no-op)
516 * @par Boolean flags for operations (operation-specific):
517 * - ignoreMissingSource : The operation will simply succeed and do
518 * nothing if the source file does not exist.
519 * - headers : If supplied with a header name/value map, the backend will
520 * reply with these headers when GETs/HEADs of the destination
521 * file are made. Header values should be smaller than 256 bytes.
522 * Content-Disposition headers can be longer, though the system
523 * might ignore or truncate ones that are too long to store.
524 * Existing headers will remain, but these will replace any
525 * conflicting previous headers, and headers will be removed
526 * if they are set to an empty string.
527 * Backends that don't support metadata ignore this. (since 1.21)
529 * $opts is an associative of boolean flags, including:
530 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
533 * This returns a Status, which contains all warnings and fatals that occurred
534 * during the operation. The 'failCount', 'successCount', and 'success' members
535 * will reflect each operation attempted for the given files. The status will be
536 * considered "OK" as long as no fatal errors occurred.
538 * @param array $ops Set of operations to execute
539 * @param array $opts Batch operation options
543 final public function doQuickOperations( array $ops, array $opts = array() ) {
544 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
545 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
547 foreach ( $ops as &$op ) {
548 $op['overwrite'] = true; // avoids RTTs in key/value stores
549 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
550 $op['headers']['Content-Disposition'] = $op['disposition'];
553 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
554 return $this->doQuickOperationsInternal( $ops );
558 * @see FileBackend::doQuickOperations()
561 abstract protected function doQuickOperationsInternal( array $ops );
564 * Same as doQuickOperations() except it takes a single operation.
565 * If you are doing a batch of operations, then use that function instead.
567 * @see FileBackend::doQuickOperations()
569 * @param array $op Operation
573 final public function doQuickOperation( array $op ) {
574 return $this->doQuickOperations( array( $op ) );
578 * Performs a single quick create operation.
579 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
581 * @see FileBackend::doQuickOperation()
583 * @param array $params Operation parameters
587 final public function quickCreate( array $params ) {
588 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
592 * Performs a single quick store operation.
593 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
595 * @see FileBackend::doQuickOperation()
597 * @param array $params Operation parameters
601 final public function quickStore( array $params ) {
602 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
606 * Performs a single quick copy operation.
607 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
609 * @see FileBackend::doQuickOperation()
611 * @param array $params Operation parameters
615 final public function quickCopy( array $params ) {
616 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
620 * Performs a single quick move operation.
621 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
623 * @see FileBackend::doQuickOperation()
625 * @param array $params Operation parameters
629 final public function quickMove( array $params ) {
630 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
634 * Performs a single quick delete operation.
635 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
637 * @see FileBackend::doQuickOperation()
639 * @param array $params Operation parameters
643 final public function quickDelete( array $params ) {
644 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
648 * Performs a single quick describe operation.
649 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
651 * @see FileBackend::doQuickOperation()
653 * @param array $params Operation parameters
657 final public function quickDescribe( array $params ) {
658 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
662 * Concatenate a list of storage files into a single file system file.
663 * The target path should refer to a file that is already locked or
664 * otherwise safe from modification from other processes. Normally,
665 * the file will be a new temp file, which should be adequate.
667 * @param array $params Operation parameters
669 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
670 * - dst : file system path to 0-byte temp file
671 * - parallelize : try to do operations in parallel when possible
674 abstract public function concatenate( array $params );
677 * Prepare a storage directory for usage.
678 * This will create any required containers and parent directories.
679 * Backends using key/value stores only need to create the container.
681 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
682 * except they are only applied *if* the directory/container had to be created.
683 * These flags should always be set for directories that have private files.
685 * @param array $params
687 * - dir : storage directory
688 * - noAccess : try to deny file access (since 1.20)
689 * - noListing : try to deny file listing (since 1.20)
690 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
693 final public function prepare( array $params ) {
694 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
695 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
697 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
698 return $this->doPrepare( $params );
702 * @see FileBackend::prepare()
704 abstract protected function doPrepare( array $params );
707 * Take measures to block web access to a storage directory and
708 * the container it belongs to. FS backends might add .htaccess
709 * files whereas key/value store backends might revoke container
710 * access to the storage user representing end-users in web requests.
711 * This is not guaranteed to actually do anything.
713 * @param array $params
715 * - dir : storage directory
716 * - noAccess : try to deny file access
717 * - noListing : try to deny file listing
718 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
721 final public function secure( array $params ) {
722 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
723 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
725 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
726 return $this->doSecure( $params );
730 * @see FileBackend::secure()
732 abstract protected function doSecure( array $params );
735 * Remove measures to block web access to a storage directory and
736 * the container it belongs to. FS backends might remove .htaccess
737 * files whereas key/value store backends might grant container
738 * access to the storage user representing end-users in web requests.
739 * This essentially can undo the result of secure() calls.
741 * @param array $params
743 * - dir : storage directory
744 * - access : try to allow file access
745 * - listing : try to allow file listing
746 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
750 final public function publish( array $params ) {
751 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
752 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
754 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
755 return $this->doPublish( $params );
759 * @see FileBackend::publish()
761 abstract protected function doPublish( array $params );
764 * Delete a storage directory if it is empty.
765 * Backends using key/value stores may do nothing unless the directory
766 * is that of an empty container, in which case it will be deleted.
768 * @param array $params
770 * - dir : storage directory
771 * - recursive : recursively delete empty subdirectories first (since 1.20)
772 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
775 final public function clean( array $params ) {
776 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
777 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
779 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
780 return $this->doClean( $params );
784 * @see FileBackend::clean()
786 abstract protected function doClean( array $params );
789 * Enter file operation scope.
790 * This just makes PHP ignore user aborts/disconnects until the return
791 * value leaves scope. This returns null and does nothing in CLI mode.
793 * @return ScopedCallback|null
795 final protected function getScopedPHPBehaviorForOps() {
796 if ( php_sapi_name() != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
797 $old = ignore_user_abort( true ); // avoid half-finished operations
798 return new ScopedCallback( function() use ( $old ) { ignore_user_abort( $old ); } );
804 * Check if a file exists at a storage path in the backend.
805 * This returns false if only a directory exists at the path.
807 * @param array $params
809 * - src : source storage path
810 * - latest : use the latest available data
811 * @return bool|null Returns null on failure
813 abstract public function fileExists( array $params );
816 * Get the last-modified timestamp of the file at a storage path.
818 * @param array $params
820 * - src : source storage path
821 * - latest : use the latest available data
822 * @return string|bool TS_MW timestamp or false on failure
824 abstract public function getFileTimestamp( array $params );
827 * Get the contents of a file at a storage path in the backend.
828 * This should be avoided for potentially large files.
830 * @param array $params
832 * - src : source storage path
833 * - latest : use the latest available data
834 * @return string|bool Returns false on failure
836 final public function getFileContents( array $params ) {
837 $contents = $this->getFileContentsMulti(
838 array( 'srcs' => array( $params['src'] ) ) +
$params );
840 return $contents[$params['src']];
844 * Like getFileContents() except it takes an array of storage paths
845 * and returns a map of storage paths to strings (or null on failure).
846 * The map keys (paths) are in the same order as the provided list of paths.
848 * @see FileBackend::getFileContents()
850 * @param array $params
852 * - srcs : list of source storage paths
853 * - latest : use the latest available data
854 * - parallelize : try to do operations in parallel when possible
855 * @return Array Map of (path name => string or false on failure)
858 abstract public function getFileContentsMulti( array $params );
861 * Get the size (bytes) of a file at a storage path in the backend.
863 * @param array $params
865 * - src : source storage path
866 * - latest : use the latest available data
867 * @return integer|bool Returns false on failure
869 abstract public function getFileSize( array $params );
872 * Get quick information about a file at a storage path in the backend.
873 * If the file does not exist, then this returns false.
874 * Otherwise, the result is an associative array that includes:
875 * - mtime : the last-modified timestamp (TS_MW)
876 * - size : the file size (bytes)
877 * Additional values may be included for internal use only.
879 * @param array $params
881 * - src : source storage path
882 * - latest : use the latest available data
883 * @return Array|bool|null Returns null on failure
885 abstract public function getFileStat( array $params );
888 * Get a SHA-1 hash of the file at a storage path in the backend.
890 * @param array $params
892 * - src : source storage path
893 * - latest : use the latest available data
894 * @return string|bool Hash string or false on failure
896 abstract public function getFileSha1Base36( array $params );
899 * Get the properties of the file at a storage path in the backend.
900 * This gives the result of FSFile::getProps() on a local copy of the file.
902 * @param array $params
904 * - src : source storage path
905 * - latest : use the latest available data
906 * @return Array Returns FSFile::placeholderProps() on failure
908 abstract public function getFileProps( array $params );
911 * Stream the file at a storage path in the backend.
912 * If the file does not exists, an HTTP 404 error will be given.
913 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
914 * will be sent if streaming began, while none will be sent otherwise.
915 * Implementations should flush the output buffer before sending data.
917 * @param array $params
919 * - src : source storage path
920 * - headers : list of additional HTTP headers to send on success
921 * - latest : use the latest available data
924 abstract public function streamFile( array $params );
927 * Returns a file system file, identical to the file at a storage path.
928 * The file returned is either:
929 * - a) A local copy of the file at a storage path in the backend.
930 * The temporary copy will have the same extension as the source.
931 * - b) An original of the file at a storage path in the backend.
932 * Temporary files may be purged when the file object falls out of scope.
934 * Write operations should *never* be done on this file as some backends
935 * may do internal tracking or may be instances of FileBackendMultiWrite.
936 * In that later case, there are copies of the file that must stay in sync.
937 * Additionally, further calls to this function may return the same file.
939 * @param array $params
941 * - src : source storage path
942 * - latest : use the latest available data
943 * @return FSFile|null Returns null on failure
945 final public function getLocalReference( array $params ) {
946 $fsFiles = $this->getLocalReferenceMulti(
947 array( 'srcs' => array( $params['src'] ) ) +
$params );
949 return $fsFiles[$params['src']];
953 * Like getLocalReference() except it takes an array of storage paths
954 * and returns a map of storage paths to FSFile objects (or null on failure).
955 * The map keys (paths) are in the same order as the provided list of paths.
957 * @see FileBackend::getLocalReference()
959 * @param array $params
961 * - srcs : list of source storage paths
962 * - latest : use the latest available data
963 * - parallelize : try to do operations in parallel when possible
964 * @return Array Map of (path name => FSFile or null on failure)
967 abstract public function getLocalReferenceMulti( array $params );
970 * Get a local copy on disk of the file at a storage path in the backend.
971 * The temporary copy will have the same file extension as the source.
972 * Temporary files may be purged when the file object falls out of scope.
974 * @param array $params
976 * - src : source storage path
977 * - latest : use the latest available data
978 * @return TempFSFile|null Returns null on failure
980 final public function getLocalCopy( array $params ) {
981 $tmpFiles = $this->getLocalCopyMulti(
982 array( 'srcs' => array( $params['src'] ) ) +
$params );
984 return $tmpFiles[$params['src']];
988 * Like getLocalCopy() except it takes an array of storage paths and
989 * returns a map of storage paths to TempFSFile objects (or null on failure).
990 * The map keys (paths) are in the same order as the provided list of paths.
992 * @see FileBackend::getLocalCopy()
994 * @param array $params
996 * - srcs : list of source storage paths
997 * - latest : use the latest available data
998 * - parallelize : try to do operations in parallel when possible
999 * @return Array Map of (path name => TempFSFile or null on failure)
1002 abstract public function getLocalCopyMulti( array $params );
1005 * Return an HTTP URL to a given file that requires no authentication to use.
1006 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1007 * This will return null if the backend cannot make an HTTP URL for the file.
1009 * This is useful for key/value stores when using scripts that seek around
1010 * large files and those scripts (and the backend) support HTTP Range headers.
1011 * Otherwise, one would need to use getLocalReference(), which involves loading
1012 * the entire file on to local disk.
1014 * @param array $params
1016 * - src : source storage path
1017 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1018 * @return string|null
1021 abstract public function getFileHttpUrl( array $params );
1024 * Check if a directory exists at a given storage path.
1025 * Backends using key/value stores will check if the path is a
1026 * virtual directory, meaning there are files under the given directory.
1028 * Storage backends with eventual consistency might return stale data.
1030 * @param $params array
1032 * - dir : storage directory
1033 * @return bool|null Returns null on failure
1036 abstract public function directoryExists( array $params );
1039 * Get an iterator to list *all* directories under a storage directory.
1040 * If the directory is of the form "mwstore://backend/container",
1041 * then all directories in the container will be listed.
1042 * If the directory is of form "mwstore://backend/container/dir",
1043 * then all directories directly under that directory will be listed.
1044 * Results will be storage directories relative to the given directory.
1046 * Storage backends with eventual consistency might return stale data.
1048 * @param $params array
1050 * - dir : storage directory
1051 * - topOnly : only return direct child dirs of the directory
1052 * @return Traversable|Array|null Returns null on failure
1055 abstract public function getDirectoryList( array $params );
1058 * Same as FileBackend::getDirectoryList() except only lists
1059 * directories that are immediately under the given directory.
1061 * Storage backends with eventual consistency might return stale data.
1063 * @param $params array
1065 * - dir : storage directory
1066 * @return Traversable|Array|null Returns null on failure
1069 final public function getTopDirectoryList( array $params ) {
1070 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1074 * Get an iterator to list *all* stored files under a storage directory.
1075 * If the directory is of the form "mwstore://backend/container",
1076 * then all files in the container will be listed.
1077 * If the directory is of form "mwstore://backend/container/dir",
1078 * then all files under that directory will be listed.
1079 * Results will be storage paths relative to the given directory.
1081 * Storage backends with eventual consistency might return stale data.
1083 * @param $params array
1085 * - dir : storage directory
1086 * - topOnly : only return direct child files of the directory (since 1.20)
1087 * @return Traversable|Array|null Returns null on failure
1089 abstract public function getFileList( array $params );
1092 * Same as FileBackend::getFileList() except only lists
1093 * files that are immediately under the given directory.
1095 * Storage backends with eventual consistency might return stale data.
1097 * @param $params array
1099 * - dir : storage directory
1100 * @return Traversable|Array|null Returns null on failure
1103 final public function getTopFileList( array $params ) {
1104 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1108 * Preload persistent file stat and property cache into in-process cache.
1109 * This should be used when stat calls will be made on a known list of a many files.
1111 * @param array $paths Storage paths
1114 public function preloadCache( array $paths ) {}
1117 * Invalidate any in-process file stat and property cache.
1118 * If $paths is given, then only the cache for those files will be cleared.
1120 * @param array $paths Storage paths (optional)
1123 public function clearCache( array $paths = null ) {}
1126 * Lock the files at the given storage paths in the backend.
1127 * This will either lock all the files or none (on failure).
1129 * Callers should consider using getScopedFileLocks() instead.
1131 * @param array $paths Storage paths
1132 * @param $type integer LockManager::LOCK_* constant
1135 final public function lockFiles( array $paths, $type ) {
1136 return $this->lockManager
->lock( $paths, $type );
1140 * Unlock the files at the given storage paths in the backend.
1142 * @param array $paths Storage paths
1143 * @param $type integer LockManager::LOCK_* constant
1146 final public function unlockFiles( array $paths, $type ) {
1147 return $this->lockManager
->unlock( $paths, $type );
1151 * Lock the files at the given storage paths in the backend.
1152 * This will either lock all the files or none (on failure).
1153 * On failure, the status object will be updated with errors.
1155 * Once the return value goes out scope, the locks will be released and
1156 * the status updated. Unlock fatals will not change the status "OK" value.
1158 * @param array $paths Storage paths
1159 * @param $type integer LockManager::LOCK_* constant
1160 * @param $status Status Status to update on lock/unlock
1161 * @return ScopedLock|null Returns null on failure
1163 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1164 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1168 * Get an array of scoped locks needed for a batch of file operations.
1170 * Normally, FileBackend::doOperations() handles locking, unless
1171 * the 'nonLocking' param is passed in. This function is useful if you
1172 * want the files to be locked for a broader scope than just when the
1173 * files are changing. For example, if you need to update DB metadata,
1174 * you may want to keep the files locked until finished.
1176 * @see FileBackend::doOperations()
1178 * @param array $ops List of file operations to FileBackend::doOperations()
1179 * @param $status Status Status to update on lock/unlock
1180 * @return Array List of ScopedFileLocks or null values
1183 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1186 * Get the root storage path of this backend.
1187 * All container paths are "subdirectories" of this path.
1189 * @return string Storage path
1192 final public function getRootStoragePath() {
1193 return "mwstore://{$this->name}";
1197 * Get the storage path for the given container for this backend
1199 * @param string $container Container name
1200 * @return string Storage path
1203 final public function getContainerStoragePath( $container ) {
1204 return $this->getRootStoragePath() . "/{$container}";
1208 * Get the file journal object for this backend
1210 * @return FileJournal
1212 final public function getJournal() {
1213 return $this->fileJournal
;
1217 * Check if a given path is a "mwstore://" path.
1218 * This does not do any further validation or any existence checks.
1220 * @param $path string
1223 final public static function isStoragePath( $path ) {
1224 return ( strpos( $path, 'mwstore://' ) === 0 );
1228 * Split a storage path into a backend name, a container name,
1229 * and a relative file path. The relative path may be the empty string.
1230 * This does not do any path normalization or traversal checks.
1232 * @param $storagePath string
1233 * @return Array (backend, container, rel object) or (null, null, null)
1235 final public static function splitStoragePath( $storagePath ) {
1236 if ( self
::isStoragePath( $storagePath ) ) {
1237 // Remove the "mwstore://" prefix and split the path
1238 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1239 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1240 if ( count( $parts ) == 3 ) {
1241 return $parts; // e.g. "backend/container/path"
1243 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1247 return array( null, null, null );
1251 * Normalize a storage path by cleaning up directory separators.
1252 * Returns null if the path is not of the format of a valid storage path.
1254 * @param $storagePath string
1255 * @return string|null
1257 final public static function normalizeStoragePath( $storagePath ) {
1258 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1259 if ( $relPath !== null ) { // must be for this backend
1260 $relPath = self
::normalizeContainerPath( $relPath );
1261 if ( $relPath !== null ) {
1262 return ( $relPath != '' )
1263 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1264 : "mwstore://{$backend}/{$container}";
1271 * Get the parent storage directory of a storage path.
1272 * This returns a path like "mwstore://backend/container",
1273 * "mwstore://backend/container/...", or null if there is no parent.
1275 * @param $storagePath string
1276 * @return string|null
1278 final public static function parentStoragePath( $storagePath ) {
1279 $storagePath = dirname( $storagePath );
1280 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1281 return ( $rel === null ) ?
null : $storagePath;
1285 * Get the final extension from a storage or FS path
1287 * @param $path string
1290 final public static function extensionFromPath( $path ) {
1291 $i = strrpos( $path, '.' );
1292 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1296 * Check if a relative path has no directory traversals
1298 * @param $path string
1302 final public static function isPathTraversalFree( $path ) {
1303 return ( self
::normalizeContainerPath( $path ) !== null );
1307 * Build a Content-Disposition header value per RFC 6266.
1309 * @param string $type One of (attachment, inline)
1310 * @param string $filename Suggested file name (should not contain slashes)
1311 * @throws MWException
1315 final public static function makeContentDisposition( $type, $filename = '' ) {
1318 $type = strtolower( $type );
1319 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1320 throw new MWException( "Invalid Content-Disposition type '$type'." );
1324 if ( strlen( $filename ) ) {
1325 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1328 return implode( ';', $parts );
1332 * Validate and normalize a relative storage path.
1333 * Null is returned if the path involves directory traversal.
1334 * Traversal is insecure for FS backends and broken for others.
1336 * This uses the same traversal protection as Title::secureAndSplit().
1338 * @param string $path Storage path relative to a container
1339 * @return string|null
1341 final protected static function normalizeContainerPath( $path ) {
1342 // Normalize directory separators
1343 $path = strtr( $path, '\\', '/' );
1344 // Collapse any consecutive directory separators
1345 $path = preg_replace( '![/]{2,}!', '/', $path );
1346 // Remove any leading directory separator
1347 $path = ltrim( $path, '/' );
1348 // Use the same traversal protection as Title::secureAndSplit()
1349 if ( strpos( $path, '.' ) !== false ) {
1353 strpos( $path, './' ) === 0 ||
1354 strpos( $path, '../' ) === 0 ||
1355 strpos( $path, '/./' ) !== false ||
1356 strpos( $path, '/../' ) !== false