Convert Special:DeletedContributions to use OOUI.
[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 * If the file does not exists, an HTTP 404 error will be given.
1009 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1010 * will be sent if streaming began, while none will be sent otherwise.
1011 * Implementations should flush the output buffer before sending data.
1012 *
1013 * @param array $params Parameters include:
1014 * - src : source storage path
1015 * - headers : list of additional HTTP headers to send on success
1016 * - latest : use the latest available data
1017 * @return Status
1018 */
1019 abstract public function streamFile( array $params );
1020
1021 /**
1022 * Returns a file system file, identical to the file at a storage path.
1023 * The file returned is either:
1024 * - a) A local copy of the file at a storage path in the backend.
1025 * The temporary copy will have the same extension as the source.
1026 * - b) An original of the file at a storage path in the backend.
1027 * Temporary files may be purged when the file object falls out of scope.
1028 *
1029 * Write operations should *never* be done on this file as some backends
1030 * may do internal tracking or may be instances of FileBackendMultiWrite.
1031 * In that later case, there are copies of the file that must stay in sync.
1032 * Additionally, further calls to this function may return the same file.
1033 *
1034 * @param array $params Parameters include:
1035 * - src : source storage path
1036 * - latest : use the latest available data
1037 * @return FSFile|null Returns null on failure
1038 */
1039 final public function getLocalReference( array $params ) {
1040 $fsFiles = $this->getLocalReferenceMulti(
1041 [ 'srcs' => [ $params['src'] ] ] + $params );
1042
1043 return $fsFiles[$params['src']];
1044 }
1045
1046 /**
1047 * Like getLocalReference() except it takes an array of storage paths
1048 * and returns a map of storage paths to FSFile objects (or null on failure).
1049 * The map keys (paths) are in the same order as the provided list of paths.
1050 *
1051 * @see FileBackend::getLocalReference()
1052 *
1053 * @param array $params Parameters include:
1054 * - srcs : list of source storage paths
1055 * - latest : use the latest available data
1056 * - parallelize : try to do operations in parallel when possible
1057 * @return array Map of (path name => FSFile or null on failure)
1058 * @since 1.20
1059 */
1060 abstract public function getLocalReferenceMulti( array $params );
1061
1062 /**
1063 * Get a local copy on disk of the file at a storage path in the backend.
1064 * The temporary copy will have the same file extension as the source.
1065 * Temporary files may be purged when the file object falls out of scope.
1066 *
1067 * @param array $params Parameters include:
1068 * - src : source storage path
1069 * - latest : use the latest available data
1070 * @return TempFSFile|null Returns null on failure
1071 */
1072 final public function getLocalCopy( array $params ) {
1073 $tmpFiles = $this->getLocalCopyMulti(
1074 [ 'srcs' => [ $params['src'] ] ] + $params );
1075
1076 return $tmpFiles[$params['src']];
1077 }
1078
1079 /**
1080 * Like getLocalCopy() except it takes an array of storage paths and
1081 * returns a map of storage paths to TempFSFile objects (or null on failure).
1082 * The map keys (paths) are in the same order as the provided list of paths.
1083 *
1084 * @see FileBackend::getLocalCopy()
1085 *
1086 * @param array $params Parameters include:
1087 * - srcs : list of source storage paths
1088 * - latest : use the latest available data
1089 * - parallelize : try to do operations in parallel when possible
1090 * @return array Map of (path name => TempFSFile or null on failure)
1091 * @since 1.20
1092 */
1093 abstract public function getLocalCopyMulti( array $params );
1094
1095 /**
1096 * Return an HTTP URL to a given file that requires no authentication to use.
1097 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1098 * This will return null if the backend cannot make an HTTP URL for the file.
1099 *
1100 * This is useful for key/value stores when using scripts that seek around
1101 * large files and those scripts (and the backend) support HTTP Range headers.
1102 * Otherwise, one would need to use getLocalReference(), which involves loading
1103 * the entire file on to local disk.
1104 *
1105 * @param array $params Parameters include:
1106 * - src : source storage path
1107 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1108 * @return string|null
1109 * @since 1.21
1110 */
1111 abstract public function getFileHttpUrl( array $params );
1112
1113 /**
1114 * Check if a directory exists at a given storage path.
1115 * Backends using key/value stores will check if the path is a
1116 * virtual directory, meaning there are files under the given directory.
1117 *
1118 * Storage backends with eventual consistency might return stale data.
1119 *
1120 * @param array $params Parameters include:
1121 * - dir : storage directory
1122 * @return bool|null Returns null on failure
1123 * @since 1.20
1124 */
1125 abstract public function directoryExists( array $params );
1126
1127 /**
1128 * Get an iterator to list *all* directories under a storage directory.
1129 * If the directory is of the form "mwstore://backend/container",
1130 * then all directories in the container will be listed.
1131 * If the directory is of form "mwstore://backend/container/dir",
1132 * then all directories directly under that directory will be listed.
1133 * Results will be storage directories relative to the given directory.
1134 *
1135 * Storage backends with eventual consistency might return stale data.
1136 *
1137 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1138 *
1139 * @param array $params Parameters include:
1140 * - dir : storage directory
1141 * - topOnly : only return direct child dirs of the directory
1142 * @return Traversable|array|null Returns null on failure
1143 * @since 1.20
1144 */
1145 abstract public function getDirectoryList( array $params );
1146
1147 /**
1148 * Same as FileBackend::getDirectoryList() except only lists
1149 * directories that are immediately under 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 * @return Traversable|array|null Returns null on failure
1158 * @since 1.20
1159 */
1160 final public function getTopDirectoryList( array $params ) {
1161 return $this->getDirectoryList( [ 'topOnly' => true ] + $params );
1162 }
1163
1164 /**
1165 * Get an iterator to list *all* stored files under a storage directory.
1166 * If the directory is of the form "mwstore://backend/container",
1167 * then all files in the container will be listed.
1168 * If the directory is of form "mwstore://backend/container/dir",
1169 * then all files under that directory will be listed.
1170 * Results will be storage paths relative to the given directory.
1171 *
1172 * Storage backends with eventual consistency might return stale data.
1173 *
1174 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1175 *
1176 * @param array $params Parameters include:
1177 * - dir : storage directory
1178 * - topOnly : only return direct child files of the directory (since 1.20)
1179 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1180 * @return Traversable|array|null Returns null on failure
1181 */
1182 abstract public function getFileList( array $params );
1183
1184 /**
1185 * Same as FileBackend::getFileList() except only lists
1186 * files that are immediately under 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 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1195 * @return Traversable|array|null Returns null on failure
1196 * @since 1.20
1197 */
1198 final public function getTopFileList( array $params ) {
1199 return $this->getFileList( [ 'topOnly' => true ] + $params );
1200 }
1201
1202 /**
1203 * Preload persistent file stat cache and property cache into in-process cache.
1204 * This should be used when stat calls will be made on a known list of a many files.
1205 *
1206 * @see FileBackend::getFileStat()
1207 *
1208 * @param array $paths Storage paths
1209 */
1210 abstract public function preloadCache( array $paths );
1211
1212 /**
1213 * Invalidate any in-process file stat and property cache.
1214 * If $paths is given, then only the cache for those files will be cleared.
1215 *
1216 * @see FileBackend::getFileStat()
1217 *
1218 * @param array $paths Storage paths (optional)
1219 */
1220 abstract public function clearCache( array $paths = null );
1221
1222 /**
1223 * Preload file stat information (concurrently if possible) into in-process cache.
1224 *
1225 * This should be used when stat calls will be made on a known list of a many files.
1226 * This does not make use of the persistent file stat cache.
1227 *
1228 * @see FileBackend::getFileStat()
1229 *
1230 * @param array $params Parameters include:
1231 * - srcs : list of source storage paths
1232 * - latest : use the latest available data
1233 * @return bool All requests proceeded without I/O errors (since 1.24)
1234 * @since 1.23
1235 */
1236 abstract public function preloadFileStat( array $params );
1237
1238 /**
1239 * Lock the files at the given storage paths in the backend.
1240 * This will either lock all the files or none (on failure).
1241 *
1242 * Callers should consider using getScopedFileLocks() instead.
1243 *
1244 * @param array $paths Storage paths
1245 * @param int $type LockManager::LOCK_* constant
1246 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1247 * @return Status
1248 */
1249 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1250 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1251
1252 return $this->lockManager->lock( $paths, $type, $timeout );
1253 }
1254
1255 /**
1256 * Unlock the files at the given storage paths in the backend.
1257 *
1258 * @param array $paths Storage paths
1259 * @param int $type LockManager::LOCK_* constant
1260 * @return Status
1261 */
1262 final public function unlockFiles( array $paths, $type ) {
1263 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1264
1265 return $this->lockManager->unlock( $paths, $type );
1266 }
1267
1268 /**
1269 * Lock the files at the given storage paths in the backend.
1270 * This will either lock all the files or none (on failure).
1271 * On failure, the status object will be updated with errors.
1272 *
1273 * Once the return value goes out scope, the locks will be released and
1274 * the status updated. Unlock fatals will not change the status "OK" value.
1275 *
1276 * @see ScopedLock::factory()
1277 *
1278 * @param array $paths List of storage paths or map of lock types to path lists
1279 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1280 * @param Status $status Status to update on lock/unlock
1281 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1282 * @return ScopedLock|null Returns null on failure
1283 */
1284 final public function getScopedFileLocks( array $paths, $type, Status $status, $timeout = 0 ) {
1285 if ( $type === 'mixed' ) {
1286 foreach ( $paths as &$typePaths ) {
1287 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1288 }
1289 } else {
1290 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1291 }
1292
1293 return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
1294 }
1295
1296 /**
1297 * Get an array of scoped locks needed for a batch of file operations.
1298 *
1299 * Normally, FileBackend::doOperations() handles locking, unless
1300 * the 'nonLocking' param is passed in. This function is useful if you
1301 * want the files to be locked for a broader scope than just when the
1302 * files are changing. For example, if you need to update DB metadata,
1303 * you may want to keep the files locked until finished.
1304 *
1305 * @see FileBackend::doOperations()
1306 *
1307 * @param array $ops List of file operations to FileBackend::doOperations()
1308 * @param Status $status Status to update on lock/unlock
1309 * @return ScopedLock|null
1310 * @since 1.20
1311 */
1312 abstract public function getScopedLocksForOps( array $ops, Status $status );
1313
1314 /**
1315 * Get the root storage path of this backend.
1316 * All container paths are "subdirectories" of this path.
1317 *
1318 * @return string Storage path
1319 * @since 1.20
1320 */
1321 final public function getRootStoragePath() {
1322 return "mwstore://{$this->name}";
1323 }
1324
1325 /**
1326 * Get the storage path for the given container for this backend
1327 *
1328 * @param string $container Container name
1329 * @return string Storage path
1330 * @since 1.21
1331 */
1332 final public function getContainerStoragePath( $container ) {
1333 return $this->getRootStoragePath() . "/{$container}";
1334 }
1335
1336 /**
1337 * Get the file journal object for this backend
1338 *
1339 * @return FileJournal
1340 */
1341 final public function getJournal() {
1342 return $this->fileJournal;
1343 }
1344
1345 /**
1346 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1347 *
1348 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1349 * around as long it needs (which may vary greatly depending on configuration)
1350 *
1351 * @param array $ops File operation batch for FileBaclend::doOperations()
1352 * @return array File operation batch
1353 */
1354 protected function resolveFSFileObjects( array $ops ) {
1355 foreach ( $ops as &$op ) {
1356 $src = isset( $op['src'] ) ? $op['src'] : null;
1357 if ( $src instanceof FSFile ) {
1358 $op['srcRef'] = $src;
1359 $op['src'] = $src->getPath();
1360 }
1361 }
1362 unset( $op );
1363
1364 return $ops;
1365 }
1366
1367 /**
1368 * Check if a given path is a "mwstore://" path.
1369 * This does not do any further validation or any existence checks.
1370 *
1371 * @param string $path
1372 * @return bool
1373 */
1374 final public static function isStoragePath( $path ) {
1375 return ( strpos( $path, 'mwstore://' ) === 0 );
1376 }
1377
1378 /**
1379 * Split a storage path into a backend name, a container name,
1380 * and a relative file path. The relative path may be the empty string.
1381 * This does not do any path normalization or traversal checks.
1382 *
1383 * @param string $storagePath
1384 * @return array (backend, container, rel object) or (null, null, null)
1385 */
1386 final public static function splitStoragePath( $storagePath ) {
1387 if ( self::isStoragePath( $storagePath ) ) {
1388 // Remove the "mwstore://" prefix and split the path
1389 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1390 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1391 if ( count( $parts ) == 3 ) {
1392 return $parts; // e.g. "backend/container/path"
1393 } else {
1394 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1395 }
1396 }
1397 }
1398
1399 return [ null, null, null ];
1400 }
1401
1402 /**
1403 * Normalize a storage path by cleaning up directory separators.
1404 * Returns null if the path is not of the format of a valid storage path.
1405 *
1406 * @param string $storagePath
1407 * @return string|null
1408 */
1409 final public static function normalizeStoragePath( $storagePath ) {
1410 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1411 if ( $relPath !== null ) { // must be for this backend
1412 $relPath = self::normalizeContainerPath( $relPath );
1413 if ( $relPath !== null ) {
1414 return ( $relPath != '' )
1415 ? "mwstore://{$backend}/{$container}/{$relPath}"
1416 : "mwstore://{$backend}/{$container}";
1417 }
1418 }
1419
1420 return null;
1421 }
1422
1423 /**
1424 * Get the parent storage directory of a storage path.
1425 * This returns a path like "mwstore://backend/container",
1426 * "mwstore://backend/container/...", or null if there is no parent.
1427 *
1428 * @param string $storagePath
1429 * @return string|null
1430 */
1431 final public static function parentStoragePath( $storagePath ) {
1432 $storagePath = dirname( $storagePath );
1433 list( , , $rel ) = self::splitStoragePath( $storagePath );
1434
1435 return ( $rel === null ) ? null : $storagePath;
1436 }
1437
1438 /**
1439 * Get the final extension from a storage or FS path
1440 *
1441 * @param string $path
1442 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1443 * @return string
1444 */
1445 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1446 $i = strrpos( $path, '.' );
1447 $ext = $i ? substr( $path, $i + 1 ) : '';
1448
1449 if ( $case === 'lowercase' ) {
1450 $ext = strtolower( $ext );
1451 } elseif ( $case === 'uppercase' ) {
1452 $ext = strtoupper( $ext );
1453 }
1454
1455 return $ext;
1456 }
1457
1458 /**
1459 * Check if a relative path has no directory traversals
1460 *
1461 * @param string $path
1462 * @return bool
1463 * @since 1.20
1464 */
1465 final public static function isPathTraversalFree( $path ) {
1466 return ( self::normalizeContainerPath( $path ) !== null );
1467 }
1468
1469 /**
1470 * Build a Content-Disposition header value per RFC 6266.
1471 *
1472 * @param string $type One of (attachment, inline)
1473 * @param string $filename Suggested file name (should not contain slashes)
1474 * @throws FileBackendError
1475 * @return string
1476 * @since 1.20
1477 */
1478 final public static function makeContentDisposition( $type, $filename = '' ) {
1479 $parts = [];
1480
1481 $type = strtolower( $type );
1482 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1483 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1484 }
1485 $parts[] = $type;
1486
1487 if ( strlen( $filename ) ) {
1488 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1489 }
1490
1491 return implode( ';', $parts );
1492 }
1493
1494 /**
1495 * Validate and normalize a relative storage path.
1496 * Null is returned if the path involves directory traversal.
1497 * Traversal is insecure for FS backends and broken for others.
1498 *
1499 * This uses the same traversal protection as Title::secureAndSplit().
1500 *
1501 * @param string $path Storage path relative to a container
1502 * @return string|null
1503 */
1504 final protected static function normalizeContainerPath( $path ) {
1505 // Normalize directory separators
1506 $path = strtr( $path, '\\', '/' );
1507 // Collapse any consecutive directory separators
1508 $path = preg_replace( '![/]{2,}!', '/', $path );
1509 // Remove any leading directory separator
1510 $path = ltrim( $path, '/' );
1511 // Use the same traversal protection as Title::secureAndSplit()
1512 if ( strpos( $path, '.' ) !== false ) {
1513 if (
1514 $path === '.' ||
1515 $path === '..' ||
1516 strpos( $path, './' ) === 0 ||
1517 strpos( $path, '../' ) === 0 ||
1518 strpos( $path, '/./' ) !== false ||
1519 strpos( $path, '/../' ) !== false
1520 ) {
1521 return null;
1522 }
1523 }
1524
1525 return $path;
1526 }
1527 }
1528
1529 /**
1530 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1531 *
1532 * @ingroup FileBackend
1533 * @since 1.23
1534 */
1535 class FileBackendException extends Exception {
1536 }
1537
1538 /**
1539 * File backend exception for checked exceptions (e.g. I/O errors)
1540 *
1541 * @ingroup FileBackend
1542 * @since 1.22
1543 */
1544 class FileBackendError extends FileBackendException {
1545 }