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