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;
107 /** Bitfield flags for supported features */
108 const ATTR_HEADERS
= 1; // files can be tagged with standard HTTP headers
109 const ATTR_METADATA
= 2; // files can be stored with metadata key/values
110 const ATTR_UNICODE_PATHS
= 4; // files can have Unicode paths (not just ASCII)
113 * Create a new backend instance from configuration.
114 * This should only be called from within FileBackendGroup.
116 * @param array $config Parameters include:
117 * - name : The unique name of this backend.
118 * This should consist of alphanumberic, '-', and '_' characters.
119 * This name should not be changed after use (e.g. with journaling).
120 * Note that the name is *not* used in actual container names.
121 * - wikiId : Prefix to container names that is unique to this backend.
122 * It should only consist of alphanumberic, '-', and '_' characters.
123 * This ID is what avoids collisions if multiple logical backends
124 * use the same storage system, so this should be set carefully.
125 * - lockManager : LockManager object to use for any file locking.
126 * If not provided, then no file locking will be enforced.
127 * - fileJournal : FileJournal object to use for logging changes to files.
128 * If not provided, then change journaling will be disabled.
129 * - readOnly : Write operations are disallowed if this is a non-empty string.
130 * It should be an explanation for the backend being read-only.
131 * - parallelize : When to do file operations in parallel (when possible).
132 * Allowed values are "implicit", "explicit" and "off".
133 * - concurrency : How many file operations can be done in parallel.
134 * @throws FileBackendException
136 public function __construct( array $config ) {
137 $this->name
= $config['name'];
138 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
139 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
140 throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
141 } elseif ( !is_string( $this->wikiId
) ) {
142 throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
144 $this->lockManager
= isset( $config['lockManager'] )
145 ?
$config['lockManager']
146 : new NullLockManager( [] );
147 $this->fileJournal
= isset( $config['fileJournal'] )
148 ?
$config['fileJournal']
149 : FileJournal
::factory( [ 'class' => 'NullFileJournal' ], $this->name
);
150 $this->readOnly
= isset( $config['readOnly'] )
151 ?
(string)$config['readOnly']
153 $this->parallelize
= isset( $config['parallelize'] )
154 ?
(string)$config['parallelize']
156 $this->concurrency
= isset( $config['concurrency'] )
157 ?
(int)$config['concurrency']
162 * Get the unique backend name.
163 * We may have multiple different backends of the same type.
164 * For example, we can have two Swift backends using different proxies.
168 final public function getName() {
173 * Get the wiki identifier used for this backend (possibly empty).
174 * Note that this might *not* be in the same format as wfWikiID().
179 final public function getWikiId() {
180 return $this->wikiId
;
184 * Check if this backend is read-only
188 final public function isReadOnly() {
189 return ( $this->readOnly
!= '' );
193 * Get an explanatory message if this backend is read-only
195 * @return string|bool Returns false if the backend is not read-only
197 final public function getReadOnlyReason() {
198 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
202 * Get the a bitfield of extra features supported by the backend medium
204 * @return int Bitfield of FileBackend::ATTR_* flags
207 public function getFeatures() {
208 return self
::ATTR_UNICODE_PATHS
;
212 * Check if the backend medium supports a field of extra features
214 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
218 final public function hasFeatures( $bitfield ) {
219 return ( $this->getFeatures() & $bitfield ) === $bitfield;
223 * This is the main entry point into the backend for write operations.
224 * Callers supply an ordered list of operations to perform as a transaction.
225 * Files will be locked, the stat cache cleared, and then the operations attempted.
226 * If any serious errors occur, all attempted operations will be rolled back.
228 * $ops is an array of arrays. The outer array holds a list of operations.
229 * Each inner array is a set of key value pairs that specify an operation.
231 * Supported operations and their parameters. The supported actions are:
237 * - describe (since 1.21)
240 * FSFile/TempFSFile object support was added in 1.27.
242 * a) Create a new file in storage with the contents of a string
246 * 'dst' => <storage path>,
247 * 'content' => <string of new file contents>,
248 * 'overwrite' => <boolean>,
249 * 'overwriteSame' => <boolean>,
250 * 'headers' => <HTTP header name/value map> # since 1.21
254 * b) Copy a file system file into storage
258 * 'src' => <file system path, FSFile, or TempFSFile>,
259 * 'dst' => <storage path>,
260 * 'overwrite' => <boolean>,
261 * 'overwriteSame' => <boolean>,
262 * 'headers' => <HTTP header name/value map> # since 1.21
266 * c) Copy a file within storage
270 * 'src' => <storage path>,
271 * 'dst' => <storage path>,
272 * 'overwrite' => <boolean>,
273 * 'overwriteSame' => <boolean>,
274 * 'ignoreMissingSource' => <boolean>, # since 1.21
275 * 'headers' => <HTTP header name/value map> # since 1.21
279 * d) Move a file within storage
283 * 'src' => <storage path>,
284 * 'dst' => <storage path>,
285 * 'overwrite' => <boolean>,
286 * 'overwriteSame' => <boolean>,
287 * 'ignoreMissingSource' => <boolean>, # since 1.21
288 * 'headers' => <HTTP header name/value map> # since 1.21
292 * e) Delete a file within storage
296 * 'src' => <storage path>,
297 * 'ignoreMissingSource' => <boolean>
301 * f) Update metadata for a file within storage
304 * 'op' => 'describe',
305 * 'src' => <storage path>,
306 * 'headers' => <HTTP header name/value map>
310 * g) Do nothing (no-op)
317 * Boolean flags for operations (operation-specific):
318 * - ignoreMissingSource : The operation will simply succeed and do
319 * nothing if the source file does not exist.
320 * - overwrite : Any destination file will be overwritten.
321 * - overwriteSame : If a file already exists at the destination with the
322 * same contents, then do nothing to the destination file
323 * instead of giving an error. This does not compare headers.
324 * This option is ignored if 'overwrite' is already provided.
325 * - headers : If supplied, the result of merging these headers with any
326 * existing source file headers (replacing conflicting ones)
327 * will be set as the destination file headers. Headers are
328 * deleted if their value is set to the empty string. When a
329 * file has headers they are included in responses to GET and
330 * HEAD requests to the backing store for that file.
331 * Header values should be no larger than 255 bytes, except for
332 * Content-Disposition. The system might ignore or truncate any
333 * headers that are too long to store (exact limits will vary).
334 * Backends that don't support metadata ignore this. (since 1.21)
336 * $opts is an associative of boolean flags, including:
337 * - force : Operation precondition errors no longer trigger an abort.
338 * Any remaining operations are still attempted. Unexpected
339 * failures may still cause remaining operations to be aborted.
340 * - nonLocking : No locks are acquired for the operations.
341 * This can increase performance for non-critical writes.
342 * This has no effect unless the 'force' flag is set.
343 * - nonJournaled : Don't log this operation batch in the file journal.
344 * This limits the ability of recovery scripts.
345 * - parallelize : Try to do operations in parallel when possible.
346 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
347 * - preserveCache : Don't clear the process cache before checking files.
348 * This should only be used if all entries in the process
349 * cache were added after the files were already locked. (since 1.20)
351 * @remarks Remarks on locking:
352 * File system paths given to operations should refer to files that are
353 * already locked or otherwise safe from modification from other processes.
354 * Normally these files will be new temp files, which should be adequate.
358 * This returns a Status, which contains all warnings and fatals that occurred
359 * during the operation. The 'failCount', 'successCount', and 'success' members
360 * will reflect each operation attempted.
362 * The status will be "OK" unless:
363 * - a) unexpected operation errors occurred (network partitions, disk full...)
364 * - b) significant operation errors occurred and 'force' was not set
366 * @param array $ops List of operations to execute in order
367 * @param array $opts Batch operation options
370 final public function doOperations( array $ops, array $opts = [] ) {
371 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
372 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
374 if ( !count( $ops ) ) {
375 return Status
::newGood(); // nothing to do
378 $ops = $this->resolveFSFileObjects( $ops );
379 if ( empty( $opts['force'] ) ) { // sanity
380 unset( $opts['nonLocking'] );
383 /** @noinspection PhpUnusedLocalVariableInspection */
384 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
386 return $this->doOperationsInternal( $ops, $opts );
390 * @see FileBackend::doOperations()
394 abstract protected function doOperationsInternal( array $ops, array $opts );
397 * Same as doOperations() except it takes a single operation.
398 * If you are doing a batch of operations that should either
399 * all succeed or all fail, then use that function instead.
401 * @see FileBackend::doOperations()
403 * @param array $op Operation
404 * @param array $opts Operation options
407 final public function doOperation( array $op, array $opts = [] ) {
408 return $this->doOperations( [ $op ], $opts );
412 * Performs a single create operation.
413 * This sets $params['op'] to 'create' 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 create( array $params, array $opts = [] ) {
422 return $this->doOperation( [ 'op' => 'create' ] +
$params, $opts );
426 * Performs a single store operation.
427 * This sets $params['op'] to 'store' 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 store( array $params, array $opts = [] ) {
436 return $this->doOperation( [ 'op' => 'store' ] +
$params, $opts );
440 * Performs a single copy operation.
441 * This sets $params['op'] to 'copy' 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 copy( array $params, array $opts = [] ) {
450 return $this->doOperation( [ 'op' => 'copy' ] +
$params, $opts );
454 * Performs a single move operation.
455 * This sets $params['op'] to 'move' and passes it to doOperation().
457 * @see FileBackend::doOperation()
459 * @param array $params Operation parameters
460 * @param array $opts Operation options
463 final public function move( array $params, array $opts = [] ) {
464 return $this->doOperation( [ 'op' => 'move' ] +
$params, $opts );
468 * Performs a single delete operation.
469 * This sets $params['op'] to 'delete' and passes it to doOperation().
471 * @see FileBackend::doOperation()
473 * @param array $params Operation parameters
474 * @param array $opts Operation options
477 final public function delete( array $params, array $opts = [] ) {
478 return $this->doOperation( [ 'op' => 'delete' ] +
$params, $opts );
482 * Performs a single describe operation.
483 * This sets $params['op'] to 'describe' and passes it to doOperation().
485 * @see FileBackend::doOperation()
487 * @param array $params Operation parameters
488 * @param array $opts Operation options
492 final public function describe( array $params, array $opts = [] ) {
493 return $this->doOperation( [ 'op' => 'describe' ] +
$params, $opts );
497 * Perform a set of independent file operations on some files.
499 * This does no locking, nor journaling, and possibly no stat calls.
500 * Any destination files that already exist will be overwritten.
501 * This should *only* be used on non-original files, like cache files.
503 * Supported operations and their parameters:
509 * - describe (since 1.21)
512 * FSFile/TempFSFile object support was added in 1.27.
514 * a) Create a new file in storage with the contents of a string
518 * 'dst' => <storage path>,
519 * 'content' => <string of new file contents>,
520 * 'headers' => <HTTP header name/value map> # since 1.21
524 * b) Copy a file system file into storage
528 * 'src' => <file system path, FSFile, or TempFSFile>,
529 * 'dst' => <storage path>,
530 * 'headers' => <HTTP header name/value map> # since 1.21
534 * c) Copy a file within storage
538 * 'src' => <storage path>,
539 * 'dst' => <storage path>,
540 * 'ignoreMissingSource' => <boolean>, # since 1.21
541 * 'headers' => <HTTP header name/value map> # since 1.21
545 * d) Move a file within storage
549 * 'src' => <storage path>,
550 * 'dst' => <storage path>,
551 * 'ignoreMissingSource' => <boolean>, # since 1.21
552 * 'headers' => <HTTP header name/value map> # since 1.21
556 * e) Delete a file within storage
560 * 'src' => <storage path>,
561 * 'ignoreMissingSource' => <boolean>
565 * f) Update metadata for a file within storage
568 * 'op' => 'describe',
569 * 'src' => <storage path>,
570 * 'headers' => <HTTP header name/value map>
574 * g) Do nothing (no-op)
581 * @par Boolean flags for operations (operation-specific):
582 * - ignoreMissingSource : The operation will simply succeed and do
583 * nothing if the source file does not exist.
584 * - headers : If supplied with a header name/value map, the backend will
585 * reply with these headers when GETs/HEADs of the destination
586 * file are made. Header values should be smaller than 256 bytes.
587 * Content-Disposition headers can be longer, though the system
588 * might ignore or truncate ones that are too long to store.
589 * Existing headers will remain, but these will replace any
590 * conflicting previous headers, and headers will be removed
591 * if they are set to an empty string.
592 * Backends that don't support metadata ignore this. (since 1.21)
594 * $opts is an associative of boolean flags, including:
595 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
598 * This returns a Status, which contains all warnings and fatals that occurred
599 * during the operation. The 'failCount', 'successCount', and 'success' members
600 * will reflect each operation attempted for the given files. The status will be
601 * considered "OK" as long as no fatal errors occurred.
603 * @param array $ops Set of operations to execute
604 * @param array $opts Batch operation options
608 final public function doQuickOperations( array $ops, array $opts = [] ) {
609 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
610 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
612 if ( !count( $ops ) ) {
613 return Status
::newGood(); // nothing to do
616 $ops = $this->resolveFSFileObjects( $ops );
617 foreach ( $ops as &$op ) {
618 $op['overwrite'] = true; // avoids RTTs in key/value stores
621 /** @noinspection PhpUnusedLocalVariableInspection */
622 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
624 return $this->doQuickOperationsInternal( $ops );
628 * @see FileBackend::doQuickOperations()
632 abstract protected function doQuickOperationsInternal( array $ops );
635 * Same as doQuickOperations() except it takes a single operation.
636 * If you are doing a batch of operations, then use that function instead.
638 * @see FileBackend::doQuickOperations()
640 * @param array $op Operation
644 final public function doQuickOperation( array $op ) {
645 return $this->doQuickOperations( [ $op ] );
649 * Performs a single quick create operation.
650 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
652 * @see FileBackend::doQuickOperation()
654 * @param array $params Operation parameters
658 final public function quickCreate( array $params ) {
659 return $this->doQuickOperation( [ 'op' => 'create' ] +
$params );
663 * Performs a single quick store operation.
664 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
666 * @see FileBackend::doQuickOperation()
668 * @param array $params Operation parameters
672 final public function quickStore( array $params ) {
673 return $this->doQuickOperation( [ 'op' => 'store' ] +
$params );
677 * Performs a single quick copy operation.
678 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
680 * @see FileBackend::doQuickOperation()
682 * @param array $params Operation parameters
686 final public function quickCopy( array $params ) {
687 return $this->doQuickOperation( [ 'op' => 'copy' ] +
$params );
691 * Performs a single quick move operation.
692 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
694 * @see FileBackend::doQuickOperation()
696 * @param array $params Operation parameters
700 final public function quickMove( array $params ) {
701 return $this->doQuickOperation( [ 'op' => 'move' ] +
$params );
705 * Performs a single quick delete operation.
706 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
708 * @see FileBackend::doQuickOperation()
710 * @param array $params Operation parameters
714 final public function quickDelete( array $params ) {
715 return $this->doQuickOperation( [ 'op' => 'delete' ] +
$params );
719 * Performs a single quick describe operation.
720 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
722 * @see FileBackend::doQuickOperation()
724 * @param array $params Operation parameters
728 final public function quickDescribe( array $params ) {
729 return $this->doQuickOperation( [ 'op' => 'describe' ] +
$params );
733 * Concatenate a list of storage files into a single file system file.
734 * The target path should refer to a file that is already locked or
735 * otherwise safe from modification from other processes. Normally,
736 * the file will be a new temp file, which should be adequate.
738 * @param array $params Operation parameters, include:
739 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
740 * - dst : file system path to 0-byte temp file
741 * - parallelize : try to do operations in parallel when possible
744 abstract public function concatenate( array $params );
747 * Prepare a storage directory for usage.
748 * This will create any required containers and parent directories.
749 * Backends using key/value stores only need to create the container.
751 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
752 * except they are only applied *if* the directory/container had to be created.
753 * These flags should always be set for directories that have private files.
754 * However, setting them is not guaranteed to actually do anything.
755 * Additional server configuration may be needed to achieve the desired effect.
757 * @param array $params Parameters include:
758 * - dir : storage directory
759 * - noAccess : try to deny file access (since 1.20)
760 * - noListing : try to deny file listing (since 1.20)
761 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
764 final public function prepare( array $params ) {
765 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
766 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
768 /** @noinspection PhpUnusedLocalVariableInspection */
769 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
770 return $this->doPrepare( $params );
774 * @see FileBackend::prepare()
775 * @param array $params
777 abstract protected function doPrepare( array $params );
780 * Take measures to block web access to a storage directory and
781 * the container it belongs to. FS backends might add .htaccess
782 * files whereas key/value store backends might revoke container
783 * access to the storage user representing end-users in web requests.
785 * This is not guaranteed to actually make files or listings publically hidden.
786 * Additional server configuration may be needed to achieve the desired effect.
788 * @param array $params Parameters include:
789 * - dir : storage directory
790 * - noAccess : try to deny file access
791 * - noListing : try to deny file listing
792 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
795 final public function secure( array $params ) {
796 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
797 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
799 /** @noinspection PhpUnusedLocalVariableInspection */
800 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
801 return $this->doSecure( $params );
805 * @see FileBackend::secure()
806 * @param array $params
808 abstract protected function doSecure( array $params );
811 * Remove measures to block web access to a storage directory and
812 * the container it belongs to. FS backends might remove .htaccess
813 * files whereas key/value store backends might grant container
814 * access to the storage user representing end-users in web requests.
815 * This essentially can undo the result of secure() calls.
817 * This is not guaranteed to actually make files or listings publically viewable.
818 * Additional server configuration may be needed to achieve the desired effect.
820 * @param array $params Parameters include:
821 * - dir : storage directory
822 * - access : try to allow file access
823 * - listing : try to allow file listing
824 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
828 final public function publish( array $params ) {
829 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
830 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
832 /** @noinspection PhpUnusedLocalVariableInspection */
833 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
834 return $this->doPublish( $params );
838 * @see FileBackend::publish()
839 * @param array $params
841 abstract protected function doPublish( array $params );
844 * Delete a storage directory if it is empty.
845 * Backends using key/value stores may do nothing unless the directory
846 * is that of an empty container, in which case it will be deleted.
848 * @param array $params Parameters include:
849 * - dir : storage directory
850 * - recursive : recursively delete empty subdirectories first (since 1.20)
851 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
854 final public function clean( array $params ) {
855 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
856 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
858 /** @noinspection PhpUnusedLocalVariableInspection */
859 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
860 return $this->doClean( $params );
864 * @see FileBackend::clean()
865 * @param array $params
867 abstract protected function doClean( array $params );
870 * Enter file operation scope.
871 * This just makes PHP ignore user aborts/disconnects until the return
872 * value leaves scope. This returns null and does nothing in CLI mode.
874 * @return ScopedCallback|null
876 final protected function getScopedPHPBehaviorForOps() {
877 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
878 $old = ignore_user_abort( true ); // avoid half-finished operations
879 return new ScopedCallback( function () use ( $old ) {
880 ignore_user_abort( $old );
888 * Check if a file exists at a storage path in the backend.
889 * This returns false if only a directory exists at the path.
891 * @param array $params Parameters include:
892 * - src : source storage path
893 * - latest : use the latest available data
894 * @return bool|null Returns null on failure
896 abstract public function fileExists( array $params );
899 * Get the last-modified timestamp of the file at a storage path.
901 * @param array $params Parameters include:
902 * - src : source storage path
903 * - latest : use the latest available data
904 * @return string|bool TS_MW timestamp or false on failure
906 abstract public function getFileTimestamp( array $params );
909 * Get the contents of a file at a storage path in the backend.
910 * This should be avoided for potentially large files.
912 * @param array $params Parameters include:
913 * - src : source storage path
914 * - latest : use the latest available data
915 * @return string|bool Returns false on failure
917 final public function getFileContents( array $params ) {
918 $contents = $this->getFileContentsMulti(
919 [ 'srcs' => [ $params['src'] ] ] +
$params );
921 return $contents[$params['src']];
925 * Like getFileContents() except it takes an array of storage paths
926 * and returns a map of storage paths to strings (or null on failure).
927 * The map keys (paths) are in the same order as the provided list of paths.
929 * @see FileBackend::getFileContents()
931 * @param array $params Parameters include:
932 * - srcs : list of source storage paths
933 * - latest : use the latest available data
934 * - parallelize : try to do operations in parallel when possible
935 * @return array Map of (path name => string or false on failure)
938 abstract public function getFileContentsMulti( array $params );
941 * Get metadata about a file at a storage path in the backend.
942 * If the file does not exist, then this returns false.
943 * Otherwise, the result is an associative array that includes:
944 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
945 * - metadata : map of file metadata (name => value)
946 * Metadata keys and headers names will be returned in all lower-case.
947 * Additional values may be included for internal use only.
949 * Use FileBackend::hasFeatures() to check how well this is supported.
951 * @param array $params
953 * - src : source storage path
954 * - latest : use the latest available data
955 * @return array|bool Returns false on failure
958 abstract public function getFileXAttributes( array $params );
961 * Get the size (bytes) of a file at a storage path in the backend.
963 * @param array $params Parameters include:
964 * - src : source storage path
965 * - latest : use the latest available data
966 * @return int|bool Returns false on failure
968 abstract public function getFileSize( array $params );
971 * Get quick information about a file at a storage path in the backend.
972 * If the file does not exist, then this returns false.
973 * Otherwise, the result is an associative array that includes:
974 * - mtime : the last-modified timestamp (TS_MW)
975 * - size : the file size (bytes)
976 * Additional values may be included for internal use only.
978 * @param array $params Parameters include:
979 * - src : source storage path
980 * - latest : use the latest available data
981 * @return array|bool|null Returns null on failure
983 abstract public function getFileStat( array $params );
986 * Get a SHA-1 hash of the file at a storage path in the backend.
988 * @param array $params Parameters include:
989 * - src : source storage path
990 * - latest : use the latest available data
991 * @return string|bool Hash string or false on failure
993 abstract public function getFileSha1Base36( array $params );
996 * Get the properties of the file at a storage path in the backend.
997 * This gives the result of FSFile::getProps() on a local copy of the file.
999 * @param array $params Parameters include:
1000 * - src : source storage path
1001 * - latest : use the latest available data
1002 * @return array Returns FSFile::placeholderProps() on failure
1004 abstract public function getFileProps( array $params );
1007 * Stream the file at a storage path in the backend.
1008 * If the file does not exists, an HTTP 404 error will be given.
1009 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1010 * will be sent if streaming began, while none will be sent otherwise.
1011 * Implementations should flush the output buffer before sending data.
1013 * @param array $params Parameters include:
1014 * - src : source storage path
1015 * - headers : list of additional HTTP headers to send on success
1016 * - latest : use the latest available data
1019 abstract public function streamFile( array $params );
1022 * Returns a file system file, identical to the file at a storage path.
1023 * The file returned is either:
1024 * - a) A local copy of the file at a storage path in the backend.
1025 * The temporary copy will have the same extension as the source.
1026 * - b) An original of the file at a storage path in the backend.
1027 * Temporary files may be purged when the file object falls out of scope.
1029 * Write operations should *never* be done on this file as some backends
1030 * may do internal tracking or may be instances of FileBackendMultiWrite.
1031 * In that later case, there are copies of the file that must stay in sync.
1032 * Additionally, further calls to this function may return the same file.
1034 * @param array $params Parameters include:
1035 * - src : source storage path
1036 * - latest : use the latest available data
1037 * @return FSFile|null Returns null on failure
1039 final public function getLocalReference( array $params ) {
1040 $fsFiles = $this->getLocalReferenceMulti(
1041 [ 'srcs' => [ $params['src'] ] ] +
$params );
1043 return $fsFiles[$params['src']];
1047 * Like getLocalReference() except it takes an array of storage paths
1048 * and returns a map of storage paths to FSFile objects (or null on failure).
1049 * The map keys (paths) are in the same order as the provided list of paths.
1051 * @see FileBackend::getLocalReference()
1053 * @param array $params Parameters include:
1054 * - srcs : list of source storage paths
1055 * - latest : use the latest available data
1056 * - parallelize : try to do operations in parallel when possible
1057 * @return array Map of (path name => FSFile or null on failure)
1060 abstract public function getLocalReferenceMulti( array $params );
1063 * Get a local copy on disk of the file at a storage path in the backend.
1064 * The temporary copy will have the same file extension as the source.
1065 * Temporary files may be purged when the file object falls out of scope.
1067 * @param array $params Parameters include:
1068 * - src : source storage path
1069 * - latest : use the latest available data
1070 * @return TempFSFile|null Returns null on failure
1072 final public function getLocalCopy( array $params ) {
1073 $tmpFiles = $this->getLocalCopyMulti(
1074 [ 'srcs' => [ $params['src'] ] ] +
$params );
1076 return $tmpFiles[$params['src']];
1080 * Like getLocalCopy() except it takes an array of storage paths and
1081 * returns a map of storage paths to TempFSFile objects (or null on failure).
1082 * The map keys (paths) are in the same order as the provided list of paths.
1084 * @see FileBackend::getLocalCopy()
1086 * @param array $params Parameters include:
1087 * - srcs : list of source storage paths
1088 * - latest : use the latest available data
1089 * - parallelize : try to do operations in parallel when possible
1090 * @return array Map of (path name => TempFSFile or null on failure)
1093 abstract public function getLocalCopyMulti( array $params );
1096 * Return an HTTP URL to a given file that requires no authentication to use.
1097 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1098 * This will return null if the backend cannot make an HTTP URL for the file.
1100 * This is useful for key/value stores when using scripts that seek around
1101 * large files and those scripts (and the backend) support HTTP Range headers.
1102 * Otherwise, one would need to use getLocalReference(), which involves loading
1103 * the entire file on to local disk.
1105 * @param array $params Parameters include:
1106 * - src : source storage path
1107 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1108 * @return string|null
1111 abstract public function getFileHttpUrl( array $params );
1114 * Check if a directory exists at a given storage path.
1115 * Backends using key/value stores will check if the path is a
1116 * virtual directory, meaning there are files under the given directory.
1118 * Storage backends with eventual consistency might return stale data.
1120 * @param array $params Parameters include:
1121 * - dir : storage directory
1122 * @return bool|null Returns null on failure
1125 abstract public function directoryExists( array $params );
1128 * Get an iterator to list *all* directories under a storage directory.
1129 * If the directory is of the form "mwstore://backend/container",
1130 * then all directories in the container will be listed.
1131 * If the directory is of form "mwstore://backend/container/dir",
1132 * then all directories directly under that directory will be listed.
1133 * Results will be storage directories relative to the given directory.
1135 * Storage backends with eventual consistency might return stale data.
1137 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1139 * @param array $params Parameters include:
1140 * - dir : storage directory
1141 * - topOnly : only return direct child dirs of the directory
1142 * @return Traversable|array|null Returns null on failure
1145 abstract public function getDirectoryList( array $params );
1148 * Same as FileBackend::getDirectoryList() except only lists
1149 * directories that are immediately under the given directory.
1151 * Storage backends with eventual consistency might return stale data.
1153 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1155 * @param array $params Parameters include:
1156 * - dir : storage directory
1157 * @return Traversable|array|null Returns null on failure
1160 final public function getTopDirectoryList( array $params ) {
1161 return $this->getDirectoryList( [ 'topOnly' => true ] +
$params );
1165 * Get an iterator to list *all* stored files under a storage directory.
1166 * If the directory is of the form "mwstore://backend/container",
1167 * then all files in the container will be listed.
1168 * If the directory is of form "mwstore://backend/container/dir",
1169 * then all files under that directory will be listed.
1170 * Results will be storage paths relative to the given directory.
1172 * Storage backends with eventual consistency might return stale data.
1174 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1176 * @param array $params Parameters include:
1177 * - dir : storage directory
1178 * - topOnly : only return direct child files of the directory (since 1.20)
1179 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1180 * @return Traversable|array|null Returns null on failure
1182 abstract public function getFileList( array $params );
1185 * Same as FileBackend::getFileList() except only lists
1186 * files that are immediately under the given directory.
1188 * Storage backends with eventual consistency might return stale data.
1190 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1192 * @param array $params Parameters include:
1193 * - dir : storage directory
1194 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1195 * @return Traversable|array|null Returns null on failure
1198 final public function getTopFileList( array $params ) {
1199 return $this->getFileList( [ 'topOnly' => true ] +
$params );
1203 * Preload persistent file stat cache and property cache into in-process cache.
1204 * This should be used when stat calls will be made on a known list of a many files.
1206 * @see FileBackend::getFileStat()
1208 * @param array $paths Storage paths
1210 abstract public function preloadCache( array $paths );
1213 * Invalidate any in-process file stat and property cache.
1214 * If $paths is given, then only the cache for those files will be cleared.
1216 * @see FileBackend::getFileStat()
1218 * @param array $paths Storage paths (optional)
1220 abstract public function clearCache( array $paths = null );
1223 * Preload file stat information (concurrently if possible) into in-process cache.
1225 * This should be used when stat calls will be made on a known list of a many files.
1226 * This does not make use of the persistent file stat cache.
1228 * @see FileBackend::getFileStat()
1230 * @param array $params Parameters include:
1231 * - srcs : list of source storage paths
1232 * - latest : use the latest available data
1233 * @return bool All requests proceeded without I/O errors (since 1.24)
1236 abstract public function preloadFileStat( array $params );
1239 * Lock the files at the given storage paths in the backend.
1240 * This will either lock all the files or none (on failure).
1242 * Callers should consider using getScopedFileLocks() instead.
1244 * @param array $paths Storage paths
1245 * @param int $type LockManager::LOCK_* constant
1246 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1249 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1250 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1252 return $this->lockManager
->lock( $paths, $type, $timeout );
1256 * Unlock the files at the given storage paths in the backend.
1258 * @param array $paths Storage paths
1259 * @param int $type LockManager::LOCK_* constant
1262 final public function unlockFiles( array $paths, $type ) {
1263 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1265 return $this->lockManager
->unlock( $paths, $type );
1269 * Lock the files at the given storage paths in the backend.
1270 * This will either lock all the files or none (on failure).
1271 * On failure, the status object will be updated with errors.
1273 * Once the return value goes out scope, the locks will be released and
1274 * the status updated. Unlock fatals will not change the status "OK" value.
1276 * @see ScopedLock::factory()
1278 * @param array $paths List of storage paths or map of lock types to path lists
1279 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1280 * @param Status $status Status to update on lock/unlock
1281 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1282 * @return ScopedLock|null Returns null on failure
1284 final public function getScopedFileLocks( array $paths, $type, Status
$status, $timeout = 0 ) {
1285 if ( $type === 'mixed' ) {
1286 foreach ( $paths as &$typePaths ) {
1287 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1290 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1293 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status, $timeout );
1297 * Get an array of scoped locks needed for a batch of file operations.
1299 * Normally, FileBackend::doOperations() handles locking, unless
1300 * the 'nonLocking' param is passed in. This function is useful if you
1301 * want the files to be locked for a broader scope than just when the
1302 * files are changing. For example, if you need to update DB metadata,
1303 * you may want to keep the files locked until finished.
1305 * @see FileBackend::doOperations()
1307 * @param array $ops List of file operations to FileBackend::doOperations()
1308 * @param Status $status Status to update on lock/unlock
1309 * @return ScopedLock|null
1312 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1315 * Get the root storage path of this backend.
1316 * All container paths are "subdirectories" of this path.
1318 * @return string Storage path
1321 final public function getRootStoragePath() {
1322 return "mwstore://{$this->name}";
1326 * Get the storage path for the given container for this backend
1328 * @param string $container Container name
1329 * @return string Storage path
1332 final public function getContainerStoragePath( $container ) {
1333 return $this->getRootStoragePath() . "/{$container}";
1337 * Get the file journal object for this backend
1339 * @return FileJournal
1341 final public function getJournal() {
1342 return $this->fileJournal
;
1346 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1348 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1349 * around as long it needs (which may vary greatly depending on configuration)
1351 * @param array $ops File operation batch for FileBaclend::doOperations()
1352 * @return array File operation batch
1354 protected function resolveFSFileObjects( array $ops ) {
1355 foreach ( $ops as &$op ) {
1356 $src = isset( $op['src'] ) ?
$op['src'] : null;
1357 if ( $src instanceof FSFile
) {
1358 $op['srcRef'] = $src;
1359 $op['src'] = $src->getPath();
1368 * Check if a given path is a "mwstore://" path.
1369 * This does not do any further validation or any existence checks.
1371 * @param string $path
1374 final public static function isStoragePath( $path ) {
1375 return ( strpos( $path, 'mwstore://' ) === 0 );
1379 * Split a storage path into a backend name, a container name,
1380 * and a relative file path. The relative path may be the empty string.
1381 * This does not do any path normalization or traversal checks.
1383 * @param string $storagePath
1384 * @return array (backend, container, rel object) or (null, null, null)
1386 final public static function splitStoragePath( $storagePath ) {
1387 if ( self
::isStoragePath( $storagePath ) ) {
1388 // Remove the "mwstore://" prefix and split the path
1389 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1390 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1391 if ( count( $parts ) == 3 ) {
1392 return $parts; // e.g. "backend/container/path"
1394 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1399 return [ null, null, null ];
1403 * Normalize a storage path by cleaning up directory separators.
1404 * Returns null if the path is not of the format of a valid storage path.
1406 * @param string $storagePath
1407 * @return string|null
1409 final public static function normalizeStoragePath( $storagePath ) {
1410 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1411 if ( $relPath !== null ) { // must be for this backend
1412 $relPath = self
::normalizeContainerPath( $relPath );
1413 if ( $relPath !== null ) {
1414 return ( $relPath != '' )
1415 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1416 : "mwstore://{$backend}/{$container}";
1424 * Get the parent storage directory of a storage path.
1425 * This returns a path like "mwstore://backend/container",
1426 * "mwstore://backend/container/...", or null if there is no parent.
1428 * @param string $storagePath
1429 * @return string|null
1431 final public static function parentStoragePath( $storagePath ) {
1432 $storagePath = dirname( $storagePath );
1433 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1435 return ( $rel === null ) ?
null : $storagePath;
1439 * Get the final extension from a storage or FS path
1441 * @param string $path
1442 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1445 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1446 $i = strrpos( $path, '.' );
1447 $ext = $i ?
substr( $path, $i +
1 ) : '';
1449 if ( $case === 'lowercase' ) {
1450 $ext = strtolower( $ext );
1451 } elseif ( $case === 'uppercase' ) {
1452 $ext = strtoupper( $ext );
1459 * Check if a relative path has no directory traversals
1461 * @param string $path
1465 final public static function isPathTraversalFree( $path ) {
1466 return ( self
::normalizeContainerPath( $path ) !== null );
1470 * Build a Content-Disposition header value per RFC 6266.
1472 * @param string $type One of (attachment, inline)
1473 * @param string $filename Suggested file name (should not contain slashes)
1474 * @throws FileBackendError
1478 final public static function makeContentDisposition( $type, $filename = '' ) {
1481 $type = strtolower( $type );
1482 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1483 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1487 if ( strlen( $filename ) ) {
1488 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1491 return implode( ';', $parts );
1495 * Validate and normalize a relative storage path.
1496 * Null is returned if the path involves directory traversal.
1497 * Traversal is insecure for FS backends and broken for others.
1499 * This uses the same traversal protection as Title::secureAndSplit().
1501 * @param string $path Storage path relative to a container
1502 * @return string|null
1504 final protected static function normalizeContainerPath( $path ) {
1505 // Normalize directory separators
1506 $path = strtr( $path, '\\', '/' );
1507 // Collapse any consecutive directory separators
1508 $path = preg_replace( '![/]{2,}!', '/', $path );
1509 // Remove any leading directory separator
1510 $path = ltrim( $path, '/' );
1511 // Use the same traversal protection as Title::secureAndSplit()
1512 if ( strpos( $path, '.' ) !== false ) {
1516 strpos( $path, './' ) === 0 ||
1517 strpos( $path, '../' ) === 0 ||
1518 strpos( $path, '/./' ) !== false ||
1519 strpos( $path, '/../' ) !== false
1530 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1532 * @ingroup FileBackend
1535 class FileBackendException
extends Exception
{
1539 * File backend exception for checked exceptions (e.g. I/O errors)
1541 * @ingroup FileBackend
1544 class FileBackendError
extends FileBackendException
{