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