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