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;
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 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
139 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
140 throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
141 } elseif ( !is_string( $this->wikiId
) ) {
142 throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
144 $this->lockManager
= isset( $config['lockManager'] )
145 ?
$config['lockManager']
146 : new NullLockManager( array() );
147 $this->fileJournal
= isset( $config['fileJournal'] )
148 ?
$config['fileJournal']
149 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
150 $this->readOnly
= isset( $config['readOnly'] )
151 ?
(string)$config['readOnly']
153 $this->parallelize
= isset( $config['parallelize'] )
154 ?
(string)$config['parallelize']
156 $this->concurrency
= isset( $config['concurrency'] )
157 ?
(int)$config['concurrency']
162 * Get the unique backend name.
163 * We may have multiple different backends of the same type.
164 * For example, we can have two Swift backends using different proxies.
168 final public function getName() {
173 * Get the wiki identifier used for this backend (possibly empty).
174 * Note that this might *not* be in the same format as wfWikiID().
179 final public function getWikiId() {
180 return $this->wikiId
;
184 * Check if this backend is read-only
188 final public function isReadOnly() {
189 return ( $this->readOnly
!= '' );
193 * Get an explanatory message if this backend is read-only
195 * @return string|bool Returns false if the backend is not read-only
197 final public function getReadOnlyReason() {
198 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
202 * Get the a bitfield of extra features supported by the backend medium
204 * @return int Bitfield of FileBackend::ATTR_* flags
207 public function getFeatures() {
208 return self
::ATTR_UNICODE_PATHS
;
212 * Check if the backend medium supports a field of extra features
214 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
218 final public function hasFeatures( $bitfield ) {
219 return ( $this->getFeatures() & $bitfield ) === $bitfield;
223 * This is the main entry point into the backend for write operations.
224 * Callers supply an ordered list of operations to perform as a transaction.
225 * Files will be locked, the stat cache cleared, and then the operations attempted.
226 * If any serious errors occur, all attempted operations will be rolled back.
228 * $ops is an array of arrays. The outer array holds a list of operations.
229 * Each inner array is a set of key value pairs that specify an operation.
231 * Supported operations and their parameters. The supported actions are:
237 * - describe (since 1.21)
240 * a) Create a new file in storage with the contents of a string
244 * 'dst' => <storage path>,
245 * 'content' => <string of new file contents>,
246 * 'overwrite' => <boolean>,
247 * 'overwriteSame' => <boolean>,
248 * 'headers' => <HTTP header name/value map> # since 1.21
252 * b) Copy a file system file into storage
256 * 'src' => <file system path>,
257 * 'dst' => <storage path>,
258 * 'overwrite' => <boolean>,
259 * 'overwriteSame' => <boolean>,
260 * 'headers' => <HTTP header name/value map> # since 1.21
264 * c) Copy a file within storage
268 * 'src' => <storage path>,
269 * 'dst' => <storage path>,
270 * 'overwrite' => <boolean>,
271 * 'overwriteSame' => <boolean>,
272 * 'ignoreMissingSource' => <boolean>, # since 1.21
273 * 'headers' => <HTTP header name/value map> # since 1.21
277 * d) Move a file within storage
281 * 'src' => <storage path>,
282 * 'dst' => <storage path>,
283 * 'overwrite' => <boolean>,
284 * 'overwriteSame' => <boolean>,
285 * 'ignoreMissingSource' => <boolean>, # since 1.21
286 * 'headers' => <HTTP header name/value map> # since 1.21
290 * e) Delete a file within storage
294 * 'src' => <storage path>,
295 * 'ignoreMissingSource' => <boolean>
299 * f) Update metadata for a file within storage
302 * 'op' => 'describe',
303 * 'src' => <storage path>,
304 * 'headers' => <HTTP header name/value map>
308 * g) Do nothing (no-op)
315 * Boolean flags for operations (operation-specific):
316 * - ignoreMissingSource : The operation will simply succeed and do
317 * nothing if the source file does not exist.
318 * - overwrite : Any destination file will be overwritten.
319 * - overwriteSame : If a file already exists at the destination with the
320 * same contents, then do nothing to the destination file
321 * instead of giving an error. This does not compare headers.
322 * This option is ignored if 'overwrite' is already provided.
323 * - headers : If supplied, the result of merging these headers with any
324 * existing source file headers (replacing conflicting ones)
325 * will be set as the destination file headers. Headers are
326 * deleted if their value is set to the empty string. When a
327 * file has headers they are included in responses to GET and
328 * HEAD requests to the backing store for that file.
329 * Header values should be no larger than 255 bytes, except for
330 * Content-Disposition. The system might ignore or truncate any
331 * headers that are too long to store (exact limits will vary).
332 * Backends that don't support metadata ignore this. (since 1.21)
334 * $opts is an associative of boolean flags, including:
335 * - force : Operation precondition errors no longer trigger an abort.
336 * Any remaining operations are still attempted. Unexpected
337 * failures may still cause remaining operations to be aborted.
338 * - nonLocking : No locks are acquired for the operations.
339 * This can increase performance for non-critical writes.
340 * This has no effect unless the 'force' flag is set.
341 * - nonJournaled : Don't log this operation batch in the file journal.
342 * This limits the ability of recovery scripts.
343 * - parallelize : Try to do operations in parallel when possible.
344 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
345 * - preserveCache : Don't clear the process cache before checking files.
346 * This should only be used if all entries in the process
347 * cache were added after the files were already locked. (since 1.20)
349 * @remarks Remarks on locking:
350 * File system paths given to operations should refer to files that are
351 * already locked or otherwise safe from modification from other processes.
352 * Normally these files will be new temp files, which should be adequate.
356 * This returns a Status, which contains all warnings and fatals that occurred
357 * during the operation. The 'failCount', 'successCount', and 'success' members
358 * will reflect each operation attempted.
360 * The status will be "OK" unless:
361 * - a) unexpected operation errors occurred (network partitions, disk full...)
362 * - b) significant operation errors occurred and 'force' was not set
364 * @param array $ops List of operations to execute in order
365 * @param array $opts Batch operation options
368 final public function doOperations( array $ops, array $opts = array() ) {
369 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
370 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
372 if ( !count( $ops ) ) {
373 return Status
::newGood(); // nothing to do
375 if ( empty( $opts['force'] ) ) { // sanity
376 unset( $opts['nonLocking'] );
378 foreach ( $ops as &$op ) {
379 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
380 $op['headers']['Content-Disposition'] = $op['disposition'];
383 /** @noinspection PhpUnusedLocalVariableInspection */
384 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
385 return $this->doOperationsInternal( $ops, $opts );
389 * @see FileBackend::doOperations()
393 abstract protected function doOperationsInternal( array $ops, array $opts );
396 * Same as doOperations() except it takes a single operation.
397 * If you are doing a batch of operations that should either
398 * all succeed or all fail, then use that function instead.
400 * @see FileBackend::doOperations()
402 * @param array $op Operation
403 * @param array $opts Operation options
406 final public function doOperation( array $op, array $opts = array() ) {
407 return $this->doOperations( array( $op ), $opts );
411 * Performs a single create operation.
412 * This sets $params['op'] to 'create' and passes it to doOperation().
414 * @see FileBackend::doOperation()
416 * @param array $params Operation parameters
417 * @param array $opts Operation options
420 final public function create( array $params, array $opts = array() ) {
421 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
425 * Performs a single store operation.
426 * This sets $params['op'] to 'store' and passes it to doOperation().
428 * @see FileBackend::doOperation()
430 * @param array $params Operation parameters
431 * @param array $opts Operation options
434 final public function store( array $params, array $opts = array() ) {
435 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
439 * Performs a single copy operation.
440 * This sets $params['op'] to 'copy' and passes it to doOperation().
442 * @see FileBackend::doOperation()
444 * @param array $params Operation parameters
445 * @param array $opts Operation options
448 final public function copy( array $params, array $opts = array() ) {
449 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
453 * Performs a single move operation.
454 * This sets $params['op'] to 'move' and passes it to doOperation().
456 * @see FileBackend::doOperation()
458 * @param array $params Operation parameters
459 * @param array $opts Operation options
462 final public function move( array $params, array $opts = array() ) {
463 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
467 * Performs a single delete operation.
468 * This sets $params['op'] to 'delete' and passes it to doOperation().
470 * @see FileBackend::doOperation()
472 * @param array $params Operation parameters
473 * @param array $opts Operation options
476 final public function delete( array $params, array $opts = array() ) {
477 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
481 * Performs a single describe operation.
482 * This sets $params['op'] to 'describe' and passes it to doOperation().
484 * @see FileBackend::doOperation()
486 * @param array $params Operation parameters
487 * @param array $opts Operation options
491 final public function describe( array $params, array $opts = array() ) {
492 return $this->doOperation( array( 'op' => 'describe' ) +
$params, $opts );
496 * Perform a set of independent file operations on some files.
498 * This does no locking, nor journaling, and possibly no stat calls.
499 * Any destination files that already exist will be overwritten.
500 * This should *only* be used on non-original files, like cache files.
502 * Supported operations and their parameters:
508 * - describe (since 1.21)
511 * a) Create a new file in storage with the contents of a string
515 * 'dst' => <storage path>,
516 * 'content' => <string of new file contents>,
517 * 'headers' => <HTTP header name/value map> # since 1.21
521 * b) Copy a file system file into storage
525 * 'src' => <file system path>,
526 * 'dst' => <storage path>,
527 * 'headers' => <HTTP header name/value map> # since 1.21
531 * c) Copy a file within storage
535 * 'src' => <storage path>,
536 * 'dst' => <storage path>,
537 * 'ignoreMissingSource' => <boolean>, # since 1.21
538 * 'headers' => <HTTP header name/value map> # since 1.21
542 * d) Move a file within storage
546 * 'src' => <storage path>,
547 * 'dst' => <storage path>,
548 * 'ignoreMissingSource' => <boolean>, # since 1.21
549 * 'headers' => <HTTP header name/value map> # since 1.21
553 * e) Delete a file within storage
557 * 'src' => <storage path>,
558 * 'ignoreMissingSource' => <boolean>
562 * f) Update metadata for a file within storage
565 * 'op' => 'describe',
566 * 'src' => <storage path>,
567 * 'headers' => <HTTP header name/value map>
571 * g) Do nothing (no-op)
578 * @par Boolean flags for operations (operation-specific):
579 * - ignoreMissingSource : The operation will simply succeed and do
580 * nothing if the source file does not exist.
581 * - headers : If supplied with a header name/value map, the backend will
582 * reply with these headers when GETs/HEADs of the destination
583 * file are made. Header values should be smaller than 256 bytes.
584 * Content-Disposition headers can be longer, though the system
585 * might ignore or truncate ones that are too long to store.
586 * Existing headers will remain, but these will replace any
587 * conflicting previous headers, and headers will be removed
588 * if they are set to an empty string.
589 * Backends that don't support metadata ignore this. (since 1.21)
591 * $opts is an associative of boolean flags, including:
592 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
595 * This returns a Status, which contains all warnings and fatals that occurred
596 * during the operation. The 'failCount', 'successCount', and 'success' members
597 * will reflect each operation attempted for the given files. The status will be
598 * considered "OK" as long as no fatal errors occurred.
600 * @param array $ops Set of operations to execute
601 * @param array $opts Batch operation options
605 final public function doQuickOperations( array $ops, array $opts = array() ) {
606 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
607 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
609 if ( !count( $ops ) ) {
610 return Status
::newGood(); // nothing to do
612 foreach ( $ops as &$op ) {
613 $op['overwrite'] = true; // avoids RTTs in key/value stores
614 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
615 $op['headers']['Content-Disposition'] = $op['disposition'];
618 /** @noinspection PhpUnusedLocalVariableInspection */
619 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
620 return $this->doQuickOperationsInternal( $ops );
624 * @see FileBackend::doQuickOperations()
628 abstract protected function doQuickOperationsInternal( array $ops );
631 * Same as doQuickOperations() except it takes a single operation.
632 * If you are doing a batch of operations, then use that function instead.
634 * @see FileBackend::doQuickOperations()
636 * @param array $op Operation
640 final public function doQuickOperation( array $op ) {
641 return $this->doQuickOperations( array( $op ) );
645 * Performs a single quick create operation.
646 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
648 * @see FileBackend::doQuickOperation()
650 * @param array $params Operation parameters
654 final public function quickCreate( array $params ) {
655 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
659 * Performs a single quick store operation.
660 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
662 * @see FileBackend::doQuickOperation()
664 * @param array $params Operation parameters
668 final public function quickStore( array $params ) {
669 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
673 * Performs a single quick copy operation.
674 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
676 * @see FileBackend::doQuickOperation()
678 * @param array $params Operation parameters
682 final public function quickCopy( array $params ) {
683 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
687 * Performs a single quick move operation.
688 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
690 * @see FileBackend::doQuickOperation()
692 * @param array $params Operation parameters
696 final public function quickMove( array $params ) {
697 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
701 * Performs a single quick delete operation.
702 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
704 * @see FileBackend::doQuickOperation()
706 * @param array $params Operation parameters
710 final public function quickDelete( array $params ) {
711 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
715 * Performs a single quick describe operation.
716 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
718 * @see FileBackend::doQuickOperation()
720 * @param array $params Operation parameters
724 final public function quickDescribe( array $params ) {
725 return $this->doQuickOperation( array( 'op' => 'describe' ) +
$params );
729 * Concatenate a list of storage files into a single file system file.
730 * The target path should refer to a file that is already locked or
731 * otherwise safe from modification from other processes. Normally,
732 * the file will be a new temp file, which should be adequate.
734 * @param array $params Operation parameters, include:
735 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
736 * - dst : file system path to 0-byte temp file
737 * - parallelize : try to do operations in parallel when possible
740 abstract public function concatenate( array $params );
743 * Prepare a storage directory for usage.
744 * This will create any required containers and parent directories.
745 * Backends using key/value stores only need to create the container.
747 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
748 * except they are only applied *if* the directory/container had to be created.
749 * These flags should always be set for directories that have private files.
750 * However, setting them is not guaranteed to actually do anything.
751 * Additional server configuration may be needed to achieve the desired effect.
753 * @param array $params Parameters include:
754 * - dir : storage directory
755 * - noAccess : try to deny file access (since 1.20)
756 * - noListing : try to deny file listing (since 1.20)
757 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
760 final public function prepare( array $params ) {
761 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
762 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
764 /** @noinspection PhpUnusedLocalVariableInspection */
765 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
766 return $this->doPrepare( $params );
770 * @see FileBackend::prepare()
771 * @param array $params
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)
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 /** @noinspection PhpUnusedLocalVariableInspection */
796 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
797 return $this->doSecure( $params );
801 * @see FileBackend::secure()
802 * @param array $params
804 abstract protected function doSecure( array $params );
807 * Remove measures to block web access to a storage directory and
808 * the container it belongs to. FS backends might remove .htaccess
809 * files whereas key/value store backends might grant container
810 * access to the storage user representing end-users in web requests.
811 * This essentially can undo the result of secure() calls.
813 * This is not guaranteed to actually make files or listings publically viewable.
814 * Additional server configuration may be needed to achieve the desired effect.
816 * @param array $params Parameters include:
817 * - dir : storage directory
818 * - access : try to allow file access
819 * - listing : try to allow file listing
820 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
824 final public function publish( array $params ) {
825 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
826 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
828 /** @noinspection PhpUnusedLocalVariableInspection */
829 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
830 return $this->doPublish( $params );
834 * @see FileBackend::publish()
835 * @param array $params
837 abstract protected function doPublish( array $params );
840 * Delete a storage directory if it is empty.
841 * Backends using key/value stores may do nothing unless the directory
842 * is that of an empty container, in which case it will be deleted.
844 * @param array $params Parameters include:
845 * - dir : storage directory
846 * - recursive : recursively delete empty subdirectories first (since 1.20)
847 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
850 final public function clean( array $params ) {
851 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
852 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
854 /** @noinspection PhpUnusedLocalVariableInspection */
855 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
856 return $this->doClean( $params );
860 * @see FileBackend::clean()
861 * @param array $params
863 abstract protected function doClean( array $params );
866 * Enter file operation scope.
867 * This just makes PHP ignore user aborts/disconnects until the return
868 * value leaves scope. This returns null and does nothing in CLI mode.
870 * @return ScopedCallback|null
872 final protected function getScopedPHPBehaviorForOps() {
873 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
874 $old = ignore_user_abort( true ); // avoid half-finished operations
875 return new ScopedCallback( function () use ( $old ) {
876 ignore_user_abort( $old );
884 * Check if a file exists at a storage path in the backend.
885 * This returns false if only a directory exists at the path.
887 * @param array $params Parameters include:
888 * - src : source storage path
889 * - latest : use the latest available data
890 * @return bool|null Returns null on failure
892 abstract public function fileExists( array $params );
895 * Get the last-modified timestamp of the file at a storage path.
897 * @param array $params Parameters include:
898 * - src : source storage path
899 * - latest : use the latest available data
900 * @return string|bool TS_MW timestamp or false on failure
902 abstract public function getFileTimestamp( array $params );
905 * Get the contents of a file at a storage path in the backend.
906 * This should be avoided for potentially large files.
908 * @param array $params Parameters include:
909 * - src : source storage path
910 * - latest : use the latest available data
911 * @return string|bool Returns false on failure
913 final public function getFileContents( array $params ) {
914 $contents = $this->getFileContentsMulti(
915 array( 'srcs' => array( $params['src'] ) ) +
$params );
917 return $contents[$params['src']];
921 * Like getFileContents() except it takes an array of storage paths
922 * and returns a map of storage paths to strings (or null on failure).
923 * The map keys (paths) are in the same order as the provided list of paths.
925 * @see FileBackend::getFileContents()
927 * @param array $params Parameters include:
928 * - srcs : list of source storage paths
929 * - latest : use the latest available data
930 * - parallelize : try to do operations in parallel when possible
931 * @return array Map of (path name => string or false on failure)
934 abstract public function getFileContentsMulti( array $params );
937 * Get metadata about a file at a storage path in the backend.
938 * If the file does not exist, then this returns false.
939 * Otherwise, the result is an associative array that includes:
940 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
941 * - metadata : map of file metadata (name => value)
942 * Metadata keys and headers names will be returned in all lower-case.
943 * Additional values may be included for internal use only.
945 * Use FileBackend::hasFeatures() to check how well this is supported.
947 * @param array $params
949 * - src : source storage path
950 * - latest : use the latest available data
951 * @return array|bool Returns false on failure
954 abstract public function getFileXAttributes( array $params );
957 * Get the size (bytes) of a file at a storage path in the backend.
959 * @param array $params Parameters include:
960 * - src : source storage path
961 * - latest : use the latest available data
962 * @return int|bool Returns false on failure
964 abstract public function getFileSize( array $params );
967 * Get quick information about a file at a storage path in the backend.
968 * If the file does not exist, then this returns false.
969 * Otherwise, the result is an associative array that includes:
970 * - mtime : the last-modified timestamp (TS_MW)
971 * - size : the file size (bytes)
972 * Additional values may be included for internal use only.
974 * @param array $params Parameters include:
975 * - src : source storage path
976 * - latest : use the latest available data
977 * @return array|bool|null Returns null on failure
979 abstract public function getFileStat( array $params );
982 * Get a SHA-1 hash of the file at a storage path in the backend.
984 * @param array $params Parameters include:
985 * - src : source storage path
986 * - latest : use the latest available data
987 * @return string|bool Hash string or false on failure
989 abstract public function getFileSha1Base36( array $params );
992 * Get the properties of the file at a storage path in the backend.
993 * This gives the result of FSFile::getProps() on a local copy of the file.
995 * @param array $params Parameters include:
996 * - src : source storage path
997 * - latest : use the latest available data
998 * @return array Returns FSFile::placeholderProps() on failure
1000 abstract public function getFileProps( array $params );
1003 * Stream the file at a storage path in the backend.
1004 * If the file does not exists, an HTTP 404 error will be given.
1005 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1006 * will be sent if streaming began, while none will be sent otherwise.
1007 * Implementations should flush the output buffer before sending data.
1009 * @param array $params Parameters include:
1010 * - src : source storage path
1011 * - headers : list of additional HTTP headers to send on success
1012 * - latest : use the latest available data
1015 abstract public function streamFile( array $params );
1018 * Returns a file system file, identical to the file at a storage path.
1019 * The file returned is either:
1020 * - a) A local copy of the file at a storage path in the backend.
1021 * The temporary copy will have the same extension as the source.
1022 * - b) An original of the file at a storage path in the backend.
1023 * Temporary files may be purged when the file object falls out of scope.
1025 * Write operations should *never* be done on this file as some backends
1026 * may do internal tracking or may be instances of FileBackendMultiWrite.
1027 * In that later case, there are copies of the file that must stay in sync.
1028 * Additionally, further calls to this function may return the same file.
1030 * @param array $params Parameters include:
1031 * - src : source storage path
1032 * - latest : use the latest available data
1033 * @return FSFile|null Returns null on failure
1035 final public function getLocalReference( array $params ) {
1036 $fsFiles = $this->getLocalReferenceMulti(
1037 array( 'srcs' => array( $params['src'] ) ) +
$params );
1039 return $fsFiles[$params['src']];
1043 * Like getLocalReference() except it takes an array of storage paths
1044 * and returns a map of storage paths to FSFile objects (or null on failure).
1045 * The map keys (paths) are in the same order as the provided list of paths.
1047 * @see FileBackend::getLocalReference()
1049 * @param array $params Parameters include:
1050 * - srcs : list of source storage paths
1051 * - latest : use the latest available data
1052 * - parallelize : try to do operations in parallel when possible
1053 * @return array Map of (path name => FSFile or null on failure)
1056 abstract public function getLocalReferenceMulti( array $params );
1059 * Get a local copy on disk of the file at a storage path in the backend.
1060 * The temporary copy will have the same file extension as the source.
1061 * Temporary files may be purged when the file object falls out of scope.
1063 * @param array $params Parameters include:
1064 * - src : source storage path
1065 * - latest : use the latest available data
1066 * @return TempFSFile|null Returns null on failure
1068 final public function getLocalCopy( array $params ) {
1069 $tmpFiles = $this->getLocalCopyMulti(
1070 array( 'srcs' => array( $params['src'] ) ) +
$params );
1072 return $tmpFiles[$params['src']];
1076 * Like getLocalCopy() except it takes an array of storage paths and
1077 * returns a map of storage paths to TempFSFile objects (or null on failure).
1078 * The map keys (paths) are in the same order as the provided list of paths.
1080 * @see FileBackend::getLocalCopy()
1082 * @param array $params Parameters include:
1083 * - srcs : list of source storage paths
1084 * - latest : use the latest available data
1085 * - parallelize : try to do operations in parallel when possible
1086 * @return array Map of (path name => TempFSFile or null on failure)
1089 abstract public function getLocalCopyMulti( array $params );
1092 * Return an HTTP URL to a given file that requires no authentication to use.
1093 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1094 * This will return null if the backend cannot make an HTTP URL for the file.
1096 * This is useful for key/value stores when using scripts that seek around
1097 * large files and those scripts (and the backend) support HTTP Range headers.
1098 * Otherwise, one would need to use getLocalReference(), which involves loading
1099 * the entire file on to local disk.
1101 * @param array $params Parameters include:
1102 * - src : source storage path
1103 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1104 * @return string|null
1107 abstract public function getFileHttpUrl( array $params );
1110 * Check if a directory exists at a given storage path.
1111 * Backends using key/value stores will check if the path is a
1112 * virtual directory, meaning there are files under the given directory.
1114 * Storage backends with eventual consistency might return stale data.
1116 * @param array $params Parameters include:
1117 * - dir : storage directory
1118 * @return bool|null Returns null on failure
1121 abstract public function directoryExists( array $params );
1124 * Get an iterator to list *all* directories under a storage directory.
1125 * If the directory is of the form "mwstore://backend/container",
1126 * then all directories in the container will be listed.
1127 * If the directory is of form "mwstore://backend/container/dir",
1128 * then all directories directly under that directory will be listed.
1129 * Results will be storage directories relative to the given directory.
1131 * Storage backends with eventual consistency might return stale data.
1133 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1135 * @param array $params Parameters include:
1136 * - dir : storage directory
1137 * - topOnly : only return direct child dirs of the directory
1138 * @return Traversable|array|null Returns null on failure
1141 abstract public function getDirectoryList( array $params );
1144 * Same as FileBackend::getDirectoryList() except only lists
1145 * directories that are immediately under the given directory.
1147 * Storage backends with eventual consistency might return stale data.
1149 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1151 * @param array $params Parameters include:
1152 * - dir : storage directory
1153 * @return Traversable|array|null Returns null on failure
1156 final public function getTopDirectoryList( array $params ) {
1157 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
1161 * Get an iterator to list *all* stored files under a storage directory.
1162 * If the directory is of the form "mwstore://backend/container",
1163 * then all files in the container will be listed.
1164 * If the directory is of form "mwstore://backend/container/dir",
1165 * then all files under that directory will be listed.
1166 * Results will be storage paths relative to the given directory.
1168 * Storage backends with eventual consistency might return stale data.
1170 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1172 * @param array $params Parameters include:
1173 * - dir : storage directory
1174 * - topOnly : only return direct child files of the directory (since 1.20)
1175 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1176 * @return Traversable|array|null Returns null on failure
1178 abstract public function getFileList( array $params );
1181 * Same as FileBackend::getFileList() except only lists
1182 * files that are immediately under the given directory.
1184 * Storage backends with eventual consistency might return stale data.
1186 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1188 * @param array $params Parameters include:
1189 * - dir : storage directory
1190 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1191 * @return Traversable|array|null Returns null on failure
1194 final public function getTopFileList( array $params ) {
1195 return $this->getFileList( array( 'topOnly' => true ) +
$params );
1199 * Preload persistent file stat cache and property cache into in-process cache.
1200 * This should be used when stat calls will be made on a known list of a many files.
1202 * @see FileBackend::getFileStat()
1204 * @param array $paths Storage paths
1206 abstract public function preloadCache( array $paths );
1209 * Invalidate any in-process file stat and property cache.
1210 * If $paths is given, then only the cache for those files will be cleared.
1212 * @see FileBackend::getFileStat()
1214 * @param array $paths Storage paths (optional)
1216 abstract public function clearCache( array $paths = null );
1219 * Preload file stat information (concurrently if possible) into in-process cache.
1221 * This should be used when stat calls will be made on a known list of a many files.
1222 * This does not make use of the persistent file stat cache.
1224 * @see FileBackend::getFileStat()
1226 * @param array $params Parameters include:
1227 * - srcs : list of source storage paths
1228 * - latest : use the latest available data
1229 * @return bool All requests proceeded without I/O errors (since 1.24)
1232 abstract public function preloadFileStat( array $params );
1235 * Lock the files at the given storage paths in the backend.
1236 * This will either lock all the files or none (on failure).
1238 * Callers should consider using getScopedFileLocks() instead.
1240 * @param array $paths Storage paths
1241 * @param int $type LockManager::LOCK_* constant
1242 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1245 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1246 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1248 return $this->lockManager
->lock( $paths, $type, $timeout );
1252 * Unlock the files at the given storage paths in the backend.
1254 * @param array $paths Storage paths
1255 * @param int $type LockManager::LOCK_* constant
1258 final public function unlockFiles( array $paths, $type ) {
1259 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1261 return $this->lockManager
->unlock( $paths, $type );
1265 * Lock the files at the given storage paths in the backend.
1266 * This will either lock all the files or none (on failure).
1267 * On failure, the status object will be updated with errors.
1269 * Once the return value goes out scope, the locks will be released and
1270 * the status updated. Unlock fatals will not change the status "OK" value.
1272 * @see ScopedLock::factory()
1274 * @param array $paths List of storage paths or map of lock types to path lists
1275 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1276 * @param Status $status Status to update on lock/unlock
1277 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1278 * @return ScopedLock|null Returns null on failure
1280 final public function getScopedFileLocks( array $paths, $type, Status
$status, $timeout = 0 ) {
1281 if ( $type === 'mixed' ) {
1282 foreach ( $paths as &$typePaths ) {
1283 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1286 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1289 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status, $timeout );
1293 * Get an array of scoped locks needed for a batch of file operations.
1295 * Normally, FileBackend::doOperations() handles locking, unless
1296 * the 'nonLocking' param is passed in. This function is useful if you
1297 * want the files to be locked for a broader scope than just when the
1298 * files are changing. For example, if you need to update DB metadata,
1299 * you may want to keep the files locked until finished.
1301 * @see FileBackend::doOperations()
1303 * @param array $ops List of file operations to FileBackend::doOperations()
1304 * @param Status $status Status to update on lock/unlock
1305 * @return array List of ScopedFileLocks or null values
1308 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1311 * Get the root storage path of this backend.
1312 * All container paths are "subdirectories" of this path.
1314 * @return string Storage path
1317 final public function getRootStoragePath() {
1318 return "mwstore://{$this->name}";
1322 * Get the storage path for the given container for this backend
1324 * @param string $container Container name
1325 * @return string Storage path
1328 final public function getContainerStoragePath( $container ) {
1329 return $this->getRootStoragePath() . "/{$container}";
1333 * Get the file journal object for this backend
1335 * @return FileJournal
1337 final public function getJournal() {
1338 return $this->fileJournal
;
1342 * Check if a given path is a "mwstore://" path.
1343 * This does not do any further validation or any existence checks.
1345 * @param string $path
1348 final public static function isStoragePath( $path ) {
1349 return ( strpos( $path, 'mwstore://' ) === 0 );
1353 * Split a storage path into a backend name, a container name,
1354 * and a relative file path. The relative path may be the empty string.
1355 * This does not do any path normalization or traversal checks.
1357 * @param string $storagePath
1358 * @return array (backend, container, rel object) or (null, null, null)
1360 final public static function splitStoragePath( $storagePath ) {
1361 if ( self
::isStoragePath( $storagePath ) ) {
1362 // Remove the "mwstore://" prefix and split the path
1363 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1364 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1365 if ( count( $parts ) == 3 ) {
1366 return $parts; // e.g. "backend/container/path"
1368 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1373 return array( null, null, null );
1377 * Normalize a storage path by cleaning up directory separators.
1378 * Returns null if the path is not of the format of a valid storage path.
1380 * @param string $storagePath
1381 * @return string|null
1383 final public static function normalizeStoragePath( $storagePath ) {
1384 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1385 if ( $relPath !== null ) { // must be for this backend
1386 $relPath = self
::normalizeContainerPath( $relPath );
1387 if ( $relPath !== null ) {
1388 return ( $relPath != '' )
1389 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1390 : "mwstore://{$backend}/{$container}";
1398 * Get the parent storage directory of a storage path.
1399 * This returns a path like "mwstore://backend/container",
1400 * "mwstore://backend/container/...", or null if there is no parent.
1402 * @param string $storagePath
1403 * @return string|null
1405 final public static function parentStoragePath( $storagePath ) {
1406 $storagePath = dirname( $storagePath );
1407 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1409 return ( $rel === null ) ?
null : $storagePath;
1413 * Get the final extension from a storage or FS path
1415 * @param string $path
1416 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1419 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1420 $i = strrpos( $path, '.' );
1421 $ext = $i ?
substr( $path, $i +
1 ) : '';
1423 if ( $case === 'lowercase' ) {
1424 $ext = strtolower( $ext );
1425 } elseif ( $case === 'uppercase' ) {
1426 $ext = strtoupper( $ext );
1433 * Check if a relative path has no directory traversals
1435 * @param string $path
1439 final public static function isPathTraversalFree( $path ) {
1440 return ( self
::normalizeContainerPath( $path ) !== null );
1444 * Build a Content-Disposition header value per RFC 6266.
1446 * @param string $type One of (attachment, inline)
1447 * @param string $filename Suggested file name (should not contain slashes)
1448 * @throws FileBackendError
1452 final public static function makeContentDisposition( $type, $filename = '' ) {
1455 $type = strtolower( $type );
1456 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1457 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1461 if ( strlen( $filename ) ) {
1462 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1465 return implode( ';', $parts );
1469 * Validate and normalize a relative storage path.
1470 * Null is returned if the path involves directory traversal.
1471 * Traversal is insecure for FS backends and broken for others.
1473 * This uses the same traversal protection as Title::secureAndSplit().
1475 * @param string $path Storage path relative to a container
1476 * @return string|null
1478 final protected static function normalizeContainerPath( $path ) {
1479 // Normalize directory separators
1480 $path = strtr( $path, '\\', '/' );
1481 // Collapse any consecutive directory separators
1482 $path = preg_replace( '![/]{2,}!', '/', $path );
1483 // Remove any leading directory separator
1484 $path = ltrim( $path, '/' );
1485 // Use the same traversal protection as Title::secureAndSplit()
1486 if ( strpos( $path, '.' ) !== false ) {
1490 strpos( $path, './' ) === 0 ||
1491 strpos( $path, '../' ) === 0 ||
1492 strpos( $path, '/./' ) !== false ||
1493 strpos( $path, '/../' ) !== false
1504 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1506 * @ingroup FileBackend
1509 class FileBackendException
extends Exception
{
1513 * File backend exception for checked exceptions (e.g. I/O errors)
1515 * @ingroup FileBackend
1518 class FileBackendError
extends FileBackendException
{