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