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