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