3 * @defgroup FileBackend File backend
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
10 * Base class for all file backends.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
28 * @ingroup FileBackend
29 * @author Aaron Schulz
33 * @brief Base class for all file backend classes (including multi-write backends).
35 * This class defines the methods as abstract that subclasses must implement.
36 * Outside callers can assume that all backends will have these functions.
38 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
39 * The "backend" portion is unique name for MediaWiki to refer to a backend, while
40 * the "container" portion is a top-level directory of the backend. The "path" portion
41 * is a relative path that uses UNIX file system (FS) notation, though any particular
42 * backend may not actually be using a local filesystem. Therefore, the relative paths
45 * Backend contents are stored under wiki-specific container names by default.
46 * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
47 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
48 * containers to ones that do not respect the "wiki ID".
50 * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
51 * FS-based backends are somewhat more restrictive due to the existence of real
52 * directory files; a regular file cannot have the same name as a directory. Other
53 * backends with virtual directories may not have this limitation. Callers should
54 * store files in such a way that no files and directories are under the same path.
56 * In general, this class allows for callers to access storage through the same
57 * interface, without regard to the underlying storage system. However, calling code
58 * must follow certain patterns and be aware of certain things to ensure compatibility:
59 * - a) Always call prepare() on the parent directory before trying to put a file there;
60 * key/value stores only need the container to exist first, but filesystems need
61 * all the parent directories to exist first (prepare() is aware of all this)
62 * - b) Always call clean() on a directory when it might become empty to avoid empty
63 * directory buildup on filesystems; key/value stores never have empty directories,
64 * so doing this helps preserve consistency in both cases
65 * - c) Likewise, do not rely on the existence of empty directories for anything;
66 * calling directoryExists() on a path that prepare() was previously called on
67 * will return false for key/value stores if there are no files under that path
68 * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
69 * either be a copy of the source file in /tmp or the original source file itself
70 * - e) Use a file layout that results in never attempting to store files over directories
71 * or directories over files; key/value stores allow this but filesystems do not
72 * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
73 * - g) Do not assume that move operations are atomic (difficult with key/value stores)
74 * - h) Do not assume that file stat or read operations always have immediate consistency;
75 * various methods have a "latest" flag that should always be used if up-to-date
76 * information is required (this trades performance for correctness as needed)
77 * - i) Do not assume that directory listings have immediate consistency
79 * Methods of subclasses should avoid throwing exceptions at all costs.
80 * As a corollary, external dependencies should be kept to a minimum.
82 * @ingroup FileBackend
85 abstract class FileBackend
{
86 /** @var string Unique backend name */
89 /** @var string Unique wiki name */
92 /** @var string Read-only explanation message */
95 /** @var string When to do operations in parallel */
96 protected $parallelize;
98 /** @var int How many operations can be done in parallel */
99 protected $concurrency;
101 /** @var LockManager */
102 protected $lockManager;
104 /** @var FileJournal */
105 protected $fileJournal;
108 * Create a new backend instance from configuration.
109 * This should only be called from within FileBackendGroup.
111 * @param array $config Parameters include:
112 * - name : The unique name of this backend.
113 * This should consist of alphanumberic, '-', and '_' characters.
114 * This name should not be changed after use (e.g. with journaling).
115 * Note that the name is *not* used in actual container names.
116 * - wikiId : Prefix to container names that is unique to this backend.
117 * If not provided, this defaults to the current wiki ID.
118 * It should only consist of alphanumberic, '-', and '_' characters.
119 * This ID is what avoids collisions if multiple logical backends
120 * use the same storage system, so this should be set carefully.
121 * - lockManager : Registered name of a file lock manager to use.
122 * - fileJournal : File journal configuration; see FileJournal::factory().
123 * Journals simply log changes to files stored in the backend.
124 * - readOnly : Write operations are disallowed if this is a non-empty string.
125 * It should be an explanation for the backend being read-only.
126 * - parallelize : When to do file operations in parallel (when possible).
127 * Allowed values are "implicit", "explicit" and "off".
128 * - concurrency : How many file operations can be done in parallel.
129 * @throws MWException
131 public function __construct( array $config ) {
132 $this->name
= $config['name'];
133 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
134 throw new MWException( "Backend name `{$this->name}` is invalid." );
136 $this->wikiId
= isset( $config['wikiId'] )
138 : wfWikiID(); // e.g. "my_wiki-en_"
139 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
140 ?
$config['lockManager']
141 : LockManagerGroup
::singleton( $this->wikiId
)->get( $config['lockManager'] );
142 $this->fileJournal
= isset( $config['fileJournal'] )
143 ?
( ( $config['fileJournal'] instanceof FileJournal
)
144 ?
$config['fileJournal']
145 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
146 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
147 $this->readOnly
= isset( $config['readOnly'] )
148 ?
(string)$config['readOnly']
150 $this->parallelize
= isset( $config['parallelize'] )
151 ?
(string)$config['parallelize']
153 $this->concurrency
= isset( $config['concurrency'] )
154 ?
(int)$config['concurrency']
159 * Get the unique backend name.
160 * We may have multiple different backends of the same type.
161 * For example, we can have two Swift backends using different proxies.
165 final public function getName() {
170 * Get the wiki identifier used for this backend (possibly empty).
171 * Note that this might *not* be in the same format as wfWikiID().
176 final public function getWikiId() {
177 return $this->wikiId
;
181 * Check if this backend is read-only
185 final public function isReadOnly() {
186 return ( $this->readOnly
!= '' );
190 * Get an explanatory message if this backend is read-only
192 * @return string|bool Returns false if the backend is not read-only
194 final public function getReadOnlyReason() {
195 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
199 * This is the main entry point into the backend for write operations.
200 * Callers supply an ordered list of operations to perform as a transaction.
201 * Files will be locked, the stat cache cleared, and then the operations attempted.
202 * If any serious errors occur, all attempted operations will be rolled back.
204 * $ops is an array of arrays. The outer array holds a list of operations.
205 * Each inner array is a set of key value pairs that specify an operation.
207 * Supported operations and their parameters. The supported actions are:
213 * - describe (since 1.21)
216 * a) Create a new file in storage with the contents of a string
220 * 'dst' => <storage path>,
221 * 'content' => <string of new file contents>,
222 * 'overwrite' => <boolean>,
223 * 'overwriteSame' => <boolean>,
224 * 'headers' => <HTTP header name/value map> # since 1.21
228 * b) Copy a file system file into storage
232 * 'src' => <file system path>,
233 * 'dst' => <storage path>,
234 * 'overwrite' => <boolean>,
235 * 'overwriteSame' => <boolean>,
236 * 'headers' => <HTTP header name/value map> # since 1.21
240 * c) Copy a file within storage
244 * 'src' => <storage path>,
245 * 'dst' => <storage path>,
246 * 'overwrite' => <boolean>,
247 * 'overwriteSame' => <boolean>,
248 * 'ignoreMissingSource' => <boolean>, # since 1.21
249 * 'headers' => <HTTP header name/value map> # since 1.21
253 * d) Move a file within storage
257 * 'src' => <storage path>,
258 * 'dst' => <storage path>,
259 * 'overwrite' => <boolean>,
260 * 'overwriteSame' => <boolean>,
261 * 'ignoreMissingSource' => <boolean>, # since 1.21
262 * 'headers' => <HTTP header name/value map> # since 1.21
266 * e) Delete a file within storage
270 * 'src' => <storage path>,
271 * 'ignoreMissingSource' => <boolean>
275 * f) Update metadata for a file within storage
278 * 'op' => 'describe',
279 * 'src' => <storage path>,
280 * 'headers' => <HTTP header name/value map>
284 * g) Do nothing (no-op)
291 * Boolean flags for operations (operation-specific):
292 * - ignoreMissingSource : The operation will simply succeed and do
293 * nothing if the source file does not exist.
294 * - overwrite : Any destination file will be overwritten.
295 * - overwriteSame : If a file already exists at the destination with the
296 * same contents, then do nothing to the destination file
297 * instead of giving an error. This does not compare headers.
298 * This option is ignored if 'overwrite' is already provided.
299 * - headers : If supplied, the result of merging these headers with any
300 * existing source file headers (replacing conflicting ones)
301 * will be set as the destination file headers. Headers are
302 * deleted if their value is set to the empty string. When a
303 * file has headers they are included in responses to GET and
304 * HEAD requests to the backing store for that file.
305 * Header values should be no larger than 255 bytes, except for
306 * Content-Disposition. The system might ignore or truncate any
307 * headers that are too long to store (exact limits will vary).
308 * Backends that don't support metadata ignore this. (since 1.21)
310 * $opts is an associative of boolean flags, including:
311 * - force : Operation precondition errors no longer trigger an abort.
312 * Any remaining operations are still attempted. Unexpected
313 * failures may still cause remaining operations to be aborted.
314 * - nonLocking : No locks are acquired for the operations.
315 * This can increase performance for non-critical writes.
316 * This has no effect unless the 'force' flag is set.
317 * - nonJournaled : Don't log this operation batch in the file journal.
318 * This limits the ability of recovery scripts.
319 * - parallelize : Try to do operations in parallel when possible.
320 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
321 * - preserveCache : Don't clear the process cache before checking files.
322 * This should only be used if all entries in the process
323 * cache were added after the files were already locked. (since 1.20)
325 * @remarks Remarks on locking:
326 * File system paths given to operations should refer to files that are
327 * already locked or otherwise safe from modification from other processes.
328 * Normally these files will be new temp files, which should be adequate.
332 * This returns a Status, which contains all warnings and fatals that occurred
333 * during the operation. The 'failCount', 'successCount', and 'success' members
334 * will reflect each operation attempted.
336 * The status will be "OK" unless:
337 * - a) unexpected operation errors occurred (network partitions, disk full...)
338 * - b) significant operation errors occurred and 'force' was not set
340 * @param array $ops List of operations to execute in order
341 * @param array $opts Batch operation options
344 final public function doOperations( array $ops, array $opts = array() ) {
345 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
346 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
348 if ( !count( $ops ) ) {
349 return Status
::newGood(); // nothing to do
351 if ( empty( $opts['force'] ) ) { // sanity
352 unset( $opts['nonLocking'] );
354 foreach ( $ops as &$op ) {
355 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
356 $op['headers']['Content-Disposition'] = $op['disposition'];
359 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
360 return $this->doOperationsInternal( $ops, $opts );
364 * @see FileBackend::doOperations()
366 abstract protected function doOperationsInternal( array $ops, array $opts );
369 * Same as doOperations() except it takes a single operation.
370 * If you are doing a batch of operations that should either
371 * all succeed or all fail, then use that function instead.
373 * @see FileBackend::doOperations()
375 * @param array $op Operation
376 * @param array $opts Operation options
379 final public function doOperation( array $op, array $opts = array() ) {
380 return $this->doOperations( array( $op ), $opts );
384 * Performs a single create operation.
385 * This sets $params['op'] to 'create' and passes it to doOperation().
387 * @see FileBackend::doOperation()
389 * @param array $params Operation parameters
390 * @param array $opts Operation options
393 final public function create( array $params, array $opts = array() ) {
394 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
398 * Performs a single store operation.
399 * This sets $params['op'] to 'store' and passes it to doOperation().
401 * @see FileBackend::doOperation()
403 * @param array $params Operation parameters
404 * @param array $opts Operation options
407 final public function store( array $params, array $opts = array() ) {
408 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
412 * Performs a single copy operation.
413 * This sets $params['op'] to 'copy' and passes it to doOperation().
415 * @see FileBackend::doOperation()
417 * @param array $params Operation parameters
418 * @param array $opts Operation options
421 final public function copy( array $params, array $opts = array() ) {
422 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
426 * Performs a single move operation.
427 * This sets $params['op'] to 'move' and passes it to doOperation().
429 * @see FileBackend::doOperation()
431 * @param array $params Operation parameters
432 * @param array $opts Operation options
435 final public function move( array $params, array $opts = array() ) {
436 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
440 * Performs a single delete operation.
441 * This sets $params['op'] to 'delete' and passes it to doOperation().
443 * @see FileBackend::doOperation()
445 * @param array $params Operation parameters
446 * @param array $opts Operation options
449 final public function delete( array $params, array $opts = array() ) {
450 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
454 * Performs a single describe operation.
455 * This sets $params['op'] to 'describe' and passes it to doOperation().
457 * @see FileBackend::doOperation()
459 * @param array $params Operation parameters
460 * @param array $opts Operation options
464 final public function describe( array $params, array $opts = array() ) {
465 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
469 * Perform a set of independent file operations on some files.
471 * This does no locking, nor journaling, and possibly no stat calls.
472 * Any destination files that already exist will be overwritten.
473 * This should *only* be used on non-original files, like cache files.
475 * Supported operations and their parameters:
481 * - describe (since 1.21)
484 * a) Create a new file in storage with the contents of a string
488 * 'dst' => <storage path>,
489 * 'content' => <string of new file contents>,
490 * 'headers' => <HTTP header name/value map> # since 1.21
494 * b) Copy a file system file into storage
498 * 'src' => <file system path>,
499 * 'dst' => <storage path>,
500 * 'headers' => <HTTP header name/value map> # since 1.21
504 * c) Copy a file within storage
508 * 'src' => <storage path>,
509 * 'dst' => <storage path>,
510 * 'ignoreMissingSource' => <boolean>, # since 1.21
511 * 'headers' => <HTTP header name/value map> # since 1.21
515 * d) Move a file within storage
519 * 'src' => <storage path>,
520 * 'dst' => <storage path>,
521 * 'ignoreMissingSource' => <boolean>, # since 1.21
522 * 'headers' => <HTTP header name/value map> # since 1.21
526 * e) Delete a file within storage
530 * 'src' => <storage path>,
531 * 'ignoreMissingSource' => <boolean>
535 * f) Update metadata for a file within storage
538 * 'op' => 'describe',
539 * 'src' => <storage path>,
540 * 'headers' => <HTTP header name/value map>
544 * g) Do nothing (no-op)
551 * @par Boolean flags for operations (operation-specific):
552 * - ignoreMissingSource : The operation will simply succeed and do
553 * nothing if the source file does not exist.
554 * - headers : If supplied with a header name/value map, the backend will
555 * reply with these headers when GETs/HEADs of the destination
556 * file are made. Header values should be smaller than 256 bytes.
557 * Content-Disposition headers can be longer, though the system
558 * might ignore or truncate ones that are too long to store.
559 * Existing headers will remain, but these will replace any
560 * conflicting previous headers, and headers will be removed
561 * if they are set to an empty string.
562 * Backends that don't support metadata ignore this. (since 1.21)
564 * $opts is an associative of boolean flags, including:
565 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
568 * This returns a Status, which contains all warnings and fatals that occurred
569 * during the operation. The 'failCount', 'successCount', and 'success' members
570 * will reflect each operation attempted for the given files. The status will be
571 * considered "OK" as long as no fatal errors occurred.
573 * @param array $ops Set of operations to execute
574 * @param array $opts Batch operation options
578 final public function doQuickOperations( array $ops, array $opts = array() ) {
579 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
580 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
582 if ( !count( $ops ) ) {
583 return Status
::newGood(); // nothing to do
585 foreach ( $ops as &$op ) {
586 $op['overwrite'] = true; // avoids RTTs in key/value stores
587 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
588 $op['headers']['Content-Disposition'] = $op['disposition'];
591 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
592 return $this->doQuickOperationsInternal( $ops );
596 * @see FileBackend::doQuickOperations()
599 abstract protected function doQuickOperationsInternal( array $ops );
602 * Same as doQuickOperations() except it takes a single operation.
603 * If you are doing a batch of operations, then use that function instead.
605 * @see FileBackend::doQuickOperations()
607 * @param array $op Operation
611 final public function doQuickOperation( array $op ) {
612 return $this->doQuickOperations( array( $op ) );
616 * Performs a single quick create operation.
617 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
619 * @see FileBackend::doQuickOperation()
621 * @param array $params Operation parameters
625 final public function quickCreate( array $params ) {
626 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
630 * Performs a single quick store operation.
631 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
633 * @see FileBackend::doQuickOperation()
635 * @param array $params Operation parameters
639 final public function quickStore( array $params ) {
640 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
644 * Performs a single quick copy operation.
645 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
647 * @see FileBackend::doQuickOperation()
649 * @param array $params Operation parameters
653 final public function quickCopy( array $params ) {
654 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
658 * Performs a single quick move operation.
659 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
661 * @see FileBackend::doQuickOperation()
663 * @param array $params Operation parameters
667 final public function quickMove( array $params ) {
668 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
672 * Performs a single quick delete operation.
673 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
675 * @see FileBackend::doQuickOperation()
677 * @param array $params Operation parameters
681 final public function quickDelete( array $params ) {
682 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
686 * Performs a single quick describe operation.
687 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
689 * @see FileBackend::doQuickOperation()
691 * @param array $params Operation parameters
695 final public function quickDescribe( array $params ) {
696 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
700 * Concatenate a list of storage files into a single file system file.
701 * The target path should refer to a file that is already locked or
702 * otherwise safe from modification from other processes. Normally,
703 * the file will be a new temp file, which should be adequate.
705 * @param array $params Operation parameters, include:
706 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
707 * - dst : file system path to 0-byte temp file
708 * - parallelize : try to do operations in parallel when possible
711 abstract public function concatenate( array $params );
714 * Prepare a storage directory for usage.
715 * This will create any required containers and parent directories.
716 * Backends using key/value stores only need to create the container.
718 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
719 * except they are only applied *if* the directory/container had to be created.
720 * These flags should always be set for directories that have private files.
721 * However, setting them is not guaranteed to actually do anything.
722 * Additional server configuration may be needed to achieve the desired effect.
724 * @param array $params Parameters include:
725 * - dir : storage directory
726 * - noAccess : try to deny file access (since 1.20)
727 * - noListing : try to deny file listing (since 1.20)
728 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
731 final public function prepare( array $params ) {
732 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
733 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
735 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
736 return $this->doPrepare( $params );
740 * @see FileBackend::prepare()
742 abstract protected function doPrepare( array $params );
745 * Take measures to block web access to a storage directory and
746 * the container it belongs to. FS backends might add .htaccess
747 * files whereas key/value store backends might revoke container
748 * access to the storage user representing end-users in web requests.
750 * This is not guaranteed to actually make files or listings publically hidden.
751 * Additional server configuration may be needed to achieve the desired effect.
753 * @param array $params Parameters include:
754 * - dir : storage directory
755 * - noAccess : try to deny file access
756 * - noListing : try to deny file listing
757 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
760 final public function secure( array $params ) {
761 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
762 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
764 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
765 return $this->doSecure( $params );
769 * @see FileBackend::secure()
771 abstract protected function doSecure( array $params );
774 * Remove measures to block web access to a storage directory and
775 * the container it belongs to. FS backends might remove .htaccess
776 * files whereas key/value store backends might grant container
777 * access to the storage user representing end-users in web requests.
778 * This essentially can undo the result of secure() calls.
780 * This is not guaranteed to actually make files or listings publically viewable.
781 * Additional server configuration may be needed to achieve the desired effect.
783 * @param array $params Parameters include:
784 * - dir : storage directory
785 * - access : try to allow file access
786 * - listing : try to allow file listing
787 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
791 final public function publish( array $params ) {
792 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
793 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
795 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
796 return $this->doPublish( $params );
800 * @see FileBackend::publish()
802 abstract protected function doPublish( array $params );
805 * Delete a storage directory if it is empty.
806 * Backends using key/value stores may do nothing unless the directory
807 * is that of an empty container, in which case it will be deleted.
809 * @param array $params Parameters include:
810 * - dir : storage directory
811 * - recursive : recursively delete empty subdirectories first (since 1.20)
812 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
815 final public function clean( array $params ) {
816 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
817 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
819 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
820 return $this->doClean( $params );
824 * @see FileBackend::clean()
826 abstract protected function doClean( array $params );
829 * Enter file operation scope.
830 * This just makes PHP ignore user aborts/disconnects until the return
831 * value leaves scope. This returns null and does nothing in CLI mode.
833 * @return ScopedCallback|null
835 final protected function getScopedPHPBehaviorForOps() {
836 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
837 $old = ignore_user_abort( true ); // avoid half-finished operations
838 return new ScopedCallback( function () use ( $old ) {
839 ignore_user_abort( $old );
847 * Check if a file exists at a storage path in the backend.
848 * This returns false if only a directory exists at the path.
850 * @param array $params Parameters include:
851 * - src : source storage path
852 * - latest : use the latest available data
853 * @return bool|null Returns null on failure
855 abstract public function fileExists( array $params );
858 * Get the last-modified timestamp of the file at a storage path.
860 * @param array $params Parameters include:
861 * - src : source storage path
862 * - latest : use the latest available data
863 * @return string|bool TS_MW timestamp or false on failure
865 abstract public function getFileTimestamp( array $params );
868 * Get the contents of a file at a storage path in the backend.
869 * This should be avoided for potentially large files.
871 * @param array $params Parameters include:
872 * - src : source storage path
873 * - latest : use the latest available data
874 * @return string|bool Returns false on failure
876 final public function getFileContents( array $params ) {
877 $contents = $this->getFileContentsMulti(
878 array( 'srcs' => array( $params['src'] ) ) +
$params );
880 return $contents[$params['src']];
884 * Like getFileContents() except it takes an array of storage paths
885 * and returns a map of storage paths to strings (or null on failure).
886 * The map keys (paths) are in the same order as the provided list of paths.
888 * @see FileBackend::getFileContents()
890 * @param array $params Parameters include:
891 * - srcs : list of source storage paths
892 * - latest : use the latest available data
893 * - parallelize : try to do operations in parallel when possible
894 * @return array Map of (path name => string or false on failure)
897 abstract public function getFileContentsMulti( array $params );
900 * Get the size (bytes) of a file at a storage path in the backend.
902 * @param array $params Parameters include:
903 * - src : source storage path
904 * - latest : use the latest available data
905 * @return int|bool Returns false on failure
907 abstract public function getFileSize( array $params );
910 * Get quick information about a file at a storage path in the backend.
911 * If the file does not exist, then this returns false.
912 * Otherwise, the result is an associative array that includes:
913 * - mtime : the last-modified timestamp (TS_MW)
914 * - size : the file size (bytes)
915 * Additional values may be included for internal use only.
917 * @param array $params Parameters include:
918 * - src : source storage path
919 * - latest : use the latest available data
920 * @return array|bool|null Returns null on failure
922 abstract public function getFileStat( array $params );
925 * Get a SHA-1 hash of the file at a storage path in the backend.
927 * @param array $params Parameters include:
928 * - src : source storage path
929 * - latest : use the latest available data
930 * @return string|bool Hash string or false on failure
932 abstract public function getFileSha1Base36( array $params );
935 * Get the properties of the file at a storage path in the backend.
936 * This gives the result of FSFile::getProps() on a local copy of the file.
938 * @param array $params Parameters include:
939 * - src : source storage path
940 * - latest : use the latest available data
941 * @return array Returns FSFile::placeholderProps() on failure
943 abstract public function getFileProps( array $params );
946 * Stream the file at a storage path in the backend.
947 * If the file does not exists, an HTTP 404 error will be given.
948 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
949 * will be sent if streaming began, while none will be sent otherwise.
950 * Implementations should flush the output buffer before sending data.
952 * @param array $params Parameters include:
953 * - src : source storage path
954 * - headers : list of additional HTTP headers to send on success
955 * - latest : use the latest available data
958 abstract public function streamFile( array $params );
961 * Returns a file system file, identical to the file at a storage path.
962 * The file returned is either:
963 * - a) A local copy of the file at a storage path in the backend.
964 * The temporary copy will have the same extension as the source.
965 * - b) An original of the file at a storage path in the backend.
966 * Temporary files may be purged when the file object falls out of scope.
968 * Write operations should *never* be done on this file as some backends
969 * may do internal tracking or may be instances of FileBackendMultiWrite.
970 * In that later case, there are copies of the file that must stay in sync.
971 * Additionally, further calls to this function may return the same file.
973 * @param array $params Parameters include:
974 * - src : source storage path
975 * - latest : use the latest available data
976 * @return FSFile|null Returns null on failure
978 final public function getLocalReference( array $params ) {
979 $fsFiles = $this->getLocalReferenceMulti(
980 array( 'srcs' => array( $params['src'] ) ) +
$params );
982 return $fsFiles[$params['src']];
986 * Like getLocalReference() except it takes an array of storage paths
987 * and returns a map of storage paths to FSFile objects (or null on failure).
988 * The map keys (paths) are in the same order as the provided list of paths.
990 * @see FileBackend::getLocalReference()
992 * @param array $params Parameters include:
993 * - srcs : list of source storage paths
994 * - latest : use the latest available data
995 * - parallelize : try to do operations in parallel when possible
996 * @return array Map of (path name => FSFile or null on failure)
999 abstract public function getLocalReferenceMulti( array $params );
1002 * Get a local copy on disk of the file at a storage path in the backend.
1003 * The temporary copy will have the same file extension as the source.
1004 * Temporary files may be purged when the file object falls out of scope.
1006 * @param array $params Parameters include:
1007 * - src : source storage path
1008 * - latest : use the latest available data
1009 * @return TempFSFile|null Returns null on failure
1011 final public function getLocalCopy( array $params ) {
1012 $tmpFiles = $this->getLocalCopyMulti(
1013 array( 'srcs' => array( $params['src'] ) ) +
$params );
1015 return $tmpFiles[$params['src']];
1019 * Like getLocalCopy() except it takes an array of storage paths and
1020 * returns a map of storage paths to TempFSFile objects (or null on failure).
1021 * The map keys (paths) are in the same order as the provided list of paths.
1023 * @see FileBackend::getLocalCopy()
1025 * @param array $params Parameters include:
1026 * - srcs : list of source storage paths
1027 * - latest : use the latest available data
1028 * - parallelize : try to do operations in parallel when possible
1029 * @return array Map of (path name => TempFSFile or null on failure)
1032 abstract public function getLocalCopyMulti( array $params );
1035 * Return an HTTP URL to a given file that requires no authentication to use.
1036 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1037 * This will return null if the backend cannot make an HTTP URL for the file.
1039 * This is useful for key/value stores when using scripts that seek around
1040 * large files and those scripts (and the backend) support HTTP Range headers.
1041 * Otherwise, one would need to use getLocalReference(), which involves loading
1042 * the entire file on to local disk.
1044 * @param array $params Parameters include:
1045 * - src : source storage path
1046 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1047 * @return string|null
1050 abstract public function getFileHttpUrl( array $params );
1053 * Check if a directory exists at a given storage path.
1054 * Backends using key/value stores will check if the path is a
1055 * virtual directory, meaning there are files under the given directory.
1057 * Storage backends with eventual consistency might return stale data.
1059 * @param array $params Parameters include:
1060 * - dir : storage directory
1061 * @return bool|null Returns null on failure
1064 abstract public function directoryExists( array $params );
1067 * Get an iterator to list *all* directories under a storage directory.
1068 * If the directory is of the form "mwstore://backend/container",
1069 * then all directories in the container will be listed.
1070 * If the directory is of form "mwstore://backend/container/dir",
1071 * then all directories directly under that directory will be listed.
1072 * Results will be storage directories relative to the given directory.
1074 * Storage backends with eventual consistency might return stale data.
1076 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1078 * @param array $params Parameters include:
1079 * - dir : storage directory
1080 * - topOnly : only return direct child dirs of the directory
1081 * @return Traversable|Array|null Returns null on failure
1084 abstract public function getDirectoryList( array $params );
1087 * Same as FileBackend::getDirectoryList() except only lists
1088 * directories that are immediately under the given directory.
1090 * Storage backends with eventual consistency might return stale data.
1092 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1094 * @param array $params Parameters include:
1095 * - dir : storage directory
1096 * @return Traversable|Array|null Returns null on failure
1099 final public function getTopDirectoryList( array $params ) {
1100 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1104 * Get an iterator to list *all* stored files under a storage directory.
1105 * If the directory is of the form "mwstore://backend/container",
1106 * then all files in the container will be listed.
1107 * If the directory is of form "mwstore://backend/container/dir",
1108 * then all files under that directory will be listed.
1109 * Results will be storage paths relative to the given directory.
1111 * Storage backends with eventual consistency might return stale data.
1113 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1115 * @param array $params Parameters include:
1116 * - dir : storage directory
1117 * - topOnly : only return direct child files of the directory (since 1.20)
1118 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1119 * @return Traversable|Array|null Returns null on failure
1121 abstract public function getFileList( array $params );
1124 * Same as FileBackend::getFileList() except only lists
1125 * files that are immediately under the given directory.
1127 * Storage backends with eventual consistency might return stale data.
1129 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1131 * @param array $params Parameters include:
1132 * - dir : storage directory
1133 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1134 * @return Traversable|Array|null Returns null on failure
1137 final public function getTopFileList( array $params ) {
1138 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1142 * Preload persistent file stat and property cache into in-process cache.
1143 * This should be used when stat calls will be made on a known list of a many files.
1145 * @param array $paths Storage paths
1147 public function preloadCache( array $paths ) {
1151 * Invalidate any in-process file stat and property cache.
1152 * If $paths is given, then only the cache for those files will be cleared.
1154 * @param array $paths Storage paths (optional)
1156 public function clearCache( array $paths = null ) {
1160 * Lock the files at the given storage paths in the backend.
1161 * This will either lock all the files or none (on failure).
1163 * Callers should consider using getScopedFileLocks() instead.
1165 * @param array $paths Storage paths
1166 * @param int $type LockManager::LOCK_* constant
1169 final public function lockFiles( array $paths, $type ) {
1170 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1172 return $this->lockManager
->lock( $paths, $type );
1176 * Unlock the files at the given storage paths in the backend.
1178 * @param array $paths Storage paths
1179 * @param int $type LockManager::LOCK_* constant
1182 final public function unlockFiles( array $paths, $type ) {
1183 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1185 return $this->lockManager
->unlock( $paths, $type );
1189 * Lock the files at the given storage paths in the backend.
1190 * This will either lock all the files or none (on failure).
1191 * On failure, the status object will be updated with errors.
1193 * Once the return value goes out scope, the locks will be released and
1194 * the status updated. Unlock fatals will not change the status "OK" value.
1196 * @see ScopedLock::factory()
1198 * @param array $paths List of storage paths or map of lock types to path lists
1199 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1200 * @param Status $status Status to update on lock/unlock
1201 * @return ScopedLock|null Returns null on failure
1203 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1204 if ( $type === 'mixed' ) {
1205 foreach ( $paths as &$typePaths ) {
1206 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1209 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1212 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1216 * Get an array of scoped locks needed for a batch of file operations.
1218 * Normally, FileBackend::doOperations() handles locking, unless
1219 * the 'nonLocking' param is passed in. This function is useful if you
1220 * want the files to be locked for a broader scope than just when the
1221 * files are changing. For example, if you need to update DB metadata,
1222 * you may want to keep the files locked until finished.
1224 * @see FileBackend::doOperations()
1226 * @param array $ops List of file operations to FileBackend::doOperations()
1227 * @param Status $status Status to update on lock/unlock
1228 * @return array List of ScopedFileLocks or null values
1231 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1234 * Get the root storage path of this backend.
1235 * All container paths are "subdirectories" of this path.
1237 * @return string Storage path
1240 final public function getRootStoragePath() {
1241 return "mwstore://{$this->name}";
1245 * Get the storage path for the given container for this backend
1247 * @param string $container Container name
1248 * @return string Storage path
1251 final public function getContainerStoragePath( $container ) {
1252 return $this->getRootStoragePath() . "/{$container}";
1256 * Get the file journal object for this backend
1258 * @return FileJournal
1260 final public function getJournal() {
1261 return $this->fileJournal
;
1265 * Check if a given path is a "mwstore://" path.
1266 * This does not do any further validation or any existence checks.
1268 * @param string $path
1271 final public static function isStoragePath( $path ) {
1272 return ( strpos( $path, 'mwstore://' ) === 0 );
1276 * Split a storage path into a backend name, a container name,
1277 * and a relative file path. The relative path may be the empty string.
1278 * This does not do any path normalization or traversal checks.
1280 * @param string $storagePath
1281 * @return array (backend, container, rel object) or (null, null, null)
1283 final public static function splitStoragePath( $storagePath ) {
1284 if ( self
::isStoragePath( $storagePath ) ) {
1285 // Remove the "mwstore://" prefix and split the path
1286 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1287 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1288 if ( count( $parts ) == 3 ) {
1289 return $parts; // e.g. "backend/container/path"
1291 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1296 return array( null, null, null );
1300 * Normalize a storage path by cleaning up directory separators.
1301 * Returns null if the path is not of the format of a valid storage path.
1303 * @param string $storagePath
1304 * @return string|null
1306 final public static function normalizeStoragePath( $storagePath ) {
1307 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1308 if ( $relPath !== null ) { // must be for this backend
1309 $relPath = self
::normalizeContainerPath( $relPath );
1310 if ( $relPath !== null ) {
1311 return ( $relPath != '' )
1312 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1313 : "mwstore://{$backend}/{$container}";
1321 * Get the parent storage directory of a storage path.
1322 * This returns a path like "mwstore://backend/container",
1323 * "mwstore://backend/container/...", or null if there is no parent.
1325 * @param string $storagePath
1326 * @return string|null
1328 final public static function parentStoragePath( $storagePath ) {
1329 $storagePath = dirname( $storagePath );
1330 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1332 return ( $rel === null ) ?
null : $storagePath;
1336 * Get the final extension from a storage or FS path
1338 * @param string $path
1341 final public static function extensionFromPath( $path ) {
1342 $i = strrpos( $path, '.' );
1344 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1348 * Check if a relative path has no directory traversals
1350 * @param string $path
1354 final public static function isPathTraversalFree( $path ) {
1355 return ( self
::normalizeContainerPath( $path ) !== null );
1359 * Build a Content-Disposition header value per RFC 6266.
1361 * @param string $type One of (attachment, inline)
1362 * @param string $filename Suggested file name (should not contain slashes)
1363 * @throws MWException
1367 final public static function makeContentDisposition( $type, $filename = '' ) {
1370 $type = strtolower( $type );
1371 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1372 throw new MWException( "Invalid Content-Disposition type '$type'." );
1376 if ( strlen( $filename ) ) {
1377 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1380 return implode( ';', $parts );
1384 * Validate and normalize a relative storage path.
1385 * Null is returned if the path involves directory traversal.
1386 * Traversal is insecure for FS backends and broken for others.
1388 * This uses the same traversal protection as Title::secureAndSplit().
1390 * @param string $path Storage path relative to a container
1391 * @return string|null
1393 final protected static function normalizeContainerPath( $path ) {
1394 // Normalize directory separators
1395 $path = strtr( $path, '\\', '/' );
1396 // Collapse any consecutive directory separators
1397 $path = preg_replace( '![/]{2,}!', '/', $path );
1398 // Remove any leading directory separator
1399 $path = ltrim( $path, '/' );
1400 // Use the same traversal protection as Title::secureAndSplit()
1401 if ( strpos( $path, '.' ) !== false ) {
1405 strpos( $path, './' ) === 0 ||
1406 strpos( $path, '../' ) === 0 ||
1407 strpos( $path, '/./' ) !== false ||
1408 strpos( $path, '/../' ) !== false
1419 * @ingroup FileBackend
1422 class FileBackendError
extends MWException
{