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