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