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