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