Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / libs / filebackend / FileBackend.php
blob705810e6803dfa3eb16fe520df3500d902545d32
1 <?php
2 /**
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.
7 * See [the architecture doc](@ref filebackendarch) for more information.
8 */
10 /**
11 * Base class for all file backends.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
28 * @file
29 * @ingroup FileBackend
32 namespace Wikimedia\FileBackend;
34 use InvalidArgumentException;
35 use LockManager;
36 use MediaWiki\FileBackend\FSFile\TempFSFileFactory;
37 use NullLockManager;
38 use Psr\Log\LoggerAwareInterface;
39 use Psr\Log\LoggerInterface;
40 use Psr\Log\NullLogger;
41 use ScopedLock;
42 use Shellbox\Command\BoxedCommand;
43 use StatusValue;
44 use Wikimedia\FileBackend\FSFile\FSFile;
45 use Wikimedia\FileBackend\FSFile\TempFSFile;
46 use Wikimedia\Message\MessageParam;
47 use Wikimedia\Message\MessageSpecifier;
48 use Wikimedia\ScopedCallback;
50 /**
51 * @brief Base class for all file backend classes (including multi-write backends).
53 * This class defines the methods as abstract that subclasses must implement.
54 * Outside callers can assume that all backends will have these functions.
56 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
57 * The "backend" portion is unique name for the application to refer to a backend, while
58 * the "container" portion is a top-level directory of the backend. The "path" portion
59 * is a relative path that uses UNIX file system (FS) notation, though any particular
60 * backend may not actually be using a local filesystem. Therefore, the relative paths
61 * are only virtual.
63 * Backend contents are stored under "domain"-specific container names by default.
64 * A domain is simply a logical umbrella for entities, such as those belonging to a certain
65 * application or portion of a website, for example. A domain can be local or global.
66 * Global (qualified) backends are achieved by configuring the "domain ID" to a constant.
67 * Global domains are simpler, but local domains can be used by choosing a domain ID based on
68 * the current context, such as which language of a website is being used.
70 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
71 * containers to ones that do not respect the "domain ID".
73 * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
74 * FS-based backends are somewhat more restrictive due to the existence of real
75 * directory files; a regular file cannot have the same name as a directory. Other
76 * backends with virtual directories may not have this limitation. Callers should
77 * store files in such a way that no files and directories are under the same path.
79 * In general, this class allows for callers to access storage through the same
80 * interface, without regard to the underlying storage system. However, calling code
81 * must follow certain patterns and be aware of certain things to ensure compatibility:
82 * - a) Always call prepare() on the parent directory before trying to put a file there;
83 * key/value stores only need the container to exist first, but filesystems need
84 * all the parent directories to exist first (prepare() is aware of all this)
85 * - b) Always call clean() on a directory when it might become empty to avoid empty
86 * directory buildup on filesystems; key/value stores never have empty directories,
87 * so doing this helps preserve consistency in both cases
88 * - c) Likewise, do not rely on the existence of empty directories for anything;
89 * calling directoryExists() on a path that prepare() was previously called on
90 * will return false for key/value stores if there are no files under that path
91 * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
92 * either be a copy of the source file in /tmp or the original source file itself
93 * - e) Use a file layout that results in never attempting to store files over directories
94 * or directories over files; key/value stores allow this but filesystems do not
95 * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
96 * - g) Do not assume that move operations are atomic (difficult with key/value stores)
97 * - h) Do not assume that file stat or read operations always have immediate consistency;
98 * various methods have a "latest" flag that should always be used if up-to-date
99 * information is required (this trades performance for correctness as needed)
100 * - i) Do not assume that directory listings have immediate consistency
102 * Methods of subclasses should avoid throwing exceptions at all costs.
103 * As a corollary, external dependencies should be kept to a minimum.
105 * See [the architecture doc](@ref filebackendarch) for more information.
107 * @stable to extend
109 * @ingroup FileBackend
110 * @since 1.19
112 abstract class FileBackend implements LoggerAwareInterface {
113 /** @var string Unique backend name */
114 protected $name;
116 /** @var string Unique domain name */
117 protected $domainId;
119 /** @var string Read-only explanation message */
120 protected $readOnly;
122 /** @var string When to do operations in parallel */
123 protected $parallelize;
125 /** @var int How many operations can be done in parallel */
126 protected $concurrency;
128 /** @var TempFSFileFactory */
129 protected $tmpFileFactory;
131 /** @var LockManager */
132 protected $lockManager;
133 /** @var LoggerInterface */
134 protected $logger;
135 /** @var callable|null */
136 protected $profiler;
138 /** @var callable */
139 private $obResetFunc;
140 /** @var callable */
141 private $headerFunc;
142 /** @var array Option map for use with HTTPFileStreamer */
143 protected $streamerOptions;
144 /** @var callable|null */
145 protected $statusWrapper;
147 /** Bitfield flags for supported features */
148 public const ATTR_HEADERS = 1; // files can be tagged with standard HTTP headers
149 public const ATTR_METADATA = 2; // files can be stored with metadata key/values
150 public const ATTR_UNICODE_PATHS = 4; // files can have Unicode paths (not just ASCII)
152 /** @var false Idiom for "no info; non-existant file" (since 1.34) */
153 protected const STAT_ABSENT = false;
155 /** @var null Idiom for "no info; I/O errors" (since 1.34) */
156 public const STAT_ERROR = null;
157 /** @var null Idiom for "no file/directory list; I/O errors" (since 1.34) */
158 public const LIST_ERROR = null;
159 /** @var null Idiom for "no temp URL; not supported or I/O errors" (since 1.34) */
160 public const TEMPURL_ERROR = null;
161 /** @var null Idiom for "existence unknown; I/O errors" (since 1.34) */
162 public const EXISTENCE_ERROR = null;
164 /** @var false Idiom for "no timestamp; missing file or I/O errors" (since 1.34) */
165 public const TIMESTAMP_FAIL = false;
166 /** @var false Idiom for "no content; missing file or I/O errors" (since 1.34) */
167 public const CONTENT_FAIL = false;
168 /** @var false Idiom for "no metadata; missing file or I/O errors" (since 1.34) */
169 public const XATTRS_FAIL = false;
170 /** @var false Idiom for "no size; missing file or I/O errors" (since 1.34) */
171 public const SIZE_FAIL = false;
172 /** @var false Idiom for "no SHA1 hash; missing file or I/O errors" (since 1.34) */
173 public const SHA1_FAIL = false;
176 * Create a new backend instance from configuration.
177 * This should only be called from within FileBackendGroup.
178 * @stable to call
180 * @param array $config Parameters include:
181 * - name : The unique name of this backend.
182 * This should consist of alphanumberic, '-', and '_' characters.
183 * This name should not be changed after use.
184 * Note that the name is *not* used in actual container names.
185 * - domainId : Prefix to container names that is unique to this backend.
186 * It should only consist of alphanumberic, '-', and '_' characters.
187 * This ID is what avoids collisions if multiple logical backends
188 * use the same storage system, so this should be set carefully.
189 * - lockManager : LockManager object to use for any file locking.
190 * If not provided, then no file locking will be enforced.
191 * - readOnly : Write operations are disallowed if this is a non-empty string.
192 * It should be an explanation for the backend being read-only.
193 * - parallelize : When to do file operations in parallel (when possible).
194 * Allowed values are "implicit", "explicit" and "off".
195 * - concurrency : How many file operations can be done in parallel.
196 * - tmpDirectory : Directory to use for temporary files.
197 * - tmpFileFactory : Optional TempFSFileFactory object. Only has an effect if
198 * tmpDirectory is not set. If both are unset or null, then the backend will
199 * try to discover a usable temporary directory.
200 * - obResetFunc : alternative callback to clear the output buffer
201 * - streamMimeFunc : alternative method to determine the content type from the path
202 * - headerFunc : alternative callback for sending response headers
203 * - logger : Optional PSR logger object.
204 * - profiler : Optional callback that takes a section name argument and returns
205 * a ScopedCallback instance that ends the profile section in its destructor.
206 * - statusWrapper : Optional callback that is used to wrap returned StatusValues
208 public function __construct( array $config ) {
209 if ( !array_key_exists( 'name', $config ) ) {
210 throw new InvalidArgumentException( 'Backend name not specified.' );
212 $this->name = $config['name'];
213 $this->domainId = $config['domainId'] // e.g. "my_wiki-en_"
214 ?? $config['wikiId'] // b/c alias
215 ?? null;
216 if ( !is_string( $this->name ) || !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
217 throw new InvalidArgumentException( "Backend name '{$this->name}' is invalid." );
219 if ( !is_string( $this->domainId ) ) {
220 throw new InvalidArgumentException(
221 "Backend domain ID not provided for '{$this->name}'." );
223 $this->lockManager = $config['lockManager'] ?? new NullLockManager( [] );
224 $this->readOnly = isset( $config['readOnly'] )
225 ? (string)$config['readOnly']
226 : '';
227 $this->parallelize = isset( $config['parallelize'] )
228 ? (string)$config['parallelize']
229 : 'off';
230 $this->concurrency = isset( $config['concurrency'] )
231 ? (int)$config['concurrency']
232 : 50;
233 $this->obResetFunc = $config['obResetFunc']
234 ?? [ self::class, 'resetOutputBufferTheDefaultWay' ];
235 $this->headerFunc = $config['headerFunc'] ?? 'header';
236 $this->streamerOptions = [
237 'obResetFunc' => $this->obResetFunc,
238 'headerFunc' => $this->headerFunc,
239 'streamMimeFunc' => $config['streamMimeFunc'] ?? null,
242 $this->profiler = $config['profiler'] ?? null;
243 if ( !is_callable( $this->profiler ) ) {
244 $this->profiler = null;
246 $this->logger = $config['logger'] ?? new NullLogger();
247 $this->statusWrapper = $config['statusWrapper'] ?? null;
248 // tmpDirectory gets precedence for backward compatibility
249 if ( isset( $config['tmpDirectory'] ) ) {
250 $this->tmpFileFactory = new TempFSFileFactory( $config['tmpDirectory'] );
251 } else {
252 $this->tmpFileFactory = $config['tmpFileFactory'] ?? new TempFSFileFactory();
256 protected function header( $header ) {
257 ( $this->headerFunc )( $header );
260 protected function resetOutputBuffer() {
261 // By default, this ends up calling $this->defaultOutputBufferReset
262 ( $this->obResetFunc )();
265 public function setLogger( LoggerInterface $logger ) {
266 $this->logger = $logger;
270 * Get the unique backend name
272 * We may have multiple different backends of the same type.
273 * For example, we can have two Swift backends using different proxies.
275 * @return string
277 final public function getName() {
278 return $this->name;
282 * Get the domain identifier used for this backend (possibly empty).
284 * @return string
285 * @since 1.28
287 final public function getDomainId() {
288 return $this->domainId;
292 * Alias to getDomainId()
294 * @return string
295 * @since 1.20
296 * @deprecated Since 1.34 Use getDomainId()
298 final public function getWikiId() {
299 return $this->getDomainId();
303 * Check if this backend is read-only
305 * @return bool
307 final public function isReadOnly() {
308 return ( $this->readOnly != '' );
312 * Get an explanatory message if this backend is read-only
314 * @return string|bool Returns false if the backend is not read-only
316 final public function getReadOnlyReason() {
317 return ( $this->readOnly != '' ) ? $this->readOnly : false;
321 * Get the a bitfield of extra features supported by the backend medium
322 * @stable to override
324 * @return int Bitfield of FileBackend::ATTR_* flags
325 * @since 1.23
327 public function getFeatures() {
328 return self::ATTR_UNICODE_PATHS;
332 * Check if the backend medium supports a field of extra features
334 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
335 * @return bool
336 * @since 1.23
338 final public function hasFeatures( $bitfield ) {
339 return ( $this->getFeatures() & $bitfield ) === $bitfield;
343 * This is the main entry point into the backend for write operations.
344 * Callers supply an ordered list of operations to perform as a transaction.
345 * Files will be locked, the stat cache cleared, and then the operations attempted.
346 * If any serious errors occur, all attempted operations will be rolled back.
348 * $ops is an array of arrays. The outer array holds a list of operations.
349 * Each inner array is a set of key value pairs that specify an operation.
351 * Supported operations and their parameters. The supported actions are:
352 * - create
353 * - store
354 * - copy
355 * - move
356 * - delete
357 * - describe (since 1.21)
358 * - null
360 * FSFile/TempFSFile object support was added in 1.27.
362 * a) Create a new file in storage with the contents of a string
363 * @code
365 * 'op' => 'create',
366 * 'dst' => <storage path>,
367 * 'content' => <string of new file contents>,
368 * 'overwrite' => <boolean>,
369 * 'overwriteSame' => <boolean>,
370 * 'headers' => <HTTP header name/value map> # since 1.21
372 * @endcode
374 * b) Copy a file system file into storage
375 * @code
377 * 'op' => 'store',
378 * 'src' => <file system path, FSFile, or TempFSFile>,
379 * 'dst' => <storage path>,
380 * 'overwrite' => <boolean>,
381 * 'overwriteSame' => <boolean>,
382 * 'headers' => <HTTP header name/value map> # since 1.21
384 * @endcode
386 * c) Copy a file within storage
387 * @code
389 * 'op' => 'copy',
390 * 'src' => <storage path>,
391 * 'dst' => <storage path>,
392 * 'overwrite' => <boolean>,
393 * 'overwriteSame' => <boolean>,
394 * 'ignoreMissingSource' => <boolean>, # since 1.21
395 * 'headers' => <HTTP header name/value map> # since 1.21
397 * @endcode
399 * d) Move a file within storage
400 * @code
402 * 'op' => 'move',
403 * 'src' => <storage path>,
404 * 'dst' => <storage path>,
405 * 'overwrite' => <boolean>,
406 * 'overwriteSame' => <boolean>,
407 * 'ignoreMissingSource' => <boolean>, # since 1.21
408 * 'headers' => <HTTP header name/value map> # since 1.21
410 * @endcode
412 * e) Delete a file within storage
413 * @code
415 * 'op' => 'delete',
416 * 'src' => <storage path>,
417 * 'ignoreMissingSource' => <boolean>
419 * @endcode
421 * f) Update metadata for a file within storage
422 * @code
424 * 'op' => 'describe',
425 * 'src' => <storage path>,
426 * 'headers' => <HTTP header name/value map>
428 * @endcode
430 * g) Do nothing (no-op)
431 * @code
433 * 'op' => 'null',
435 * @endcode
437 * Boolean flags for operations (operation-specific):
438 * - ignoreMissingSource : The operation will simply succeed and do
439 * nothing if the source file does not exist.
440 * - overwrite : Any destination file will be overwritten.
441 * - overwriteSame : If a file already exists at the destination with the
442 * same contents, then do nothing to the destination file
443 * instead of giving an error. This does not compare headers.
444 * This option is ignored if 'overwrite' is already provided.
445 * - headers : If supplied, the result of merging these headers with any
446 * existing source file headers (replacing conflicting ones)
447 * will be set as the destination file headers. Headers are
448 * deleted if their value is set to the empty string. When a
449 * file has headers they are included in responses to GET and
450 * HEAD requests to the backing store for that file.
451 * Header values should be no larger than 255 bytes, except for
452 * Content-Disposition. The system might ignore or truncate any
453 * headers that are too long to store (exact limits will vary).
454 * Backends that don't support metadata ignore this. (since 1.21)
456 * $opts is an associative of boolean flags, including:
457 * - force : Operation precondition errors no longer trigger an abort.
458 * Any remaining operations are still attempted. Unexpected
459 * failures may still cause remaining operations to be aborted.
460 * - nonLocking : No locks are acquired for the operations.
461 * This can increase performance for non-critical writes.
462 * This has no effect unless the 'force' flag is set.
463 * - parallelize : Try to do operations in parallel when possible.
464 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
465 * - preserveCache : Don't clear the process cache before checking files.
466 * This should only be used if all entries in the process
467 * cache were added after the files were already locked. (since 1.20)
469 * @note Remarks on locking:
470 * File system paths given to operations should refer to files that are
471 * already locked or otherwise safe from modification from other processes.
472 * Normally these files will be new temp files, which should be adequate.
474 * @par Return value:
476 * This returns a Status, which contains all warnings and fatals that occurred
477 * during the operation. The 'failCount', 'successCount', and 'success' members
478 * will reflect each operation attempted.
480 * The StatusValue will be "OK" unless:
481 * - a) unexpected operation errors occurred (network partitions, disk full...)
482 * - b) predicted operation errors occurred and 'force' was not set
484 * @param array[] $ops List of operations to execute in order
485 * @phan-param array<int,array{ignoreMissingSource?:bool,overwrite?:bool,overwriteSame?:bool,headers?:bool}> $ops
486 * @param array $opts Batch operation options
487 * @phpcs:ignore Generic.Files.LineLength
488 * @phan-param array{force?:bool,nonLocking?:bool,parallelize?:bool,bypassReadOnly?:bool,preserveCache?:bool} $opts
489 * @return StatusValue
491 final public function doOperations( array $ops, array $opts = [] ) {
492 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
493 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
495 if ( $ops === [] ) {
496 return $this->newStatus(); // nothing to do
499 $ops = $this->resolveFSFileObjects( $ops );
500 if ( empty( $opts['force'] ) ) {
501 unset( $opts['nonLocking'] );
504 /** @noinspection PhpUnusedLocalVariableInspection */
505 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
507 return $this->doOperationsInternal( $ops, $opts );
511 * @see FileBackend::doOperations()
512 * @param array $ops
513 * @param array $opts
514 * @return StatusValue
516 abstract protected function doOperationsInternal( array $ops, array $opts );
519 * Same as doOperations() except it takes a single operation.
520 * If you are doing a batch of operations that should either
521 * all succeed or all fail, then use that function instead.
523 * @see FileBackend::doOperations()
525 * @param array $op Operation
526 * @param array $opts Operation options
527 * @return StatusValue
529 final public function doOperation( array $op, array $opts = [] ) {
530 return $this->doOperations( [ $op ], $opts );
534 * Performs a single create operation.
535 * This sets $params['op'] to 'create' and passes it to doOperation().
537 * @see FileBackend::doOperation()
539 * @param array $params Operation parameters
540 * @param array $opts Operation options
541 * @return StatusValue
543 final public function create( array $params, array $opts = [] ) {
544 return $this->doOperation( [ 'op' => 'create' ] + $params, $opts );
548 * Performs a single store operation.
549 * This sets $params['op'] to 'store' and passes it to doOperation().
551 * @see FileBackend::doOperation()
553 * @param array $params Operation parameters
554 * @param array $opts Operation options
555 * @return StatusValue
557 final public function store( array $params, array $opts = [] ) {
558 return $this->doOperation( [ 'op' => 'store' ] + $params, $opts );
562 * Performs a single copy operation.
563 * This sets $params['op'] to 'copy' and passes it to doOperation().
565 * @see FileBackend::doOperation()
567 * @param array $params Operation parameters
568 * @param array $opts Operation options
569 * @return StatusValue
571 final public function copy( array $params, array $opts = [] ) {
572 return $this->doOperation( [ 'op' => 'copy' ] + $params, $opts );
576 * Performs a single move operation.
577 * This sets $params['op'] to 'move' and passes it to doOperation().
579 * @see FileBackend::doOperation()
581 * @param array $params Operation parameters
582 * @param array $opts Operation options
583 * @return StatusValue
585 final public function move( array $params, array $opts = [] ) {
586 return $this->doOperation( [ 'op' => 'move' ] + $params, $opts );
590 * Performs a single delete operation.
591 * This sets $params['op'] to 'delete' and passes it to doOperation().
593 * @see FileBackend::doOperation()
595 * @param array $params Operation parameters
596 * @param array $opts Operation options
597 * @return StatusValue
599 final public function delete( array $params, array $opts = [] ) {
600 return $this->doOperation( [ 'op' => 'delete' ] + $params, $opts );
604 * Performs a single describe operation.
605 * This sets $params['op'] to 'describe' and passes it to doOperation().
607 * @see FileBackend::doOperation()
609 * @param array $params Operation parameters
610 * @param array $opts Operation options
611 * @return StatusValue
612 * @since 1.21
614 final public function describe( array $params, array $opts = [] ) {
615 return $this->doOperation( [ 'op' => 'describe' ] + $params, $opts );
619 * Perform a set of independent file operations on some files.
621 * This does no locking, and possibly no stat calls.
622 * Any destination files that already exist will be overwritten.
623 * This should *only* be used on non-original files, like cache files.
625 * Supported operations and their parameters:
626 * - create
627 * - store
628 * - copy
629 * - move
630 * - delete
631 * - describe (since 1.21)
632 * - null
634 * FSFile/TempFSFile object support was added in 1.27.
636 * a) Create a new file in storage with the contents of a string
637 * @code
639 * 'op' => 'create',
640 * 'dst' => <storage path>,
641 * 'content' => <string of new file contents>,
642 * 'headers' => <HTTP header name/value map> # since 1.21
644 * @endcode
646 * b) Copy a file system file into storage
647 * @code
649 * 'op' => 'store',
650 * 'src' => <file system path, FSFile, or TempFSFile>,
651 * 'dst' => <storage path>,
652 * 'headers' => <HTTP header name/value map> # since 1.21
654 * @endcode
656 * c) Copy a file within storage
657 * @code
659 * 'op' => 'copy',
660 * 'src' => <storage path>,
661 * 'dst' => <storage path>,
662 * 'ignoreMissingSource' => <boolean>, # since 1.21
663 * 'headers' => <HTTP header name/value map> # since 1.21
665 * @endcode
667 * d) Move a file within storage
668 * @code
670 * 'op' => 'move',
671 * 'src' => <storage path>,
672 * 'dst' => <storage path>,
673 * 'ignoreMissingSource' => <boolean>, # since 1.21
674 * 'headers' => <HTTP header name/value map> # since 1.21
676 * @endcode
678 * e) Delete a file within storage
679 * @code
681 * 'op' => 'delete',
682 * 'src' => <storage path>,
683 * 'ignoreMissingSource' => <boolean>
685 * @endcode
687 * f) Update metadata for a file within storage
688 * @code
690 * 'op' => 'describe',
691 * 'src' => <storage path>,
692 * 'headers' => <HTTP header name/value map>
694 * @endcode
696 * g) Do nothing (no-op)
697 * @code
699 * 'op' => 'null',
701 * @endcode
703 * @par Boolean flags for operations (operation-specific):
704 * - ignoreMissingSource : The operation will simply succeed and do
705 * nothing if the source file does not exist.
706 * - headers : If supplied with a header name/value map, the backend will
707 * reply with these headers when GETs/HEADs of the destination
708 * file are made. Header values should be smaller than 256 bytes.
709 * Content-Disposition headers can be longer, though the system
710 * might ignore or truncate ones that are too long to store.
711 * Existing headers will remain, but these will replace any
712 * conflicting previous headers, and headers will be removed
713 * if they are set to an empty string.
714 * Backends that don't support metadata ignore this. (since 1.21)
716 * $opts is an associative of boolean flags, including:
717 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
719 * @par Return value:
720 * This returns a Status, which contains all warnings and fatals that occurred
721 * during the operation. The 'failCount', 'successCount', and 'success' members
722 * will reflect each operation attempted for the given files. The StatusValue will be
723 * considered "OK" as long as no fatal errors occurred.
725 * @param array $ops Set of operations to execute
726 * @phan-param list<array{op:?string,src?:string,dst?:string,ignoreMissingSource?:bool,headers?:array}> $ops
727 * @param array $opts Batch operation options
728 * @phan-param array{bypassReadOnly?:bool} $opts
729 * @return StatusValue
730 * @since 1.20
732 final public function doQuickOperations( array $ops, array $opts = [] ) {
733 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
734 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
736 if ( $ops === [] ) {
737 return $this->newStatus(); // nothing to do
740 $ops = $this->resolveFSFileObjects( $ops );
741 foreach ( $ops as &$op ) {
742 $op['overwrite'] = true; // avoids RTTs in key/value stores
745 /** @noinspection PhpUnusedLocalVariableInspection */
746 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
748 return $this->doQuickOperationsInternal( $ops, $opts );
752 * @see FileBackend::doQuickOperations()
753 * @param array $ops
754 * @param array $opts
755 * @return StatusValue
756 * @since 1.20
758 abstract protected function doQuickOperationsInternal( array $ops, array $opts );
761 * Same as doQuickOperations() except it takes a single operation.
762 * If you are doing a batch of operations, then use that function instead.
764 * @see FileBackend::doQuickOperations()
766 * @param array $op Operation
767 * @param array $opts Batch operation options
768 * @return StatusValue
769 * @since 1.20
771 final public function doQuickOperation( array $op, array $opts = [] ) {
772 return $this->doQuickOperations( [ $op ], $opts );
776 * Performs a single quick create operation.
777 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
779 * @see FileBackend::doQuickOperation()
781 * @param array $params Operation parameters
782 * @param array $opts Operation options
783 * @return StatusValue
784 * @since 1.20
786 final public function quickCreate( array $params, array $opts = [] ) {
787 return $this->doQuickOperation( [ 'op' => 'create' ] + $params, $opts );
791 * Performs a single quick store operation.
792 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
794 * @see FileBackend::doQuickOperation()
796 * @param array $params Operation parameters
797 * @param array $opts Operation options
798 * @return StatusValue
799 * @since 1.20
801 final public function quickStore( array $params, array $opts = [] ) {
802 return $this->doQuickOperation( [ 'op' => 'store' ] + $params, $opts );
806 * Performs a single quick copy operation.
807 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
809 * @see FileBackend::doQuickOperation()
811 * @param array $params Operation parameters
812 * @param array $opts Operation options
813 * @return StatusValue
814 * @since 1.20
816 final public function quickCopy( array $params, array $opts = [] ) {
817 return $this->doQuickOperation( [ 'op' => 'copy' ] + $params, $opts );
821 * Performs a single quick move operation.
822 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
824 * @see FileBackend::doQuickOperation()
826 * @param array $params Operation parameters
827 * @param array $opts Operation options
828 * @return StatusValue
829 * @since 1.20
831 final public function quickMove( array $params, array $opts = [] ) {
832 return $this->doQuickOperation( [ 'op' => 'move' ] + $params, $opts );
836 * Performs a single quick delete operation.
837 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
839 * @see FileBackend::doQuickOperation()
841 * @param array $params Operation parameters
842 * @param array $opts Operation options
843 * @return StatusValue
844 * @since 1.20
846 final public function quickDelete( array $params, array $opts = [] ) {
847 return $this->doQuickOperation( [ 'op' => 'delete' ] + $params, $opts );
851 * Performs a single quick describe operation.
852 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
854 * @see FileBackend::doQuickOperation()
856 * @param array $params Operation parameters
857 * @param array $opts Operation options
858 * @return StatusValue
859 * @since 1.21
861 final public function quickDescribe( array $params, array $opts = [] ) {
862 return $this->doQuickOperation( [ 'op' => 'describe' ] + $params, $opts );
866 * Concatenate a list of storage files into a single file system file.
867 * The target path should refer to a file that is already locked or
868 * otherwise safe from modification from other processes. Normally,
869 * the file will be a new temp file, which should be adequate.
871 * @param array $params Operation parameters, include:
872 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
873 * - dst : file system path to 0-byte temp file
874 * - parallelize : try to do operations in parallel when possible
875 * @return StatusValue
877 abstract public function concatenate( array $params );
880 * Prepare a storage directory for usage.
881 * This will create any required containers and parent directories.
882 * Backends using key/value stores only need to create the container.
884 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
885 * except they are only applied *if* the directory/container had to be created.
886 * These flags should always be set for directories that have private files.
887 * However, setting them is not guaranteed to actually do anything.
888 * Additional server configuration may be needed to achieve the desired effect.
890 * @param array $params Parameters include:
891 * - dir : storage directory
892 * - noAccess : try to deny file access (since 1.20)
893 * - noListing : try to deny file listing (since 1.20)
894 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
895 * @return StatusValue Good status without value for success, fatal otherwise.
897 final public function prepare( array $params ) {
898 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
899 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
901 /** @noinspection PhpUnusedLocalVariableInspection */
902 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
903 return $this->doPrepare( $params );
907 * @see FileBackend::prepare()
908 * @param array $params
909 * @return StatusValue Good status without value for success, fatal otherwise.
911 abstract protected function doPrepare( array $params );
914 * Take measures to block web access to a storage directory and
915 * the container it belongs to. FS backends might add .htaccess
916 * files whereas key/value store backends might revoke container
917 * access to the storage user representing end-users in web requests.
919 * This is not guaranteed to actually make files or listings publicly hidden.
920 * Additional server configuration may be needed to achieve the desired effect.
922 * @param array $params Parameters include:
923 * - dir : storage directory
924 * - noAccess : try to deny file access
925 * - noListing : try to deny file listing
926 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
927 * @return StatusValue
929 final public function secure( array $params ) {
930 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
931 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
933 /** @noinspection PhpUnusedLocalVariableInspection */
934 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
935 return $this->doSecure( $params );
939 * @see FileBackend::secure()
940 * @param array $params
941 * @return StatusValue
943 abstract protected function doSecure( array $params );
946 * Remove measures to block web access to a storage directory and
947 * the container it belongs to. FS backends might remove .htaccess
948 * files whereas key/value store backends might grant container
949 * access to the storage user representing end-users in web requests.
950 * This essentially can undo the result of secure() calls.
952 * This is not guaranteed to actually make files or listings publicly viewable.
953 * Additional server configuration may be needed to achieve the desired effect.
955 * @param array $params Parameters include:
956 * - dir : storage directory
957 * - access : try to allow file access
958 * - listing : try to allow file listing
959 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
960 * @return StatusValue
961 * @since 1.20
963 final public function publish( array $params ) {
964 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
965 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
967 /** @noinspection PhpUnusedLocalVariableInspection */
968 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
969 return $this->doPublish( $params );
973 * @see FileBackend::publish()
974 * @param array $params
975 * @return StatusValue
977 abstract protected function doPublish( array $params );
980 * Delete a storage directory if it is empty.
981 * Backends using key/value stores may do nothing unless the directory
982 * is that of an empty container, in which case it will be deleted.
984 * @param array $params Parameters include:
985 * - dir : storage directory
986 * - recursive : recursively delete empty subdirectories first (since 1.20)
987 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
988 * @return StatusValue
990 final public function clean( array $params ) {
991 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
992 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
994 /** @noinspection PhpUnusedLocalVariableInspection */
995 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
996 return $this->doClean( $params );
1000 * @see FileBackend::clean()
1001 * @param array $params
1002 * @return StatusValue
1004 abstract protected function doClean( array $params );
1007 * Check if a file exists at a storage path in the backend.
1008 * This returns false if only a directory exists at the path.
1010 * Callers that only care if a file is readily accessible can use non-strict
1011 * comparisons on the result. If "does not exist" and "existence is unknown"
1012 * must be distinguished, then strict comparisons to true/null should be used.
1014 * @see FileBackend::EXISTENCE_ERROR
1015 * @see FileBackend::directoryExists()
1017 * @param array $params Parameters include:
1018 * - src : source storage path
1019 * - latest : use the latest available data
1020 * @return bool|null Whether the file exists or null (I/O error)
1022 abstract public function fileExists( array $params );
1025 * Get the last-modified timestamp of the file at a storage path.
1027 * @see FileBackend::TIMESTAMP_FAIL
1029 * @param array $params Parameters include:
1030 * - src : source storage path
1031 * - latest : use the latest available data
1032 * @return string|false TS_MW timestamp or false (missing file or I/O error)
1034 abstract public function getFileTimestamp( array $params );
1037 * Get the contents of a file at a storage path in the backend.
1038 * This should be avoided for potentially large files.
1040 * @see FileBackend::CONTENT_FAIL
1042 * @param array $params Parameters include:
1043 * - src : source storage path
1044 * - latest : use the latest available data
1045 * @return string|false Content string or false (missing file or I/O error)
1047 final public function getFileContents( array $params ) {
1048 $contents = $this->getFileContentsMulti( [ 'srcs' => [ $params['src'] ] ] + $params );
1050 return $contents[$params['src']];
1054 * Like getFileContents() except it takes an array of storage paths
1055 * and returns an order preserved map of storage paths to their content.
1057 * @see FileBackend::getFileContents()
1059 * @param array $params Parameters include:
1060 * - srcs : list of source storage paths
1061 * - latest : use the latest available data
1062 * - parallelize : try to do operations in parallel when possible
1063 * @return string[]|false[] Map of (path name => file content or false on failure)
1064 * @since 1.20
1066 abstract public function getFileContentsMulti( array $params );
1069 * Get metadata about a file at a storage path in the backend.
1070 * If the file does not exist, then this returns false.
1071 * Otherwise, the result is an associative array that includes:
1072 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
1073 * - metadata : map of file metadata (name => value)
1074 * Metadata keys and headers names will be returned in all lower-case.
1075 * Additional values may be included for internal use only.
1077 * Use FileBackend::hasFeatures() to check how well this is supported.
1079 * @see FileBackend::XATTRS_FAIL
1081 * @param array $params
1082 * $params include:
1083 * - src : source storage path
1084 * - latest : use the latest available data
1085 * @return array|false File metadata array or false (missing file or I/O error)
1086 * @since 1.23
1088 abstract public function getFileXAttributes( array $params );
1091 * Get the size (bytes) of a file at a storage path in the backend.
1093 * @see FileBackend::SIZE_FAIL
1095 * @param array $params Parameters include:
1096 * - src : source storage path
1097 * - latest : use the latest available data
1098 * @return int|false File size in bytes or false (missing file or I/O error)
1100 abstract public function getFileSize( array $params );
1103 * Get quick information about a file at a storage path in the backend.
1104 * If the file does not exist, then this returns false.
1105 * Otherwise, the result is an associative array that includes:
1106 * - mtime : the last-modified timestamp (TS_MW)
1107 * - size : the file size (bytes)
1108 * Additional values may be included for internal use only.
1110 * @see FileBackend::STAT_ABSENT
1111 * @see FileBackend::STAT_ERROR
1113 * @param array $params Parameters include:
1114 * - src : source storage path
1115 * - latest : use the latest available data
1116 * @return array|false|null Attribute map, false (missing file), or null (I/O error)
1118 abstract public function getFileStat( array $params );
1121 * Get a SHA-1 hash of the content of the file at a storage path in the backend.
1123 * @see FileBackend::SHA1_FAIL
1125 * @param array $params Parameters include:
1126 * - src : source storage path
1127 * - latest : use the latest available data
1128 * @return string|false Hash string or false (missing file or I/O error)
1130 abstract public function getFileSha1Base36( array $params );
1133 * Get the properties of the content of the file at a storage path in the backend.
1134 * This gives the result of FSFile::getProps() on a local copy of the file.
1136 * @param array $params Parameters include:
1137 * - src : source storage path
1138 * - latest : use the latest available data
1139 * @return array Properties map; FSFile::placeholderProps() if file missing or on I/O error
1141 abstract public function getFileProps( array $params );
1144 * Stream the content of the file at a storage path in the backend.
1146 * If the file does not exists, an HTTP 404 error will be given.
1147 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1148 * will be sent if streaming began, while none will be sent otherwise.
1149 * Implementations should flush the output buffer before sending data.
1151 * @param array $params Parameters include:
1152 * - src : source storage path
1153 * - headers : list of additional HTTP headers to send if the file exists
1154 * - options : HTTP request header map with lower case keys (since 1.28). Supports:
1155 * range : format is "bytes=(\d*-\d*)"
1156 * if-modified-since : format is an HTTP date
1157 * - headless : do not send HTTP headers (including those of "headers") (since 1.28)
1158 * - latest : use the latest available data
1159 * - allowOB : preserve any output buffers (since 1.28)
1160 * @return StatusValue
1162 abstract public function streamFile( array $params );
1165 * Returns a file system file, identical in content to the file at a storage path.
1166 * The file returned is either:
1167 * - a) A TempFSFile local copy of the file at a storage path in the backend.
1168 * The temporary copy will have the same extension as the source.
1169 * Temporary files may be purged when the file object falls out of scope.
1170 * - b) An FSFile pointing to the original file at a storage path in the backend.
1171 * This is applicable for backends layered directly on top of file systems.
1173 * Never modify the returned file since it might be the original, it might be shared
1174 * among multiple callers of this method, or the backend might internally keep FSFile
1175 * references for deferred operations.
1177 * @param array $params Parameters include:
1178 * - src : source storage path
1179 * - latest : use the latest available data
1180 * @return FSFile|null|false Local file copy or false (missing) or null (error)
1182 final public function getLocalReference( array $params ) {
1183 $fsFiles = $this->getLocalReferenceMulti( [ 'srcs' => [ $params['src'] ] ] + $params );
1185 return $fsFiles[$params['src']];
1189 * Like getLocalReference() except it takes an array of storage paths and
1190 * yields an order-preserved map of storage paths to temporary local file copies.
1192 * Never modify the returned files since they might be originals, they might be shared
1193 * among multiple callers of this method, or the backend might internally keep FSFile
1194 * references for deferred operations.
1196 * @see FileBackend::getLocalReference()
1198 * @param array $params Parameters include:
1199 * - srcs : list of source storage paths
1200 * - latest : use the latest available data
1201 * - parallelize : try to do operations in parallel when possible
1202 * @return array Map of (path name => FSFile or false (missing) or null (error))
1203 * @since 1.20
1205 abstract public function getLocalReferenceMulti( array $params );
1208 * Get a local copy on disk of the file at a storage path in the backend.
1209 * The temporary copy will have the same file extension as the source.
1210 * Temporary files may be purged when the file object falls out of scope.
1212 * Multiple calls to this method for the same path will create new copies.
1214 * @param array $params Parameters include:
1215 * - src : source storage path
1216 * - latest : use the latest available data
1217 * @return TempFSFile|null|false Temporary local file copy or false (missing) or null (error)
1219 final public function getLocalCopy( array $params ) {
1220 $tmpFiles = $this->getLocalCopyMulti( [ 'srcs' => [ $params['src'] ] ] + $params );
1222 return $tmpFiles[$params['src']];
1226 * Like getLocalCopy() except it takes an array of storage paths and yields
1227 * an order preserved-map of storage paths to temporary local file copies.
1229 * Multiple calls to this method for the same path will create new copies.
1231 * @see FileBackend::getLocalCopy()
1233 * @param array $params Parameters include:
1234 * - srcs : list of source storage paths
1235 * - latest : use the latest available data
1236 * - parallelize : try to do operations in parallel when possible
1237 * @return array Map of (path name => TempFSFile or false (missing) or null (error))
1238 * @since 1.20
1240 abstract public function getLocalCopyMulti( array $params );
1243 * Return an HTTP URL to a given file that requires no authentication to use.
1244 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1245 * This will return null if the backend cannot make an HTTP URL for the file.
1247 * This is useful for key/value stores when using scripts that seek around
1248 * large files and those scripts (and the backend) support HTTP Range headers.
1249 * Otherwise, one would need to use getLocalReference(), which involves loading
1250 * the entire file on to local disk.
1252 * @see FileBackend::TEMPURL_ERROR
1254 * @param array $params Parameters include:
1255 * - src : source storage path
1256 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1257 * - latest : use the latest available data
1258 * - method : the allowed method; default GET
1259 * - ipRange : the allowed IP range; default unlimited
1260 * @return string|null URL or null (not supported or I/O error)
1261 * @since 1.21
1263 abstract public function getFileHttpUrl( array $params );
1266 * Add a file to a Shellbox command as an input file.
1268 * @param BoxedCommand $command
1269 * @param string $boxedName
1270 * @param array $params Parameters include:
1271 * - src : source storage path
1272 * - latest : use the latest available data
1273 * @return StatusValue
1274 * @since 1.43
1276 abstract public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1277 array $params );
1280 * Check if a directory exists at a given storage path
1282 * For backends using key/value stores, a directory is said to exist whenever
1283 * there exist any files with paths using the given directory path as a prefix
1284 * followed by a forward slash. For example, if there is a file called
1285 * "mwstore://backend/container/dir/path.svg" then directories are said to exist
1286 * at "mwstore://backend/container" and "mwstore://backend/container/dir". These
1287 * can be thought of as "virtual" directories.
1289 * Backends that directly use a filesystem layer might enumerate empty directories.
1290 * The clean() method should always be used when files are deleted or moved if this
1291 * is a concern. This is a trade-off to avoid write amplication/contention on file
1292 * changes or read amplification when calling this method.
1294 * Storage backends with eventual consistency might return stale data.
1296 * @see FileBackend::EXISTENCE_ERROR
1297 * @see FileBackend::clean()
1299 * @param array $params Parameters include:
1300 * - dir : storage directory
1301 * @return bool|null Whether a directory exists or null (I/O error)
1302 * @since 1.20
1304 abstract public function directoryExists( array $params );
1307 * Get an iterator to list *all* directories under a storage directory
1309 * If the directory is of the form "mwstore://backend/container",
1310 * then all directories in the container will be listed.
1311 * If the directory is of form "mwstore://backend/container/dir",
1312 * then all directories directly under that directory will be listed.
1313 * Results will be storage directories relative to the given directory.
1315 * Storage backends with eventual consistency might return stale data.
1317 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1319 * @see FileBackend::LIST_ERROR
1320 * @see FileBackend::directoryExists()
1322 * @param array $params Parameters include:
1323 * - dir : storage directory
1324 * - topOnly : only return direct child dirs of the directory
1325 * @return \Traversable|array|null Directory list enumerator or null (initial I/O error)
1326 * @since 1.20
1328 abstract public function getDirectoryList( array $params );
1331 * Same as FileBackend::getDirectoryList() except only lists
1332 * directories that are immediately under the given directory.
1334 * Storage backends with eventual consistency might return stale data.
1336 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1338 * @see FileBackend::LIST_ERROR
1339 * @see FileBackend::directoryExists()
1341 * @param array $params Parameters include:
1342 * - dir : storage directory
1343 * @return \Traversable|array|null Directory list enumerator or null (initial I/O error)
1344 * @since 1.20
1346 final public function getTopDirectoryList( array $params ) {
1347 return $this->getDirectoryList( [ 'topOnly' => true ] + $params );
1351 * Get an iterator to list *all* stored files under a storage directory
1353 * If the directory is of the form "mwstore://backend/container", then all
1354 * files in the container will be listed. If the directory is of form
1355 * "mwstore://backend/container/dir", then all files under that directory will
1356 * be listed. Results will be storage paths relative to the given directory.
1358 * Storage backends with eventual consistency might return stale data.
1360 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1362 * @see FileBackend::LIST_ERROR
1364 * @param array $params Parameters include:
1365 * - dir : storage directory
1366 * - topOnly : only return direct child files of the directory (since 1.20)
1367 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1368 * - forWrite : true if the list will inform a write operations (since 1.41)
1369 * @return \Traversable|array|null File list enumerator or null (initial I/O error)
1371 abstract public function getFileList( array $params );
1374 * Same as FileBackend::getFileList() except only lists
1375 * files that are immediately under the given directory.
1377 * Storage backends with eventual consistency might return stale data.
1379 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1381 * @see FileBackend::LIST_ERROR
1383 * @param array $params Parameters include:
1384 * - dir : storage directory
1385 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1386 * @return \Traversable|array|null File list enumerator or null on failure
1387 * @since 1.20
1389 final public function getTopFileList( array $params ) {
1390 return $this->getFileList( [ 'topOnly' => true ] + $params );
1394 * Preload persistent file stat cache and property cache into in-process cache.
1395 * This should be used when stat calls will be made on a known list of a many files.
1397 * @see FileBackend::getFileStat()
1399 * @param array $paths Storage paths
1401 abstract public function preloadCache( array $paths );
1404 * Invalidate any in-process file stat and property cache.
1405 * If $paths is given, then only the cache for those files will be cleared.
1407 * @see FileBackend::getFileStat()
1409 * @param array|null $paths Storage paths (optional)
1411 abstract public function clearCache( ?array $paths = null );
1414 * Preload file stat information (concurrently if possible) into in-process cache.
1416 * This should be used when stat calls will be made on a known list of a many files.
1417 * This does not make use of the persistent file stat cache.
1419 * @see FileBackend::getFileStat()
1421 * @param array $params Parameters include:
1422 * - srcs : list of source storage paths
1423 * - latest : use the latest available data
1424 * @return bool Whether all requests proceeded without I/O errors (since 1.24)
1425 * @since 1.23
1427 abstract public function preloadFileStat( array $params );
1430 * Lock the files at the given storage paths in the backend.
1431 * This will either lock all the files or none (on failure).
1433 * Callers should consider using getScopedFileLocks() instead.
1435 * @param array $paths Storage paths
1436 * @param int $type LockManager::LOCK_* constant
1437 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1438 * @return StatusValue
1440 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1441 $paths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $paths );
1443 return $this->wrapStatus( $this->lockManager->lock( $paths, $type, $timeout ) );
1447 * Unlock the files at the given storage paths in the backend.
1449 * @param array $paths Storage paths
1450 * @param int $type LockManager::LOCK_* constant
1451 * @return StatusValue
1453 final public function unlockFiles( array $paths, $type ) {
1454 $paths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $paths );
1456 return $this->wrapStatus( $this->lockManager->unlock( $paths, $type ) );
1460 * Lock the files at the given storage paths in the backend.
1461 * This will either lock all the files or none (on failure).
1462 * On failure, the StatusValue object will be updated with errors.
1464 * Once the return value goes out scope, the locks will be released and
1465 * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
1467 * @see ScopedLock::factory()
1469 * @param array $paths List of storage paths or map of lock types to path lists
1470 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1471 * @param StatusValue $status StatusValue to update on lock/unlock
1472 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1473 * @return ScopedLock|null RAII-style self-unlocking lock or null on failure
1475 final public function getScopedFileLocks(
1476 array $paths, $type, StatusValue $status, $timeout = 0
1478 if ( $type === 'mixed' ) {
1479 foreach ( $paths as &$typePaths ) {
1480 $typePaths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $typePaths );
1482 } else {
1483 $paths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $paths );
1486 return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
1490 * Get an array of scoped locks needed for a batch of file operations.
1492 * Normally, FileBackend::doOperations() handles locking, unless
1493 * the 'nonLocking' param is passed in. This function is useful if you
1494 * want the files to be locked for a broader scope than just when the
1495 * files are changing. For example, if you need to update DB metadata,
1496 * you may want to keep the files locked until finished.
1498 * @see FileBackend::doOperations()
1500 * @param array $ops List of file operations to FileBackend::doOperations()
1501 * @param StatusValue $status StatusValue to update on lock/unlock
1502 * @return ScopedLock|null RAII-style self-unlocking lock or null on failure
1503 * @since 1.20
1505 abstract public function getScopedLocksForOps( array $ops, StatusValue $status );
1508 * Get the root storage path of this backend.
1509 * All container paths are "subdirectories" of this path.
1511 * @return string Storage path
1512 * @since 1.20
1514 final public function getRootStoragePath() {
1515 return "mwstore://{$this->name}";
1519 * Get the storage path for the given container for this backend
1521 * @param string $container Container name
1522 * @return string Storage path
1523 * @since 1.21
1525 final public function getContainerStoragePath( $container ) {
1526 return $this->getRootStoragePath() . "/{$container}";
1530 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1532 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1533 * around as long it needs (which may vary greatly depending on configuration)
1535 * @param array $ops File operation batch for FileBaclend::doOperations()
1536 * @return array File operation batch
1538 protected function resolveFSFileObjects( array $ops ) {
1539 foreach ( $ops as &$op ) {
1540 $src = $op['src'] ?? null;
1541 if ( $src instanceof FSFile ) {
1542 $op['srcRef'] = $src;
1543 $op['src'] = $src->getPath();
1546 unset( $op );
1548 return $ops;
1552 * Check if a given path is a "mwstore://" path.
1553 * This does not do any further validation or any existence checks.
1555 * @param string|null $path
1556 * @return bool
1558 final public static function isStoragePath( $path ) {
1559 return ( strpos( $path ?? '', 'mwstore://' ) === 0 );
1563 * Split a storage path into a backend name, a container name,
1564 * and a relative file path. The relative path may be the empty string.
1565 * This does not do any path normalization or traversal checks.
1567 * @param string $storagePath
1568 * @return array (backend, container, rel object) or (null, null, null)
1570 final public static function splitStoragePath( $storagePath ) {
1571 if ( self::isStoragePath( $storagePath ) ) {
1572 // Remove the "mwstore://" prefix and split the path
1573 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1574 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1575 if ( count( $parts ) == 3 ) {
1576 return $parts; // e.g. "backend/container/path"
1577 } else {
1578 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1583 return [ null, null, null ];
1587 * Normalize a storage path by cleaning up directory separators.
1588 * Returns null if the path is not of the format of a valid storage path.
1590 * @param string $storagePath
1591 * @return string|null Normalized storage path or null on failure
1593 final public static function normalizeStoragePath( $storagePath ) {
1594 [ $backend, $container, $relPath ] = self::splitStoragePath( $storagePath );
1595 if ( $relPath !== null ) { // must be for this backend
1596 $relPath = self::normalizeContainerPath( $relPath );
1597 if ( $relPath !== null ) {
1598 return ( $relPath != '' )
1599 ? "mwstore://{$backend}/{$container}/{$relPath}"
1600 : "mwstore://{$backend}/{$container}";
1604 return null;
1608 * Get the parent storage directory of a storage path.
1609 * This returns a path like "mwstore://backend/container",
1610 * "mwstore://backend/container/...", or null if there is no parent.
1612 * @param string $storagePath
1613 * @return string|null Parent storage path or null on failure
1615 final public static function parentStoragePath( $storagePath ) {
1616 // XXX dirname() depends on platform and locale! If nothing enforces that the storage path
1617 // doesn't contain characters like '\', behavior can vary by platform. We should use
1618 // explode() instead.
1619 $storagePath = dirname( $storagePath );
1620 [ , , $rel ] = self::splitStoragePath( $storagePath );
1622 return ( $rel === null ) ? null : $storagePath;
1626 * Get the final extension from a storage or FS path
1628 * @param string $path
1629 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1630 * @return string
1632 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1633 // This will treat a string starting with . as not having an extension, but store paths have
1634 // to start with 'mwstore://', so "garbage in, garbage out".
1635 $i = strrpos( $path, '.' );
1636 $ext = $i ? substr( $path, $i + 1 ) : '';
1638 if ( $case === 'lowercase' ) {
1639 $ext = strtolower( $ext );
1640 } elseif ( $case === 'uppercase' ) {
1641 $ext = strtoupper( $ext );
1644 return $ext;
1648 * Check if a relative path has no directory traversals
1650 * @param string $path
1651 * @return bool
1652 * @since 1.20
1654 final public static function isPathTraversalFree( $path ) {
1655 return ( self::normalizeContainerPath( $path ) !== null );
1659 * Build a Content-Disposition header value per RFC 6266.
1661 * @param string $type One of (attachment, inline)
1662 * @param string $filename Suggested file name (should not contain slashes)
1663 * @return string
1664 * @since 1.20
1666 final public static function makeContentDisposition( $type, $filename = '' ) {
1667 $parts = [];
1669 $type = strtolower( $type );
1670 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1671 throw new InvalidArgumentException( "Invalid Content-Disposition type '$type'." );
1673 $parts[] = $type;
1675 if ( strlen( $filename ) ) {
1676 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1679 return implode( ';', $parts );
1683 * Validate and normalize a relative storage path.
1684 * Null is returned if the path involves directory traversal.
1685 * Traversal is insecure for FS backends and broken for others.
1687 * This uses the same traversal protection as Title::secureAndSplit().
1689 * @param string $path Storage path relative to a container
1690 * @return string|null Normalized container path or null on failure
1692 final protected static function normalizeContainerPath( $path ) {
1693 // Normalize directory separators
1694 $path = strtr( $path, '\\', '/' );
1695 // Collapse any consecutive directory separators
1696 $path = preg_replace( '![/]{2,}!', '/', $path );
1697 // Remove any leading directory separator
1698 $path = ltrim( $path, '/' );
1699 // Use the same traversal protection as Title::secureAndSplit()
1700 if ( strpos( $path, '.' ) !== false ) {
1701 if (
1702 $path === '.' ||
1703 $path === '..' ||
1704 strpos( $path, './' ) === 0 ||
1705 strpos( $path, '../' ) === 0 ||
1706 strpos( $path, '/./' ) !== false ||
1707 strpos( $path, '/../' ) !== false
1709 return null;
1713 return $path;
1717 * Yields the result of the status wrapper callback on either:
1718 * - StatusValue::newGood(), if this method is called without a message
1719 * - StatusValue::newFatal( ... ) with all parameters to this method, if a message was given
1721 * @param null|string $message Message key
1722 * @phpcs:ignore Generic.Files.LineLength
1723 * @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params
1724 * See Message::params()
1725 * @return StatusValue
1727 final protected function newStatus( $message = null, ...$params ) {
1728 if ( $message !== null ) {
1729 $sv = StatusValue::newFatal( $message, ...$params );
1730 } else {
1731 $sv = StatusValue::newGood();
1734 return $this->wrapStatus( $sv );
1738 * @param StatusValue $sv
1739 * @return StatusValue Modified status or StatusValue subclass
1741 final protected function wrapStatus( StatusValue $sv ) {
1742 return $this->statusWrapper ? call_user_func( $this->statusWrapper, $sv ) : $sv;
1746 * @param string $section
1747 * @return ScopedCallback|null
1749 protected function scopedProfileSection( $section ) {
1750 return $this->profiler ? ( $this->profiler )( $section ) : null;
1754 * Default behavior of resetOutputBuffer().
1755 * @codeCoverageIgnore
1756 * @internal
1758 public static function resetOutputBufferTheDefaultWay() {
1759 // XXX According to documentation, ob_get_status() always returns a non-empty array and this
1760 // condition will always be true
1761 while ( ob_get_status() ) {
1762 if ( !ob_end_clean() ) {
1763 // Could not remove output buffer handler; abort now
1764 // to avoid getting in some kind of infinite loop.
1765 break;
1771 * Return options for use with HTTPFileStreamer.
1773 * @internal
1775 public function getStreamerOptions(): array {
1776 return $this->streamerOptions;
1779 /** @deprecated class alias since 1.43 */
1780 class_alias( FileBackend::class, 'FileBackend' );