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 string Temporary file directory */
102 protected $tmpDirectory;
104 /** @var LockManager */
105 protected $lockManager;
107 /** @var FileJournal */
108 protected $fileJournal;
111 protected $statusWrapper;
113 /** Bitfield flags for supported features */
114 const ATTR_HEADERS
= 1; // files can be tagged with standard HTTP headers
115 const ATTR_METADATA
= 2; // files can be stored with metadata key/values
116 const ATTR_UNICODE_PATHS
= 4; // files can have Unicode paths (not just ASCII)
119 * Create a new backend instance from configuration.
120 * This should only be called from within FileBackendGroup.
122 * @param array $config Parameters include:
123 * - name : The unique name of this backend.
124 * This should consist of alphanumberic, '-', and '_' characters.
125 * This name should not be changed after use (e.g. with journaling).
126 * Note that the name is *not* used in actual container names.
127 * - wikiId : Prefix to container names that is unique to this backend.
128 * It should only consist of alphanumberic, '-', and '_' characters.
129 * This ID is what avoids collisions if multiple logical backends
130 * use the same storage system, so this should be set carefully.
131 * - lockManager : LockManager object to use for any file locking.
132 * If not provided, then no file locking will be enforced.
133 * - fileJournal : FileJournal object to use for logging changes to files.
134 * If not provided, then change journaling will be disabled.
135 * - readOnly : Write operations are disallowed if this is a non-empty string.
136 * It should be an explanation for the backend being read-only.
137 * - parallelize : When to do file operations in parallel (when possible).
138 * Allowed values are "implicit", "explicit" and "off".
139 * - concurrency : How many file operations can be done in parallel.
140 * - tmpDirectory : Directory to use for temporary files. If this is not set or null,
141 * then the backend will try to discover a usable temporary directory.
142 * @throws FileBackendException
144 public function __construct( array $config ) {
145 $this->name
= $config['name'];
146 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
147 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
148 throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
149 } elseif ( !is_string( $this->wikiId
) ) {
150 throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
152 $this->lockManager
= isset( $config['lockManager'] )
153 ?
$config['lockManager']
154 : new NullLockManager( [] );
155 $this->fileJournal
= isset( $config['fileJournal'] )
156 ?
$config['fileJournal']
157 : FileJournal
::factory( [ 'class' => 'NullFileJournal' ], $this->name
);
158 $this->readOnly
= isset( $config['readOnly'] )
159 ?
(string)$config['readOnly']
161 $this->parallelize
= isset( $config['parallelize'] )
162 ?
(string)$config['parallelize']
164 $this->concurrency
= isset( $config['concurrency'] )
165 ?
(int)$config['concurrency']
167 $this->statusWrapper
= isset( $config['statusWrapper'] ) ?
$config['statusWrapper'] : null;
168 $this->tmpDirectory
= isset( $config['tmpDirectory'] ) ?
$config['tmpDirectory'] : null;
172 * Get the unique backend name.
173 * We may have multiple different backends of the same type.
174 * For example, we can have two Swift backends using different proxies.
178 final public function getName() {
183 * Get the wiki identifier used for this backend (possibly empty).
184 * Note that this might *not* be in the same format as wfWikiID().
189 final public function getWikiId() {
190 return $this->wikiId
;
194 * Check if this backend is read-only
198 final public function isReadOnly() {
199 return ( $this->readOnly
!= '' );
203 * Get an explanatory message if this backend is read-only
205 * @return string|bool Returns false if the backend is not read-only
207 final public function getReadOnlyReason() {
208 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
212 * Get the a bitfield of extra features supported by the backend medium
214 * @return int Bitfield of FileBackend::ATTR_* flags
217 public function getFeatures() {
218 return self
::ATTR_UNICODE_PATHS
;
222 * Check if the backend medium supports a field of extra features
224 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
228 final public function hasFeatures( $bitfield ) {
229 return ( $this->getFeatures() & $bitfield ) === $bitfield;
233 * This is the main entry point into the backend for write operations.
234 * Callers supply an ordered list of operations to perform as a transaction.
235 * Files will be locked, the stat cache cleared, and then the operations attempted.
236 * If any serious errors occur, all attempted operations will be rolled back.
238 * $ops is an array of arrays. The outer array holds a list of operations.
239 * Each inner array is a set of key value pairs that specify an operation.
241 * Supported operations and their parameters. The supported actions are:
247 * - describe (since 1.21)
250 * FSFile/TempFSFile object support was added in 1.27.
252 * a) Create a new file in storage with the contents of a string
256 * 'dst' => <storage path>,
257 * 'content' => <string of new file contents>,
258 * 'overwrite' => <boolean>,
259 * 'overwriteSame' => <boolean>,
260 * 'headers' => <HTTP header name/value map> # since 1.21
264 * b) Copy a file system file into storage
268 * 'src' => <file system path, FSFile, or TempFSFile>,
269 * 'dst' => <storage path>,
270 * 'overwrite' => <boolean>,
271 * 'overwriteSame' => <boolean>,
272 * 'headers' => <HTTP header name/value map> # since 1.21
276 * c) Copy a file within storage
280 * 'src' => <storage path>,
281 * 'dst' => <storage path>,
282 * 'overwrite' => <boolean>,
283 * 'overwriteSame' => <boolean>,
284 * 'ignoreMissingSource' => <boolean>, # since 1.21
285 * 'headers' => <HTTP header name/value map> # since 1.21
289 * d) Move a file within storage
293 * 'src' => <storage path>,
294 * 'dst' => <storage path>,
295 * 'overwrite' => <boolean>,
296 * 'overwriteSame' => <boolean>,
297 * 'ignoreMissingSource' => <boolean>, # since 1.21
298 * 'headers' => <HTTP header name/value map> # since 1.21
302 * e) Delete a file within storage
306 * 'src' => <storage path>,
307 * 'ignoreMissingSource' => <boolean>
311 * f) Update metadata for a file within storage
314 * 'op' => 'describe',
315 * 'src' => <storage path>,
316 * 'headers' => <HTTP header name/value map>
320 * g) Do nothing (no-op)
327 * Boolean flags for operations (operation-specific):
328 * - ignoreMissingSource : The operation will simply succeed and do
329 * nothing if the source file does not exist.
330 * - overwrite : Any destination file will be overwritten.
331 * - overwriteSame : If a file already exists at the destination with the
332 * same contents, then do nothing to the destination file
333 * instead of giving an error. This does not compare headers.
334 * This option is ignored if 'overwrite' is already provided.
335 * - headers : If supplied, the result of merging these headers with any
336 * existing source file headers (replacing conflicting ones)
337 * will be set as the destination file headers. Headers are
338 * deleted if their value is set to the empty string. When a
339 * file has headers they are included in responses to GET and
340 * HEAD requests to the backing store for that file.
341 * Header values should be no larger than 255 bytes, except for
342 * Content-Disposition. The system might ignore or truncate any
343 * headers that are too long to store (exact limits will vary).
344 * Backends that don't support metadata ignore this. (since 1.21)
346 * $opts is an associative of boolean flags, including:
347 * - force : Operation precondition errors no longer trigger an abort.
348 * Any remaining operations are still attempted. Unexpected
349 * failures may still cause remaining operations to be aborted.
350 * - nonLocking : No locks are acquired for the operations.
351 * This can increase performance for non-critical writes.
352 * This has no effect unless the 'force' flag is set.
353 * - nonJournaled : Don't log this operation batch in the file journal.
354 * This limits the ability of recovery scripts.
355 * - parallelize : Try to do operations in parallel when possible.
356 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
357 * - preserveCache : Don't clear the process cache before checking files.
358 * This should only be used if all entries in the process
359 * cache were added after the files were already locked. (since 1.20)
361 * @remarks Remarks on locking:
362 * File system paths given to operations should refer to files that are
363 * already locked or otherwise safe from modification from other processes.
364 * Normally these files will be new temp files, which should be adequate.
368 * This returns a Status, which contains all warnings and fatals that occurred
369 * during the operation. The 'failCount', 'successCount', and 'success' members
370 * will reflect each operation attempted.
372 * The StatusValue will be "OK" unless:
373 * - a) unexpected operation errors occurred (network partitions, disk full...)
374 * - b) significant operation errors occurred and 'force' was not set
376 * @param array $ops List of operations to execute in order
377 * @param array $opts Batch operation options
378 * @return StatusValue
380 final public function doOperations( array $ops, array $opts = [] ) {
381 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
382 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
384 if ( !count( $ops ) ) {
385 return $this->newStatus(); // nothing to do
388 $ops = $this->resolveFSFileObjects( $ops );
389 if ( empty( $opts['force'] ) ) { // sanity
390 unset( $opts['nonLocking'] );
393 /** @noinspection PhpUnusedLocalVariableInspection */
394 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
396 return $this->doOperationsInternal( $ops, $opts );
400 * @see FileBackend::doOperations()
404 abstract protected function doOperationsInternal( array $ops, array $opts );
407 * Same as doOperations() except it takes a single operation.
408 * If you are doing a batch of operations that should either
409 * all succeed or all fail, then use that function instead.
411 * @see FileBackend::doOperations()
413 * @param array $op Operation
414 * @param array $opts Operation options
415 * @return StatusValue
417 final public function doOperation( array $op, array $opts = [] ) {
418 return $this->doOperations( [ $op ], $opts );
422 * Performs a single create operation.
423 * This sets $params['op'] to 'create' and passes it to doOperation().
425 * @see FileBackend::doOperation()
427 * @param array $params Operation parameters
428 * @param array $opts Operation options
429 * @return StatusValue
431 final public function create( array $params, array $opts = [] ) {
432 return $this->doOperation( [ 'op' => 'create' ] +
$params, $opts );
436 * Performs a single store operation.
437 * This sets $params['op'] to 'store' and passes it to doOperation().
439 * @see FileBackend::doOperation()
441 * @param array $params Operation parameters
442 * @param array $opts Operation options
443 * @return StatusValue
445 final public function store( array $params, array $opts = [] ) {
446 return $this->doOperation( [ 'op' => 'store' ] +
$params, $opts );
450 * Performs a single copy operation.
451 * This sets $params['op'] to 'copy' and passes it to doOperation().
453 * @see FileBackend::doOperation()
455 * @param array $params Operation parameters
456 * @param array $opts Operation options
457 * @return StatusValue
459 final public function copy( array $params, array $opts = [] ) {
460 return $this->doOperation( [ 'op' => 'copy' ] +
$params, $opts );
464 * Performs a single move operation.
465 * This sets $params['op'] to 'move' and passes it to doOperation().
467 * @see FileBackend::doOperation()
469 * @param array $params Operation parameters
470 * @param array $opts Operation options
471 * @return StatusValue
473 final public function move( array $params, array $opts = [] ) {
474 return $this->doOperation( [ 'op' => 'move' ] +
$params, $opts );
478 * Performs a single delete operation.
479 * This sets $params['op'] to 'delete' and passes it to doOperation().
481 * @see FileBackend::doOperation()
483 * @param array $params Operation parameters
484 * @param array $opts Operation options
485 * @return StatusValue
487 final public function delete( array $params, array $opts = [] ) {
488 return $this->doOperation( [ 'op' => 'delete' ] +
$params, $opts );
492 * Performs a single describe operation.
493 * This sets $params['op'] to 'describe' and passes it to doOperation().
495 * @see FileBackend::doOperation()
497 * @param array $params Operation parameters
498 * @param array $opts Operation options
499 * @return StatusValue
502 final public function describe( array $params, array $opts = [] ) {
503 return $this->doOperation( [ 'op' => 'describe' ] +
$params, $opts );
507 * Perform a set of independent file operations on some files.
509 * This does no locking, nor journaling, and possibly no stat calls.
510 * Any destination files that already exist will be overwritten.
511 * This should *only* be used on non-original files, like cache files.
513 * Supported operations and their parameters:
519 * - describe (since 1.21)
522 * FSFile/TempFSFile object support was added in 1.27.
524 * a) Create a new file in storage with the contents of a string
528 * 'dst' => <storage path>,
529 * 'content' => <string of new file contents>,
530 * 'headers' => <HTTP header name/value map> # since 1.21
534 * b) Copy a file system file into storage
538 * 'src' => <file system path, FSFile, or TempFSFile>,
539 * 'dst' => <storage path>,
540 * 'headers' => <HTTP header name/value map> # since 1.21
544 * c) Copy a file within storage
548 * 'src' => <storage path>,
549 * 'dst' => <storage path>,
550 * 'ignoreMissingSource' => <boolean>, # since 1.21
551 * 'headers' => <HTTP header name/value map> # since 1.21
555 * d) Move a file within storage
559 * 'src' => <storage path>,
560 * 'dst' => <storage path>,
561 * 'ignoreMissingSource' => <boolean>, # since 1.21
562 * 'headers' => <HTTP header name/value map> # since 1.21
566 * e) Delete a file within storage
570 * 'src' => <storage path>,
571 * 'ignoreMissingSource' => <boolean>
575 * f) Update metadata for a file within storage
578 * 'op' => 'describe',
579 * 'src' => <storage path>,
580 * 'headers' => <HTTP header name/value map>
584 * g) Do nothing (no-op)
591 * @par Boolean flags for operations (operation-specific):
592 * - ignoreMissingSource : The operation will simply succeed and do
593 * nothing if the source file does not exist.
594 * - headers : If supplied with a header name/value map, the backend will
595 * reply with these headers when GETs/HEADs of the destination
596 * file are made. Header values should be smaller than 256 bytes.
597 * Content-Disposition headers can be longer, though the system
598 * might ignore or truncate ones that are too long to store.
599 * Existing headers will remain, but these will replace any
600 * conflicting previous headers, and headers will be removed
601 * if they are set to an empty string.
602 * Backends that don't support metadata ignore this. (since 1.21)
604 * $opts is an associative of boolean flags, including:
605 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
608 * This returns a Status, which contains all warnings and fatals that occurred
609 * during the operation. The 'failCount', 'successCount', and 'success' members
610 * will reflect each operation attempted for the given files. The StatusValue will be
611 * considered "OK" as long as no fatal errors occurred.
613 * @param array $ops Set of operations to execute
614 * @param array $opts Batch operation options
615 * @return StatusValue
618 final public function doQuickOperations( array $ops, array $opts = [] ) {
619 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
620 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
622 if ( !count( $ops ) ) {
623 return $this->newStatus(); // nothing to do
626 $ops = $this->resolveFSFileObjects( $ops );
627 foreach ( $ops as &$op ) {
628 $op['overwrite'] = true; // avoids RTTs in key/value stores
631 /** @noinspection PhpUnusedLocalVariableInspection */
632 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
634 return $this->doQuickOperationsInternal( $ops );
638 * @see FileBackend::doQuickOperations()
642 abstract protected function doQuickOperationsInternal( array $ops );
645 * Same as doQuickOperations() except it takes a single operation.
646 * If you are doing a batch of operations, then use that function instead.
648 * @see FileBackend::doQuickOperations()
650 * @param array $op Operation
651 * @return StatusValue
654 final public function doQuickOperation( array $op ) {
655 return $this->doQuickOperations( [ $op ] );
659 * Performs a single quick create operation.
660 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
662 * @see FileBackend::doQuickOperation()
664 * @param array $params Operation parameters
665 * @return StatusValue
668 final public function quickCreate( array $params ) {
669 return $this->doQuickOperation( [ 'op' => 'create' ] +
$params );
673 * Performs a single quick store operation.
674 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
676 * @see FileBackend::doQuickOperation()
678 * @param array $params Operation parameters
679 * @return StatusValue
682 final public function quickStore( array $params ) {
683 return $this->doQuickOperation( [ 'op' => 'store' ] +
$params );
687 * Performs a single quick copy operation.
688 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
690 * @see FileBackend::doQuickOperation()
692 * @param array $params Operation parameters
693 * @return StatusValue
696 final public function quickCopy( array $params ) {
697 return $this->doQuickOperation( [ 'op' => 'copy' ] +
$params );
701 * Performs a single quick move operation.
702 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
704 * @see FileBackend::doQuickOperation()
706 * @param array $params Operation parameters
707 * @return StatusValue
710 final public function quickMove( array $params ) {
711 return $this->doQuickOperation( [ 'op' => 'move' ] +
$params );
715 * Performs a single quick delete operation.
716 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
718 * @see FileBackend::doQuickOperation()
720 * @param array $params Operation parameters
721 * @return StatusValue
724 final public function quickDelete( array $params ) {
725 return $this->doQuickOperation( [ 'op' => 'delete' ] +
$params );
729 * Performs a single quick describe operation.
730 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
732 * @see FileBackend::doQuickOperation()
734 * @param array $params Operation parameters
735 * @return StatusValue
738 final public function quickDescribe( array $params ) {
739 return $this->doQuickOperation( [ 'op' => 'describe' ] +
$params );
743 * Concatenate a list of storage files into a single file system file.
744 * The target path should refer to a file that is already locked or
745 * otherwise safe from modification from other processes. Normally,
746 * the file will be a new temp file, which should be adequate.
748 * @param array $params Operation parameters, include:
749 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
750 * - dst : file system path to 0-byte temp file
751 * - parallelize : try to do operations in parallel when possible
752 * @return StatusValue
754 abstract public function concatenate( array $params );
757 * Prepare a storage directory for usage.
758 * This will create any required containers and parent directories.
759 * Backends using key/value stores only need to create the container.
761 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
762 * except they are only applied *if* the directory/container had to be created.
763 * These flags should always be set for directories that have private files.
764 * However, setting them is not guaranteed to actually do anything.
765 * Additional server configuration may be needed to achieve the desired effect.
767 * @param array $params Parameters include:
768 * - dir : storage directory
769 * - noAccess : try to deny file access (since 1.20)
770 * - noListing : try to deny file listing (since 1.20)
771 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
772 * @return StatusValue
774 final public function prepare( array $params ) {
775 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
776 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
778 /** @noinspection PhpUnusedLocalVariableInspection */
779 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
780 return $this->doPrepare( $params );
784 * @see FileBackend::prepare()
785 * @param array $params
787 abstract protected function doPrepare( array $params );
790 * Take measures to block web access to a storage directory and
791 * the container it belongs to. FS backends might add .htaccess
792 * files whereas key/value store backends might revoke container
793 * access to the storage user representing end-users in web requests.
795 * This is not guaranteed to actually make files or listings publically hidden.
796 * Additional server configuration may be needed to achieve the desired effect.
798 * @param array $params Parameters include:
799 * - dir : storage directory
800 * - noAccess : try to deny file access
801 * - noListing : try to deny file listing
802 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
803 * @return StatusValue
805 final public function secure( array $params ) {
806 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
807 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
809 /** @noinspection PhpUnusedLocalVariableInspection */
810 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
811 return $this->doSecure( $params );
815 * @see FileBackend::secure()
816 * @param array $params
818 abstract protected function doSecure( array $params );
821 * Remove measures to block web access to a storage directory and
822 * the container it belongs to. FS backends might remove .htaccess
823 * files whereas key/value store backends might grant container
824 * access to the storage user representing end-users in web requests.
825 * This essentially can undo the result of secure() calls.
827 * This is not guaranteed to actually make files or listings publically viewable.
828 * Additional server configuration may be needed to achieve the desired effect.
830 * @param array $params Parameters include:
831 * - dir : storage directory
832 * - access : try to allow file access
833 * - listing : try to allow file listing
834 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
835 * @return StatusValue
838 final public function publish( array $params ) {
839 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
840 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
842 /** @noinspection PhpUnusedLocalVariableInspection */
843 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
844 return $this->doPublish( $params );
848 * @see FileBackend::publish()
849 * @param array $params
851 abstract protected function doPublish( array $params );
854 * Delete a storage directory if it is empty.
855 * Backends using key/value stores may do nothing unless the directory
856 * is that of an empty container, in which case it will be deleted.
858 * @param array $params Parameters include:
859 * - dir : storage directory
860 * - recursive : recursively delete empty subdirectories first (since 1.20)
861 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
862 * @return StatusValue
864 final public function clean( array $params ) {
865 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
866 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
868 /** @noinspection PhpUnusedLocalVariableInspection */
869 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
870 return $this->doClean( $params );
874 * @see FileBackend::clean()
875 * @param array $params
877 abstract protected function doClean( array $params );
880 * Enter file operation scope.
881 * This just makes PHP ignore user aborts/disconnects until the return
882 * value leaves scope. This returns null and does nothing in CLI mode.
884 * @return ScopedCallback|null
886 final protected function getScopedPHPBehaviorForOps() {
887 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
888 $old = ignore_user_abort( true ); // avoid half-finished operations
889 return new ScopedCallback( function () use ( $old ) {
890 ignore_user_abort( $old );
898 * Check if a file exists at a storage path in the backend.
899 * This returns false if only a directory exists at the path.
901 * @param array $params Parameters include:
902 * - src : source storage path
903 * - latest : use the latest available data
904 * @return bool|null Returns null on failure
906 abstract public function fileExists( array $params );
909 * Get the last-modified timestamp of the file at a storage path.
911 * @param array $params Parameters include:
912 * - src : source storage path
913 * - latest : use the latest available data
914 * @return string|bool TS_MW timestamp or false on failure
916 abstract public function getFileTimestamp( array $params );
919 * Get the contents of a file at a storage path in the backend.
920 * This should be avoided for potentially large files.
922 * @param array $params Parameters include:
923 * - src : source storage path
924 * - latest : use the latest available data
925 * @return string|bool Returns false on failure
927 final public function getFileContents( array $params ) {
928 $contents = $this->getFileContentsMulti(
929 [ 'srcs' => [ $params['src'] ] ] +
$params );
931 return $contents[$params['src']];
935 * Like getFileContents() except it takes an array of storage paths
936 * and returns a map of storage paths to strings (or null on failure).
937 * The map keys (paths) are in the same order as the provided list of paths.
939 * @see FileBackend::getFileContents()
941 * @param array $params Parameters include:
942 * - srcs : list of source storage paths
943 * - latest : use the latest available data
944 * - parallelize : try to do operations in parallel when possible
945 * @return array Map of (path name => string or false on failure)
948 abstract public function getFileContentsMulti( array $params );
951 * Get metadata about a file at a storage path in the backend.
952 * If the file does not exist, then this returns false.
953 * Otherwise, the result is an associative array that includes:
954 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
955 * - metadata : map of file metadata (name => value)
956 * Metadata keys and headers names will be returned in all lower-case.
957 * Additional values may be included for internal use only.
959 * Use FileBackend::hasFeatures() to check how well this is supported.
961 * @param array $params
963 * - src : source storage path
964 * - latest : use the latest available data
965 * @return array|bool Returns false on failure
968 abstract public function getFileXAttributes( array $params );
971 * Get the size (bytes) of a file at a storage path in the backend.
973 * @param array $params Parameters include:
974 * - src : source storage path
975 * - latest : use the latest available data
976 * @return int|bool Returns false on failure
978 abstract public function getFileSize( array $params );
981 * Get quick information about a file at a storage path in the backend.
982 * If the file does not exist, then this returns false.
983 * Otherwise, the result is an associative array that includes:
984 * - mtime : the last-modified timestamp (TS_MW)
985 * - size : the file size (bytes)
986 * Additional values may be included for internal use only.
988 * @param array $params Parameters include:
989 * - src : source storage path
990 * - latest : use the latest available data
991 * @return array|bool|null Returns null on failure
993 abstract public function getFileStat( array $params );
996 * Get a SHA-1 hash of the file at a storage path in the backend.
998 * @param array $params Parameters include:
999 * - src : source storage path
1000 * - latest : use the latest available data
1001 * @return string|bool Hash string or false on failure
1003 abstract public function getFileSha1Base36( array $params );
1006 * Get the properties of the file at a storage path in the backend.
1007 * This gives the result of FSFile::getProps() on a local copy of the file.
1009 * @param array $params Parameters include:
1010 * - src : source storage path
1011 * - latest : use the latest available data
1012 * @return array Returns FSFile::placeholderProps() on failure
1014 abstract public function getFileProps( array $params );
1017 * Stream the file at a storage path in the backend.
1019 * If the file does not exists, an HTTP 404 error will be given.
1020 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1021 * will be sent if streaming began, while none will be sent otherwise.
1022 * Implementations should flush the output buffer before sending data.
1024 * @param array $params Parameters include:
1025 * - src : source storage path
1026 * - headers : list of additional HTTP headers to send if the file exists
1027 * - options : HTTP request header map with lower case keys (since 1.28). Supports:
1028 * range : format is "bytes=(\d*-\d*)"
1029 * if-modified-since : format is an HTTP date
1030 * - headless : only include the body (and headers from "headers") (since 1.28)
1031 * - latest : use the latest available data
1032 * - allowOB : preserve any output buffers (since 1.28)
1033 * @return StatusValue
1035 abstract public function streamFile( array $params );
1038 * Returns a file system file, identical to the file at a storage path.
1039 * The file returned is either:
1040 * - a) A local copy of the file at a storage path in the backend.
1041 * The temporary copy will have the same extension as the source.
1042 * - b) An original of the file at a storage path in the backend.
1043 * Temporary files may be purged when the file object falls out of scope.
1045 * Write operations should *never* be done on this file as some backends
1046 * may do internal tracking or may be instances of FileBackendMultiWrite.
1047 * In that latter case, there are copies of the file that must stay in sync.
1048 * Additionally, further calls to this function may return the same file.
1050 * @param array $params Parameters include:
1051 * - src : source storage path
1052 * - latest : use the latest available data
1053 * @return FSFile|null Returns null on failure
1055 final public function getLocalReference( array $params ) {
1056 $fsFiles = $this->getLocalReferenceMulti(
1057 [ 'srcs' => [ $params['src'] ] ] +
$params );
1059 return $fsFiles[$params['src']];
1063 * Like getLocalReference() except it takes an array of storage paths
1064 * and returns a map of storage paths to FSFile objects (or null on failure).
1065 * The map keys (paths) are in the same order as the provided list of paths.
1067 * @see FileBackend::getLocalReference()
1069 * @param array $params Parameters include:
1070 * - srcs : list of source storage paths
1071 * - latest : use the latest available data
1072 * - parallelize : try to do operations in parallel when possible
1073 * @return array Map of (path name => FSFile or null on failure)
1076 abstract public function getLocalReferenceMulti( array $params );
1079 * Get a local copy on disk of the file at a storage path in the backend.
1080 * The temporary copy will have the same file extension as the source.
1081 * Temporary files may be purged when the file object falls out of scope.
1083 * @param array $params Parameters include:
1084 * - src : source storage path
1085 * - latest : use the latest available data
1086 * @return TempFSFile|null Returns null on failure
1088 final public function getLocalCopy( array $params ) {
1089 $tmpFiles = $this->getLocalCopyMulti(
1090 [ 'srcs' => [ $params['src'] ] ] +
$params );
1092 return $tmpFiles[$params['src']];
1096 * Like getLocalCopy() except it takes an array of storage paths and
1097 * returns a map of storage paths to TempFSFile objects (or null on failure).
1098 * The map keys (paths) are in the same order as the provided list of paths.
1100 * @see FileBackend::getLocalCopy()
1102 * @param array $params Parameters include:
1103 * - srcs : list of source storage paths
1104 * - latest : use the latest available data
1105 * - parallelize : try to do operations in parallel when possible
1106 * @return array Map of (path name => TempFSFile or null on failure)
1109 abstract public function getLocalCopyMulti( array $params );
1112 * Return an HTTP URL to a given file that requires no authentication to use.
1113 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1114 * This will return null if the backend cannot make an HTTP URL for the file.
1116 * This is useful for key/value stores when using scripts that seek around
1117 * large files and those scripts (and the backend) support HTTP Range headers.
1118 * Otherwise, one would need to use getLocalReference(), which involves loading
1119 * the entire file on to local disk.
1121 * @param array $params Parameters include:
1122 * - src : source storage path
1123 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1124 * @return string|null
1127 abstract public function getFileHttpUrl( array $params );
1130 * Check if a directory exists at a given storage path.
1131 * Backends using key/value stores will check if the path is a
1132 * virtual directory, meaning there are files under the given directory.
1134 * Storage backends with eventual consistency might return stale data.
1136 * @param array $params Parameters include:
1137 * - dir : storage directory
1138 * @return bool|null Returns null on failure
1141 abstract public function directoryExists( array $params );
1144 * Get an iterator to list *all* directories under a storage directory.
1145 * If the directory is of the form "mwstore://backend/container",
1146 * then all directories in the container will be listed.
1147 * If the directory is of form "mwstore://backend/container/dir",
1148 * then all directories directly under that directory will be listed.
1149 * Results will be storage directories relative to 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 * - topOnly : only return direct child dirs of the directory
1158 * @return Traversable|array|null Returns null on failure
1161 abstract public function getDirectoryList( array $params );
1164 * Same as FileBackend::getDirectoryList() except only lists
1165 * directories that are immediately under the given directory.
1167 * Storage backends with eventual consistency might return stale data.
1169 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1171 * @param array $params Parameters include:
1172 * - dir : storage directory
1173 * @return Traversable|array|null Returns null on failure
1176 final public function getTopDirectoryList( array $params ) {
1177 return $this->getDirectoryList( [ 'topOnly' => true ] +
$params );
1181 * Get an iterator to list *all* stored files under a storage directory.
1182 * If the directory is of the form "mwstore://backend/container",
1183 * then all files in the container will be listed.
1184 * If the directory is of form "mwstore://backend/container/dir",
1185 * then all files under that directory will be listed.
1186 * Results will be storage paths relative to 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 * - topOnly : only return direct child files of the directory (since 1.20)
1195 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1196 * @return Traversable|array|null Returns null on failure
1198 abstract public function getFileList( array $params );
1201 * Same as FileBackend::getFileList() except only lists
1202 * files that are immediately under the given directory.
1204 * Storage backends with eventual consistency might return stale data.
1206 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1208 * @param array $params Parameters include:
1209 * - dir : storage directory
1210 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1211 * @return Traversable|array|null Returns null on failure
1214 final public function getTopFileList( array $params ) {
1215 return $this->getFileList( [ 'topOnly' => true ] +
$params );
1219 * Preload persistent file stat cache and property cache into in-process cache.
1220 * This should be used when stat calls will be made on a known list of a many files.
1222 * @see FileBackend::getFileStat()
1224 * @param array $paths Storage paths
1226 abstract public function preloadCache( array $paths );
1229 * Invalidate any in-process file stat and property cache.
1230 * If $paths is given, then only the cache for those files will be cleared.
1232 * @see FileBackend::getFileStat()
1234 * @param array $paths Storage paths (optional)
1236 abstract public function clearCache( array $paths = null );
1239 * Preload file stat information (concurrently if possible) into in-process cache.
1241 * This should be used when stat calls will be made on a known list of a many files.
1242 * This does not make use of the persistent file stat cache.
1244 * @see FileBackend::getFileStat()
1246 * @param array $params Parameters include:
1247 * - srcs : list of source storage paths
1248 * - latest : use the latest available data
1249 * @return bool All requests proceeded without I/O errors (since 1.24)
1252 abstract public function preloadFileStat( array $params );
1255 * Lock the files at the given storage paths in the backend.
1256 * This will either lock all the files or none (on failure).
1258 * Callers should consider using getScopedFileLocks() instead.
1260 * @param array $paths Storage paths
1261 * @param int $type LockManager::LOCK_* constant
1262 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1263 * @return StatusValue
1265 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1266 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1268 return $this->wrapStatus( $this->lockManager
->lock( $paths, $type, $timeout ) );
1272 * Unlock the files at the given storage paths in the backend.
1274 * @param array $paths Storage paths
1275 * @param int $type LockManager::LOCK_* constant
1276 * @return StatusValue
1278 final public function unlockFiles( array $paths, $type ) {
1279 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1281 return $this->wrapStatus( $this->lockManager
->unlock( $paths, $type ) );
1285 * Lock the files at the given storage paths in the backend.
1286 * This will either lock all the files or none (on failure).
1287 * On failure, the StatusValue object will be updated with errors.
1289 * Once the return value goes out scope, the locks will be released and
1290 * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
1292 * @see ScopedLock::factory()
1294 * @param array $paths List of storage paths or map of lock types to path lists
1295 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1296 * @param StatusValue $status StatusValue to update on lock/unlock
1297 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1298 * @return ScopedLock|null Returns null on failure
1300 final public function getScopedFileLocks(
1301 array $paths, $type, StatusValue
$status, $timeout = 0
1303 if ( $type === 'mixed' ) {
1304 foreach ( $paths as &$typePaths ) {
1305 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1308 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1311 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status, $timeout );
1315 * Get an array of scoped locks needed for a batch of file operations.
1317 * Normally, FileBackend::doOperations() handles locking, unless
1318 * the 'nonLocking' param is passed in. This function is useful if you
1319 * want the files to be locked for a broader scope than just when the
1320 * files are changing. For example, if you need to update DB metadata,
1321 * you may want to keep the files locked until finished.
1323 * @see FileBackend::doOperations()
1325 * @param array $ops List of file operations to FileBackend::doOperations()
1326 * @param StatusValue $status StatusValue to update on lock/unlock
1327 * @return ScopedLock|null
1330 abstract public function getScopedLocksForOps( array $ops, StatusValue
$status );
1333 * Get the root storage path of this backend.
1334 * All container paths are "subdirectories" of this path.
1336 * @return string Storage path
1339 final public function getRootStoragePath() {
1340 return "mwstore://{$this->name}";
1344 * Get the storage path for the given container for this backend
1346 * @param string $container Container name
1347 * @return string Storage path
1350 final public function getContainerStoragePath( $container ) {
1351 return $this->getRootStoragePath() . "/{$container}";
1355 * Get the file journal object for this backend
1357 * @return FileJournal
1359 final public function getJournal() {
1360 return $this->fileJournal
;
1364 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1366 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1367 * around as long it needs (which may vary greatly depending on configuration)
1369 * @param array $ops File operation batch for FileBaclend::doOperations()
1370 * @return array File operation batch
1372 protected function resolveFSFileObjects( array $ops ) {
1373 foreach ( $ops as &$op ) {
1374 $src = isset( $op['src'] ) ?
$op['src'] : null;
1375 if ( $src instanceof FSFile
) {
1376 $op['srcRef'] = $src;
1377 $op['src'] = $src->getPath();
1386 * Check if a given path is a "mwstore://" path.
1387 * This does not do any further validation or any existence checks.
1389 * @param string $path
1392 final public static function isStoragePath( $path ) {
1393 return ( strpos( $path, 'mwstore://' ) === 0 );
1397 * Split a storage path into a backend name, a container name,
1398 * and a relative file path. The relative path may be the empty string.
1399 * This does not do any path normalization or traversal checks.
1401 * @param string $storagePath
1402 * @return array (backend, container, rel object) or (null, null, null)
1404 final public static function splitStoragePath( $storagePath ) {
1405 if ( self
::isStoragePath( $storagePath ) ) {
1406 // Remove the "mwstore://" prefix and split the path
1407 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1408 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1409 if ( count( $parts ) == 3 ) {
1410 return $parts; // e.g. "backend/container/path"
1412 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1417 return [ null, null, null ];
1421 * Normalize a storage path by cleaning up directory separators.
1422 * Returns null if the path is not of the format of a valid storage path.
1424 * @param string $storagePath
1425 * @return string|null
1427 final public static function normalizeStoragePath( $storagePath ) {
1428 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1429 if ( $relPath !== null ) { // must be for this backend
1430 $relPath = self
::normalizeContainerPath( $relPath );
1431 if ( $relPath !== null ) {
1432 return ( $relPath != '' )
1433 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1434 : "mwstore://{$backend}/{$container}";
1442 * Get the parent storage directory of a storage path.
1443 * This returns a path like "mwstore://backend/container",
1444 * "mwstore://backend/container/...", or null if there is no parent.
1446 * @param string $storagePath
1447 * @return string|null
1449 final public static function parentStoragePath( $storagePath ) {
1450 $storagePath = dirname( $storagePath );
1451 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1453 return ( $rel === null ) ?
null : $storagePath;
1457 * Get the final extension from a storage or FS path
1459 * @param string $path
1460 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1463 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1464 $i = strrpos( $path, '.' );
1465 $ext = $i ?
substr( $path, $i +
1 ) : '';
1467 if ( $case === 'lowercase' ) {
1468 $ext = strtolower( $ext );
1469 } elseif ( $case === 'uppercase' ) {
1470 $ext = strtoupper( $ext );
1477 * Check if a relative path has no directory traversals
1479 * @param string $path
1483 final public static function isPathTraversalFree( $path ) {
1484 return ( self
::normalizeContainerPath( $path ) !== null );
1488 * Build a Content-Disposition header value per RFC 6266.
1490 * @param string $type One of (attachment, inline)
1491 * @param string $filename Suggested file name (should not contain slashes)
1492 * @throws FileBackendError
1496 final public static function makeContentDisposition( $type, $filename = '' ) {
1499 $type = strtolower( $type );
1500 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1501 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1505 if ( strlen( $filename ) ) {
1506 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1509 return implode( ';', $parts );
1513 * Validate and normalize a relative storage path.
1514 * Null is returned if the path involves directory traversal.
1515 * Traversal is insecure for FS backends and broken for others.
1517 * This uses the same traversal protection as Title::secureAndSplit().
1519 * @param string $path Storage path relative to a container
1520 * @return string|null
1522 final protected static function normalizeContainerPath( $path ) {
1523 // Normalize directory separators
1524 $path = strtr( $path, '\\', '/' );
1525 // Collapse any consecutive directory separators
1526 $path = preg_replace( '![/]{2,}!', '/', $path );
1527 // Remove any leading directory separator
1528 $path = ltrim( $path, '/' );
1529 // Use the same traversal protection as Title::secureAndSplit()
1530 if ( strpos( $path, '.' ) !== false ) {
1534 strpos( $path, './' ) === 0 ||
1535 strpos( $path, '../' ) === 0 ||
1536 strpos( $path, '/./' ) !== false ||
1537 strpos( $path, '/../' ) !== false
1547 * Yields the result of the status wrapper callback on either:
1548 * - StatusValue::newGood() if this method is called without parameters
1549 * - StatusValue::newFatal() with all parameters to this method if passed in
1552 * @return StatusValue
1554 final protected function newStatus() {
1555 $args = func_get_args();
1556 if ( count( $args ) ) {
1557 $sv = call_user_func_array( [ 'StatusValue', 'newFatal' ], $args );
1559 $sv = StatusValue
::newGood();
1562 return $this->wrapStatus( $sv );
1566 * @param StatusValue $sv
1567 * @return StatusValue Modified status or StatusValue subclass
1569 final protected function wrapStatus( StatusValue
$sv ) {
1570 return $this->statusWrapper ?
call_user_func( $this->statusWrapper
, $sv ) : $sv;