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