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