Debian Codegraph @

includes/libs/filebackend/FileBackend.php

raw symbols SCIP
1 <?php
2 /**
3 * @defgroup FileBackend File backend
4 *
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 */
9
10 /**
11 * Base class for all file backends.
12 *
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.
17 *
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.
22 *
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
27 *
28 * @file
29 * @ingroup FileBackend
30 */
31
32 namespace Wikimedia\FileBackend;
33
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\ScopedCallback;
47
48 /**
49 * @brief Base class for all file backend classes (including multi-write backends).
50 *
51 * This class defines the methods as abstract that subclasses must implement.
52 * Outside callers can assume that all backends will have these functions.
53 *
54 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
55 * The "backend" portion is unique name for the application to refer to a backend, while
56 * the "container" portion is a top-level directory of the backend. The "path" portion
57 * is a relative path that uses UNIX file system (FS) notation, though any particular
58 * backend may not actually be using a local filesystem. Therefore, the relative paths
59 * are only virtual.
60 *
61 * Backend contents are stored under "domain"-specific container names by default.
62 * A domain is simply a logical umbrella for entities, such as those belonging to a certain
63 * application or portion of a website, for example. A domain can be local or global.
64 * Global (qualified) backends are achieved by configuring the "domain ID" to a constant.
65 * Global domains are simpler, but local domains can be used by choosing a domain ID based on
66 * the current context, such as which language of a website is being used.
67 *
68 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
69 * containers to ones that do not respect the "domain ID".
70 *
71 * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
72 * FS-based backends are somewhat more restrictive due to the existence of real
73 * directory files; a regular file cannot have the same name as a directory. Other
74 * backends with virtual directories may not have this limitation. Callers should
75 * store files in such a way that no files and directories are under the same path.
76 *
77 * In general, this class allows for callers to access storage through the same
78 * interface, without regard to the underlying storage system. However, calling code
79 * must follow certain patterns and be aware of certain things to ensure compatibility:
80 * - a) Always call prepare() on the parent directory before trying to put a file there;
81 * key/value stores only need the container to exist first, but filesystems need
82 * all the parent directories to exist first (prepare() is aware of all this)
83 * - b) Always call clean() on a directory when it might become empty to avoid empty
84 * directory buildup on filesystems; key/value stores never have empty directories,
85 * so doing this helps preserve consistency in both cases
86 * - c) Likewise, do not rely on the existence of empty directories for anything;
87 * calling directoryExists() on a path that prepare() was previously called on
88 * will return false for key/value stores if there are no files under that path
89 * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
90 * either be a copy of the source file in /tmp or the original source file itself
91 * - e) Use a file layout that results in never attempting to store files over directories
92 * or directories over files; key/value stores allow this but filesystems do not
93 * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
94 * - g) Do not assume that move operations are atomic (difficult with key/value stores)
95 * - h) Do not assume that file stat or read operations always have immediate consistency;
96 * various methods have a "latest" flag that should always be used if up-to-date
97 * information is required (this trades performance for correctness as needed)
98 * - i) Do not assume that directory listings have immediate consistency
99 *
100 * Methods of subclasses should avoid throwing exceptions at all costs.
101 * As a corollary, external dependencies should be kept to a minimum.
102 *
103 * See [the architecture doc](@ref filebackendarch) for more information.
104 *
105 * @stable to extend
106 *
107 * @ingroup FileBackend
108 * @since 1.19
109 */
110 abstract class FileBackend implements LoggerAwareInterface {
111 /** @var string Unique backend name */
112 protected $name;
113
114 /** @var string Unique domain name */
115 protected $domainId;
116
117 /** @var string Read-only explanation message */
118 protected $readOnly;
119
120 /** @var string When to do operations in parallel */
121 protected $parallelize;
122
123 /** @var int How many operations can be done in parallel */
124 protected $concurrency;
125
126 /** @var TempFSFileFactory */
127 protected $tmpFileFactory;
128
129 /** @var LockManager */
130 protected $lockManager;
131 /** @var LoggerInterface */
132 protected $logger;
133 /** @var callable|null */
134 protected $profiler;
135
136 /** @var callable */
137 private $obResetFunc;
138 /** @var callable */
139 private $headerFunc;
140 /** @var array Option map for use with HTTPFileStreamer */
141 protected $streamerOptions;
142 /** @var callable|null */
143 protected $statusWrapper;
144
145 /** Bitfield flags for supported features */
146 public const ATTR_HEADERS = 1; // files can be tagged with standard HTTP headers
147 public const ATTR_METADATA = 2; // files can be stored with metadata key/values
148 public const ATTR_UNICODE_PATHS = 4; // files can have Unicode paths (not just ASCII)
149
150 /** @var false Idiom for "no info; non-existant file" (since 1.34) */
151 protected const STAT_ABSENT = false;
152
153 /** @var null Idiom for "no info; I/O errors" (since 1.34) */
154 public const STAT_ERROR = null;
155 /** @var null Idiom for "no file/directory list; I/O errors" (since 1.34) */
156 public const LIST_ERROR = null;
157 /** @var null Idiom for "no temp URL; not supported or I/O errors" (since 1.34) */
158 public const TEMPURL_ERROR = null;
159 /** @var null Idiom for "existence unknown; I/O errors" (since 1.34) */
160 public const EXISTENCE_ERROR = null;
161
162 /** @var false Idiom for "no timestamp; missing file or I/O errors" (since 1.34) */
163 public const TIMESTAMP_FAIL = false;
164 /** @var false Idiom for "no content; missing file or I/O errors" (since 1.34) */
165 public const CONTENT_FAIL = false;
166 /** @var false Idiom for "no metadata; missing file or I/O errors" (since 1.34) */
167 public const XATTRS_FAIL = false;
168 /** @var false Idiom for "no size; missing file or I/O errors" (since 1.34) */
169 public const SIZE_FAIL = false;
170 /** @var false Idiom for "no SHA1 hash; missing file or I/O errors" (since 1.34) */
171 public const SHA1_FAIL = false;
172
173 /**
174 * Create a new backend instance from configuration.
175 * This should only be called from within FileBackendGroup.
176 * @stable to call
177 *
178 * @param array $config Parameters include:
179 * - name : The unique name of this backend.
180 * This should consist of alphanumberic, '-', and '_' characters.
181 * This name should not be changed after use.
182 * Note that the name is *not* used in actual container names.
183 * - domainId : Prefix to container names that is unique to this backend.
184 * It should only consist of alphanumberic, '-', and '_' characters.
185 * This ID is what avoids collisions if multiple logical backends
186 * use the same storage system, so this should be set carefully.
187 * - lockManager : LockManager object to use for any file locking.
188 * If not provided, then no file locking will be enforced.
189 * - readOnly : Write operations are disallowed if this is a non-empty string.
190 * It should be an explanation for the backend being read-only.
191 * - parallelize : When to do file operations in parallel (when possible).
192 * Allowed values are "implicit", "explicit" and "off".
193 * - concurrency : How many file operations can be done in parallel.
194 * - tmpDirectory : Directory to use for temporary files.
195 * - tmpFileFactory : Optional TempFSFileFactory object. Only has an effect if
196 * tmpDirectory is not set. If both are unset or null, then the backend will
197 * try to discover a usable temporary directory.
198 * - obResetFunc : alternative callback to clear the output buffer
199 * - streamMimeFunc : alternative method to determine the content type from the path
200 * - headerFunc : alternative callback for sending response headers
201 * - logger : Optional PSR logger object.
202 * - profiler : Optional callback that takes a section name argument and returns
203 * a ScopedCallback instance that ends the profile section in its destructor.
204 * - statusWrapper : Optional callback that is used to wrap returned StatusValues
205 */
206 public function __construct( array $config ) {
207 if ( !array_key_exists( 'name', $config ) ) {
208 throw new InvalidArgumentException( 'Backend name not specified.' );
209 }
210 $this->name = $config['name'];
211 $this->domainId = $config['domainId'] // e.g. "my_wiki-en_"
212 ?? $config['wikiId'] // b/c alias
213 ?? null;
214 if ( !is_string( $this->name ) || !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
215 throw new InvalidArgumentException( "Backend name '{$this->name}' is invalid." );
216 }
217 if ( !is_string( $this->domainId ) ) {
218 throw new InvalidArgumentException(
219 "Backend domain ID not provided for '{$this->name}'." );
220 }
221 $this->lockManager = $config['lockManager'] ?? new NullLockManager( [] );
222 $this->readOnly = isset( $config['readOnly'] )
223 ? (string)$config['readOnly']
224 : '';
225 $this->parallelize = isset( $config['parallelize'] )
226 ? (string)$config['parallelize']
227 : 'off';
228 $this->concurrency = isset( $config['concurrency'] )
229 ? (int)$config['concurrency']
230 : 50;
231 $this->obResetFunc = $config['obResetFunc']
232 ?? [ self::class, 'resetOutputBufferTheDefaultWay' ];
233 $this->headerFunc = $config['headerFunc'] ?? 'header';
234 $this->streamerOptions = [
235 'obResetFunc' => $this->obResetFunc,
236 'headerFunc' => $this->headerFunc,
237 'streamMimeFunc' => $config['streamMimeFunc'] ?? null,
238 ];
239
240 $this->profiler = $config['profiler'] ?? null;
241 if ( !is_callable( $this->profiler ) ) {
242 $this->profiler = null;
243 }
244 $this->logger = $config['logger'] ?? new NullLogger();
245 $this->statusWrapper = $config['statusWrapper'] ?? null;
246 // tmpDirectory gets precedence for backward compatibility
247 if ( isset( $config['tmpDirectory'] ) ) {
248 $this->tmpFileFactory = new TempFSFileFactory( $config['tmpDirectory'] );
249 } else {
250 $this->tmpFileFactory = $config['tmpFileFactory'] ?? new TempFSFileFactory();
251 }
252 }
253
254 protected function header( $header ) {
255 ( $this->headerFunc )( $header );
256 }
257
258 protected function resetOutputBuffer() {
259 // By default, this ends up calling $this->defaultOutputBufferReset
260 ( $this->obResetFunc )();
261 }
262
263 public function setLogger( LoggerInterface $logger ) {
264 $this->logger = $logger;
265 }
266
267 /**
268 * Get the unique backend name
269 *
270 * We may have multiple different backends of the same type.
271 * For example, we can have two Swift backends using different proxies.
272 *
273 * @return string
274 */
275 final public function getName() {
276 return $this->name;
277 }
278
279 /**
280 * Get the domain identifier used for this backend (possibly empty).
281 *
282 * @return string
283 * @since 1.28
284 */
285 final public function getDomainId() {
286 return $this->domainId;
287 }
288
289 /**
290 * Alias to getDomainId()
291 *
292 * @return string
293 * @since 1.20
294 * @deprecated Since 1.34 Use getDomainId()
295 */
296 final public function getWikiId() {
297 return $this->getDomainId();
298 }
299
300 /**
301 * Check if this backend is read-only
302 *
303 * @return bool
304 */
305 final public function isReadOnly() {
306 return ( $this->readOnly != '' );
307 }
308
309 /**
310 * Get an explanatory message if this backend is read-only
311 *
312 * @return string|bool Returns false if the backend is not read-only
313 */
314 final public function getReadOnlyReason() {
315 return ( $this->readOnly != '' ) ? $this->readOnly : false;
316 }
317
318 /**
319 * Get the a bitfield of extra features supported by the backend medium
320 * @stable to override
321 *
322 * @return int Bitfield of FileBackend::ATTR_* flags
323 * @since 1.23
324 */
325 public function getFeatures() {
326 return self::ATTR_UNICODE_PATHS;
327 }
328
329 /**
330 * Check if the backend medium supports a field of extra features
331 *
332 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
333 * @return bool
334 * @since 1.23
335 */
336 final public function hasFeatures( $bitfield ) {
337 return ( $this->getFeatures() & $bitfield ) === $bitfield;
338 }
339
340 /**
341 * This is the main entry point into the backend for write operations.
342 * Callers supply an ordered list of operations to perform as a transaction.
343 * Files will be locked, the stat cache cleared, and then the operations attempted.
344 * If any serious errors occur, all attempted operations will be rolled back.
345 *
346 * $ops is an array of arrays. The outer array holds a list of operations.
347 * Each inner array is a set of key value pairs that specify an operation.
348 *
349 * Supported operations and their parameters. The supported actions are:
350 * - create
351 * - store
352 * - copy
353 * - move
354 * - delete
355 * - describe (since 1.21)
356 * - null
357 *
358 * FSFile/TempFSFile object support was added in 1.27.
359 *
360 * a) Create a new file in storage with the contents of a string
361 * @code
362 * [
363 * 'op' => 'create',
364 * 'dst' => <storage path>,
365 * 'content' => <string of new file contents>,
366 * 'overwrite' => <boolean>,
367 * 'overwriteSame' => <boolean>,
368 * 'headers' => <HTTP header name/value map> # since 1.21
369 * ]
370 * @endcode
371 *
372 * b) Copy a file system file into storage
373 * @code
374 * [
375 * 'op' => 'store',
376 * 'src' => <file system path, FSFile, or TempFSFile>,
377 * 'dst' => <storage path>,
378 * 'overwrite' => <boolean>,
379 * 'overwriteSame' => <boolean>,
380 * 'headers' => <HTTP header name/value map> # since 1.21
381 * ]
382 * @endcode
383 *
384 * c) Copy a file within storage
385 * @code
386 * [
387 * 'op' => 'copy',
388 * 'src' => <storage path>,
389 * 'dst' => <storage path>,
390 * 'overwrite' => <boolean>,
391 * 'overwriteSame' => <boolean>,
392 * 'ignoreMissingSource' => <boolean>, # since 1.21
393 * 'headers' => <HTTP header name/value map> # since 1.21
394 * ]
395 * @endcode
396 *
397 * d) Move a file within storage
398 * @code
399 * [
400 * 'op' => 'move',
401 * 'src' => <storage path>,
402 * 'dst' => <storage path>,
403 * 'overwrite' => <boolean>,
404 * 'overwriteSame' => <boolean>,
405 * 'ignoreMissingSource' => <boolean>, # since 1.21
406 * 'headers' => <HTTP header name/value map> # since 1.21
407 * ]
408 * @endcode
409 *
410 * e) Delete a file within storage
411 * @code
412 * [
413 * 'op' => 'delete',
414 * 'src' => <storage path>,
415 * 'ignoreMissingSource' => <boolean>
416 * ]
417 * @endcode
418 *
419 * f) Update metadata for a file within storage
420 * @code
421 * [
422 * 'op' => 'describe',
423 * 'src' => <storage path>,
424 * 'headers' => <HTTP header name/value map>
425 * ]
426 * @endcode
427 *
428 * g) Do nothing (no-op)
429 * @code
430 * [
431 * 'op' => 'null',
432 * ]
433 * @endcode
434 *
435 * Boolean flags for operations (operation-specific):
436 * - ignoreMissingSource : The operation will simply succeed and do
437 * nothing if the source file does not exist.
438 * - overwrite : Any destination file will be overwritten.
439 * - overwriteSame : If a file already exists at the destination with the
440 * same contents, then do nothing to the destination file
441 * instead of giving an error. This does not compare headers.
442 * This option is ignored if 'overwrite' is already provided.
443 * - headers : If supplied, the result of merging these headers with any
444 * existing source file headers (replacing conflicting ones)
445 * will be set as the destination file headers. Headers are
446 * deleted if their value is set to the empty string. When a
447 * file has headers they are included in responses to GET and
448 * HEAD requests to the backing store for that file.
449 * Header values should be no larger than 255 bytes, except for
450 * Content-Disposition. The system might ignore or truncate any
451 * headers that are too long to store (exact limits will vary).
452 * Backends that don't support metadata ignore this. (since 1.21)
453 *
454 * $opts is an associative of boolean flags, including:
455 * - force : Operation precondition errors no longer trigger an abort.
456 * Any remaining operations are still attempted. Unexpected
457 * failures may still cause remaining operations to be aborted.
458 * - nonLocking : No locks are acquired for the operations.
459 * This can increase performance for non-critical writes.
460 * This has no effect unless the 'force' flag is set.
461 * - parallelize : Try to do operations in parallel when possible.
462 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
463 * - preserveCache : Don't clear the process cache before checking files.
464 * This should only be used if all entries in the process
465 * cache were added after the files were already locked. (since 1.20)
466 *
467 * @note Remarks on locking:
468 * File system paths given to operations should refer to files that are
469 * already locked or otherwise safe from modification from other processes.
470 * Normally these files will be new temp files, which should be adequate.
471 *
472 * @par Return value:
473 *
474 * This returns a Status, which contains all warnings and fatals that occurred
475 * during the operation. The 'failCount', 'successCount', and 'success' members
476 * will reflect each operation attempted.
477 *
478 * The StatusValue will be "OK" unless:
479 * - a) unexpected operation errors occurred (network partitions, disk full...)
480 * - b) predicted operation errors occurred and 'force' was not set
481 *
482 * @param array[] $ops List of operations to execute in order
483 * @phan-param array<int,array{ignoreMissingSource?:bool,overwrite?:bool,overwriteSame?:bool,headers?:bool}> $ops
484 * @param array $opts Batch operation options
485 * @phpcs:ignore Generic.Files.LineLength
486 * @phan-param array{force?:bool,nonLocking?:bool,parallelize?:bool,bypassReadOnly?:bool,preserveCache?:bool} $opts
487 * @return StatusValue
488 */
489 final public function doOperations( array $ops, array $opts = [] ) {
490 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
491 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
492 }
493 if ( $ops === [] ) {
494 return $this->newStatus(); // nothing to do
495 }
496
497 $ops = $this->resolveFSFileObjects( $ops );
498 if ( empty( $opts['force'] ) ) {
499 unset( $opts['nonLocking'] );
500 }
501
502 /** @noinspection PhpUnusedLocalVariableInspection */
503 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
504
505 return $this->doOperationsInternal( $ops, $opts );
506 }
507
508 /**
509 * @see FileBackend::doOperations()
510 * @param array $ops
511 * @param array $opts
512 * @return StatusValue
513 */
514 abstract protected function doOperationsInternal( array $ops, array $opts );
515
516 /**
517 * Same as doOperations() except it takes a single operation.
518 * If you are doing a batch of operations that should either
519 * all succeed or all fail, then use that function instead.
520 *
521 * @see FileBackend::doOperations()
522 *
523 * @param array $op Operation
524 * @param array $opts Operation options
525 * @return StatusValue
526 */
527 final public function doOperation( array $op, array $opts = [] ) {
528 return $this->doOperations( [ $op ], $opts );
529 }
530
531 /**
532 * Performs a single create operation.
533 * This sets $params['op'] to 'create' and passes it to doOperation().
534 *
535 * @see FileBackend::doOperation()
536 *
537 * @param array $params Operation parameters
538 * @param array $opts Operation options
539 * @return StatusValue
540 */
541 final public function create( array $params, array $opts = [] ) {
542 return $this->doOperation( [ 'op' => 'create' ] + $params, $opts );
543 }
544
545 /**
546 * Performs a single store operation.
547 * This sets $params['op'] to 'store' and passes it to doOperation().
548 *
549 * @see FileBackend::doOperation()
550 *
551 * @param array $params Operation parameters
552 * @param array $opts Operation options
553 * @return StatusValue
554 */
555 final public function store( array $params, array $opts = [] ) {
556 return $this->doOperation( [ 'op' => 'store' ] + $params, $opts );
557 }
558
559 /**
560 * Performs a single copy operation.
561 * This sets $params['op'] to 'copy' and passes it to doOperation().
562 *
563 * @see FileBackend::doOperation()
564 *
565 * @param array $params Operation parameters
566 * @param array $opts Operation options
567 * @return StatusValue
568 */
569 final public function copy( array $params, array $opts = [] ) {
570 return $this->doOperation( [ 'op' => 'copy' ] + $params, $opts );
571 }
572
573 /**
574 * Performs a single move operation.
575 * This sets $params['op'] to 'move' and passes it to doOperation().
576 *
577 * @see FileBackend::doOperation()
578 *
579 * @param array $params Operation parameters
580 * @param array $opts Operation options
581 * @return StatusValue
582 */
583 final public function move( array $params, array $opts = [] ) {
584 return $this->doOperation( [ 'op' => 'move' ] + $params, $opts );
585 }
586
587 /**
588 * Performs a single delete operation.
589 * This sets $params['op'] to 'delete' and passes it to doOperation().
590 *
591 * @see FileBackend::doOperation()
592 *
593 * @param array $params Operation parameters
594 * @param array $opts Operation options
595 * @return StatusValue
596 */
597 final public function delete( array $params, array $opts = [] ) {
598 return $this->doOperation( [ 'op' => 'delete' ] + $params, $opts );
599 }
600
601 /**
602 * Performs a single describe operation.
603 * This sets $params['op'] to 'describe' and passes it to doOperation().
604 *
605 * @see FileBackend::doOperation()
606 *
607 * @param array $params Operation parameters
608 * @param array $opts Operation options
609 * @return StatusValue
610 * @since 1.21
611 */
612 final public function describe( array $params, array $opts = [] ) {
613 return $this->doOperation( [ 'op' => 'describe' ] + $params, $opts );
614 }
615
616 /**
617 * Perform a set of independent file operations on some files.
618 *
619 * This does no locking, and possibly no stat calls.
620 * Any destination files that already exist will be overwritten.
621 * This should *only* be used on non-original files, like cache files.
622 *
623 * Supported operations and their parameters:
624 * - create
625 * - store
626 * - copy
627 * - move
628 * - delete
629 * - describe (since 1.21)
630 * - null
631 *
632 * FSFile/TempFSFile object support was added in 1.27.
633 *
634 * a) Create a new file in storage with the contents of a string
635 * @code
636 * [
637 * 'op' => 'create',
638 * 'dst' => <storage path>,
639 * 'content' => <string of new file contents>,
640 * 'headers' => <HTTP header name/value map> # since 1.21
641 * ]
642 * @endcode
643 *
644 * b) Copy a file system file into storage
645 * @code
646 * [
647 * 'op' => 'store',
648 * 'src' => <file system path, FSFile, or TempFSFile>,
649 * 'dst' => <storage path>,
650 * 'headers' => <HTTP header name/value map> # since 1.21
651 * ]
652 * @endcode
653 *
654 * c) Copy a file within storage
655 * @code
656 * [
657 * 'op' => 'copy',
658 * 'src' => <storage path>,
659 * 'dst' => <storage path>,
660 * 'ignoreMissingSource' => <boolean>, # since 1.21
661 * 'headers' => <HTTP header name/value map> # since 1.21
662 * ]
663 * @endcode
664 *
665 * d) Move a file within storage
666 * @code
667 * [
668 * 'op' => 'move',
669 * 'src' => <storage path>,
670 * 'dst' => <storage path>,
671 * 'ignoreMissingSource' => <boolean>, # since 1.21
672 * 'headers' => <HTTP header name/value map> # since 1.21
673 * ]
674 * @endcode
675 *
676 * e) Delete a file within storage
677 * @code
678 * [
679 * 'op' => 'delete',
680 * 'src' => <storage path>,
681 * 'ignoreMissingSource' => <boolean>
682 * ]
683 * @endcode
684 *
685 * f) Update metadata for a file within storage
686 * @code
687 * [
688 * 'op' => 'describe',
689 * 'src' => <storage path>,
690 * 'headers' => <HTTP header name/value map>
691 * ]
692 * @endcode
693 *
694 * g) Do nothing (no-op)
695 * @code
696 * [
697 * 'op' => 'null',
698 * ]
699 * @endcode
700 *
701 * @par Boolean flags for operations (operation-specific):
702 * - ignoreMissingSource : The operation will simply succeed and do
703 * nothing if the source file does not exist.
704 * - headers : If supplied with a header name/value map, the backend will
705 * reply with these headers when GETs/HEADs of the destination
706 * file are made. Header values should be smaller than 256 bytes.
707 * Content-Disposition headers can be longer, though the system
708 * might ignore or truncate ones that are too long to store.
709 * Existing headers will remain, but these will replace any
710 * conflicting previous headers, and headers will be removed
711 * if they are set to an empty string.
712 * Backends that don't support metadata ignore this. (since 1.21)
713 *
714 * $opts is an associative of boolean flags, including:
715 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
716 *
717 * @par Return value:
718 * This returns a Status, which contains all warnings and fatals that occurred
719 * during the operation. The 'failCount', 'successCount', and 'success' members
720 * will reflect each operation attempted for the given files. The StatusValue will be
721 * considered "OK" as long as no fatal errors occurred.
722 *
723 * @param array $ops Set of operations to execute
724 * @phan-param list<array{op:?string,src?:string,dst?:string,ignoreMissingSource?:bool,headers?:array}> $ops
725 * @param array $opts Batch operation options
726 * @phan-param array{bypassReadOnly?:bool} $opts
727 * @return StatusValue
728 * @since 1.20
729 */
730 final public function doQuickOperations( array $ops, array $opts = [] ) {
731 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
732 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
733 }
734 if ( $ops === [] ) {
735 return $this->newStatus(); // nothing to do
736 }
737
738 $ops = $this->resolveFSFileObjects( $ops );
739 foreach ( $ops as &$op ) {
740 $op['overwrite'] = true; // avoids RTTs in key/value stores
741 }
742
743 /** @noinspection PhpUnusedLocalVariableInspection */
744 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
745
746 return $this->doQuickOperationsInternal( $ops, $opts );
747 }
748
749 /**
750 * @see FileBackend::doQuickOperations()
751 * @param array $ops
752 * @param array $opts
753 * @return StatusValue
754 * @since 1.20
755 */
756 abstract protected function doQuickOperationsInternal( array $ops, array $opts );
757
758 /**
759 * Same as doQuickOperations() except it takes a single operation.
760 * If you are doing a batch of operations, then use that function instead.
761 *
762 * @see FileBackend::doQuickOperations()
763 *
764 * @param array $op Operation
765 * @param array $opts Batch operation options
766 * @return StatusValue
767 * @since 1.20
768 */
769 final public function doQuickOperation( array $op, array $opts = [] ) {
770 return $this->doQuickOperations( [ $op ], $opts );
771 }
772
773 /**
774 * Performs a single quick create operation.
775 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
776 *
777 * @see FileBackend::doQuickOperation()
778 *
779 * @param array $params Operation parameters
780 * @param array $opts Operation options
781 * @return StatusValue
782 * @since 1.20
783 */
784 final public function quickCreate( array $params, array $opts = [] ) {
785 return $this->doQuickOperation( [ 'op' => 'create' ] + $params, $opts );
786 }
787
788 /**
789 * Performs a single quick store operation.
790 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
791 *
792 * @see FileBackend::doQuickOperation()
793 *
794 * @param array $params Operation parameters
795 * @param array $opts Operation options
796 * @return StatusValue
797 * @since 1.20
798 */
799 final public function quickStore( array $params, array $opts = [] ) {
800 return $this->doQuickOperation( [ 'op' => 'store' ] + $params, $opts );
801 }
802
803 /**
804 * Performs a single quick copy operation.
805 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
806 *
807 * @see FileBackend::doQuickOperation()
808 *
809 * @param array $params Operation parameters
810 * @param array $opts Operation options
811 * @return StatusValue
812 * @since 1.20
813 */
814 final public function quickCopy( array $params, array $opts = [] ) {
815 return $this->doQuickOperation( [ 'op' => 'copy' ] + $params, $opts );
816 }
817
818 /**
819 * Performs a single quick move operation.
820 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
821 *
822 * @see FileBackend::doQuickOperation()
823 *
824 * @param array $params Operation parameters
825 * @param array $opts Operation options
826 * @return StatusValue
827 * @since 1.20
828 */
829 final public function quickMove( array $params, array $opts = [] ) {
830 return $this->doQuickOperation( [ 'op' => 'move' ] + $params, $opts );
831 }
832
833 /**
834 * Performs a single quick delete operation.
835 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
836 *
837 * @see FileBackend::doQuickOperation()
838 *
839 * @param array $params Operation parameters
840 * @param array $opts Operation options
841 * @return StatusValue
842 * @since 1.20
843 */
844 final public function quickDelete( array $params, array $opts = [] ) {
845 return $this->doQuickOperation( [ 'op' => 'delete' ] + $params, $opts );
846 }
847
848 /**
849 * Performs a single quick describe operation.
850 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
851 *
852 * @see FileBackend::doQuickOperation()
853 *
854 * @param array $params Operation parameters
855 * @param array $opts Operation options
856 * @return StatusValue
857 * @since 1.21
858 */
859 final public function quickDescribe( array $params, array $opts = [] ) {
860 return $this->doQuickOperation( [ 'op' => 'describe' ] + $params, $opts );
861 }
862
863 /**
864 * Concatenate a list of storage files into a single file system file.
865 * The target path should refer to a file that is already locked or
866 * otherwise safe from modification from other processes. Normally,
867 * the file will be a new temp file, which should be adequate.
868 *
869 * @param array $params Operation parameters, include:
870 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
871 * - dst : file system path to 0-byte temp file
872 * - parallelize : try to do operations in parallel when possible
873 * @return StatusValue
874 */
875 abstract public function concatenate( array $params );
876
877 /**
878 * Prepare a storage directory for usage.
879 * This will create any required containers and parent directories.
880 * Backends using key/value stores only need to create the container.
881 *
882 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
883 * except they are only applied *if* the directory/container had to be created.
884 * These flags should always be set for directories that have private files.
885 * However, setting them is not guaranteed to actually do anything.
886 * Additional server configuration may be needed to achieve the desired effect.
887 *
888 * @param array $params Parameters include:
889 * - dir : storage directory
890 * - noAccess : try to deny file access (since 1.20)
891 * - noListing : try to deny file listing (since 1.20)
892 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
893 * @return StatusValue Good status without value for success, fatal otherwise.
894 */
895 final public function prepare( array $params ) {
896 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
897 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
898 }
899 /** @noinspection PhpUnusedLocalVariableInspection */
900 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
901 return $this->doPrepare( $params );
902 }
903
904 /**
905 * @see FileBackend::prepare()
906 * @param array $params
907 * @return StatusValue Good status without value for success, fatal otherwise.
908 */
909 abstract protected function doPrepare( array $params );
910
911 /**
912 * Take measures to block web access to a storage directory and
913 * the container it belongs to. FS backends might add .htaccess
914 * files whereas key/value store backends might revoke container
915 * access to the storage user representing end-users in web requests.
916 *
917 * This is not guaranteed to actually make files or listings publicly hidden.
918 * Additional server configuration may be needed to achieve the desired effect.
919 *
920 * @param array $params Parameters include:
921 * - dir : storage directory
922 * - noAccess : try to deny file access
923 * - noListing : try to deny file listing
924 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
925 * @return StatusValue
926 */
927 final public function secure( array $params ) {
928 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
929 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
930 }
931 /** @noinspection PhpUnusedLocalVariableInspection */
932 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
933 return $this->doSecure( $params );
934 }
935
936 /**
937 * @see FileBackend::secure()
938 * @param array $params
939 * @return StatusValue
940 */
941 abstract protected function doSecure( array $params );
942
943 /**
944 * Remove measures to block web access to a storage directory and
945 * the container it belongs to. FS backends might remove .htaccess
946 * files whereas key/value store backends might grant container
947 * access to the storage user representing end-users in web requests.
948 * This essentially can undo the result of secure() calls.
949 *
950 * This is not guaranteed to actually make files or listings publicly viewable.
951 * Additional server configuration may be needed to achieve the desired effect.
952 *
953 * @param array $params Parameters include:
954 * - dir : storage directory
955 * - access : try to allow file access
956 * - listing : try to allow file listing
957 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
958 * @return StatusValue
959 * @since 1.20
960 */
961 final public function publish( array $params ) {
962 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
963 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
964 }
965 /** @noinspection PhpUnusedLocalVariableInspection */
966 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
967 return $this->doPublish( $params );
968 }
969
970 /**
971 * @see FileBackend::publish()
972 * @param array $params
973 * @return StatusValue
974 */
975 abstract protected function doPublish( array $params );
976
977 /**
978 * Delete a storage directory if it is empty.
979 * Backends using key/value stores may do nothing unless the directory
980 * is that of an empty container, in which case it will be deleted.
981 *
982 * @param array $params Parameters include:
983 * - dir : storage directory
984 * - recursive : recursively delete empty subdirectories first (since 1.20)
985 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
986 * @return StatusValue
987 */
988 final public function clean( array $params ) {
989 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
990 return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
991 }
992 /** @noinspection PhpUnusedLocalVariableInspection */
993 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
994 return $this->doClean( $params );
995 }
996
997 /**
998 * @see FileBackend::clean()
999 * @param array $params
1000 * @return StatusValue
1001 */
1002 abstract protected function doClean( array $params );
1003
1004 /**
1005 * Check if a file exists at a storage path in the backend.
1006 * This returns false if only a directory exists at the path.
1007 *
1008 * Callers that only care if a file is readily accessible can use non-strict
1009 * comparisons on the result. If "does not exist" and "existence is unknown"
1010 * must be distinguished, then strict comparisons to true/null should be used.
1011 *
1012 * @see FileBackend::EXISTENCE_ERROR
1013 * @see FileBackend::directoryExists()
1014 *
1015 * @param array $params Parameters include:
1016 * - src : source storage path
1017 * - latest : use the latest available data
1018 * @return bool|null Whether the file exists or null (I/O error)
1019 */
1020 abstract public function fileExists( array $params );
1021
1022 /**
1023 * Get the last-modified timestamp of the file at a storage path.
1024 *
1025 * @see FileBackend::TIMESTAMP_FAIL
1026 *
1027 * @param array $params Parameters include:
1028 * - src : source storage path
1029 * - latest : use the latest available data
1030 * @return string|false TS_MW timestamp or false (missing file or I/O error)
1031 */
1032 abstract public function getFileTimestamp( array $params );
1033
1034 /**
1035 * Get the contents of a file at a storage path in the backend.
1036 * This should be avoided for potentially large files.
1037 *
1038 * @see FileBackend::CONTENT_FAIL
1039 *
1040 * @param array $params Parameters include:
1041 * - src : source storage path
1042 * - latest : use the latest available data
1043 * @return string|false Content string or false (missing file or I/O error)
1044 */
1045 final public function getFileContents( array $params ) {
1046 $contents = $this->getFileContentsMulti( [ 'srcs' => [ $params['src'] ] ] + $params );
1047
1048 return $contents[$params['src']];
1049 }
1050
1051 /**
1052 * Like getFileContents() except it takes an array of storage paths
1053 * and returns an order preserved map of storage paths to their content.
1054 *
1055 * @see FileBackend::getFileContents()
1056 *
1057 * @param array $params Parameters include:
1058 * - srcs : list of source storage paths
1059 * - latest : use the latest available data
1060 * - parallelize : try to do operations in parallel when possible
1061 * @return string[]|false[] Map of (path name => file content or false on failure)
1062 * @since 1.20
1063 */
1064 abstract public function getFileContentsMulti( array $params );
1065
1066 /**
1067 * Get metadata about a file at a storage path in the backend.
1068 * If the file does not exist, then this returns false.
1069 * Otherwise, the result is an associative array that includes:
1070 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
1071 * - metadata : map of file metadata (name => value)
1072 * Metadata keys and headers names will be returned in all lower-case.
1073 * Additional values may be included for internal use only.
1074 *
1075 * Use FileBackend::hasFeatures() to check how well this is supported.
1076 *
1077 * @see FileBackend::XATTRS_FAIL
1078 *
1079 * @param array $params
1080 * $params include:
1081 * - src : source storage path
1082 * - latest : use the latest available data
1083 * @return array|false File metadata array or false (missing file or I/O error)
1084 * @since 1.23
1085 */
1086 abstract public function getFileXAttributes( array $params );
1087
1088 /**
1089 * Get the size (bytes) of a file at a storage path in the backend.
1090 *
1091 * @see FileBackend::SIZE_FAIL
1092 *
1093 * @param array $params Parameters include:
1094 * - src : source storage path
1095 * - latest : use the latest available data
1096 * @return int|false File size in bytes or false (missing file or I/O error)
1097 */
1098 abstract public function getFileSize( array $params );
1099
1100 /**
1101 * Get quick information about a file at a storage path in the backend.
1102 * If the file does not exist, then this returns false.
1103 * Otherwise, the result is an associative array that includes:
1104 * - mtime : the last-modified timestamp (TS_MW)
1105 * - size : the file size (bytes)
1106 * Additional values may be included for internal use only.
1107 *
1108 * @see FileBackend::STAT_ABSENT
1109 * @see FileBackend::STAT_ERROR
1110 *
1111 * @param array $params Parameters include:
1112 * - src : source storage path
1113 * - latest : use the latest available data
1114 * @return array|false|null Attribute map, false (missing file), or null (I/O error)
1115 */
1116 abstract public function getFileStat( array $params );
1117
1118 /**
1119 * Get a SHA-1 hash of the content of the file at a storage path in the backend.
1120 *
1121 * @see FileBackend::SHA1_FAIL
1122 *
1123 * @param array $params Parameters include:
1124 * - src : source storage path
1125 * - latest : use the latest available data
1126 * @return string|false Hash string or false (missing file or I/O error)
1127 */
1128 abstract public function getFileSha1Base36( array $params );
1129
1130 /**
1131 * Get the properties of the content of the file at a storage path in the backend.
1132 * This gives the result of FSFile::getProps() on a local copy of the file.
1133 *
1134 * @param array $params Parameters include:
1135 * - src : source storage path
1136 * - latest : use the latest available data
1137 * @return array Properties map; FSFile::placeholderProps() if file missing or on I/O error
1138 */
1139 abstract public function getFileProps( array $params );
1140
1141 /**
1142 * Stream the content of the file at a storage path in the backend.
1143 *
1144 * If the file does not exists, an HTTP 404 error will be given.
1145 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1146 * will be sent if streaming began, while none will be sent otherwise.
1147 * Implementations should flush the output buffer before sending data.
1148 *
1149 * @param array $params Parameters include:
1150 * - src : source storage path
1151 * - headers : list of additional HTTP headers to send if the file exists
1152 * - options : HTTP request header map with lower case keys (since 1.28). Supports:
1153 * range : format is "bytes=(\d*-\d*)"
1154 * if-modified-since : format is an HTTP date
1155 * - headless : do not send HTTP headers (including those of "headers") (since 1.28)
1156 * - latest : use the latest available data
1157 * - allowOB : preserve any output buffers (since 1.28)
1158 * @return StatusValue
1159 */
1160 abstract public function streamFile( array $params );
1161
1162 /**
1163 * Returns a file system file, identical in content to the file at a storage path.
1164 * The file returned is either:
1165 * - a) A TempFSFile local copy of the file at a storage path in the backend.
1166 * The temporary copy will have the same extension as the source.
1167 * Temporary files may be purged when the file object falls out of scope.
1168 * - b) An FSFile pointing to the original file at a storage path in the backend.
1169 * This is applicable for backends layered directly on top of file systems.
1170 *
1171 * Never modify the returned file since it might be the original, it might be shared
1172 * among multiple callers of this method, or the backend might internally keep FSFile
1173 * references for deferred operations.
1174 *
1175 * @param array $params Parameters include:
1176 * - src : source storage path
1177 * - latest : use the latest available data
1178 * @return FSFile|null|false Local file copy or false (missing) or null (error)
1179 */
1180 final public function getLocalReference( array $params ) {
1181 $fsFiles = $this->getLocalReferenceMulti( [ 'srcs' => [ $params['src'] ] ] + $params );
1182
1183 return $fsFiles[$params['src']];
1184 }
1185
1186 /**
1187 * Like getLocalReference() except it takes an array of storage paths and
1188 * yields an order-preserved map of storage paths to temporary local file copies.
1189 *
1190 * Never modify the returned files since they might be originals, they might be shared
1191 * among multiple callers of this method, or the backend might internally keep FSFile
1192 * references for deferred operations.
1193 *
1194 * @see FileBackend::getLocalReference()
1195 *
1196 * @param array $params Parameters include:
1197 * - srcs : list of source storage paths
1198 * - latest : use the latest available data
1199 * - parallelize : try to do operations in parallel when possible
1200 * @return array Map of (path name => FSFile or false (missing) or null (error))
1201 * @since 1.20
1202 */
1203 abstract public function getLocalReferenceMulti( array $params );
1204
1205 /**
1206 * Get a local copy on disk of the file at a storage path in the backend.
1207 * The temporary copy will have the same file extension as the source.
1208 * Temporary files may be purged when the file object falls out of scope.
1209 *
1210 * Multiple calls to this method for the same path will create new copies.
1211 *
1212 * @param array $params Parameters include:
1213 * - src : source storage path
1214 * - latest : use the latest available data
1215 * @return TempFSFile|null|false Temporary local file copy or false (missing) or null (error)
1216 */
1217 final public function getLocalCopy( array $params ) {
1218 $tmpFiles = $this->getLocalCopyMulti( [ 'srcs' => [ $params['src'] ] ] + $params );
1219
1220 return $tmpFiles[$params['src']];
1221 }
1222
1223 /**
1224 * Like getLocalCopy() except it takes an array of storage paths and yields
1225 * an order preserved-map of storage paths to temporary local file copies.
1226 *
1227 * Multiple calls to this method for the same path will create new copies.
1228 *
1229 * @see FileBackend::getLocalCopy()
1230 *
1231 * @param array $params Parameters include:
1232 * - srcs : list of source storage paths
1233 * - latest : use the latest available data
1234 * - parallelize : try to do operations in parallel when possible
1235 * @return array Map of (path name => TempFSFile or false (missing) or null (error))
1236 * @since 1.20
1237 */
1238 abstract public function getLocalCopyMulti( array $params );
1239
1240 /**
1241 * Return an HTTP URL to a given file that requires no authentication to use.
1242 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1243 * This will return null if the backend cannot make an HTTP URL for the file.
1244 *
1245 * This is useful for key/value stores when using scripts that seek around
1246 * large files and those scripts (and the backend) support HTTP Range headers.
1247 * Otherwise, one would need to use getLocalReference(), which involves loading
1248 * the entire file on to local disk.
1249 *
1250 * @see FileBackend::TEMPURL_ERROR
1251 *
1252 * @param array $params Parameters include:
1253 * - src : source storage path
1254 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1255 * - latest : use the latest available data
1256 * - method : the allowed method; default GET
1257 * - ipRange : the allowed IP range; default unlimited
1258 * @return string|null URL or null (not supported or I/O error)
1259 * @since 1.21
1260 */
1261 abstract public function getFileHttpUrl( array $params );
1262
1263 /**
1264 * Add a file to a Shellbox command as an input file.
1265 *
1266 * @param BoxedCommand $command
1267 * @param string $boxedName
1268 * @param array $params Parameters include:
1269 * - src : source storage path
1270 * - latest : use the latest available data
1271 * @return StatusValue
1272 * @since 1.43
1273 */
1274 abstract public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1275 array $params );
1276
1277 /**
1278 * Check if a directory exists at a given storage path
1279 *
1280 * For backends using key/value stores, a directory is said to exist whenever
1281 * there exist any files with paths using the given directory path as a prefix
1282 * followed by a forward slash. For example, if there is a file called
1283 * "mwstore://backend/container/dir/path.svg" then directories are said to exist
1284 * at "mwstore://backend/container" and "mwstore://backend/container/dir". These
1285 * can be thought of as "virtual" directories.
1286 *
1287 * Backends that directly use a filesystem layer might enumerate empty directories.
1288 * The clean() method should always be used when files are deleted or moved if this
1289 * is a concern. This is a trade-off to avoid write amplication/contention on file
1290 * changes or read amplification when calling this method.
1291 *
1292 * Storage backends with eventual consistency might return stale data.
1293 *
1294 * @see FileBackend::EXISTENCE_ERROR
1295 * @see FileBackend::clean()
1296 *
1297 * @param array $params Parameters include:
1298 * - dir : storage directory
1299 * @return bool|null Whether a directory exists or null (I/O error)
1300 * @since 1.20
1301 */
1302 abstract public function directoryExists( array $params );
1303
1304 /**
1305 * Get an iterator to list *all* directories under a storage directory
1306 *
1307 * If the directory is of the form "mwstore://backend/container",
1308 * then all directories in the container will be listed.
1309 * If the directory is of form "mwstore://backend/container/dir",
1310 * then all directories directly under that directory will be listed.
1311 * Results will be storage directories relative to the given directory.
1312 *
1313 * Storage backends with eventual consistency might return stale data.
1314 *
1315 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1316 *
1317 * @see FileBackend::LIST_ERROR
1318 * @see FileBackend::directoryExists()
1319 *
1320 * @param array $params Parameters include:
1321 * - dir : storage directory
1322 * - topOnly : only return direct child dirs of the directory
1323 * @return \Traversable|array|null Directory list enumerator or null (initial I/O error)
1324 * @since 1.20
1325 */
1326 abstract public function getDirectoryList( array $params );
1327
1328 /**
1329 * Same as FileBackend::getDirectoryList() except only lists
1330 * directories that are immediately under the given directory.
1331 *
1332 * Storage backends with eventual consistency might return stale data.
1333 *
1334 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1335 *
1336 * @see FileBackend::LIST_ERROR
1337 * @see FileBackend::directoryExists()
1338 *
1339 * @param array $params Parameters include:
1340 * - dir : storage directory
1341 * @return \Traversable|array|null Directory list enumerator or null (initial I/O error)
1342 * @since 1.20
1343 */
1344 final public function getTopDirectoryList( array $params ) {
1345 return $this->getDirectoryList( [ 'topOnly' => true ] + $params );
1346 }
1347
1348 /**
1349 * Get an iterator to list *all* stored files under a storage directory
1350 *
1351 * If the directory is of the form "mwstore://backend/container", then all
1352 * files in the container will be listed. If the directory is of form
1353 * "mwstore://backend/container/dir", then all files under that directory will
1354 * be listed. Results will be storage paths relative to the given directory.
1355 *
1356 * Storage backends with eventual consistency might return stale data.
1357 *
1358 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1359 *
1360 * @see FileBackend::LIST_ERROR
1361 *
1362 * @param array $params Parameters include:
1363 * - dir : storage directory
1364 * - topOnly : only return direct child files of the directory (since 1.20)
1365 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1366 * - forWrite : true if the list will inform a write operations (since 1.41)
1367 * @return \Traversable|array|null File list enumerator or null (initial I/O error)
1368 */
1369 abstract public function getFileList( array $params );
1370
1371 /**
1372 * Same as FileBackend::getFileList() except only lists
1373 * files that are immediately under the given directory.
1374 *
1375 * Storage backends with eventual consistency might return stale data.
1376 *
1377 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1378 *
1379 * @see FileBackend::LIST_ERROR
1380 *
1381 * @param array $params Parameters include:
1382 * - dir : storage directory
1383 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1384 * @return \Traversable|array|null File list enumerator or null on failure
1385 * @since 1.20
1386 */
1387 final public function getTopFileList( array $params ) {
1388 return $this->getFileList( [ 'topOnly' => true ] + $params );
1389 }
1390
1391 /**
1392 * Preload persistent file stat cache and property cache into in-process cache.
1393 * This should be used when stat calls will be made on a known list of a many files.
1394 *
1395 * @see FileBackend::getFileStat()
1396 *
1397 * @param array $paths Storage paths
1398 */
1399 abstract public function preloadCache( array $paths );
1400
1401 /**
1402 * Invalidate any in-process file stat and property cache.
1403 * If $paths is given, then only the cache for those files will be cleared.
1404 *
1405 * @see FileBackend::getFileStat()
1406 *
1407 * @param array|null $paths Storage paths (optional)
1408 */
1409 abstract public function clearCache( ?array $paths = null );
1410
1411 /**
1412 * Preload file stat information (concurrently if possible) into in-process cache.
1413 *
1414 * This should be used when stat calls will be made on a known list of a many files.
1415 * This does not make use of the persistent file stat cache.
1416 *
1417 * @see FileBackend::getFileStat()
1418 *
1419 * @param array $params Parameters include:
1420 * - srcs : list of source storage paths
1421 * - latest : use the latest available data
1422 * @return bool Whether all requests proceeded without I/O errors (since 1.24)
1423 * @since 1.23
1424 */
1425 abstract public function preloadFileStat( array $params );
1426
1427 /**
1428 * Lock the files at the given storage paths in the backend.
1429 * This will either lock all the files or none (on failure).
1430 *
1431 * Callers should consider using getScopedFileLocks() instead.
1432 *
1433 * @param array $paths Storage paths
1434 * @param int $type LockManager::LOCK_* constant
1435 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1436 * @return StatusValue
1437 */
1438 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1439 $paths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $paths );
1440
1441 return $this->wrapStatus( $this->lockManager->lock( $paths, $type, $timeout ) );
1442 }
1443
1444 /**
1445 * Unlock the files at the given storage paths in the backend.
1446 *
1447 * @param array $paths Storage paths
1448 * @param int $type LockManager::LOCK_* constant
1449 * @return StatusValue
1450 */
1451 final public function unlockFiles( array $paths, $type ) {
1452 $paths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $paths );
1453
1454 return $this->wrapStatus( $this->lockManager->unlock( $paths, $type ) );
1455 }
1456
1457 /**
1458 * Lock the files at the given storage paths in the backend.
1459 * This will either lock all the files or none (on failure).
1460 * On failure, the StatusValue object will be updated with errors.
1461 *
1462 * Once the return value goes out scope, the locks will be released and
1463 * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
1464 *
1465 * @see ScopedLock::factory()
1466 *
1467 * @param array $paths List of storage paths or map of lock types to path lists
1468 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1469 * @param StatusValue $status StatusValue to update on lock/unlock
1470 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1471 * @return ScopedLock|null RAII-style self-unlocking lock or null on failure
1472 */
1473 final public function getScopedFileLocks(
1474 array $paths, $type, StatusValue $status, $timeout = 0
1475 ) {
1476 if ( $type === 'mixed' ) {
1477 foreach ( $paths as &$typePaths ) {
1478 $typePaths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $typePaths );
1479 }
1480 } else {
1481 $paths = array_map( [ __CLASS__, 'normalizeStoragePath' ], $paths );
1482 }
1483
1484 return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
1485 }
1486
1487 /**
1488 * Get an array of scoped locks needed for a batch of file operations.
1489 *
1490 * Normally, FileBackend::doOperations() handles locking, unless
1491 * the 'nonLocking' param is passed in. This function is useful if you
1492 * want the files to be locked for a broader scope than just when the
1493 * files are changing. For example, if you need to update DB metadata,
1494 * you may want to keep the files locked until finished.
1495 *
1496 * @see FileBackend::doOperations()
1497 *
1498 * @param array $ops List of file operations to FileBackend::doOperations()
1499 * @param StatusValue $status StatusValue to update on lock/unlock
1500 * @return ScopedLock|null RAII-style self-unlocking lock or null on failure
1501 * @since 1.20
1502 */
1503 abstract public function getScopedLocksForOps( array $ops, StatusValue $status );
1504
1505 /**
1506 * Get the root storage path of this backend.
1507 * All container paths are "subdirectories" of this path.
1508 *
1509 * @return string Storage path
1510 * @since 1.20
1511 */
1512 final public function getRootStoragePath() {
1513 return "mwstore://{$this->name}";
1514 }
1515
1516 /**
1517 * Get the storage path for the given container for this backend
1518 *
1519 * @param string $container Container name
1520 * @return string Storage path
1521 * @since 1.21
1522 */
1523 final public function getContainerStoragePath( $container ) {
1524 return $this->getRootStoragePath() . "/{$container}";
1525 }
1526
1527 /**
1528 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1529 *
1530 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1531 * around as long it needs (which may vary greatly depending on configuration)
1532 *
1533 * @param array $ops File operation batch for FileBaclend::doOperations()
1534 * @return array File operation batch
1535 */
1536 protected function resolveFSFileObjects( array $ops ) {
1537 foreach ( $ops as &$op ) {
1538 $src = $op['src'] ?? null;
1539 if ( $src instanceof FSFile ) {
1540 $op['srcRef'] = $src;
1541 $op['src'] = $src->getPath();
1542 }
1543 }
1544 unset( $op );
1545
1546 return $ops;
1547 }
1548
1549 /**
1550 * Check if a given path is a "mwstore://" path.
1551 * This does not do any further validation or any existence checks.
1552 *
1553 * @param string|null $path
1554 * @return bool
1555 */
1556 final public static function isStoragePath( $path ) {
1557 return ( strpos( $path ?? '', 'mwstore://' ) === 0 );
1558 }
1559
1560 /**
1561 * Split a storage path into a backend name, a container name,
1562 * and a relative file path. The relative path may be the empty string.
1563 * This does not do any path normalization or traversal checks.
1564 *
1565 * @param string $storagePath
1566 * @return array (backend, container, rel object) or (null, null, null)
1567 */
1568 final public static function splitStoragePath( $storagePath ) {
1569 if ( self::isStoragePath( $storagePath ) ) {
1570 // Remove the "mwstore://" prefix and split the path
1571 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1572 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1573 if ( count( $parts ) == 3 ) {
1574 return $parts; // e.g. "backend/container/path"
1575 } else {
1576 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1577 }
1578 }
1579 }
1580
1581 return [ null, null, null ];
1582 }
1583
1584 /**
1585 * Normalize a storage path by cleaning up directory separators.
1586 * Returns null if the path is not of the format of a valid storage path.
1587 *
1588 * @param string $storagePath
1589 * @return string|null Normalized storage path or null on failure
1590 */
1591 final public static function normalizeStoragePath( $storagePath ) {
1592 [ $backend, $container, $relPath ] = self::splitStoragePath( $storagePath );
1593 if ( $relPath !== null ) { // must be for this backend
1594 $relPath = self::normalizeContainerPath( $relPath );
1595 if ( $relPath !== null ) {
1596 return ( $relPath != '' )
1597 ? "mwstore://{$backend}/{$container}/{$relPath}"
1598 : "mwstore://{$backend}/{$container}";
1599 }
1600 }
1601
1602 return null;
1603 }
1604
1605 /**
1606 * Get the parent storage directory of a storage path.
1607 * This returns a path like "mwstore://backend/container",
1608 * "mwstore://backend/container/...", or null if there is no parent.
1609 *
1610 * @param string $storagePath
1611 * @return string|null Parent storage path or null on failure
1612 */
1613 final public static function parentStoragePath( $storagePath ) {
1614 // XXX dirname() depends on platform and locale! If nothing enforces that the storage path
1615 // doesn't contain characters like '\', behavior can vary by platform. We should use
1616 // explode() instead.
1617 $storagePath = dirname( $storagePath );
1618 [ , , $rel ] = self::splitStoragePath( $storagePath );
1619
1620 return ( $rel === null ) ? null : $storagePath;
1621 }
1622
1623 /**
1624 * Get the final extension from a storage or FS path
1625 *
1626 * @param string $path
1627 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1628 * @return string
1629 */
1630 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1631 // This will treat a string starting with . as not having an extension, but store paths have
1632 // to start with 'mwstore://', so "garbage in, garbage out".
1633 $i = strrpos( $path ?? '', '.' );
1634 $ext = $i ? substr( $path, $i + 1 ) : '';
1635
1636 if ( $case === 'lowercase' ) {
1637 $ext = strtolower( $ext );
1638 } elseif ( $case === 'uppercase' ) {
1639 $ext = strtoupper( $ext );
1640 }
1641
1642 return $ext;
1643 }
1644
1645 /**
1646 * Check if a relative path has no directory traversals
1647 *
1648 * @param string $path
1649 * @return bool
1650 * @since 1.20
1651 */
1652 final public static function isPathTraversalFree( $path ) {
1653 return ( self::normalizeContainerPath( $path ) !== null );
1654 }
1655
1656 /**
1657 * Build a Content-Disposition header value per RFC 6266.
1658 *
1659 * @param string $type One of (attachment, inline)
1660 * @param string $filename Suggested file name (should not contain slashes)
1661 * @return string
1662 * @since 1.20
1663 */
1664 final public static function makeContentDisposition( $type, $filename = '' ) {
1665 $parts = [];
1666
1667 $type = strtolower( $type );
1668 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1669 throw new InvalidArgumentException( "Invalid Content-Disposition type '$type'." );
1670 }
1671 $parts[] = $type;
1672
1673 if ( strlen( $filename ) ) {
1674 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1675 }
1676
1677 return implode( ';', $parts );
1678 }
1679
1680 /**
1681 * Validate and normalize a relative storage path.
1682 * Null is returned if the path involves directory traversal.
1683 * Traversal is insecure for FS backends and broken for others.
1684 *
1685 * This uses the same traversal protection as Title::secureAndSplit().
1686 *
1687 * @param string $path Storage path relative to a container
1688 * @return string|null Normalized container path or null on failure
1689 */
1690 final protected static function normalizeContainerPath( $path ) {
1691 // Normalize directory separators
1692 $path = strtr( $path, '\\', '/' );
1693 // Collapse any consecutive directory separators
1694 $path = preg_replace( '![/]{2,}!', '/', $path );
1695 // Remove any leading directory separator
1696 $path = ltrim( $path, '/' );
1697 // Use the same traversal protection as Title::secureAndSplit()
1698 if ( strpos( $path, '.' ) !== false ) {
1699 if (
1700 $path === '.' ||
1701 $path === '..' ||
1702 strpos( $path, './' ) === 0 ||
1703 strpos( $path, '../' ) === 0 ||
1704 strpos( $path, '/./' ) !== false ||
1705 strpos( $path, '/../' ) !== false
1706 ) {
1707 return null;
1708 }
1709 }
1710
1711 return $path;
1712 }
1713
1714 /**
1715 * Yields the result of the status wrapper callback on either:
1716 * - StatusValue::newGood() if this method is called without parameters
1717 * - StatusValue::newFatal() with all parameters to this method if passed in
1718 *
1719 * @param mixed ...$args
1720 * @return StatusValue
1721 */
1722 final protected function newStatus( ...$args ) {
1723 if ( count( $args ) ) {
1724 $sv = StatusValue::newFatal( ...$args );
1725 } else {
1726 $sv = StatusValue::newGood();
1727 }
1728
1729 return $this->wrapStatus( $sv );
1730 }
1731
1732 /**
1733 * @param StatusValue $sv
1734 * @return StatusValue Modified status or StatusValue subclass
1735 */
1736 final protected function wrapStatus( StatusValue $sv ) {
1737 return $this->statusWrapper ? call_user_func( $this->statusWrapper, $sv ) : $sv;
1738 }
1739
1740 /**
1741 * @param string $section
1742 * @return ScopedCallback|null
1743 */
1744 protected function scopedProfileSection( $section ) {
1745 return $this->profiler ? ( $this->profiler )( $section ) : null;
1746 }
1747
1748 /**
1749 * Default behavior of resetOutputBuffer().
1750 * @codeCoverageIgnore
1751 * @internal
1752 */
1753 public static function resetOutputBufferTheDefaultWay() {
1754 // XXX According to documentation, ob_get_status() always returns a non-empty array and this
1755 // condition will always be true
1756 while ( ob_get_status() ) {
1757 if ( !ob_end_clean() ) {
1758 // Could not remove output buffer handler; abort now
1759 // to avoid getting in some kind of infinite loop.
1760 break;
1761 }
1762 }
1763 }
1764
1765 /**
1766 * Return options for use with HTTPFileStreamer.
1767 *
1768 * @internal
1769 */
1770 public function getStreamerOptions(): array {
1771 return $this->streamerOptions;
1772 }
1773 }
1774 /** @deprecated class alias since 1.43 */
1775 class_alias( FileBackend::class, 'FileBackend' );