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 protected $statusWrapper;
110 /** Bitfield flags for supported features */
111 const ATTR_HEADERS
= 1; // files can be tagged with standard HTTP headers
112 const ATTR_METADATA
= 2; // files can be stored with metadata key/values
113 const ATTR_UNICODE_PATHS
= 4; // files can have Unicode paths (not just ASCII)
116 * Create a new backend instance from configuration.
117 * This should only be called from within FileBackendGroup.
119 * @param array $config Parameters include:
120 * - name : The unique name of this backend.
121 * This should consist of alphanumberic, '-', and '_' characters.
122 * This name should not be changed after use (e.g. with journaling).
123 * Note that the name is *not* used in actual container names.
124 * - wikiId : Prefix to container names that is unique to this backend.
125 * It should only consist of alphanumberic, '-', and '_' characters.
126 * This ID is what avoids collisions if multiple logical backends
127 * use the same storage system, so this should be set carefully.
128 * - lockManager : LockManager object to use for any file locking.
129 * If not provided, then no file locking will be enforced.
130 * - fileJournal : FileJournal object to use for logging changes to files.
131 * If not provided, then change journaling will be disabled.
132 * - readOnly : Write operations are disallowed if this is a non-empty string.
133 * It should be an explanation for the backend being read-only.
134 * - parallelize : When to do file operations in parallel (when possible).
135 * Allowed values are "implicit", "explicit" and "off".
136 * - concurrency : How many file operations can be done in parallel.
137 * @throws FileBackendException
139 public function __construct( array $config ) {
140 $this->name
= $config['name'];
141 $this->wikiId
= $config['wikiId']; // e.g. "my_wiki-en_"
142 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
143 throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
144 } elseif ( !is_string( $this->wikiId
) ) {
145 throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
147 $this->lockManager
= isset( $config['lockManager'] )
148 ?
$config['lockManager']
149 : new NullLockManager( [] );
150 $this->fileJournal
= isset( $config['fileJournal'] )
151 ?
$config['fileJournal']
152 : FileJournal
::factory( [ 'class' => 'NullFileJournal' ], $this->name
);
153 $this->readOnly
= isset( $config['readOnly'] )
154 ?
(string)$config['readOnly']
156 $this->parallelize
= isset( $config['parallelize'] )
157 ?
(string)$config['parallelize']
159 $this->concurrency
= isset( $config['concurrency'] )
160 ?
(int)$config['concurrency']
162 // @TODO: dependency inject this
163 $this->statusWrapper
= [ 'Status', 'wrap' ];
167 * Get the unique backend name.
168 * We may have multiple different backends of the same type.
169 * For example, we can have two Swift backends using different proxies.
173 final public function getName() {
178 * Get the wiki identifier used for this backend (possibly empty).
179 * Note that this might *not* be in the same format as wfWikiID().
184 final public function getWikiId() {
185 return $this->wikiId
;
189 * Check if this backend is read-only
193 final public function isReadOnly() {
194 return ( $this->readOnly
!= '' );
198 * Get an explanatory message if this backend is read-only
200 * @return string|bool Returns false if the backend is not read-only
202 final public function getReadOnlyReason() {
203 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
207 * Get the a bitfield of extra features supported by the backend medium
209 * @return int Bitfield of FileBackend::ATTR_* flags
212 public function getFeatures() {
213 return self
::ATTR_UNICODE_PATHS
;
217 * Check if the backend medium supports a field of extra features
219 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
223 final public function hasFeatures( $bitfield ) {
224 return ( $this->getFeatures() & $bitfield ) === $bitfield;
228 * This is the main entry point into the backend for write operations.
229 * Callers supply an ordered list of operations to perform as a transaction.
230 * Files will be locked, the stat cache cleared, and then the operations attempted.
231 * If any serious errors occur, all attempted operations will be rolled back.
233 * $ops is an array of arrays. The outer array holds a list of operations.
234 * Each inner array is a set of key value pairs that specify an operation.
236 * Supported operations and their parameters. The supported actions are:
242 * - describe (since 1.21)
245 * FSFile/TempFSFile object support was added in 1.27.
247 * a) Create a new file in storage with the contents of a string
251 * 'dst' => <storage path>,
252 * 'content' => <string of new file contents>,
253 * 'overwrite' => <boolean>,
254 * 'overwriteSame' => <boolean>,
255 * 'headers' => <HTTP header name/value map> # since 1.21
259 * b) Copy a file system file into storage
263 * 'src' => <file system path, FSFile, or TempFSFile>,
264 * 'dst' => <storage path>,
265 * 'overwrite' => <boolean>,
266 * 'overwriteSame' => <boolean>,
267 * 'headers' => <HTTP header name/value map> # since 1.21
271 * c) Copy a file within storage
275 * 'src' => <storage path>,
276 * 'dst' => <storage path>,
277 * 'overwrite' => <boolean>,
278 * 'overwriteSame' => <boolean>,
279 * 'ignoreMissingSource' => <boolean>, # since 1.21
280 * 'headers' => <HTTP header name/value map> # since 1.21
284 * d) Move a file within storage
288 * 'src' => <storage path>,
289 * 'dst' => <storage path>,
290 * 'overwrite' => <boolean>,
291 * 'overwriteSame' => <boolean>,
292 * 'ignoreMissingSource' => <boolean>, # since 1.21
293 * 'headers' => <HTTP header name/value map> # since 1.21
297 * e) Delete a file within storage
301 * 'src' => <storage path>,
302 * 'ignoreMissingSource' => <boolean>
306 * f) Update metadata for a file within storage
309 * 'op' => 'describe',
310 * 'src' => <storage path>,
311 * 'headers' => <HTTP header name/value map>
315 * g) Do nothing (no-op)
322 * Boolean flags for operations (operation-specific):
323 * - ignoreMissingSource : The operation will simply succeed and do
324 * nothing if the source file does not exist.
325 * - overwrite : Any destination file will be overwritten.
326 * - overwriteSame : If a file already exists at the destination with the
327 * same contents, then do nothing to the destination file
328 * instead of giving an error. This does not compare headers.
329 * This option is ignored if 'overwrite' is already provided.
330 * - headers : If supplied, the result of merging these headers with any
331 * existing source file headers (replacing conflicting ones)
332 * will be set as the destination file headers. Headers are
333 * deleted if their value is set to the empty string. When a
334 * file has headers they are included in responses to GET and
335 * HEAD requests to the backing store for that file.
336 * Header values should be no larger than 255 bytes, except for
337 * Content-Disposition. The system might ignore or truncate any
338 * headers that are too long to store (exact limits will vary).
339 * Backends that don't support metadata ignore this. (since 1.21)
341 * $opts is an associative of boolean flags, including:
342 * - force : Operation precondition errors no longer trigger an abort.
343 * Any remaining operations are still attempted. Unexpected
344 * failures may still cause remaining operations to be aborted.
345 * - nonLocking : No locks are acquired for the operations.
346 * This can increase performance for non-critical writes.
347 * This has no effect unless the 'force' flag is set.
348 * - nonJournaled : Don't log this operation batch in the file journal.
349 * This limits the ability of recovery scripts.
350 * - parallelize : Try to do operations in parallel when possible.
351 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
352 * - preserveCache : Don't clear the process cache before checking files.
353 * This should only be used if all entries in the process
354 * cache were added after the files were already locked. (since 1.20)
356 * @remarks Remarks on locking:
357 * File system paths given to operations should refer to files that are
358 * already locked or otherwise safe from modification from other processes.
359 * Normally these files will be new temp files, which should be adequate.
363 * This returns a Status, which contains all warnings and fatals that occurred
364 * during the operation. The 'failCount', 'successCount', and 'success' members
365 * will reflect each operation attempted.
367 * The StatusValue will be "OK" unless:
368 * - a) unexpected operation errors occurred (network partitions, disk full...)
369 * - b) significant operation errors occurred and 'force' was not set
371 * @param array $ops List of operations to execute in order
372 * @param array $opts Batch operation options
373 * @return StatusValue
375 final public function doOperations( array $ops, array $opts = [] ) {
376 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
377 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
379 if ( !count( $ops ) ) {
380 return $this->newStatus(); // nothing to do
383 $ops = $this->resolveFSFileObjects( $ops );
384 if ( empty( $opts['force'] ) ) { // sanity
385 unset( $opts['nonLocking'] );
388 /** @noinspection PhpUnusedLocalVariableInspection */
389 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
391 return $this->doOperationsInternal( $ops, $opts );
395 * @see FileBackend::doOperations()
399 abstract protected function doOperationsInternal( array $ops, array $opts );
402 * Same as doOperations() except it takes a single operation.
403 * If you are doing a batch of operations that should either
404 * all succeed or all fail, then use that function instead.
406 * @see FileBackend::doOperations()
408 * @param array $op Operation
409 * @param array $opts Operation options
410 * @return StatusValue
412 final public function doOperation( array $op, array $opts = [] ) {
413 return $this->doOperations( [ $op ], $opts );
417 * Performs a single create operation.
418 * This sets $params['op'] to 'create' and passes it to doOperation().
420 * @see FileBackend::doOperation()
422 * @param array $params Operation parameters
423 * @param array $opts Operation options
424 * @return StatusValue
426 final public function create( array $params, array $opts = [] ) {
427 return $this->doOperation( [ 'op' => 'create' ] +
$params, $opts );
431 * Performs a single store operation.
432 * This sets $params['op'] to 'store' and passes it to doOperation().
434 * @see FileBackend::doOperation()
436 * @param array $params Operation parameters
437 * @param array $opts Operation options
438 * @return StatusValue
440 final public function store( array $params, array $opts = [] ) {
441 return $this->doOperation( [ 'op' => 'store' ] +
$params, $opts );
445 * Performs a single copy operation.
446 * This sets $params['op'] to 'copy' and passes it to doOperation().
448 * @see FileBackend::doOperation()
450 * @param array $params Operation parameters
451 * @param array $opts Operation options
452 * @return StatusValue
454 final public function copy( array $params, array $opts = [] ) {
455 return $this->doOperation( [ 'op' => 'copy' ] +
$params, $opts );
459 * Performs a single move operation.
460 * This sets $params['op'] to 'move' and passes it to doOperation().
462 * @see FileBackend::doOperation()
464 * @param array $params Operation parameters
465 * @param array $opts Operation options
466 * @return StatusValue
468 final public function move( array $params, array $opts = [] ) {
469 return $this->doOperation( [ 'op' => 'move' ] +
$params, $opts );
473 * Performs a single delete operation.
474 * This sets $params['op'] to 'delete' and passes it to doOperation().
476 * @see FileBackend::doOperation()
478 * @param array $params Operation parameters
479 * @param array $opts Operation options
480 * @return StatusValue
482 final public function delete( array $params, array $opts = [] ) {
483 return $this->doOperation( [ 'op' => 'delete' ] +
$params, $opts );
487 * Performs a single describe operation.
488 * This sets $params['op'] to 'describe' and passes it to doOperation().
490 * @see FileBackend::doOperation()
492 * @param array $params Operation parameters
493 * @param array $opts Operation options
494 * @return StatusValue
497 final public function describe( array $params, array $opts = [] ) {
498 return $this->doOperation( [ 'op' => 'describe' ] +
$params, $opts );
502 * Perform a set of independent file operations on some files.
504 * This does no locking, nor journaling, and possibly no stat calls.
505 * Any destination files that already exist will be overwritten.
506 * This should *only* be used on non-original files, like cache files.
508 * Supported operations and their parameters:
514 * - describe (since 1.21)
517 * FSFile/TempFSFile object support was added in 1.27.
519 * a) Create a new file in storage with the contents of a string
523 * 'dst' => <storage path>,
524 * 'content' => <string of new file contents>,
525 * 'headers' => <HTTP header name/value map> # since 1.21
529 * b) Copy a file system file into storage
533 * 'src' => <file system path, FSFile, or TempFSFile>,
534 * 'dst' => <storage path>,
535 * 'headers' => <HTTP header name/value map> # since 1.21
539 * c) Copy a file within storage
543 * 'src' => <storage path>,
544 * 'dst' => <storage path>,
545 * 'ignoreMissingSource' => <boolean>, # since 1.21
546 * 'headers' => <HTTP header name/value map> # since 1.21
550 * d) Move a file within storage
554 * 'src' => <storage path>,
555 * 'dst' => <storage path>,
556 * 'ignoreMissingSource' => <boolean>, # since 1.21
557 * 'headers' => <HTTP header name/value map> # since 1.21
561 * e) Delete a file within storage
565 * 'src' => <storage path>,
566 * 'ignoreMissingSource' => <boolean>
570 * f) Update metadata for a file within storage
573 * 'op' => 'describe',
574 * 'src' => <storage path>,
575 * 'headers' => <HTTP header name/value map>
579 * g) Do nothing (no-op)
586 * @par Boolean flags for operations (operation-specific):
587 * - ignoreMissingSource : The operation will simply succeed and do
588 * nothing if the source file does not exist.
589 * - headers : If supplied with a header name/value map, the backend will
590 * reply with these headers when GETs/HEADs of the destination
591 * file are made. Header values should be smaller than 256 bytes.
592 * Content-Disposition headers can be longer, though the system
593 * might ignore or truncate ones that are too long to store.
594 * Existing headers will remain, but these will replace any
595 * conflicting previous headers, and headers will be removed
596 * if they are set to an empty string.
597 * Backends that don't support metadata ignore this. (since 1.21)
599 * $opts is an associative of boolean flags, including:
600 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
603 * This returns a Status, which contains all warnings and fatals that occurred
604 * during the operation. The 'failCount', 'successCount', and 'success' members
605 * will reflect each operation attempted for the given files. The StatusValue will be
606 * considered "OK" as long as no fatal errors occurred.
608 * @param array $ops Set of operations to execute
609 * @param array $opts Batch operation options
610 * @return StatusValue
613 final public function doQuickOperations( array $ops, array $opts = [] ) {
614 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
615 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
617 if ( !count( $ops ) ) {
618 return $this->newStatus(); // nothing to do
621 $ops = $this->resolveFSFileObjects( $ops );
622 foreach ( $ops as &$op ) {
623 $op['overwrite'] = true; // avoids RTTs in key/value stores
626 /** @noinspection PhpUnusedLocalVariableInspection */
627 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
629 return $this->doQuickOperationsInternal( $ops );
633 * @see FileBackend::doQuickOperations()
637 abstract protected function doQuickOperationsInternal( array $ops );
640 * Same as doQuickOperations() except it takes a single operation.
641 * If you are doing a batch of operations, then use that function instead.
643 * @see FileBackend::doQuickOperations()
645 * @param array $op Operation
646 * @return StatusValue
649 final public function doQuickOperation( array $op ) {
650 return $this->doQuickOperations( [ $op ] );
654 * Performs a single quick create operation.
655 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
657 * @see FileBackend::doQuickOperation()
659 * @param array $params Operation parameters
660 * @return StatusValue
663 final public function quickCreate( array $params ) {
664 return $this->doQuickOperation( [ 'op' => 'create' ] +
$params );
668 * Performs a single quick store operation.
669 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
671 * @see FileBackend::doQuickOperation()
673 * @param array $params Operation parameters
674 * @return StatusValue
677 final public function quickStore( array $params ) {
678 return $this->doQuickOperation( [ 'op' => 'store' ] +
$params );
682 * Performs a single quick copy operation.
683 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
685 * @see FileBackend::doQuickOperation()
687 * @param array $params Operation parameters
688 * @return StatusValue
691 final public function quickCopy( array $params ) {
692 return $this->doQuickOperation( [ 'op' => 'copy' ] +
$params );
696 * Performs a single quick move operation.
697 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
699 * @see FileBackend::doQuickOperation()
701 * @param array $params Operation parameters
702 * @return StatusValue
705 final public function quickMove( array $params ) {
706 return $this->doQuickOperation( [ 'op' => 'move' ] +
$params );
710 * Performs a single quick delete operation.
711 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
713 * @see FileBackend::doQuickOperation()
715 * @param array $params Operation parameters
716 * @return StatusValue
719 final public function quickDelete( array $params ) {
720 return $this->doQuickOperation( [ 'op' => 'delete' ] +
$params );
724 * Performs a single quick describe operation.
725 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
727 * @see FileBackend::doQuickOperation()
729 * @param array $params Operation parameters
730 * @return StatusValue
733 final public function quickDescribe( array $params ) {
734 return $this->doQuickOperation( [ 'op' => 'describe' ] +
$params );
738 * Concatenate a list of storage files into a single file system file.
739 * The target path should refer to a file that is already locked or
740 * otherwise safe from modification from other processes. Normally,
741 * the file will be a new temp file, which should be adequate.
743 * @param array $params Operation parameters, include:
744 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
745 * - dst : file system path to 0-byte temp file
746 * - parallelize : try to do operations in parallel when possible
747 * @return StatusValue
749 abstract public function concatenate( array $params );
752 * Prepare a storage directory for usage.
753 * This will create any required containers and parent directories.
754 * Backends using key/value stores only need to create the container.
756 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
757 * except they are only applied *if* the directory/container had to be created.
758 * These flags should always be set for directories that have private files.
759 * However, setting them is not guaranteed to actually do anything.
760 * Additional server configuration may be needed to achieve the desired effect.
762 * @param array $params Parameters include:
763 * - dir : storage directory
764 * - noAccess : try to deny file access (since 1.20)
765 * - noListing : try to deny file listing (since 1.20)
766 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
767 * @return StatusValue
769 final public function prepare( array $params ) {
770 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
771 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
773 /** @noinspection PhpUnusedLocalVariableInspection */
774 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
775 return $this->doPrepare( $params );
779 * @see FileBackend::prepare()
780 * @param array $params
782 abstract protected function doPrepare( array $params );
785 * Take measures to block web access to a storage directory and
786 * the container it belongs to. FS backends might add .htaccess
787 * files whereas key/value store backends might revoke container
788 * access to the storage user representing end-users in web requests.
790 * This is not guaranteed to actually make files or listings publically hidden.
791 * Additional server configuration may be needed to achieve the desired effect.
793 * @param array $params Parameters include:
794 * - dir : storage directory
795 * - noAccess : try to deny file access
796 * - noListing : try to deny file listing
797 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
798 * @return StatusValue
800 final public function secure( array $params ) {
801 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
802 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
804 /** @noinspection PhpUnusedLocalVariableInspection */
805 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
806 return $this->doSecure( $params );
810 * @see FileBackend::secure()
811 * @param array $params
813 abstract protected function doSecure( array $params );
816 * Remove measures to block web access to a storage directory and
817 * the container it belongs to. FS backends might remove .htaccess
818 * files whereas key/value store backends might grant container
819 * access to the storage user representing end-users in web requests.
820 * This essentially can undo the result of secure() calls.
822 * This is not guaranteed to actually make files or listings publically viewable.
823 * Additional server configuration may be needed to achieve the desired effect.
825 * @param array $params Parameters include:
826 * - dir : storage directory
827 * - access : try to allow file access
828 * - listing : try to allow file listing
829 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
830 * @return StatusValue
833 final public function publish( array $params ) {
834 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
835 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
837 /** @noinspection PhpUnusedLocalVariableInspection */
838 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
839 return $this->doPublish( $params );
843 * @see FileBackend::publish()
844 * @param array $params
846 abstract protected function doPublish( array $params );
849 * Delete a storage directory if it is empty.
850 * Backends using key/value stores may do nothing unless the directory
851 * is that of an empty container, in which case it will be deleted.
853 * @param array $params Parameters include:
854 * - dir : storage directory
855 * - recursive : recursively delete empty subdirectories first (since 1.20)
856 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
857 * @return StatusValue
859 final public function clean( array $params ) {
860 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
861 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
863 /** @noinspection PhpUnusedLocalVariableInspection */
864 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
865 return $this->doClean( $params );
869 * @see FileBackend::clean()
870 * @param array $params
872 abstract protected function doClean( array $params );
875 * Enter file operation scope.
876 * This just makes PHP ignore user aborts/disconnects until the return
877 * value leaves scope. This returns null and does nothing in CLI mode.
879 * @return ScopedCallback|null
881 final protected function getScopedPHPBehaviorForOps() {
882 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
883 $old = ignore_user_abort( true ); // avoid half-finished operations
884 return new ScopedCallback( function () use ( $old ) {
885 ignore_user_abort( $old );
893 * Check if a file exists at a storage path in the backend.
894 * This returns false if only a directory exists at the path.
896 * @param array $params Parameters include:
897 * - src : source storage path
898 * - latest : use the latest available data
899 * @return bool|null Returns null on failure
901 abstract public function fileExists( array $params );
904 * Get the last-modified timestamp of the file at a storage path.
906 * @param array $params Parameters include:
907 * - src : source storage path
908 * - latest : use the latest available data
909 * @return string|bool TS_MW timestamp or false on failure
911 abstract public function getFileTimestamp( array $params );
914 * Get the contents of a file at a storage path in the backend.
915 * This should be avoided for potentially large files.
917 * @param array $params Parameters include:
918 * - src : source storage path
919 * - latest : use the latest available data
920 * @return string|bool Returns false on failure
922 final public function getFileContents( array $params ) {
923 $contents = $this->getFileContentsMulti(
924 [ 'srcs' => [ $params['src'] ] ] +
$params );
926 return $contents[$params['src']];
930 * Like getFileContents() except it takes an array of storage paths
931 * and returns a map of storage paths to strings (or null on failure).
932 * The map keys (paths) are in the same order as the provided list of paths.
934 * @see FileBackend::getFileContents()
936 * @param array $params Parameters include:
937 * - srcs : list of source storage paths
938 * - latest : use the latest available data
939 * - parallelize : try to do operations in parallel when possible
940 * @return array Map of (path name => string or false on failure)
943 abstract public function getFileContentsMulti( array $params );
946 * Get metadata about a file at a storage path in the backend.
947 * If the file does not exist, then this returns false.
948 * Otherwise, the result is an associative array that includes:
949 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
950 * - metadata : map of file metadata (name => value)
951 * Metadata keys and headers names will be returned in all lower-case.
952 * Additional values may be included for internal use only.
954 * Use FileBackend::hasFeatures() to check how well this is supported.
956 * @param array $params
958 * - src : source storage path
959 * - latest : use the latest available data
960 * @return array|bool Returns false on failure
963 abstract public function getFileXAttributes( array $params );
966 * Get the size (bytes) of a file at a storage path in the backend.
968 * @param array $params Parameters include:
969 * - src : source storage path
970 * - latest : use the latest available data
971 * @return int|bool Returns false on failure
973 abstract public function getFileSize( array $params );
976 * Get quick information about a file at a storage path in the backend.
977 * If the file does not exist, then this returns false.
978 * Otherwise, the result is an associative array that includes:
979 * - mtime : the last-modified timestamp (TS_MW)
980 * - size : the file size (bytes)
981 * Additional values may be included for internal use only.
983 * @param array $params Parameters include:
984 * - src : source storage path
985 * - latest : use the latest available data
986 * @return array|bool|null Returns null on failure
988 abstract public function getFileStat( array $params );
991 * Get a SHA-1 hash of the file at a storage path in the backend.
993 * @param array $params Parameters include:
994 * - src : source storage path
995 * - latest : use the latest available data
996 * @return string|bool Hash string or false on failure
998 abstract public function getFileSha1Base36( array $params );
1001 * Get the properties of the file at a storage path in the backend.
1002 * This gives the result of FSFile::getProps() on a local copy of the file.
1004 * @param array $params Parameters include:
1005 * - src : source storage path
1006 * - latest : use the latest available data
1007 * @return array Returns FSFile::placeholderProps() on failure
1009 abstract public function getFileProps( array $params );
1012 * Stream the file at a storage path in the backend.
1014 * If the file does not exists, an HTTP 404 error will be given.
1015 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1016 * will be sent if streaming began, while none will be sent otherwise.
1017 * Implementations should flush the output buffer before sending data.
1019 * @param array $params Parameters include:
1020 * - src : source storage path
1021 * - headers : list of additional HTTP headers to send if the file exists
1022 * - options : HTTP request header map with lower case keys (since 1.28). Supports:
1023 * range : format is "bytes=(\d*-\d*)"
1024 * if-modified-since : format is an HTTP date
1025 * - headless : only include the body (and headers from "headers") (since 1.28)
1026 * - latest : use the latest available data
1027 * - allowOB : preserve any output buffers (since 1.28)
1028 * @return StatusValue
1030 abstract public function streamFile( array $params );
1033 * Returns a file system file, identical to the file at a storage path.
1034 * The file returned is either:
1035 * - a) A local copy of the file at a storage path in the backend.
1036 * The temporary copy will have the same extension as the source.
1037 * - b) An original of the file at a storage path in the backend.
1038 * Temporary files may be purged when the file object falls out of scope.
1040 * Write operations should *never* be done on this file as some backends
1041 * may do internal tracking or may be instances of FileBackendMultiWrite.
1042 * In that latter case, there are copies of the file that must stay in sync.
1043 * Additionally, further calls to this function may return the same file.
1045 * @param array $params Parameters include:
1046 * - src : source storage path
1047 * - latest : use the latest available data
1048 * @return FSFile|null Returns null on failure
1050 final public function getLocalReference( array $params ) {
1051 $fsFiles = $this->getLocalReferenceMulti(
1052 [ 'srcs' => [ $params['src'] ] ] +
$params );
1054 return $fsFiles[$params['src']];
1058 * Like getLocalReference() except it takes an array of storage paths
1059 * and returns a map of storage paths to FSFile objects (or null on failure).
1060 * The map keys (paths) are in the same order as the provided list of paths.
1062 * @see FileBackend::getLocalReference()
1064 * @param array $params Parameters include:
1065 * - srcs : list of source storage paths
1066 * - latest : use the latest available data
1067 * - parallelize : try to do operations in parallel when possible
1068 * @return array Map of (path name => FSFile or null on failure)
1071 abstract public function getLocalReferenceMulti( array $params );
1074 * Get a local copy on disk of the file at a storage path in the backend.
1075 * The temporary copy will have the same file extension as the source.
1076 * Temporary files may be purged when the file object falls out of scope.
1078 * @param array $params Parameters include:
1079 * - src : source storage path
1080 * - latest : use the latest available data
1081 * @return TempFSFile|null Returns null on failure
1083 final public function getLocalCopy( array $params ) {
1084 $tmpFiles = $this->getLocalCopyMulti(
1085 [ 'srcs' => [ $params['src'] ] ] +
$params );
1087 return $tmpFiles[$params['src']];
1091 * Like getLocalCopy() except it takes an array of storage paths and
1092 * returns a map of storage paths to TempFSFile objects (or null on failure).
1093 * The map keys (paths) are in the same order as the provided list of paths.
1095 * @see FileBackend::getLocalCopy()
1097 * @param array $params Parameters include:
1098 * - srcs : list of source storage paths
1099 * - latest : use the latest available data
1100 * - parallelize : try to do operations in parallel when possible
1101 * @return array Map of (path name => TempFSFile or null on failure)
1104 abstract public function getLocalCopyMulti( array $params );
1107 * Return an HTTP URL to a given file that requires no authentication to use.
1108 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1109 * This will return null if the backend cannot make an HTTP URL for the file.
1111 * This is useful for key/value stores when using scripts that seek around
1112 * large files and those scripts (and the backend) support HTTP Range headers.
1113 * Otherwise, one would need to use getLocalReference(), which involves loading
1114 * the entire file on to local disk.
1116 * @param array $params Parameters include:
1117 * - src : source storage path
1118 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1119 * @return string|null
1122 abstract public function getFileHttpUrl( array $params );
1125 * Check if a directory exists at a given storage path.
1126 * Backends using key/value stores will check if the path is a
1127 * virtual directory, meaning there are files under the given directory.
1129 * Storage backends with eventual consistency might return stale data.
1131 * @param array $params Parameters include:
1132 * - dir : storage directory
1133 * @return bool|null Returns null on failure
1136 abstract public function directoryExists( array $params );
1139 * Get an iterator to list *all* directories under a storage directory.
1140 * If the directory is of the form "mwstore://backend/container",
1141 * then all directories in the container will be listed.
1142 * If the directory is of form "mwstore://backend/container/dir",
1143 * then all directories directly under that directory will be listed.
1144 * Results will be storage directories relative to the given directory.
1146 * Storage backends with eventual consistency might return stale data.
1148 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1150 * @param array $params Parameters include:
1151 * - dir : storage directory
1152 * - topOnly : only return direct child dirs of the directory
1153 * @return Traversable|array|null Returns null on failure
1156 abstract public function getDirectoryList( array $params );
1159 * Same as FileBackend::getDirectoryList() except only lists
1160 * directories that are immediately under the given directory.
1162 * Storage backends with eventual consistency might return stale data.
1164 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1166 * @param array $params Parameters include:
1167 * - dir : storage directory
1168 * @return Traversable|array|null Returns null on failure
1171 final public function getTopDirectoryList( array $params ) {
1172 return $this->getDirectoryList( [ 'topOnly' => true ] +
$params );
1176 * Get an iterator to list *all* stored files under a storage directory.
1177 * If the directory is of the form "mwstore://backend/container",
1178 * then all files in the container will be listed.
1179 * If the directory is of form "mwstore://backend/container/dir",
1180 * then all files under that directory will be listed.
1181 * Results will be storage paths relative to the given directory.
1183 * Storage backends with eventual consistency might return stale data.
1185 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1187 * @param array $params Parameters include:
1188 * - dir : storage directory
1189 * - topOnly : only return direct child files of the directory (since 1.20)
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
1193 abstract public function getFileList( array $params );
1196 * Same as FileBackend::getFileList() except only lists
1197 * files that are immediately under the given directory.
1199 * Storage backends with eventual consistency might return stale data.
1201 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1203 * @param array $params Parameters include:
1204 * - dir : storage directory
1205 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1206 * @return Traversable|array|null Returns null on failure
1209 final public function getTopFileList( array $params ) {
1210 return $this->getFileList( [ 'topOnly' => true ] +
$params );
1214 * Preload persistent file stat cache and property cache into in-process cache.
1215 * This should be used when stat calls will be made on a known list of a many files.
1217 * @see FileBackend::getFileStat()
1219 * @param array $paths Storage paths
1221 abstract public function preloadCache( array $paths );
1224 * Invalidate any in-process file stat and property cache.
1225 * If $paths is given, then only the cache for those files will be cleared.
1227 * @see FileBackend::getFileStat()
1229 * @param array $paths Storage paths (optional)
1231 abstract public function clearCache( array $paths = null );
1234 * Preload file stat information (concurrently if possible) into in-process cache.
1236 * This should be used when stat calls will be made on a known list of a many files.
1237 * This does not make use of the persistent file stat cache.
1239 * @see FileBackend::getFileStat()
1241 * @param array $params Parameters include:
1242 * - srcs : list of source storage paths
1243 * - latest : use the latest available data
1244 * @return bool All requests proceeded without I/O errors (since 1.24)
1247 abstract public function preloadFileStat( array $params );
1250 * Lock the files at the given storage paths in the backend.
1251 * This will either lock all the files or none (on failure).
1253 * Callers should consider using getScopedFileLocks() instead.
1255 * @param array $paths Storage paths
1256 * @param int $type LockManager::LOCK_* constant
1257 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1258 * @return StatusValue
1260 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1261 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1263 return $this->lockManager
->lock( $paths, $type, $timeout );
1267 * Unlock the files at the given storage paths in the backend.
1269 * @param array $paths Storage paths
1270 * @param int $type LockManager::LOCK_* constant
1271 * @return StatusValue
1273 final public function unlockFiles( array $paths, $type ) {
1274 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1276 return $this->lockManager
->unlock( $paths, $type );
1280 * Lock the files at the given storage paths in the backend.
1281 * This will either lock all the files or none (on failure).
1282 * On failure, the StatusValue object will be updated with errors.
1284 * Once the return value goes out scope, the locks will be released and
1285 * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
1287 * @see ScopedLock::factory()
1289 * @param array $paths List of storage paths or map of lock types to path lists
1290 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1291 * @param StatusValue $status StatusValue to update on lock/unlock
1292 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1293 * @return ScopedLock|null Returns null on failure
1295 final public function getScopedFileLocks(
1296 array $paths, $type, StatusValue
$status, $timeout = 0
1298 if ( $type === 'mixed' ) {
1299 foreach ( $paths as &$typePaths ) {
1300 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1303 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1306 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status, $timeout );
1310 * Get an array of scoped locks needed for a batch of file operations.
1312 * Normally, FileBackend::doOperations() handles locking, unless
1313 * the 'nonLocking' param is passed in. This function is useful if you
1314 * want the files to be locked for a broader scope than just when the
1315 * files are changing. For example, if you need to update DB metadata,
1316 * you may want to keep the files locked until finished.
1318 * @see FileBackend::doOperations()
1320 * @param array $ops List of file operations to FileBackend::doOperations()
1321 * @param StatusValue $status StatusValue to update on lock/unlock
1322 * @return ScopedLock|null
1325 abstract public function getScopedLocksForOps( array $ops, StatusValue
$status );
1328 * Get the root storage path of this backend.
1329 * All container paths are "subdirectories" of this path.
1331 * @return string Storage path
1334 final public function getRootStoragePath() {
1335 return "mwstore://{$this->name}";
1339 * Get the storage path for the given container for this backend
1341 * @param string $container Container name
1342 * @return string Storage path
1345 final public function getContainerStoragePath( $container ) {
1346 return $this->getRootStoragePath() . "/{$container}";
1350 * Get the file journal object for this backend
1352 * @return FileJournal
1354 final public function getJournal() {
1355 return $this->fileJournal
;
1359 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1361 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1362 * around as long it needs (which may vary greatly depending on configuration)
1364 * @param array $ops File operation batch for FileBaclend::doOperations()
1365 * @return array File operation batch
1367 protected function resolveFSFileObjects( array $ops ) {
1368 foreach ( $ops as &$op ) {
1369 $src = isset( $op['src'] ) ?
$op['src'] : null;
1370 if ( $src instanceof FSFile
) {
1371 $op['srcRef'] = $src;
1372 $op['src'] = $src->getPath();
1381 * Check if a given path is a "mwstore://" path.
1382 * This does not do any further validation or any existence checks.
1384 * @param string $path
1387 final public static function isStoragePath( $path ) {
1388 return ( strpos( $path, 'mwstore://' ) === 0 );
1392 * Split a storage path into a backend name, a container name,
1393 * and a relative file path. The relative path may be the empty string.
1394 * This does not do any path normalization or traversal checks.
1396 * @param string $storagePath
1397 * @return array (backend, container, rel object) or (null, null, null)
1399 final public static function splitStoragePath( $storagePath ) {
1400 if ( self
::isStoragePath( $storagePath ) ) {
1401 // Remove the "mwstore://" prefix and split the path
1402 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1403 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1404 if ( count( $parts ) == 3 ) {
1405 return $parts; // e.g. "backend/container/path"
1407 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1412 return [ null, null, null ];
1416 * Normalize a storage path by cleaning up directory separators.
1417 * Returns null if the path is not of the format of a valid storage path.
1419 * @param string $storagePath
1420 * @return string|null
1422 final public static function normalizeStoragePath( $storagePath ) {
1423 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1424 if ( $relPath !== null ) { // must be for this backend
1425 $relPath = self
::normalizeContainerPath( $relPath );
1426 if ( $relPath !== null ) {
1427 return ( $relPath != '' )
1428 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1429 : "mwstore://{$backend}/{$container}";
1437 * Get the parent storage directory of a storage path.
1438 * This returns a path like "mwstore://backend/container",
1439 * "mwstore://backend/container/...", or null if there is no parent.
1441 * @param string $storagePath
1442 * @return string|null
1444 final public static function parentStoragePath( $storagePath ) {
1445 $storagePath = dirname( $storagePath );
1446 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1448 return ( $rel === null ) ?
null : $storagePath;
1452 * Get the final extension from a storage or FS path
1454 * @param string $path
1455 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1458 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1459 $i = strrpos( $path, '.' );
1460 $ext = $i ?
substr( $path, $i +
1 ) : '';
1462 if ( $case === 'lowercase' ) {
1463 $ext = strtolower( $ext );
1464 } elseif ( $case === 'uppercase' ) {
1465 $ext = strtoupper( $ext );
1472 * Check if a relative path has no directory traversals
1474 * @param string $path
1478 final public static function isPathTraversalFree( $path ) {
1479 return ( self
::normalizeContainerPath( $path ) !== null );
1483 * Build a Content-Disposition header value per RFC 6266.
1485 * @param string $type One of (attachment, inline)
1486 * @param string $filename Suggested file name (should not contain slashes)
1487 * @throws FileBackendError
1491 final public static function makeContentDisposition( $type, $filename = '' ) {
1494 $type = strtolower( $type );
1495 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1496 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1500 if ( strlen( $filename ) ) {
1501 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1504 return implode( ';', $parts );
1508 * Validate and normalize a relative storage path.
1509 * Null is returned if the path involves directory traversal.
1510 * Traversal is insecure for FS backends and broken for others.
1512 * This uses the same traversal protection as Title::secureAndSplit().
1514 * @param string $path Storage path relative to a container
1515 * @return string|null
1517 final protected static function normalizeContainerPath( $path ) {
1518 // Normalize directory separators
1519 $path = strtr( $path, '\\', '/' );
1520 // Collapse any consecutive directory separators
1521 $path = preg_replace( '![/]{2,}!', '/', $path );
1522 // Remove any leading directory separator
1523 $path = ltrim( $path, '/' );
1524 // Use the same traversal protection as Title::secureAndSplit()
1525 if ( strpos( $path, '.' ) !== false ) {
1529 strpos( $path, './' ) === 0 ||
1530 strpos( $path, '../' ) === 0 ||
1531 strpos( $path, '/./' ) !== false ||
1532 strpos( $path, '/../' ) !== false
1542 * Yields the result of the status wrapper callback on either:
1543 * - StatusValue::newGood() if this method is called without parameters
1544 * - StatusValue::newFatal() with all parameters to this method if passed in
1547 * @return StatusValue
1549 final protected function newStatus() {
1550 $args = func_get_args();
1551 if ( count( $args ) ) {
1552 $sv = call_user_func_array( [ 'StatusValue', 'newFatal' ], $args );
1554 $sv = StatusValue
::newGood();
1557 return $this->wrapStatus( $sv );
1561 * @param StatusValue $sv
1562 * @return StatusValue Modified status or StatusValue subclass
1564 final protected function wrapStatus( StatusValue
$sv ) {
1565 return $this->statusWrapper ?
call_user_func( $this->statusWrapper
, $sv ) : $sv;
1570 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1572 * @ingroup FileBackend
1575 class FileBackendException
extends Exception
{
1579 * File backend exception for checked exceptions (e.g. I/O errors)
1581 * @ingroup FileBackend
1584 class FileBackendError
extends FileBackendException
{