MWException: Don't send headers multiple times
[mediawiki.git] / includes / filebackend / FileBackend.php
blobf99da6dbc7950214f1caf270f49e172c1759f121
1 <?php
2 /**
3 * @defgroup FileBackend File backend
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
7 */
9 /**
10 * Base class for all file backends.
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.
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.
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
27 * @file
28 * @ingroup FileBackend
29 * @author Aaron Schulz
32 /**
33 * @brief Base class for all file backend classes (including multi-write backends).
35 * This class defines the methods as abstract that subclasses must implement.
36 * Outside callers can assume that all backends will have these functions.
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.
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".
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.
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
79 * Methods of subclasses should avoid throwing exceptions at all costs.
80 * As a corollary, external dependencies should be kept to a minimum.
82 * @ingroup FileBackend
83 * @since 1.19
85 abstract class FileBackend {
86 /** @var string Unique backend name */
87 protected $name;
89 /** @var string Unique wiki name */
90 protected $wikiId;
92 /** @var string Read-only explanation message */
93 protected $readOnly;
95 /** @var string When to do operations in parallel */
96 protected $parallelize;
98 /** @var int How many operations can be done in parallel */
99 protected $concurrency;
101 /** @var LockManager */
102 protected $lockManager;
104 /** @var FileJournal */
105 protected $fileJournal;
107 /** Flags for supported features */
108 const ATTR_HEADERS = 1;
109 const ATTR_METADATA = 2;
112 * Create a new backend instance from configuration.
113 * This should only be called from within FileBackendGroup.
115 * @param array $config Parameters include:
116 * - name : The unique name of this backend.
117 * This should consist of alphanumberic, '-', and '_' characters.
118 * This name should not be changed after use (e.g. with journaling).
119 * Note that the name is *not* used in actual container names.
120 * - wikiId : Prefix to container names that is unique to this backend.
121 * It should only consist of alphanumberic, '-', and '_' characters.
122 * This ID is what avoids collisions if multiple logical backends
123 * use the same storage system, so this should be set carefully.
124 * - lockManager : LockManager object to use for any file locking.
125 * If not provided, then no file locking will be enforced.
126 * - fileJournal : FileJournal object to use for logging changes to files.
127 * If not provided, then change journaling will be disabled.
128 * - readOnly : Write operations are disallowed if this is a non-empty string.
129 * It should be an explanation for the backend being read-only.
130 * - parallelize : When to do file operations in parallel (when possible).
131 * Allowed values are "implicit", "explicit" and "off".
132 * - concurrency : How many file operations can be done in parallel.
133 * @throws FileBackendException
135 public function __construct( array $config ) {
136 $this->name = $config['name'];
137 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
138 throw new FileBackendException( "Backend name `{$this->name}` is invalid." );
140 if ( !isset( $config['wikiId'] ) ) {
141 $config['wikiId'] = wfWikiID();
142 wfDeprecated( __METHOD__ . ' called without "wikiID".', '1.23' );
144 if ( isset( $config['lockManager'] ) && !is_object( $config['lockManager'] ) ) {
145 $config['lockManager'] =
146 LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
147 wfDeprecated( __METHOD__ . ' called with non-object "lockManager".', '1.23' );
149 $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
150 $this->lockManager = isset( $config['lockManager'] )
151 ? $config['lockManager']
152 : new NullLockManager( array() );
153 $this->fileJournal = isset( $config['fileJournal'] )
154 ? $config['fileJournal']
155 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
156 $this->readOnly = isset( $config['readOnly'] )
157 ? (string)$config['readOnly']
158 : '';
159 $this->parallelize = isset( $config['parallelize'] )
160 ? (string)$config['parallelize']
161 : 'off';
162 $this->concurrency = isset( $config['concurrency'] )
163 ? (int)$config['concurrency']
164 : 50;
168 * Get the unique backend name.
169 * We may have multiple different backends of the same type.
170 * For example, we can have two Swift backends using different proxies.
172 * @return string
174 final public function getName() {
175 return $this->name;
179 * Get the wiki identifier used for this backend (possibly empty).
180 * Note that this might *not* be in the same format as wfWikiID().
182 * @return string
183 * @since 1.20
185 final public function getWikiId() {
186 return $this->wikiId;
190 * Check if this backend is read-only
192 * @return bool
194 final public function isReadOnly() {
195 return ( $this->readOnly != '' );
199 * Get an explanatory message if this backend is read-only
201 * @return string|bool Returns false if the backend is not read-only
203 final public function getReadOnlyReason() {
204 return ( $this->readOnly != '' ) ? $this->readOnly : false;
208 * Get the a bitfield of extra features supported by the backend medium
210 * @return int Bitfield of FileBackend::ATTR_* flags
211 * @since 1.23
213 public function getFeatures() {
214 return 0;
218 * Check if the backend medium supports a field of extra features
220 * @return int Bitfield of FileBackend::ATTR_* flags
221 * @return bool
222 * @since 1.23
224 final public function hasFeatures( $bitfield ) {
225 return ( $this->getFeatures() & $bitfield ) === $bitfield;
229 * This is the main entry point into the backend for write operations.
230 * Callers supply an ordered list of operations to perform as a transaction.
231 * Files will be locked, the stat cache cleared, and then the operations attempted.
232 * If any serious errors occur, all attempted operations will be rolled back.
234 * $ops is an array of arrays. The outer array holds a list of operations.
235 * Each inner array is a set of key value pairs that specify an operation.
237 * Supported operations and their parameters. The supported actions are:
238 * - create
239 * - store
240 * - copy
241 * - move
242 * - delete
243 * - describe (since 1.21)
244 * - null
246 * a) Create a new file in storage with the contents of a string
247 * @code
248 * array(
249 * 'op' => 'create',
250 * 'dst' => <storage path>,
251 * 'content' => <string of new file contents>,
252 * 'overwrite' => <boolean>,
253 * 'overwriteSame' => <boolean>,
254 * 'headers' => <HTTP header name/value map> # since 1.21
255 * );
256 * @endcode
258 * b) Copy a file system file into storage
259 * @code
260 * array(
261 * 'op' => 'store',
262 * 'src' => <file system path>,
263 * 'dst' => <storage path>,
264 * 'overwrite' => <boolean>,
265 * 'overwriteSame' => <boolean>,
266 * 'headers' => <HTTP header name/value map> # since 1.21
268 * @endcode
270 * c) Copy a file within storage
271 * @code
272 * array(
273 * 'op' => 'copy',
274 * 'src' => <storage path>,
275 * 'dst' => <storage path>,
276 * 'overwrite' => <boolean>,
277 * 'overwriteSame' => <boolean>,
278 * 'ignoreMissingSource' => <boolean>, # since 1.21
279 * 'headers' => <HTTP header name/value map> # since 1.21
281 * @endcode
283 * d) Move a file within storage
284 * @code
285 * array(
286 * 'op' => 'move',
287 * 'src' => <storage path>,
288 * 'dst' => <storage path>,
289 * 'overwrite' => <boolean>,
290 * 'overwriteSame' => <boolean>,
291 * 'ignoreMissingSource' => <boolean>, # since 1.21
292 * 'headers' => <HTTP header name/value map> # since 1.21
294 * @endcode
296 * e) Delete a file within storage
297 * @code
298 * array(
299 * 'op' => 'delete',
300 * 'src' => <storage path>,
301 * 'ignoreMissingSource' => <boolean>
303 * @endcode
305 * f) Update metadata for a file within storage
306 * @code
307 * array(
308 * 'op' => 'describe',
309 * 'src' => <storage path>,
310 * 'headers' => <HTTP header name/value map>
312 * @endcode
314 * g) Do nothing (no-op)
315 * @code
316 * array(
317 * 'op' => 'null',
319 * @endcode
321 * Boolean flags for operations (operation-specific):
322 * - ignoreMissingSource : The operation will simply succeed and do
323 * nothing if the source file does not exist.
324 * - overwrite : Any destination file will be overwritten.
325 * - overwriteSame : If a file already exists at the destination with the
326 * same contents, then do nothing to the destination file
327 * instead of giving an error. This does not compare headers.
328 * This option is ignored if 'overwrite' is already provided.
329 * - headers : If supplied, the result of merging these headers with any
330 * existing source file headers (replacing conflicting ones)
331 * will be set as the destination file headers. Headers are
332 * deleted if their value is set to the empty string. When a
333 * file has headers they are included in responses to GET and
334 * HEAD requests to the backing store for that file.
335 * Header values should be no larger than 255 bytes, except for
336 * Content-Disposition. The system might ignore or truncate any
337 * headers that are too long to store (exact limits will vary).
338 * Backends that don't support metadata ignore this. (since 1.21)
340 * $opts is an associative of boolean flags, including:
341 * - force : Operation precondition errors no longer trigger an abort.
342 * Any remaining operations are still attempted. Unexpected
343 * failures may still cause remaining operations to be aborted.
344 * - nonLocking : No locks are acquired for the operations.
345 * This can increase performance for non-critical writes.
346 * This has no effect unless the 'force' flag is set.
347 * - nonJournaled : Don't log this operation batch in the file journal.
348 * This limits the ability of recovery scripts.
349 * - parallelize : Try to do operations in parallel when possible.
350 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
351 * - preserveCache : Don't clear the process cache before checking files.
352 * This should only be used if all entries in the process
353 * cache were added after the files were already locked. (since 1.20)
355 * @remarks Remarks on locking:
356 * File system paths given to operations should refer to files that are
357 * already locked or otherwise safe from modification from other processes.
358 * Normally these files will be new temp files, which should be adequate.
360 * @par Return value:
362 * This returns a Status, which contains all warnings and fatals that occurred
363 * during the operation. The 'failCount', 'successCount', and 'success' members
364 * will reflect each operation attempted.
366 * The status will be "OK" unless:
367 * - a) unexpected operation errors occurred (network partitions, disk full...)
368 * - b) significant operation errors occurred and 'force' was not set
370 * @param array $ops List of operations to execute in order
371 * @param array $opts Batch operation options
372 * @return Status
374 final public function doOperations( array $ops, array $opts = array() ) {
375 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
376 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
378 if ( !count( $ops ) ) {
379 return Status::newGood(); // nothing to do
381 if ( empty( $opts['force'] ) ) { // sanity
382 unset( $opts['nonLocking'] );
384 foreach ( $ops as &$op ) {
385 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
386 $op['headers']['Content-Disposition'] = $op['disposition'];
389 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
390 return $this->doOperationsInternal( $ops, $opts );
394 * @see FileBackend::doOperations()
396 abstract protected function doOperationsInternal( array $ops, array $opts );
399 * Same as doOperations() except it takes a single operation.
400 * If you are doing a batch of operations that should either
401 * all succeed or all fail, then use that function instead.
403 * @see FileBackend::doOperations()
405 * @param array $op Operation
406 * @param array $opts Operation options
407 * @return Status
409 final public function doOperation( array $op, array $opts = array() ) {
410 return $this->doOperations( array( $op ), $opts );
414 * Performs a single create operation.
415 * This sets $params['op'] to 'create' and passes it to doOperation().
417 * @see FileBackend::doOperation()
419 * @param array $params Operation parameters
420 * @param array $opts Operation options
421 * @return Status
423 final public function create( array $params, array $opts = array() ) {
424 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
428 * Performs a single store operation.
429 * This sets $params['op'] to 'store' and passes it to doOperation().
431 * @see FileBackend::doOperation()
433 * @param array $params Operation parameters
434 * @param array $opts Operation options
435 * @return Status
437 final public function store( array $params, array $opts = array() ) {
438 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
442 * Performs a single copy operation.
443 * This sets $params['op'] to 'copy' and passes it to doOperation().
445 * @see FileBackend::doOperation()
447 * @param array $params Operation parameters
448 * @param array $opts Operation options
449 * @return Status
451 final public function copy( array $params, array $opts = array() ) {
452 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
456 * Performs a single move operation.
457 * This sets $params['op'] to 'move' and passes it to doOperation().
459 * @see FileBackend::doOperation()
461 * @param array $params Operation parameters
462 * @param array $opts Operation options
463 * @return Status
465 final public function move( array $params, array $opts = array() ) {
466 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
470 * Performs a single delete operation.
471 * This sets $params['op'] to 'delete' and passes it to doOperation().
473 * @see FileBackend::doOperation()
475 * @param array $params Operation parameters
476 * @param array $opts Operation options
477 * @return Status
479 final public function delete( array $params, array $opts = array() ) {
480 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
484 * Performs a single describe operation.
485 * This sets $params['op'] to 'describe' and passes it to doOperation().
487 * @see FileBackend::doOperation()
489 * @param array $params Operation parameters
490 * @param array $opts Operation options
491 * @return Status
492 * @since 1.21
494 final public function describe( array $params, array $opts = array() ) {
495 return $this->doOperation( array( 'op' => 'describe' ) + $params, $opts );
499 * Perform a set of independent file operations on some files.
501 * This does no locking, nor journaling, and possibly no stat calls.
502 * Any destination files that already exist will be overwritten.
503 * This should *only* be used on non-original files, like cache files.
505 * Supported operations and their parameters:
506 * - create
507 * - store
508 * - copy
509 * - move
510 * - delete
511 * - describe (since 1.21)
512 * - null
514 * a) Create a new file in storage with the contents of a string
515 * @code
516 * array(
517 * 'op' => 'create',
518 * 'dst' => <storage path>,
519 * 'content' => <string of new file contents>,
520 * 'headers' => <HTTP header name/value map> # since 1.21
522 * @endcode
524 * b) Copy a file system file into storage
525 * @code
526 * array(
527 * 'op' => 'store',
528 * 'src' => <file system path>,
529 * 'dst' => <storage path>,
530 * 'headers' => <HTTP header name/value map> # since 1.21
532 * @endcode
534 * c) Copy a file within storage
535 * @code
536 * array(
537 * 'op' => 'copy',
538 * 'src' => <storage path>,
539 * 'dst' => <storage path>,
540 * 'ignoreMissingSource' => <boolean>, # since 1.21
541 * 'headers' => <HTTP header name/value map> # since 1.21
543 * @endcode
545 * d) Move a file within storage
546 * @code
547 * array(
548 * 'op' => 'move',
549 * 'src' => <storage path>,
550 * 'dst' => <storage path>,
551 * 'ignoreMissingSource' => <boolean>, # since 1.21
552 * 'headers' => <HTTP header name/value map> # since 1.21
554 * @endcode
556 * e) Delete a file within storage
557 * @code
558 * array(
559 * 'op' => 'delete',
560 * 'src' => <storage path>,
561 * 'ignoreMissingSource' => <boolean>
563 * @endcode
565 * f) Update metadata for a file within storage
566 * @code
567 * array(
568 * 'op' => 'describe',
569 * 'src' => <storage path>,
570 * 'headers' => <HTTP header name/value map>
572 * @endcode
574 * g) Do nothing (no-op)
575 * @code
576 * array(
577 * 'op' => 'null',
579 * @endcode
581 * @par Boolean flags for operations (operation-specific):
582 * - ignoreMissingSource : The operation will simply succeed and do
583 * nothing if the source file does not exist.
584 * - headers : If supplied with a header name/value map, the backend will
585 * reply with these headers when GETs/HEADs of the destination
586 * file are made. Header values should be smaller than 256 bytes.
587 * Content-Disposition headers can be longer, though the system
588 * might ignore or truncate ones that are too long to store.
589 * Existing headers will remain, but these will replace any
590 * conflicting previous headers, and headers will be removed
591 * if they are set to an empty string.
592 * Backends that don't support metadata ignore this. (since 1.21)
594 * $opts is an associative of boolean flags, including:
595 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
597 * @par Return value:
598 * This returns a Status, which contains all warnings and fatals that occurred
599 * during the operation. The 'failCount', 'successCount', and 'success' members
600 * will reflect each operation attempted for the given files. The status will be
601 * considered "OK" as long as no fatal errors occurred.
603 * @param array $ops Set of operations to execute
604 * @param array $opts Batch operation options
605 * @return Status
606 * @since 1.20
608 final public function doQuickOperations( array $ops, array $opts = array() ) {
609 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
610 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
612 if ( !count( $ops ) ) {
613 return Status::newGood(); // nothing to do
615 foreach ( $ops as &$op ) {
616 $op['overwrite'] = true; // avoids RTTs in key/value stores
617 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
618 $op['headers']['Content-Disposition'] = $op['disposition'];
621 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
622 return $this->doQuickOperationsInternal( $ops );
626 * @see FileBackend::doQuickOperations()
627 * @since 1.20
629 abstract protected function doQuickOperationsInternal( array $ops );
632 * Same as doQuickOperations() except it takes a single operation.
633 * If you are doing a batch of operations, then use that function instead.
635 * @see FileBackend::doQuickOperations()
637 * @param array $op Operation
638 * @return Status
639 * @since 1.20
641 final public function doQuickOperation( array $op ) {
642 return $this->doQuickOperations( array( $op ) );
646 * Performs a single quick create operation.
647 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
649 * @see FileBackend::doQuickOperation()
651 * @param array $params Operation parameters
652 * @return Status
653 * @since 1.20
655 final public function quickCreate( array $params ) {
656 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
660 * Performs a single quick store operation.
661 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
663 * @see FileBackend::doQuickOperation()
665 * @param array $params Operation parameters
666 * @return Status
667 * @since 1.20
669 final public function quickStore( array $params ) {
670 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
674 * Performs a single quick copy operation.
675 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
677 * @see FileBackend::doQuickOperation()
679 * @param array $params Operation parameters
680 * @return Status
681 * @since 1.20
683 final public function quickCopy( array $params ) {
684 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
688 * Performs a single quick move operation.
689 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
691 * @see FileBackend::doQuickOperation()
693 * @param array $params Operation parameters
694 * @return Status
695 * @since 1.20
697 final public function quickMove( array $params ) {
698 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
702 * Performs a single quick delete operation.
703 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
705 * @see FileBackend::doQuickOperation()
707 * @param array $params Operation parameters
708 * @return Status
709 * @since 1.20
711 final public function quickDelete( array $params ) {
712 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
716 * Performs a single quick describe operation.
717 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
719 * @see FileBackend::doQuickOperation()
721 * @param array $params Operation parameters
722 * @return Status
723 * @since 1.21
725 final public function quickDescribe( array $params ) {
726 return $this->doQuickOperation( array( 'op' => 'describe' ) + $params );
730 * Concatenate a list of storage files into a single file system file.
731 * The target path should refer to a file that is already locked or
732 * otherwise safe from modification from other processes. Normally,
733 * the file will be a new temp file, which should be adequate.
735 * @param array $params Operation parameters, include:
736 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
737 * - dst : file system path to 0-byte temp file
738 * - parallelize : try to do operations in parallel when possible
739 * @return Status
741 abstract public function concatenate( array $params );
744 * Prepare a storage directory for usage.
745 * This will create any required containers and parent directories.
746 * Backends using key/value stores only need to create the container.
748 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
749 * except they are only applied *if* the directory/container had to be created.
750 * These flags should always be set for directories that have private files.
751 * However, setting them is not guaranteed to actually do anything.
752 * Additional server configuration may be needed to achieve the desired effect.
754 * @param array $params Parameters include:
755 * - dir : storage directory
756 * - noAccess : try to deny file access (since 1.20)
757 * - noListing : try to deny file listing (since 1.20)
758 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
759 * @return Status
761 final public function prepare( array $params ) {
762 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
763 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
765 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
766 return $this->doPrepare( $params );
770 * @see FileBackend::prepare()
772 abstract protected function doPrepare( array $params );
775 * Take measures to block web access to a storage directory and
776 * the container it belongs to. FS backends might add .htaccess
777 * files whereas key/value store backends might revoke container
778 * access to the storage user representing end-users in web requests.
780 * This is not guaranteed to actually make files or listings publically hidden.
781 * Additional server configuration may be needed to achieve the desired effect.
783 * @param array $params Parameters include:
784 * - dir : storage directory
785 * - noAccess : try to deny file access
786 * - noListing : try to deny file listing
787 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
788 * @return Status
790 final public function secure( array $params ) {
791 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
792 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
794 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
795 return $this->doSecure( $params );
799 * @see FileBackend::secure()
801 abstract protected function doSecure( array $params );
804 * Remove measures to block web access to a storage directory and
805 * the container it belongs to. FS backends might remove .htaccess
806 * files whereas key/value store backends might grant container
807 * access to the storage user representing end-users in web requests.
808 * This essentially can undo the result of secure() calls.
810 * This is not guaranteed to actually make files or listings publically viewable.
811 * Additional server configuration may be needed to achieve the desired effect.
813 * @param array $params Parameters include:
814 * - dir : storage directory
815 * - access : try to allow file access
816 * - listing : try to allow file listing
817 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
818 * @return Status
819 * @since 1.20
821 final public function publish( array $params ) {
822 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
823 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
825 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
826 return $this->doPublish( $params );
830 * @see FileBackend::publish()
832 abstract protected function doPublish( array $params );
835 * Delete a storage directory if it is empty.
836 * Backends using key/value stores may do nothing unless the directory
837 * is that of an empty container, in which case it will be deleted.
839 * @param array $params Parameters include:
840 * - dir : storage directory
841 * - recursive : recursively delete empty subdirectories first (since 1.20)
842 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
843 * @return Status
845 final public function clean( array $params ) {
846 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
847 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
849 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
850 return $this->doClean( $params );
854 * @see FileBackend::clean()
856 abstract protected function doClean( array $params );
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.
863 * @return ScopedCallback|null
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 } );
873 return null;
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.
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
885 abstract public function fileExists( array $params );
888 * Get the last-modified timestamp of the file at a storage path.
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
895 abstract public function getFileTimestamp( array $params );
898 * Get the contents of a file at a storage path in the backend.
899 * This should be avoided for potentially large files.
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
906 final public function getFileContents( array $params ) {
907 $contents = $this->getFileContentsMulti(
908 array( 'srcs' => array( $params['src'] ) ) + $params );
910 return $contents[$params['src']];
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.
918 * @see FileBackend::getFileContents()
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
927 abstract public function getFileContentsMulti( array $params );
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.
938 * Use FileBackend::hasFeatures() to check how well this is supported.
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
947 abstract public function getFileXAttributes( array $params );
950 * Get the size (bytes) of a file at a storage path in the backend.
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
957 abstract public function getFileSize( array $params );
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.
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
972 abstract public function getFileStat( array $params );
975 * Get a SHA-1 hash of the file at a storage path in the backend.
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
982 abstract public function getFileSha1Base36( array $params );
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.
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
993 abstract public function getFileProps( array $params );
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.
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
1008 abstract public function streamFile( array $params );
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.
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.
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
1028 final public function getLocalReference( array $params ) {
1029 $fsFiles = $this->getLocalReferenceMulti(
1030 array( 'srcs' => array( $params['src'] ) ) + $params );
1032 return $fsFiles[$params['src']];
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.
1040 * @see FileBackend::getLocalReference()
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
1049 abstract public function getLocalReferenceMulti( array $params );
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.
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
1061 final public function getLocalCopy( array $params ) {
1062 $tmpFiles = $this->getLocalCopyMulti(
1063 array( 'srcs' => array( $params['src'] ) ) + $params );
1065 return $tmpFiles[$params['src']];
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.
1073 * @see FileBackend::getLocalCopy()
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
1082 abstract public function getLocalCopyMulti( array $params );
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.
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.
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
1100 abstract public function getFileHttpUrl( array $params );
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.
1107 * Storage backends with eventual consistency might return stale data.
1109 * @param array $params Parameters include:
1110 * - dir : storage directory
1111 * @return bool|null Returns null on failure
1112 * @since 1.20
1114 abstract public function directoryExists( array $params );
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.
1124 * Storage backends with eventual consistency might return stale data.
1126 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
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
1134 abstract public function getDirectoryList( array $params );
1137 * Same as FileBackend::getDirectoryList() except only lists
1138 * directories that are immediately under the given directory.
1140 * Storage backends with eventual consistency might return stale data.
1142 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1144 * @param array $params Parameters include:
1145 * - dir : storage directory
1146 * @return Traversable|array|null Returns null on failure
1147 * @since 1.20
1149 final public function getTopDirectoryList( array $params ) {
1150 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
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.
1161 * Storage backends with eventual consistency might return stale data.
1163 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
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
1171 abstract public function getFileList( array $params );
1174 * Same as FileBackend::getFileList() except only lists
1175 * files that are immediately under the given directory.
1177 * Storage backends with eventual consistency might return stale data.
1179 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
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
1187 final public function getTopFileList( array $params ) {
1188 return $this->getFileList( array( 'topOnly' => true ) + $params );
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.
1195 * @see FileBackend::getFileStat()
1197 * @param array $paths Storage paths
1199 abstract public function preloadCache( array $paths );
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.
1205 * @see FileBackend::getFileStat()
1207 * @param array $paths Storage paths (optional)
1209 abstract public function clearCache( array $paths = null );
1212 * Preload file stat information (concurrently if possible) into in-process cache.
1213 * This should be used when stat calls will be made on a known list of a many files.
1215 * @see FileBackend::getFileStat()
1217 * @param array $params Parameters include:
1218 * - srcs : list of source storage paths
1219 * - latest : use the latest available data
1220 * @return bool All requests proceeded without I/O errors (since 1.24)
1221 * @since 1.23
1223 abstract public function preloadFileStat( array $params );
1226 * Lock the files at the given storage paths in the backend.
1227 * This will either lock all the files or none (on failure).
1229 * Callers should consider using getScopedFileLocks() instead.
1231 * @param array $paths Storage paths
1232 * @param int $type LockManager::LOCK_* constant
1233 * @return Status
1235 final public function lockFiles( array $paths, $type ) {
1236 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1238 return $this->lockManager->lock( $paths, $type );
1242 * Unlock the files at the given storage paths in the backend.
1244 * @param array $paths Storage paths
1245 * @param int $type LockManager::LOCK_* constant
1246 * @return Status
1248 final public function unlockFiles( array $paths, $type ) {
1249 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1251 return $this->lockManager->unlock( $paths, $type );
1255 * Lock the files at the given storage paths in the backend.
1256 * This will either lock all the files or none (on failure).
1257 * On failure, the status object will be updated with errors.
1259 * Once the return value goes out scope, the locks will be released and
1260 * the status updated. Unlock fatals will not change the status "OK" value.
1262 * @see ScopedLock::factory()
1264 * @param array $paths List of storage paths or map of lock types to path lists
1265 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1266 * @param Status $status Status to update on lock/unlock
1267 * @return ScopedLock|null Returns null on failure
1269 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
1270 if ( $type === 'mixed' ) {
1271 foreach ( $paths as &$typePaths ) {
1272 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1274 } else {
1275 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1278 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
1282 * Get an array of scoped locks needed for a batch of file operations.
1284 * Normally, FileBackend::doOperations() handles locking, unless
1285 * the 'nonLocking' param is passed in. This function is useful if you
1286 * want the files to be locked for a broader scope than just when the
1287 * files are changing. For example, if you need to update DB metadata,
1288 * you may want to keep the files locked until finished.
1290 * @see FileBackend::doOperations()
1292 * @param array $ops List of file operations to FileBackend::doOperations()
1293 * @param Status $status Status to update on lock/unlock
1294 * @return array List of ScopedFileLocks or null values
1295 * @since 1.20
1297 abstract public function getScopedLocksForOps( array $ops, Status $status );
1300 * Get the root storage path of this backend.
1301 * All container paths are "subdirectories" of this path.
1303 * @return string Storage path
1304 * @since 1.20
1306 final public function getRootStoragePath() {
1307 return "mwstore://{$this->name}";
1311 * Get the storage path for the given container for this backend
1313 * @param string $container Container name
1314 * @return string Storage path
1315 * @since 1.21
1317 final public function getContainerStoragePath( $container ) {
1318 return $this->getRootStoragePath() . "/{$container}";
1322 * Get the file journal object for this backend
1324 * @return FileJournal
1326 final public function getJournal() {
1327 return $this->fileJournal;
1331 * Check if a given path is a "mwstore://" path.
1332 * This does not do any further validation or any existence checks.
1334 * @param string $path
1335 * @return bool
1337 final public static function isStoragePath( $path ) {
1338 return ( strpos( $path, 'mwstore://' ) === 0 );
1342 * Split a storage path into a backend name, a container name,
1343 * and a relative file path. The relative path may be the empty string.
1344 * This does not do any path normalization or traversal checks.
1346 * @param string $storagePath
1347 * @return array (backend, container, rel object) or (null, null, null)
1349 final public static function splitStoragePath( $storagePath ) {
1350 if ( self::isStoragePath( $storagePath ) ) {
1351 // Remove the "mwstore://" prefix and split the path
1352 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1353 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1354 if ( count( $parts ) == 3 ) {
1355 return $parts; // e.g. "backend/container/path"
1356 } else {
1357 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1362 return array( null, null, null );
1366 * Normalize a storage path by cleaning up directory separators.
1367 * Returns null if the path is not of the format of a valid storage path.
1369 * @param string $storagePath
1370 * @return string|null
1372 final public static function normalizeStoragePath( $storagePath ) {
1373 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1374 if ( $relPath !== null ) { // must be for this backend
1375 $relPath = self::normalizeContainerPath( $relPath );
1376 if ( $relPath !== null ) {
1377 return ( $relPath != '' )
1378 ? "mwstore://{$backend}/{$container}/{$relPath}"
1379 : "mwstore://{$backend}/{$container}";
1383 return null;
1387 * Get the parent storage directory of a storage path.
1388 * This returns a path like "mwstore://backend/container",
1389 * "mwstore://backend/container/...", or null if there is no parent.
1391 * @param string $storagePath
1392 * @return string|null
1394 final public static function parentStoragePath( $storagePath ) {
1395 $storagePath = dirname( $storagePath );
1396 list( , , $rel ) = self::splitStoragePath( $storagePath );
1398 return ( $rel === null ) ? null : $storagePath;
1402 * Get the final extension from a storage or FS path
1404 * @param string $path
1405 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1406 * @return string
1408 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1409 $i = strrpos( $path, '.' );
1410 $ext = $i ? substr( $path, $i + 1 ) : '';
1412 if ( $case === 'lowercase' ) {
1413 $ext = strtolower( $ext );
1414 } elseif ( $case === 'uppercase' ) {
1415 $ext = strtoupper( $ext );
1418 return $ext;
1422 * Check if a relative path has no directory traversals
1424 * @param string $path
1425 * @return bool
1426 * @since 1.20
1428 final public static function isPathTraversalFree( $path ) {
1429 return ( self::normalizeContainerPath( $path ) !== null );
1433 * Build a Content-Disposition header value per RFC 6266.
1435 * @param string $type One of (attachment, inline)
1436 * @param string $filename Suggested file name (should not contain slashes)
1437 * @throws FileBackendError
1438 * @return string
1439 * @since 1.20
1441 final public static function makeContentDisposition( $type, $filename = '' ) {
1442 $parts = array();
1444 $type = strtolower( $type );
1445 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1446 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1448 $parts[] = $type;
1450 if ( strlen( $filename ) ) {
1451 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1454 return implode( ';', $parts );
1458 * Validate and normalize a relative storage path.
1459 * Null is returned if the path involves directory traversal.
1460 * Traversal is insecure for FS backends and broken for others.
1462 * This uses the same traversal protection as Title::secureAndSplit().
1464 * @param string $path Storage path relative to a container
1465 * @return string|null
1467 final protected static function normalizeContainerPath( $path ) {
1468 // Normalize directory separators
1469 $path = strtr( $path, '\\', '/' );
1470 // Collapse any consecutive directory separators
1471 $path = preg_replace( '![/]{2,}!', '/', $path );
1472 // Remove any leading directory separator
1473 $path = ltrim( $path, '/' );
1474 // Use the same traversal protection as Title::secureAndSplit()
1475 if ( strpos( $path, '.' ) !== false ) {
1476 if (
1477 $path === '.' ||
1478 $path === '..' ||
1479 strpos( $path, './' ) === 0 ||
1480 strpos( $path, '../' ) === 0 ||
1481 strpos( $path, '/./' ) !== false ||
1482 strpos( $path, '/../' ) !== false
1484 return null;
1488 return $path;
1493 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1495 * @ingroup FileBackend
1496 * @since 1.23
1498 class FileBackendException extends MWException {
1502 * File backend exception for checked exceptions (e.g. I/O errors)
1504 * @ingroup FileBackend
1505 * @since 1.22
1507 class FileBackendError extends FileBackendException {