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.
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
28 * @ingroup FileBackend
29 * @author Aaron Schulz
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
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
85 abstract class FileBackend
{
86 /** @var string Unique backend name */
89 /** @var string Unique wiki name */
92 /** @var string Read-only explanation message */
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;
108 * Create a new backend instance from configuration.
109 * This should only be called from within FileBackendGroup.
111 * @param array $config Parameters include:
112 * - name : The unique name of this backend.
113 * This should consist of alphanumberic, '-', and '_' characters.
114 * This name should not be changed after use (e.g. with journaling).
115 * Note that the name is *not* used in actual container names.
116 * - wikiId : Prefix to container names that is unique to this backend.
117 * It should only consist of alphanumberic, '-', and '_' characters.
118 * This ID is what avoids collisions if multiple logical backends
119 * use the same storage system, so this should be set carefully.
120 * - lockManager : LockManager object to use for any file locking.
121 * If not provided, then no file locking will be enforced.
122 * - fileJournal : FileJournal object to use for logging changes to files.
123 * If not provided, then change journaling will be disabled.
124 * - readOnly : Write operations are disallowed if this is a non-empty string.
125 * It should be an explanation for the backend being read-only.
126 * - parallelize : When to do file operations in parallel (when possible).
127 * Allowed values are "implicit", "explicit" and "off".
128 * - concurrency : How many file operations can be done in parallel.
129 * @throws MWException
131 public function __construct( array $config ) {
132 $this->name
= $config['name'];
133 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
134 throw new MWException( "Backend name `{$this->name}` is invalid." );
136 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
137 $this->lockManager
= isset( $config['lockManager'] )
138 ?
$config['lockManager']
139 : new NullLockManager( array() );
140 $this->fileJournal
= isset( $config['fileJournal'] )
141 ?
$config['fileJournal']
142 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
143 $this->readOnly
= isset( $config['readOnly'] )
144 ?
(string)$config['readOnly']
146 $this->parallelize
= isset( $config['parallelize'] )
147 ?
(string)$config['parallelize']
149 $this->concurrency
= isset( $config['concurrency'] )
150 ?
(int)$config['concurrency']
155 * Get the unique backend name.
156 * We may have multiple different backends of the same type.
157 * For example, we can have two Swift backends using different proxies.
161 final public function getName() {
166 * Get the wiki identifier used for this backend (possibly empty).
167 * Note that this might *not* be in the same format as wfWikiID().
172 final public function getWikiId() {
173 return $this->wikiId
;
177 * Check if this backend is read-only
181 final public function isReadOnly() {
182 return ( $this->readOnly
!= '' );
186 * Get an explanatory message if this backend is read-only
188 * @return string|bool Returns false if the backend is not read-only
190 final public function getReadOnlyReason() {
191 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
195 * This is the main entry point into the backend for write operations.
196 * Callers supply an ordered list of operations to perform as a transaction.
197 * Files will be locked, the stat cache cleared, and then the operations attempted.
198 * If any serious errors occur, all attempted operations will be rolled back.
200 * $ops is an array of arrays. The outer array holds a list of operations.
201 * Each inner array is a set of key value pairs that specify an operation.
203 * Supported operations and their parameters. The supported actions are:
209 * - describe (since 1.21)
212 * a) Create a new file in storage with the contents of a string
216 * 'dst' => <storage path>,
217 * 'content' => <string of new file contents>,
218 * 'overwrite' => <boolean>,
219 * 'overwriteSame' => <boolean>,
220 * 'headers' => <HTTP header name/value map> # since 1.21
224 * b) Copy a file system file into storage
228 * 'src' => <file system path>,
229 * 'dst' => <storage path>,
230 * 'overwrite' => <boolean>,
231 * 'overwriteSame' => <boolean>,
232 * 'headers' => <HTTP header name/value map> # since 1.21
236 * c) Copy a file within storage
240 * 'src' => <storage path>,
241 * 'dst' => <storage path>,
242 * 'overwrite' => <boolean>,
243 * 'overwriteSame' => <boolean>,
244 * 'ignoreMissingSource' => <boolean>, # since 1.21
245 * 'headers' => <HTTP header name/value map> # since 1.21
249 * d) Move a file within storage
253 * 'src' => <storage path>,
254 * 'dst' => <storage path>,
255 * 'overwrite' => <boolean>,
256 * 'overwriteSame' => <boolean>,
257 * 'ignoreMissingSource' => <boolean>, # since 1.21
258 * 'headers' => <HTTP header name/value map> # since 1.21
262 * e) Delete a file within storage
266 * 'src' => <storage path>,
267 * 'ignoreMissingSource' => <boolean>
271 * f) Update metadata for a file within storage
274 * 'op' => 'describe',
275 * 'src' => <storage path>,
276 * 'headers' => <HTTP header name/value map>
280 * g) Do nothing (no-op)
287 * Boolean flags for operations (operation-specific):
288 * - ignoreMissingSource : The operation will simply succeed and do
289 * nothing if the source file does not exist.
290 * - overwrite : Any destination file will be overwritten.
291 * - overwriteSame : If a file already exists at the destination with the
292 * same contents, then do nothing to the destination file
293 * instead of giving an error. This does not compare headers.
294 * This option is ignored if 'overwrite' is already provided.
295 * - headers : If supplied, the result of merging these headers with any
296 * existing source file headers (replacing conflicting ones)
297 * will be set as the destination file headers. Headers are
298 * deleted if their value is set to the empty string. When a
299 * file has headers they are included in responses to GET and
300 * HEAD requests to the backing store for that file.
301 * Header values should be no larger than 255 bytes, except for
302 * Content-Disposition. The system might ignore or truncate any
303 * headers that are too long to store (exact limits will vary).
304 * Backends that don't support metadata ignore this. (since 1.21)
306 * $opts is an associative of boolean flags, including:
307 * - force : Operation precondition errors no longer trigger an abort.
308 * Any remaining operations are still attempted. Unexpected
309 * failures may still cause remaining operations to be aborted.
310 * - nonLocking : No locks are acquired for the operations.
311 * This can increase performance for non-critical writes.
312 * This has no effect unless the 'force' flag is set.
313 * - nonJournaled : Don't log this operation batch in the file journal.
314 * This limits the ability of recovery scripts.
315 * - parallelize : Try to do operations in parallel when possible.
316 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
317 * - preserveCache : Don't clear the process cache before checking files.
318 * This should only be used if all entries in the process
319 * cache were added after the files were already locked. (since 1.20)
321 * @remarks Remarks on locking:
322 * File system paths given to operations should refer to files that are
323 * already locked or otherwise safe from modification from other processes.
324 * Normally these files will be new temp files, which should be adequate.
328 * This returns a Status, which contains all warnings and fatals that occurred
329 * during the operation. The 'failCount', 'successCount', and 'success' members
330 * will reflect each operation attempted.
332 * The status will be "OK" unless:
333 * - a) unexpected operation errors occurred (network partitions, disk full...)
334 * - b) significant operation errors occurred and 'force' was not set
336 * @param array $ops List of operations to execute in order
337 * @param array $opts Batch operation options
340 final public function doOperations( array $ops, array $opts = array() ) {
341 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
342 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
344 if ( !count( $ops ) ) {
345 return Status
::newGood(); // nothing to do
347 if ( empty( $opts['force'] ) ) { // sanity
348 unset( $opts['nonLocking'] );
350 foreach ( $ops as &$op ) {
351 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
352 $op['headers']['Content-Disposition'] = $op['disposition'];
355 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
356 return $this->doOperationsInternal( $ops, $opts );
360 * @see FileBackend::doOperations()
362 abstract protected function doOperationsInternal( array $ops, array $opts );
365 * Same as doOperations() except it takes a single operation.
366 * If you are doing a batch of operations that should either
367 * all succeed or all fail, then use that function instead.
369 * @see FileBackend::doOperations()
371 * @param array $op Operation
372 * @param array $opts Operation options
375 final public function doOperation( array $op, array $opts = array() ) {
376 return $this->doOperations( array( $op ), $opts );
380 * Performs a single create operation.
381 * This sets $params['op'] to 'create' and passes it to doOperation().
383 * @see FileBackend::doOperation()
385 * @param array $params Operation parameters
386 * @param array $opts Operation options
389 final public function create( array $params, array $opts = array() ) {
390 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
394 * Performs a single store operation.
395 * This sets $params['op'] to 'store' and passes it to doOperation().
397 * @see FileBackend::doOperation()
399 * @param array $params Operation parameters
400 * @param array $opts Operation options
403 final public function store( array $params, array $opts = array() ) {
404 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
408 * Performs a single copy operation.
409 * This sets $params['op'] to 'copy' and passes it to doOperation().
411 * @see FileBackend::doOperation()
413 * @param array $params Operation parameters
414 * @param array $opts Operation options
417 final public function copy( array $params, array $opts = array() ) {
418 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
422 * Performs a single move operation.
423 * This sets $params['op'] to 'move' and passes it to doOperation().
425 * @see FileBackend::doOperation()
427 * @param array $params Operation parameters
428 * @param array $opts Operation options
431 final public function move( array $params, array $opts = array() ) {
432 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
436 * Performs a single delete operation.
437 * This sets $params['op'] to 'delete' and passes it to doOperation().
439 * @see FileBackend::doOperation()
441 * @param array $params Operation parameters
442 * @param array $opts Operation options
445 final public function delete( array $params, array $opts = array() ) {
446 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
450 * Performs a single describe operation.
451 * This sets $params['op'] to 'describe' and passes it to doOperation().
453 * @see FileBackend::doOperation()
455 * @param array $params Operation parameters
456 * @param array $opts Operation options
460 final public function describe( array $params, array $opts = array() ) {
461 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
465 * Perform a set of independent file operations on some files.
467 * This does no locking, nor journaling, and possibly no stat calls.
468 * Any destination files that already exist will be overwritten.
469 * This should *only* be used on non-original files, like cache files.
471 * Supported operations and their parameters:
477 * - describe (since 1.21)
480 * a) Create a new file in storage with the contents of a string
484 * 'dst' => <storage path>,
485 * 'content' => <string of new file contents>,
486 * 'headers' => <HTTP header name/value map> # since 1.21
490 * b) Copy a file system file into storage
494 * 'src' => <file system path>,
495 * 'dst' => <storage path>,
496 * 'headers' => <HTTP header name/value map> # since 1.21
500 * c) Copy a file within storage
504 * 'src' => <storage path>,
505 * 'dst' => <storage path>,
506 * 'ignoreMissingSource' => <boolean>, # since 1.21
507 * 'headers' => <HTTP header name/value map> # since 1.21
511 * d) Move a file within storage
515 * 'src' => <storage path>,
516 * 'dst' => <storage path>,
517 * 'ignoreMissingSource' => <boolean>, # since 1.21
518 * 'headers' => <HTTP header name/value map> # since 1.21
522 * e) Delete a file within storage
526 * 'src' => <storage path>,
527 * 'ignoreMissingSource' => <boolean>
531 * f) Update metadata for a file within storage
534 * 'op' => 'describe',
535 * 'src' => <storage path>,
536 * 'headers' => <HTTP header name/value map>
540 * g) Do nothing (no-op)
547 * @par Boolean flags for operations (operation-specific):
548 * - ignoreMissingSource : The operation will simply succeed and do
549 * nothing if the source file does not exist.
550 * - headers : If supplied with a header name/value map, the backend will
551 * reply with these headers when GETs/HEADs of the destination
552 * file are made. Header values should be smaller than 256 bytes.
553 * Content-Disposition headers can be longer, though the system
554 * might ignore or truncate ones that are too long to store.
555 * Existing headers will remain, but these will replace any
556 * conflicting previous headers, and headers will be removed
557 * if they are set to an empty string.
558 * Backends that don't support metadata ignore this. (since 1.21)
560 * $opts is an associative of boolean flags, including:
561 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
564 * This returns a Status, which contains all warnings and fatals that occurred
565 * during the operation. The 'failCount', 'successCount', and 'success' members
566 * will reflect each operation attempted for the given files. The status will be
567 * considered "OK" as long as no fatal errors occurred.
569 * @param array $ops Set of operations to execute
570 * @param array $opts Batch operation options
574 final public function doQuickOperations( array $ops, array $opts = array() ) {
575 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
576 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
578 if ( !count( $ops ) ) {
579 return Status
::newGood(); // nothing to do
581 foreach ( $ops as &$op ) {
582 $op['overwrite'] = true; // avoids RTTs in key/value stores
583 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
584 $op['headers']['Content-Disposition'] = $op['disposition'];
587 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
588 return $this->doQuickOperationsInternal( $ops );
592 * @see FileBackend::doQuickOperations()
595 abstract protected function doQuickOperationsInternal( array $ops );
598 * Same as doQuickOperations() except it takes a single operation.
599 * If you are doing a batch of operations, then use that function instead.
601 * @see FileBackend::doQuickOperations()
603 * @param array $op Operation
607 final public function doQuickOperation( array $op ) {
608 return $this->doQuickOperations( array( $op ) );
612 * Performs a single quick create operation.
613 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
615 * @see FileBackend::doQuickOperation()
617 * @param array $params Operation parameters
621 final public function quickCreate( array $params ) {
622 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
626 * Performs a single quick store operation.
627 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
629 * @see FileBackend::doQuickOperation()
631 * @param array $params Operation parameters
635 final public function quickStore( array $params ) {
636 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
640 * Performs a single quick copy operation.
641 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
643 * @see FileBackend::doQuickOperation()
645 * @param array $params Operation parameters
649 final public function quickCopy( array $params ) {
650 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
654 * Performs a single quick move operation.
655 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
657 * @see FileBackend::doQuickOperation()
659 * @param array $params Operation parameters
663 final public function quickMove( array $params ) {
664 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
668 * Performs a single quick delete operation.
669 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
671 * @see FileBackend::doQuickOperation()
673 * @param array $params Operation parameters
677 final public function quickDelete( array $params ) {
678 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
682 * Performs a single quick describe operation.
683 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
685 * @see FileBackend::doQuickOperation()
687 * @param array $params Operation parameters
691 final public function quickDescribe( array $params ) {
692 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
696 * Concatenate a list of storage files into a single file system file.
697 * The target path should refer to a file that is already locked or
698 * otherwise safe from modification from other processes. Normally,
699 * the file will be a new temp file, which should be adequate.
701 * @param array $params Operation parameters, include:
702 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
703 * - dst : file system path to 0-byte temp file
704 * - parallelize : try to do operations in parallel when possible
707 abstract public function concatenate( array $params );
710 * Prepare a storage directory for usage.
711 * This will create any required containers and parent directories.
712 * Backends using key/value stores only need to create the container.
714 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
715 * except they are only applied *if* the directory/container had to be created.
716 * These flags should always be set for directories that have private files.
717 * However, setting them is not guaranteed to actually do anything.
718 * Additional server configuration may be needed to achieve the desired effect.
720 * @param array $params Parameters include:
721 * - dir : storage directory
722 * - noAccess : try to deny file access (since 1.20)
723 * - noListing : try to deny file listing (since 1.20)
724 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
727 final public function prepare( array $params ) {
728 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
729 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
731 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
732 return $this->doPrepare( $params );
736 * @see FileBackend::prepare()
738 abstract protected function doPrepare( array $params );
741 * Take measures to block web access to a storage directory and
742 * the container it belongs to. FS backends might add .htaccess
743 * files whereas key/value store backends might revoke container
744 * access to the storage user representing end-users in web requests.
746 * This is not guaranteed to actually make files or listings publically hidden.
747 * Additional server configuration may be needed to achieve the desired effect.
749 * @param array $params Parameters include:
750 * - dir : storage directory
751 * - noAccess : try to deny file access
752 * - noListing : try to deny file listing
753 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
756 final public function secure( array $params ) {
757 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
758 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
760 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
761 return $this->doSecure( $params );
765 * @see FileBackend::secure()
767 abstract protected function doSecure( array $params );
770 * Remove measures to block web access to a storage directory and
771 * the container it belongs to. FS backends might remove .htaccess
772 * files whereas key/value store backends might grant container
773 * access to the storage user representing end-users in web requests.
774 * This essentially can undo the result of secure() calls.
776 * This is not guaranteed to actually make files or listings publically viewable.
777 * Additional server configuration may be needed to achieve the desired effect.
779 * @param array $params Parameters include:
780 * - dir : storage directory
781 * - access : try to allow file access
782 * - listing : try to allow file listing
783 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
787 final public function publish( array $params ) {
788 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
789 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
791 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
792 return $this->doPublish( $params );
796 * @see FileBackend::publish()
798 abstract protected function doPublish( array $params );
801 * Delete a storage directory if it is empty.
802 * Backends using key/value stores may do nothing unless the directory
803 * is that of an empty container, in which case it will be deleted.
805 * @param array $params Parameters include:
806 * - dir : storage directory
807 * - recursive : recursively delete empty subdirectories first (since 1.20)
808 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
811 final public function clean( array $params ) {
812 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
813 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
815 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
816 return $this->doClean( $params );
820 * @see FileBackend::clean()
822 abstract protected function doClean( array $params );
825 * Enter file operation scope.
826 * This just makes PHP ignore user aborts/disconnects until the return
827 * value leaves scope. This returns null and does nothing in CLI mode.
829 * @return ScopedCallback|null
831 final protected function getScopedPHPBehaviorForOps() {
832 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
833 $old = ignore_user_abort( true ); // avoid half-finished operations
834 return new ScopedCallback( function () use ( $old ) {
835 ignore_user_abort( $old );
843 * Check if a file exists at a storage path in the backend.
844 * This returns false if only a directory exists at the path.
846 * @param array $params Parameters include:
847 * - src : source storage path
848 * - latest : use the latest available data
849 * @return bool|null Returns null on failure
851 abstract public function fileExists( array $params );
854 * Get the last-modified timestamp of the file at a storage path.
856 * @param array $params Parameters include:
857 * - src : source storage path
858 * - latest : use the latest available data
859 * @return string|bool TS_MW timestamp or false on failure
861 abstract public function getFileTimestamp( array $params );
864 * Get the contents of a file at a storage path in the backend.
865 * This should be avoided for potentially large files.
867 * @param array $params Parameters include:
868 * - src : source storage path
869 * - latest : use the latest available data
870 * @return string|bool Returns false on failure
872 final public function getFileContents( array $params ) {
873 $contents = $this->getFileContentsMulti(
874 array( 'srcs' => array( $params['src'] ) ) +
$params );
876 return $contents[$params['src']];
880 * Like getFileContents() except it takes an array of storage paths
881 * and returns a map of storage paths to strings (or null on failure).
882 * The map keys (paths) are in the same order as the provided list of paths.
884 * @see FileBackend::getFileContents()
886 * @param array $params Parameters include:
887 * - srcs : list of source storage paths
888 * - latest : use the latest available data
889 * - parallelize : try to do operations in parallel when possible
890 * @return array Map of (path name => string or false on failure)
893 abstract public function getFileContentsMulti( array $params );
896 * Get the size (bytes) of a file at a storage path in the backend.
898 * @param array $params Parameters include:
899 * - src : source storage path
900 * - latest : use the latest available data
901 * @return int|bool Returns false on failure
903 abstract public function getFileSize( array $params );
906 * Get quick information about a file at a storage path in the backend.
907 * If the file does not exist, then this returns false.
908 * Otherwise, the result is an associative array that includes:
909 * - mtime : the last-modified timestamp (TS_MW)
910 * - size : the file size (bytes)
911 * Additional values may be included for internal use only.
913 * @param array $params Parameters include:
914 * - src : source storage path
915 * - latest : use the latest available data
916 * @return array|bool|null Returns null on failure
918 abstract public function getFileStat( array $params );
921 * Get a SHA-1 hash of the file at a storage path in the backend.
923 * @param array $params Parameters include:
924 * - src : source storage path
925 * - latest : use the latest available data
926 * @return string|bool Hash string or false on failure
928 abstract public function getFileSha1Base36( array $params );
931 * Get the properties of the file at a storage path in the backend.
932 * This gives the result of FSFile::getProps() on a local copy of the file.
934 * @param array $params Parameters include:
935 * - src : source storage path
936 * - latest : use the latest available data
937 * @return array Returns FSFile::placeholderProps() on failure
939 abstract public function getFileProps( array $params );
942 * Stream the file at a storage path in the backend.
943 * If the file does not exists, an HTTP 404 error will be given.
944 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
945 * will be sent if streaming began, while none will be sent otherwise.
946 * Implementations should flush the output buffer before sending data.
948 * @param array $params Parameters include:
949 * - src : source storage path
950 * - headers : list of additional HTTP headers to send on success
951 * - latest : use the latest available data
954 abstract public function streamFile( array $params );
957 * Returns a file system file, identical to the file at a storage path.
958 * The file returned is either:
959 * - a) A local copy of the file at a storage path in the backend.
960 * The temporary copy will have the same extension as the source.
961 * - b) An original of the file at a storage path in the backend.
962 * Temporary files may be purged when the file object falls out of scope.
964 * Write operations should *never* be done on this file as some backends
965 * may do internal tracking or may be instances of FileBackendMultiWrite.
966 * In that later case, there are copies of the file that must stay in sync.
967 * Additionally, further calls to this function may return the same file.
969 * @param array $params Parameters include:
970 * - src : source storage path
971 * - latest : use the latest available data
972 * @return FSFile|null Returns null on failure
974 final public function getLocalReference( array $params ) {
975 $fsFiles = $this->getLocalReferenceMulti(
976 array( 'srcs' => array( $params['src'] ) ) +
$params );
978 return $fsFiles[$params['src']];
982 * Like getLocalReference() except it takes an array of storage paths
983 * and returns a map of storage paths to FSFile objects (or null on failure).
984 * The map keys (paths) are in the same order as the provided list of paths.
986 * @see FileBackend::getLocalReference()
988 * @param array $params Parameters include:
989 * - srcs : list of source storage paths
990 * - latest : use the latest available data
991 * - parallelize : try to do operations in parallel when possible
992 * @return array Map of (path name => FSFile or null on failure)
995 abstract public function getLocalReferenceMulti( array $params );
998 * Get a local copy on disk of the file at a storage path in the backend.
999 * The temporary copy will have the same file extension as the source.
1000 * Temporary files may be purged when the file object falls out of scope.
1002 * @param array $params Parameters include:
1003 * - src : source storage path
1004 * - latest : use the latest available data
1005 * @return TempFSFile|null Returns null on failure
1007 final public function getLocalCopy( array $params ) {
1008 $tmpFiles = $this->getLocalCopyMulti(
1009 array( 'srcs' => array( $params['src'] ) ) +
$params );
1011 return $tmpFiles[$params['src']];
1015 * Like getLocalCopy() except it takes an array of storage paths and
1016 * returns a map of storage paths to TempFSFile objects (or null on failure).
1017 * The map keys (paths) are in the same order as the provided list of paths.
1019 * @see FileBackend::getLocalCopy()
1021 * @param array $params Parameters include:
1022 * - srcs : list of source storage paths
1023 * - latest : use the latest available data
1024 * - parallelize : try to do operations in parallel when possible
1025 * @return array Map of (path name => TempFSFile or null on failure)
1028 abstract public function getLocalCopyMulti( array $params );
1031 * Return an HTTP URL to a given file that requires no authentication to use.
1032 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1033 * This will return null if the backend cannot make an HTTP URL for the file.
1035 * This is useful for key/value stores when using scripts that seek around
1036 * large files and those scripts (and the backend) support HTTP Range headers.
1037 * Otherwise, one would need to use getLocalReference(), which involves loading
1038 * the entire file on to local disk.
1040 * @param array $params Parameters include:
1041 * - src : source storage path
1042 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1043 * @return string|null
1046 abstract public function getFileHttpUrl( array $params );
1049 * Check if a directory exists at a given storage path.
1050 * Backends using key/value stores will check if the path is a
1051 * virtual directory, meaning there are files under the given directory.
1053 * Storage backends with eventual consistency might return stale data.
1055 * @param array $params Parameters include:
1056 * - dir : storage directory
1057 * @return bool|null Returns null on failure
1060 abstract public function directoryExists( array $params );
1063 * Get an iterator to list *all* directories under a storage directory.
1064 * If the directory is of the form "mwstore://backend/container",
1065 * then all directories in the container will be listed.
1066 * If the directory is of form "mwstore://backend/container/dir",
1067 * then all directories directly under that directory will be listed.
1068 * Results will be storage directories relative to the given directory.
1070 * Storage backends with eventual consistency might return stale data.
1072 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1074 * @param array $params Parameters include:
1075 * - dir : storage directory
1076 * - topOnly : only return direct child dirs of the directory
1077 * @return Traversable|Array|null Returns null on failure
1080 abstract public function getDirectoryList( array $params );
1083 * Same as FileBackend::getDirectoryList() except only lists
1084 * directories that are immediately under the given directory.
1086 * Storage backends with eventual consistency might return stale data.
1088 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1090 * @param array $params Parameters include:
1091 * - dir : storage directory
1092 * @return Traversable|Array|null Returns null on failure
1095 final public function getTopDirectoryList( array $params ) {
1096 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1100 * Get an iterator to list *all* stored files under a storage directory.
1101 * If the directory is of the form "mwstore://backend/container",
1102 * then all files in the container will be listed.
1103 * If the directory is of form "mwstore://backend/container/dir",
1104 * then all files under that directory will be listed.
1105 * Results will be storage paths relative to the given directory.
1107 * Storage backends with eventual consistency might return stale data.
1109 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1111 * @param array $params Parameters include:
1112 * - dir : storage directory
1113 * - topOnly : only return direct child files of the directory (since 1.20)
1114 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1115 * @return Traversable|Array|null Returns null on failure
1117 abstract public function getFileList( array $params );
1120 * Same as FileBackend::getFileList() except only lists
1121 * files that are immediately under the given directory.
1123 * Storage backends with eventual consistency might return stale data.
1125 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1127 * @param array $params Parameters include:
1128 * - dir : storage directory
1129 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1130 * @return Traversable|Array|null Returns null on failure
1133 final public function getTopFileList( array $params ) {
1134 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1138 * Preload persistent file stat and property cache into in-process cache.
1139 * This should be used when stat calls will be made on a known list of a many files.
1141 * @param array $paths Storage paths
1143 public function preloadCache( array $paths ) {
1147 * Invalidate any in-process file stat and property cache.
1148 * If $paths is given, then only the cache for those files will be cleared.
1150 * @param array $paths Storage paths (optional)
1152 public function clearCache( array $paths = null ) {
1156 * Lock the files at the given storage paths in the backend.
1157 * This will either lock all the files or none (on failure).
1159 * Callers should consider using getScopedFileLocks() instead.
1161 * @param array $paths Storage paths
1162 * @param int $type LockManager::LOCK_* constant
1165 final public function lockFiles( array $paths, $type ) {
1166 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1168 return $this->lockManager
->lock( $paths, $type );
1172 * Unlock the files at the given storage paths in the backend.
1174 * @param array $paths Storage paths
1175 * @param int $type LockManager::LOCK_* constant
1178 final public function unlockFiles( array $paths, $type ) {
1179 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1181 return $this->lockManager
->unlock( $paths, $type );
1185 * Lock the files at the given storage paths in the backend.
1186 * This will either lock all the files or none (on failure).
1187 * On failure, the status object will be updated with errors.
1189 * Once the return value goes out scope, the locks will be released and
1190 * the status updated. Unlock fatals will not change the status "OK" value.
1192 * @see ScopedLock::factory()
1194 * @param array $paths List of storage paths or map of lock types to path lists
1195 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1196 * @param Status $status Status to update on lock/unlock
1197 * @return ScopedLock|null Returns null on failure
1199 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1200 if ( $type === 'mixed' ) {
1201 foreach ( $paths as &$typePaths ) {
1202 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1205 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1208 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1212 * Get an array of scoped locks needed for a batch of file operations.
1214 * Normally, FileBackend::doOperations() handles locking, unless
1215 * the 'nonLocking' param is passed in. This function is useful if you
1216 * want the files to be locked for a broader scope than just when the
1217 * files are changing. For example, if you need to update DB metadata,
1218 * you may want to keep the files locked until finished.
1220 * @see FileBackend::doOperations()
1222 * @param array $ops List of file operations to FileBackend::doOperations()
1223 * @param Status $status Status to update on lock/unlock
1224 * @return array List of ScopedFileLocks or null values
1227 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1230 * Get the root storage path of this backend.
1231 * All container paths are "subdirectories" of this path.
1233 * @return string Storage path
1236 final public function getRootStoragePath() {
1237 return "mwstore://{$this->name}";
1241 * Get the storage path for the given container for this backend
1243 * @param string $container Container name
1244 * @return string Storage path
1247 final public function getContainerStoragePath( $container ) {
1248 return $this->getRootStoragePath() . "/{$container}";
1252 * Get the file journal object for this backend
1254 * @return FileJournal
1256 final public function getJournal() {
1257 return $this->fileJournal
;
1261 * Check if a given path is a "mwstore://" path.
1262 * This does not do any further validation or any existence checks.
1264 * @param string $path
1267 final public static function isStoragePath( $path ) {
1268 return ( strpos( $path, 'mwstore://' ) === 0 );
1272 * Split a storage path into a backend name, a container name,
1273 * and a relative file path. The relative path may be the empty string.
1274 * This does not do any path normalization or traversal checks.
1276 * @param string $storagePath
1277 * @return array (backend, container, rel object) or (null, null, null)
1279 final public static function splitStoragePath( $storagePath ) {
1280 if ( self
::isStoragePath( $storagePath ) ) {
1281 // Remove the "mwstore://" prefix and split the path
1282 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1283 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1284 if ( count( $parts ) == 3 ) {
1285 return $parts; // e.g. "backend/container/path"
1287 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1292 return array( null, null, null );
1296 * Normalize a storage path by cleaning up directory separators.
1297 * Returns null if the path is not of the format of a valid storage path.
1299 * @param string $storagePath
1300 * @return string|null
1302 final public static function normalizeStoragePath( $storagePath ) {
1303 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1304 if ( $relPath !== null ) { // must be for this backend
1305 $relPath = self
::normalizeContainerPath( $relPath );
1306 if ( $relPath !== null ) {
1307 return ( $relPath != '' )
1308 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1309 : "mwstore://{$backend}/{$container}";
1317 * Get the parent storage directory of a storage path.
1318 * This returns a path like "mwstore://backend/container",
1319 * "mwstore://backend/container/...", or null if there is no parent.
1321 * @param string $storagePath
1322 * @return string|null
1324 final public static function parentStoragePath( $storagePath ) {
1325 $storagePath = dirname( $storagePath );
1326 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1328 return ( $rel === null ) ?
null : $storagePath;
1332 * Get the final extension from a storage or FS path
1334 * @param string $path
1337 final public static function extensionFromPath( $path ) {
1338 $i = strrpos( $path, '.' );
1340 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1344 * Check if a relative path has no directory traversals
1346 * @param string $path
1350 final public static function isPathTraversalFree( $path ) {
1351 return ( self
::normalizeContainerPath( $path ) !== null );
1355 * Build a Content-Disposition header value per RFC 6266.
1357 * @param string $type One of (attachment, inline)
1358 * @param string $filename Suggested file name (should not contain slashes)
1359 * @throws MWException
1363 final public static function makeContentDisposition( $type, $filename = '' ) {
1366 $type = strtolower( $type );
1367 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1368 throw new MWException( "Invalid Content-Disposition type '$type'." );
1372 if ( strlen( $filename ) ) {
1373 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1376 return implode( ';', $parts );
1380 * Validate and normalize a relative storage path.
1381 * Null is returned if the path involves directory traversal.
1382 * Traversal is insecure for FS backends and broken for others.
1384 * This uses the same traversal protection as Title::secureAndSplit().
1386 * @param string $path Storage path relative to a container
1387 * @return string|null
1389 final protected static function normalizeContainerPath( $path ) {
1390 // Normalize directory separators
1391 $path = strtr( $path, '\\', '/' );
1392 // Collapse any consecutive directory separators
1393 $path = preg_replace( '![/]{2,}!', '/', $path );
1394 // Remove any leading directory separator
1395 $path = ltrim( $path, '/' );
1396 // Use the same traversal protection as Title::secureAndSplit()
1397 if ( strpos( $path, '.' ) !== false ) {
1401 strpos( $path, './' ) === 0 ||
1402 strpos( $path, '../' ) === 0 ||
1403 strpos( $path, '/./' ) !== false ||
1404 strpos( $path, '/../' ) !== false
1415 * @ingroup FileBackend
1418 class FileBackendError
extends MWException
{