Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / filebackend / FileBackend.php
blob2820be26adbb4935f5ccd57c25a0fa542dbd5405
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 /** 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)
113 * Create a new backend instance from configuration.
114 * This should only be called from within FileBackendGroup.
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
136 public function __construct( array $config ) {
137 $this->name = $config['name'];
138 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
139 throw new FileBackendException( "Backend name `{$this->name}` is invalid." );
141 if ( !isset( $config['wikiId'] ) ) {
142 $config['wikiId'] = wfWikiID();
143 wfDeprecated( __METHOD__ . ' called without "wikiID".', '1.23' );
145 if ( isset( $config['lockManager'] ) && !is_object( $config['lockManager'] ) ) {
146 $config['lockManager'] =
147 LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
148 wfDeprecated( __METHOD__ . ' called with non-object "lockManager".', '1.23' );
150 $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
151 $this->lockManager = isset( $config['lockManager'] )
152 ? $config['lockManager']
153 : new NullLockManager( array() );
154 $this->fileJournal = isset( $config['fileJournal'] )
155 ? $config['fileJournal']
156 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
157 $this->readOnly = isset( $config['readOnly'] )
158 ? (string)$config['readOnly']
159 : '';
160 $this->parallelize = isset( $config['parallelize'] )
161 ? (string)$config['parallelize']
162 : 'off';
163 $this->concurrency = isset( $config['concurrency'] )
164 ? (int)$config['concurrency']
165 : 50;
169 * Get the unique backend name.
170 * We may have multiple different backends of the same type.
171 * For example, we can have two Swift backends using different proxies.
173 * @return string
175 final public function getName() {
176 return $this->name;
180 * Get the wiki identifier used for this backend (possibly empty).
181 * Note that this might *not* be in the same format as wfWikiID().
183 * @return string
184 * @since 1.20
186 final public function getWikiId() {
187 return $this->wikiId;
191 * Check if this backend is read-only
193 * @return bool
195 final public function isReadOnly() {
196 return ( $this->readOnly != '' );
200 * Get an explanatory message if this backend is read-only
202 * @return string|bool Returns false if the backend is not read-only
204 final public function getReadOnlyReason() {
205 return ( $this->readOnly != '' ) ? $this->readOnly : false;
209 * Get the a bitfield of extra features supported by the backend medium
211 * @return int Bitfield of FileBackend::ATTR_* flags
212 * @since 1.23
214 public function getFeatures() {
215 return self::ATTR_UNICODE_PATHS;
219 * Check if the backend medium supports a field of extra features
221 * @return int Bitfield of FileBackend::ATTR_* flags
222 * @return bool
223 * @since 1.23
225 final public function hasFeatures( $bitfield ) {
226 return ( $this->getFeatures() & $bitfield ) === $bitfield;
230 * This is the main entry point into the backend for write operations.
231 * Callers supply an ordered list of operations to perform as a transaction.
232 * Files will be locked, the stat cache cleared, and then the operations attempted.
233 * If any serious errors occur, all attempted operations will be rolled back.
235 * $ops is an array of arrays. The outer array holds a list of operations.
236 * Each inner array is a set of key value pairs that specify an operation.
238 * Supported operations and their parameters. The supported actions are:
239 * - create
240 * - store
241 * - copy
242 * - move
243 * - delete
244 * - describe (since 1.21)
245 * - null
247 * a) Create a new file in storage with the contents of a string
248 * @code
249 * array(
250 * 'op' => 'create',
251 * 'dst' => <storage path>,
252 * 'content' => <string of new file contents>,
253 * 'overwrite' => <boolean>,
254 * 'overwriteSame' => <boolean>,
255 * 'headers' => <HTTP header name/value map> # since 1.21
256 * );
257 * @endcode
259 * b) Copy a file system file into storage
260 * @code
261 * array(
262 * 'op' => 'store',
263 * 'src' => <file system path>,
264 * 'dst' => <storage path>,
265 * 'overwrite' => <boolean>,
266 * 'overwriteSame' => <boolean>,
267 * 'headers' => <HTTP header name/value map> # since 1.21
269 * @endcode
271 * c) Copy a file within storage
272 * @code
273 * array(
274 * 'op' => 'copy',
275 * 'src' => <storage path>,
276 * 'dst' => <storage path>,
277 * 'overwrite' => <boolean>,
278 * 'overwriteSame' => <boolean>,
279 * 'ignoreMissingSource' => <boolean>, # since 1.21
280 * 'headers' => <HTTP header name/value map> # since 1.21
282 * @endcode
284 * d) Move a file within storage
285 * @code
286 * array(
287 * 'op' => 'move',
288 * 'src' => <storage path>,
289 * 'dst' => <storage path>,
290 * 'overwrite' => <boolean>,
291 * 'overwriteSame' => <boolean>,
292 * 'ignoreMissingSource' => <boolean>, # since 1.21
293 * 'headers' => <HTTP header name/value map> # since 1.21
295 * @endcode
297 * e) Delete a file within storage
298 * @code
299 * array(
300 * 'op' => 'delete',
301 * 'src' => <storage path>,
302 * 'ignoreMissingSource' => <boolean>
304 * @endcode
306 * f) Update metadata for a file within storage
307 * @code
308 * array(
309 * 'op' => 'describe',
310 * 'src' => <storage path>,
311 * 'headers' => <HTTP header name/value map>
313 * @endcode
315 * g) Do nothing (no-op)
316 * @code
317 * array(
318 * 'op' => 'null',
320 * @endcode
322 * Boolean flags for operations (operation-specific):
323 * - ignoreMissingSource : The operation will simply succeed and do
324 * nothing if the source file does not exist.
325 * - overwrite : Any destination file will be overwritten.
326 * - overwriteSame : If a file already exists at the destination with the
327 * same contents, then do nothing to the destination file
328 * instead of giving an error. This does not compare headers.
329 * This option is ignored if 'overwrite' is already provided.
330 * - headers : If supplied, the result of merging these headers with any
331 * existing source file headers (replacing conflicting ones)
332 * will be set as the destination file headers. Headers are
333 * deleted if their value is set to the empty string. When a
334 * file has headers they are included in responses to GET and
335 * HEAD requests to the backing store for that file.
336 * Header values should be no larger than 255 bytes, except for
337 * Content-Disposition. The system might ignore or truncate any
338 * headers that are too long to store (exact limits will vary).
339 * Backends that don't support metadata ignore this. (since 1.21)
341 * $opts is an associative of boolean flags, including:
342 * - force : Operation precondition errors no longer trigger an abort.
343 * Any remaining operations are still attempted. Unexpected
344 * failures may still cause remaining operations to be aborted.
345 * - nonLocking : No locks are acquired for the operations.
346 * This can increase performance for non-critical writes.
347 * This has no effect unless the 'force' flag is set.
348 * - nonJournaled : Don't log this operation batch in the file journal.
349 * This limits the ability of recovery scripts.
350 * - parallelize : Try to do operations in parallel when possible.
351 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
352 * - preserveCache : Don't clear the process cache before checking files.
353 * This should only be used if all entries in the process
354 * cache were added after the files were already locked. (since 1.20)
356 * @remarks Remarks on locking:
357 * File system paths given to operations should refer to files that are
358 * already locked or otherwise safe from modification from other processes.
359 * Normally these files will be new temp files, which should be adequate.
361 * @par Return value:
363 * This returns a Status, which contains all warnings and fatals that occurred
364 * during the operation. The 'failCount', 'successCount', and 'success' members
365 * will reflect each operation attempted.
367 * The status will be "OK" unless:
368 * - a) unexpected operation errors occurred (network partitions, disk full...)
369 * - b) significant operation errors occurred and 'force' was not set
371 * @param array $ops List of operations to execute in order
372 * @param array $opts Batch operation options
373 * @return Status
375 final public function doOperations( array $ops, array $opts = array() ) {
376 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
377 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
379 if ( !count( $ops ) ) {
380 return Status::newGood(); // nothing to do
382 if ( empty( $opts['force'] ) ) { // sanity
383 unset( $opts['nonLocking'] );
385 foreach ( $ops as &$op ) {
386 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
387 $op['headers']['Content-Disposition'] = $op['disposition'];
390 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
391 return $this->doOperationsInternal( $ops, $opts );
395 * @see FileBackend::doOperations()
397 abstract protected function doOperationsInternal( array $ops, array $opts );
400 * Same as doOperations() except it takes a single operation.
401 * If you are doing a batch of operations that should either
402 * all succeed or all fail, then use that function instead.
404 * @see FileBackend::doOperations()
406 * @param array $op Operation
407 * @param array $opts Operation options
408 * @return Status
410 final public function doOperation( array $op, array $opts = array() ) {
411 return $this->doOperations( array( $op ), $opts );
415 * Performs a single create operation.
416 * This sets $params['op'] to 'create' and passes it to doOperation().
418 * @see FileBackend::doOperation()
420 * @param array $params Operation parameters
421 * @param array $opts Operation options
422 * @return Status
424 final public function create( array $params, array $opts = array() ) {
425 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
429 * Performs a single store operation.
430 * This sets $params['op'] to 'store' and passes it to doOperation().
432 * @see FileBackend::doOperation()
434 * @param array $params Operation parameters
435 * @param array $opts Operation options
436 * @return Status
438 final public function store( array $params, array $opts = array() ) {
439 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
443 * Performs a single copy operation.
444 * This sets $params['op'] to 'copy' and passes it to doOperation().
446 * @see FileBackend::doOperation()
448 * @param array $params Operation parameters
449 * @param array $opts Operation options
450 * @return Status
452 final public function copy( array $params, array $opts = array() ) {
453 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
457 * Performs a single move operation.
458 * This sets $params['op'] to 'move' and passes it to doOperation().
460 * @see FileBackend::doOperation()
462 * @param array $params Operation parameters
463 * @param array $opts Operation options
464 * @return Status
466 final public function move( array $params, array $opts = array() ) {
467 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
471 * Performs a single delete operation.
472 * This sets $params['op'] to 'delete' and passes it to doOperation().
474 * @see FileBackend::doOperation()
476 * @param array $params Operation parameters
477 * @param array $opts Operation options
478 * @return Status
480 final public function delete( array $params, array $opts = array() ) {
481 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
485 * Performs a single describe operation.
486 * This sets $params['op'] to 'describe' and passes it to doOperation().
488 * @see FileBackend::doOperation()
490 * @param array $params Operation parameters
491 * @param array $opts Operation options
492 * @return Status
493 * @since 1.21
495 final public function describe( array $params, array $opts = array() ) {
496 return $this->doOperation( array( 'op' => 'describe' ) + $params, $opts );
500 * Perform a set of independent file operations on some files.
502 * This does no locking, nor journaling, and possibly no stat calls.
503 * Any destination files that already exist will be overwritten.
504 * This should *only* be used on non-original files, like cache files.
506 * Supported operations and their parameters:
507 * - create
508 * - store
509 * - copy
510 * - move
511 * - delete
512 * - describe (since 1.21)
513 * - null
515 * a) Create a new file in storage with the contents of a string
516 * @code
517 * array(
518 * 'op' => 'create',
519 * 'dst' => <storage path>,
520 * 'content' => <string of new file contents>,
521 * 'headers' => <HTTP header name/value map> # since 1.21
523 * @endcode
525 * b) Copy a file system file into storage
526 * @code
527 * array(
528 * 'op' => 'store',
529 * 'src' => <file system path>,
530 * 'dst' => <storage path>,
531 * 'headers' => <HTTP header name/value map> # since 1.21
533 * @endcode
535 * c) Copy a file within storage
536 * @code
537 * array(
538 * 'op' => 'copy',
539 * 'src' => <storage path>,
540 * 'dst' => <storage path>,
541 * 'ignoreMissingSource' => <boolean>, # since 1.21
542 * 'headers' => <HTTP header name/value map> # since 1.21
544 * @endcode
546 * d) Move a file within storage
547 * @code
548 * array(
549 * 'op' => 'move',
550 * 'src' => <storage path>,
551 * 'dst' => <storage path>,
552 * 'ignoreMissingSource' => <boolean>, # since 1.21
553 * 'headers' => <HTTP header name/value map> # since 1.21
555 * @endcode
557 * e) Delete a file within storage
558 * @code
559 * array(
560 * 'op' => 'delete',
561 * 'src' => <storage path>,
562 * 'ignoreMissingSource' => <boolean>
564 * @endcode
566 * f) Update metadata for a file within storage
567 * @code
568 * array(
569 * 'op' => 'describe',
570 * 'src' => <storage path>,
571 * 'headers' => <HTTP header name/value map>
573 * @endcode
575 * g) Do nothing (no-op)
576 * @code
577 * array(
578 * 'op' => 'null',
580 * @endcode
582 * @par Boolean flags for operations (operation-specific):
583 * - ignoreMissingSource : The operation will simply succeed and do
584 * nothing if the source file does not exist.
585 * - headers : If supplied with a header name/value map, the backend will
586 * reply with these headers when GETs/HEADs of the destination
587 * file are made. Header values should be smaller than 256 bytes.
588 * Content-Disposition headers can be longer, though the system
589 * might ignore or truncate ones that are too long to store.
590 * Existing headers will remain, but these will replace any
591 * conflicting previous headers, and headers will be removed
592 * if they are set to an empty string.
593 * Backends that don't support metadata ignore this. (since 1.21)
595 * $opts is an associative of boolean flags, including:
596 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
598 * @par Return value:
599 * This returns a Status, which contains all warnings and fatals that occurred
600 * during the operation. The 'failCount', 'successCount', and 'success' members
601 * will reflect each operation attempted for the given files. The status will be
602 * considered "OK" as long as no fatal errors occurred.
604 * @param array $ops Set of operations to execute
605 * @param array $opts Batch operation options
606 * @return Status
607 * @since 1.20
609 final public function doQuickOperations( array $ops, array $opts = array() ) {
610 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
611 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
613 if ( !count( $ops ) ) {
614 return Status::newGood(); // nothing to do
616 foreach ( $ops as &$op ) {
617 $op['overwrite'] = true; // avoids RTTs in key/value stores
618 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
619 $op['headers']['Content-Disposition'] = $op['disposition'];
622 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
623 return $this->doQuickOperationsInternal( $ops );
627 * @see FileBackend::doQuickOperations()
628 * @since 1.20
630 abstract protected function doQuickOperationsInternal( array $ops );
633 * Same as doQuickOperations() except it takes a single operation.
634 * If you are doing a batch of operations, then use that function instead.
636 * @see FileBackend::doQuickOperations()
638 * @param array $op Operation
639 * @return Status
640 * @since 1.20
642 final public function doQuickOperation( array $op ) {
643 return $this->doQuickOperations( array( $op ) );
647 * Performs a single quick create operation.
648 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
650 * @see FileBackend::doQuickOperation()
652 * @param array $params Operation parameters
653 * @return Status
654 * @since 1.20
656 final public function quickCreate( array $params ) {
657 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
661 * Performs a single quick store operation.
662 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
664 * @see FileBackend::doQuickOperation()
666 * @param array $params Operation parameters
667 * @return Status
668 * @since 1.20
670 final public function quickStore( array $params ) {
671 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
675 * Performs a single quick copy operation.
676 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
678 * @see FileBackend::doQuickOperation()
680 * @param array $params Operation parameters
681 * @return Status
682 * @since 1.20
684 final public function quickCopy( array $params ) {
685 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
689 * Performs a single quick move operation.
690 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
692 * @see FileBackend::doQuickOperation()
694 * @param array $params Operation parameters
695 * @return Status
696 * @since 1.20
698 final public function quickMove( array $params ) {
699 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
703 * Performs a single quick delete operation.
704 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
706 * @see FileBackend::doQuickOperation()
708 * @param array $params Operation parameters
709 * @return Status
710 * @since 1.20
712 final public function quickDelete( array $params ) {
713 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
717 * Performs a single quick describe operation.
718 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
720 * @see FileBackend::doQuickOperation()
722 * @param array $params Operation parameters
723 * @return Status
724 * @since 1.21
726 final public function quickDescribe( array $params ) {
727 return $this->doQuickOperation( array( 'op' => 'describe' ) + $params );
731 * Concatenate a list of storage files into a single file system file.
732 * The target path should refer to a file that is already locked or
733 * otherwise safe from modification from other processes. Normally,
734 * the file will be a new temp file, which should be adequate.
736 * @param array $params Operation parameters, include:
737 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
738 * - dst : file system path to 0-byte temp file
739 * - parallelize : try to do operations in parallel when possible
740 * @return Status
742 abstract public function concatenate( array $params );
745 * Prepare a storage directory for usage.
746 * This will create any required containers and parent directories.
747 * Backends using key/value stores only need to create the container.
749 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
750 * except they are only applied *if* the directory/container had to be created.
751 * These flags should always be set for directories that have private files.
752 * However, setting them is not guaranteed to actually do anything.
753 * Additional server configuration may be needed to achieve the desired effect.
755 * @param array $params Parameters include:
756 * - dir : storage directory
757 * - noAccess : try to deny file access (since 1.20)
758 * - noListing : try to deny file listing (since 1.20)
759 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
760 * @return Status
762 final public function prepare( array $params ) {
763 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
764 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
766 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
767 return $this->doPrepare( $params );
771 * @see FileBackend::prepare()
773 abstract protected function doPrepare( array $params );
776 * Take measures to block web access to a storage directory and
777 * the container it belongs to. FS backends might add .htaccess
778 * files whereas key/value store backends might revoke container
779 * access to the storage user representing end-users in web requests.
781 * This is not guaranteed to actually make files or listings publically hidden.
782 * Additional server configuration may be needed to achieve the desired effect.
784 * @param array $params Parameters include:
785 * - dir : storage directory
786 * - noAccess : try to deny file access
787 * - noListing : try to deny file listing
788 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
789 * @return Status
791 final public function secure( array $params ) {
792 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
793 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
795 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
796 return $this->doSecure( $params );
800 * @see FileBackend::secure()
802 abstract protected function doSecure( array $params );
805 * Remove measures to block web access to a storage directory and
806 * the container it belongs to. FS backends might remove .htaccess
807 * files whereas key/value store backends might grant container
808 * access to the storage user representing end-users in web requests.
809 * This essentially can undo the result of secure() calls.
811 * This is not guaranteed to actually make files or listings publically viewable.
812 * Additional server configuration may be needed to achieve the desired effect.
814 * @param array $params Parameters include:
815 * - dir : storage directory
816 * - access : try to allow file access
817 * - listing : try to allow file listing
818 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
819 * @return Status
820 * @since 1.20
822 final public function publish( array $params ) {
823 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
824 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
826 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
827 return $this->doPublish( $params );
831 * @see FileBackend::publish()
833 abstract protected function doPublish( array $params );
836 * Delete a storage directory if it is empty.
837 * Backends using key/value stores may do nothing unless the directory
838 * is that of an empty container, in which case it will be deleted.
840 * @param array $params Parameters include:
841 * - dir : storage directory
842 * - recursive : recursively delete empty subdirectories first (since 1.20)
843 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
844 * @return Status
846 final public function clean( array $params ) {
847 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
848 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
850 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
851 return $this->doClean( $params );
855 * @see FileBackend::clean()
857 abstract protected function doClean( array $params );
860 * Enter file operation scope.
861 * This just makes PHP ignore user aborts/disconnects until the return
862 * value leaves scope. This returns null and does nothing in CLI mode.
864 * @return ScopedCallback|null
866 final protected function getScopedPHPBehaviorForOps() {
867 if ( PHP_SAPI != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
868 $old = ignore_user_abort( true ); // avoid half-finished operations
869 return new ScopedCallback( function () use ( $old ) {
870 ignore_user_abort( $old );
871 } );
874 return null;
878 * Check if a file exists at a storage path in the backend.
879 * This returns false if only a directory exists at the path.
881 * @param array $params Parameters include:
882 * - src : source storage path
883 * - latest : use the latest available data
884 * @return bool|null Returns null on failure
886 abstract public function fileExists( array $params );
889 * Get the last-modified timestamp of the file at a storage path.
891 * @param array $params Parameters include:
892 * - src : source storage path
893 * - latest : use the latest available data
894 * @return string|bool TS_MW timestamp or false on failure
896 abstract public function getFileTimestamp( array $params );
899 * Get the contents of a file at a storage path in the backend.
900 * This should be avoided for potentially large files.
902 * @param array $params Parameters include:
903 * - src : source storage path
904 * - latest : use the latest available data
905 * @return string|bool Returns false on failure
907 final public function getFileContents( array $params ) {
908 $contents = $this->getFileContentsMulti(
909 array( 'srcs' => array( $params['src'] ) ) + $params );
911 return $contents[$params['src']];
915 * Like getFileContents() except it takes an array of storage paths
916 * and returns a map of storage paths to strings (or null on failure).
917 * The map keys (paths) are in the same order as the provided list of paths.
919 * @see FileBackend::getFileContents()
921 * @param array $params Parameters include:
922 * - srcs : list of source storage paths
923 * - latest : use the latest available data
924 * - parallelize : try to do operations in parallel when possible
925 * @return array Map of (path name => string or false on failure)
926 * @since 1.20
928 abstract public function getFileContentsMulti( array $params );
931 * Get metadata about a file at a storage path in the backend.
932 * If the file does not exist, then this returns false.
933 * Otherwise, the result is an associative array that includes:
934 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
935 * - metadata : map of file metadata (name => value)
936 * Metadata keys and headers names will be returned in all lower-case.
937 * Additional values may be included for internal use only.
939 * Use FileBackend::hasFeatures() to check how well this is supported.
941 * @param array $params
942 * $params include:
943 * - src : source storage path
944 * - latest : use the latest available data
945 * @return array|bool Returns false on failure
946 * @since 1.23
948 abstract public function getFileXAttributes( array $params );
951 * Get the size (bytes) of a file at a storage path in the backend.
953 * @param array $params Parameters include:
954 * - src : source storage path
955 * - latest : use the latest available data
956 * @return int|bool Returns false on failure
958 abstract public function getFileSize( array $params );
961 * Get quick information about a file at a storage path in the backend.
962 * If the file does not exist, then this returns false.
963 * Otherwise, the result is an associative array that includes:
964 * - mtime : the last-modified timestamp (TS_MW)
965 * - size : the file size (bytes)
966 * Additional values may be included for internal use only.
968 * @param array $params Parameters include:
969 * - src : source storage path
970 * - latest : use the latest available data
971 * @return array|bool|null Returns null on failure
973 abstract public function getFileStat( array $params );
976 * Get a SHA-1 hash of the file at a storage path in the backend.
978 * @param array $params Parameters include:
979 * - src : source storage path
980 * - latest : use the latest available data
981 * @return string|bool Hash string or false on failure
983 abstract public function getFileSha1Base36( array $params );
986 * Get the properties of the file at a storage path in the backend.
987 * This gives the result of FSFile::getProps() on a local copy of the file.
989 * @param array $params Parameters include:
990 * - src : source storage path
991 * - latest : use the latest available data
992 * @return array Returns FSFile::placeholderProps() on failure
994 abstract public function getFileProps( array $params );
997 * Stream the file at a storage path in the backend.
998 * If the file does not exists, an HTTP 404 error will be given.
999 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1000 * will be sent if streaming began, while none will be sent otherwise.
1001 * Implementations should flush the output buffer before sending data.
1003 * @param array $params Parameters include:
1004 * - src : source storage path
1005 * - headers : list of additional HTTP headers to send on success
1006 * - latest : use the latest available data
1007 * @return Status
1009 abstract public function streamFile( array $params );
1012 * Returns a file system file, identical to the file at a storage path.
1013 * The file returned is either:
1014 * - a) A local copy of the file at a storage path in the backend.
1015 * The temporary copy will have the same extension as the source.
1016 * - b) An original of the file at a storage path in the backend.
1017 * Temporary files may be purged when the file object falls out of scope.
1019 * Write operations should *never* be done on this file as some backends
1020 * may do internal tracking or may be instances of FileBackendMultiWrite.
1021 * In that later case, there are copies of the file that must stay in sync.
1022 * Additionally, further calls to this function may return the same file.
1024 * @param array $params Parameters include:
1025 * - src : source storage path
1026 * - latest : use the latest available data
1027 * @return FSFile|null Returns null on failure
1029 final public function getLocalReference( array $params ) {
1030 $fsFiles = $this->getLocalReferenceMulti(
1031 array( 'srcs' => array( $params['src'] ) ) + $params );
1033 return $fsFiles[$params['src']];
1037 * Like getLocalReference() except it takes an array of storage paths
1038 * and returns a map of storage paths to FSFile objects (or null on failure).
1039 * The map keys (paths) are in the same order as the provided list of paths.
1041 * @see FileBackend::getLocalReference()
1043 * @param array $params Parameters include:
1044 * - srcs : list of source storage paths
1045 * - latest : use the latest available data
1046 * - parallelize : try to do operations in parallel when possible
1047 * @return array Map of (path name => FSFile or null on failure)
1048 * @since 1.20
1050 abstract public function getLocalReferenceMulti( array $params );
1053 * Get a local copy on disk of the file at a storage path in the backend.
1054 * The temporary copy will have the same file extension as the source.
1055 * Temporary files may be purged when the file object falls out of scope.
1057 * @param array $params Parameters include:
1058 * - src : source storage path
1059 * - latest : use the latest available data
1060 * @return TempFSFile|null Returns null on failure
1062 final public function getLocalCopy( array $params ) {
1063 $tmpFiles = $this->getLocalCopyMulti(
1064 array( 'srcs' => array( $params['src'] ) ) + $params );
1066 return $tmpFiles[$params['src']];
1070 * Like getLocalCopy() except it takes an array of storage paths and
1071 * returns a map of storage paths to TempFSFile objects (or null on failure).
1072 * The map keys (paths) are in the same order as the provided list of paths.
1074 * @see FileBackend::getLocalCopy()
1076 * @param array $params Parameters include:
1077 * - srcs : list of source storage paths
1078 * - latest : use the latest available data
1079 * - parallelize : try to do operations in parallel when possible
1080 * @return array Map of (path name => TempFSFile or null on failure)
1081 * @since 1.20
1083 abstract public function getLocalCopyMulti( array $params );
1086 * Return an HTTP URL to a given file that requires no authentication to use.
1087 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1088 * This will return null if the backend cannot make an HTTP URL for the file.
1090 * This is useful for key/value stores when using scripts that seek around
1091 * large files and those scripts (and the backend) support HTTP Range headers.
1092 * Otherwise, one would need to use getLocalReference(), which involves loading
1093 * the entire file on to local disk.
1095 * @param array $params Parameters include:
1096 * - src : source storage path
1097 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1098 * @return string|null
1099 * @since 1.21
1101 abstract public function getFileHttpUrl( array $params );
1104 * Check if a directory exists at a given storage path.
1105 * Backends using key/value stores will check if the path is a
1106 * virtual directory, meaning there are files under the given directory.
1108 * Storage backends with eventual consistency might return stale data.
1110 * @param array $params Parameters include:
1111 * - dir : storage directory
1112 * @return bool|null Returns null on failure
1113 * @since 1.20
1115 abstract public function directoryExists( array $params );
1118 * Get an iterator to list *all* directories under a storage directory.
1119 * If the directory is of the form "mwstore://backend/container",
1120 * then all directories in the container will be listed.
1121 * If the directory is of form "mwstore://backend/container/dir",
1122 * then all directories directly under that directory will be listed.
1123 * Results will be storage directories relative to the given directory.
1125 * Storage backends with eventual consistency might return stale data.
1127 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1129 * @param array $params Parameters include:
1130 * - dir : storage directory
1131 * - topOnly : only return direct child dirs of the directory
1132 * @return Traversable|array|null Returns null on failure
1133 * @since 1.20
1135 abstract public function getDirectoryList( array $params );
1138 * Same as FileBackend::getDirectoryList() except only lists
1139 * directories that are immediately under the given directory.
1141 * Storage backends with eventual consistency might return stale data.
1143 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1145 * @param array $params Parameters include:
1146 * - dir : storage directory
1147 * @return Traversable|array|null Returns null on failure
1148 * @since 1.20
1150 final public function getTopDirectoryList( array $params ) {
1151 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
1155 * Get an iterator to list *all* stored files under a storage directory.
1156 * If the directory is of the form "mwstore://backend/container",
1157 * then all files in the container will be listed.
1158 * If the directory is of form "mwstore://backend/container/dir",
1159 * then all files under that directory will be listed.
1160 * Results will be storage paths relative to the given directory.
1162 * Storage backends with eventual consistency might return stale data.
1164 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1166 * @param array $params Parameters include:
1167 * - dir : storage directory
1168 * - topOnly : only return direct child files of the directory (since 1.20)
1169 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1170 * @return Traversable|array|null Returns null on failure
1172 abstract public function getFileList( array $params );
1175 * Same as FileBackend::getFileList() except only lists
1176 * files that are immediately under the given directory.
1178 * Storage backends with eventual consistency might return stale data.
1180 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1182 * @param array $params Parameters include:
1183 * - dir : storage directory
1184 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1185 * @return Traversable|array|null Returns null on failure
1186 * @since 1.20
1188 final public function getTopFileList( array $params ) {
1189 return $this->getFileList( array( 'topOnly' => true ) + $params );
1193 * Preload persistent file stat cache and property cache into in-process cache.
1194 * This should be used when stat calls will be made on a known list of a many files.
1196 * @see FileBackend::getFileStat()
1198 * @param array $paths Storage paths
1200 abstract public function preloadCache( array $paths );
1203 * Invalidate any in-process file stat and property cache.
1204 * If $paths is given, then only the cache for those files will be cleared.
1206 * @see FileBackend::getFileStat()
1208 * @param array $paths Storage paths (optional)
1210 abstract public function clearCache( array $paths = null );
1213 * Preload file stat information (concurrently if possible) into in-process cache.
1214 * This should be used when stat calls will be made on a known list of a many files.
1216 * @see FileBackend::getFileStat()
1218 * @param array $params Parameters include:
1219 * - srcs : list of source storage paths
1220 * - latest : use the latest available data
1221 * @return bool All requests proceeded without I/O errors (since 1.24)
1222 * @since 1.23
1224 abstract public function preloadFileStat( array $params );
1227 * Lock the files at the given storage paths in the backend.
1228 * This will either lock all the files or none (on failure).
1230 * Callers should consider using getScopedFileLocks() instead.
1232 * @param array $paths Storage paths
1233 * @param int $type LockManager::LOCK_* constant
1234 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1235 * @return Status
1237 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1238 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1240 return $this->lockManager->lock( $paths, $type, $timeout );
1244 * Unlock the files at the given storage paths in the backend.
1246 * @param array $paths Storage paths
1247 * @param int $type LockManager::LOCK_* constant
1248 * @return Status
1250 final public function unlockFiles( array $paths, $type ) {
1251 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1253 return $this->lockManager->unlock( $paths, $type );
1257 * Lock the files at the given storage paths in the backend.
1258 * This will either lock all the files or none (on failure).
1259 * On failure, the status object will be updated with errors.
1261 * Once the return value goes out scope, the locks will be released and
1262 * the status updated. Unlock fatals will not change the status "OK" value.
1264 * @see ScopedLock::factory()
1266 * @param array $paths List of storage paths or map of lock types to path lists
1267 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1268 * @param Status $status Status to update on lock/unlock
1269 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1270 * @return ScopedLock|null Returns null on failure
1272 final public function getScopedFileLocks( array $paths, $type, Status $status, $timeout = 0 ) {
1273 if ( $type === 'mixed' ) {
1274 foreach ( $paths as &$typePaths ) {
1275 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1277 } else {
1278 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1281 return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
1285 * Get an array of scoped locks needed for a batch of file operations.
1287 * Normally, FileBackend::doOperations() handles locking, unless
1288 * the 'nonLocking' param is passed in. This function is useful if you
1289 * want the files to be locked for a broader scope than just when the
1290 * files are changing. For example, if you need to update DB metadata,
1291 * you may want to keep the files locked until finished.
1293 * @see FileBackend::doOperations()
1295 * @param array $ops List of file operations to FileBackend::doOperations()
1296 * @param Status $status Status to update on lock/unlock
1297 * @return array List of ScopedFileLocks or null values
1298 * @since 1.20
1300 abstract public function getScopedLocksForOps( array $ops, Status $status );
1303 * Get the root storage path of this backend.
1304 * All container paths are "subdirectories" of this path.
1306 * @return string Storage path
1307 * @since 1.20
1309 final public function getRootStoragePath() {
1310 return "mwstore://{$this->name}";
1314 * Get the storage path for the given container for this backend
1316 * @param string $container Container name
1317 * @return string Storage path
1318 * @since 1.21
1320 final public function getContainerStoragePath( $container ) {
1321 return $this->getRootStoragePath() . "/{$container}";
1325 * Get the file journal object for this backend
1327 * @return FileJournal
1329 final public function getJournal() {
1330 return $this->fileJournal;
1334 * Check if a given path is a "mwstore://" path.
1335 * This does not do any further validation or any existence checks.
1337 * @param string $path
1338 * @return bool
1340 final public static function isStoragePath( $path ) {
1341 return ( strpos( $path, 'mwstore://' ) === 0 );
1345 * Split a storage path into a backend name, a container name,
1346 * and a relative file path. The relative path may be the empty string.
1347 * This does not do any path normalization or traversal checks.
1349 * @param string $storagePath
1350 * @return array (backend, container, rel object) or (null, null, null)
1352 final public static function splitStoragePath( $storagePath ) {
1353 if ( self::isStoragePath( $storagePath ) ) {
1354 // Remove the "mwstore://" prefix and split the path
1355 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1356 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1357 if ( count( $parts ) == 3 ) {
1358 return $parts; // e.g. "backend/container/path"
1359 } else {
1360 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1365 return array( null, null, null );
1369 * Normalize a storage path by cleaning up directory separators.
1370 * Returns null if the path is not of the format of a valid storage path.
1372 * @param string $storagePath
1373 * @return string|null
1375 final public static function normalizeStoragePath( $storagePath ) {
1376 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1377 if ( $relPath !== null ) { // must be for this backend
1378 $relPath = self::normalizeContainerPath( $relPath );
1379 if ( $relPath !== null ) {
1380 return ( $relPath != '' )
1381 ? "mwstore://{$backend}/{$container}/{$relPath}"
1382 : "mwstore://{$backend}/{$container}";
1386 return null;
1390 * Get the parent storage directory of a storage path.
1391 * This returns a path like "mwstore://backend/container",
1392 * "mwstore://backend/container/...", or null if there is no parent.
1394 * @param string $storagePath
1395 * @return string|null
1397 final public static function parentStoragePath( $storagePath ) {
1398 $storagePath = dirname( $storagePath );
1399 list( , , $rel ) = self::splitStoragePath( $storagePath );
1401 return ( $rel === null ) ? null : $storagePath;
1405 * Get the final extension from a storage or FS path
1407 * @param string $path
1408 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1409 * @return string
1411 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1412 $i = strrpos( $path, '.' );
1413 $ext = $i ? substr( $path, $i + 1 ) : '';
1415 if ( $case === 'lowercase' ) {
1416 $ext = strtolower( $ext );
1417 } elseif ( $case === 'uppercase' ) {
1418 $ext = strtoupper( $ext );
1421 return $ext;
1425 * Check if a relative path has no directory traversals
1427 * @param string $path
1428 * @return bool
1429 * @since 1.20
1431 final public static function isPathTraversalFree( $path ) {
1432 return ( self::normalizeContainerPath( $path ) !== null );
1436 * Build a Content-Disposition header value per RFC 6266.
1438 * @param string $type One of (attachment, inline)
1439 * @param string $filename Suggested file name (should not contain slashes)
1440 * @throws FileBackendError
1441 * @return string
1442 * @since 1.20
1444 final public static function makeContentDisposition( $type, $filename = '' ) {
1445 $parts = array();
1447 $type = strtolower( $type );
1448 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1449 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1451 $parts[] = $type;
1453 if ( strlen( $filename ) ) {
1454 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1457 return implode( ';', $parts );
1461 * Validate and normalize a relative storage path.
1462 * Null is returned if the path involves directory traversal.
1463 * Traversal is insecure for FS backends and broken for others.
1465 * This uses the same traversal protection as Title::secureAndSplit().
1467 * @param string $path Storage path relative to a container
1468 * @return string|null
1470 final protected static function normalizeContainerPath( $path ) {
1471 // Normalize directory separators
1472 $path = strtr( $path, '\\', '/' );
1473 // Collapse any consecutive directory separators
1474 $path = preg_replace( '![/]{2,}!', '/', $path );
1475 // Remove any leading directory separator
1476 $path = ltrim( $path, '/' );
1477 // Use the same traversal protection as Title::secureAndSplit()
1478 if ( strpos( $path, '.' ) !== false ) {
1479 if (
1480 $path === '.' ||
1481 $path === '..' ||
1482 strpos( $path, './' ) === 0 ||
1483 strpos( $path, '../' ) === 0 ||
1484 strpos( $path, '/./' ) !== false ||
1485 strpos( $path, '/../' ) !== false
1487 return null;
1491 return $path;
1496 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1498 * @ingroup FileBackend
1499 * @since 1.23
1501 class FileBackendException extends MWException {
1505 * File backend exception for checked exceptions (e.g. I/O errors)
1507 * @ingroup FileBackend
1508 * @since 1.22
1510 class FileBackendError extends FileBackendException {