3 * @defgroup FileBackend File backend
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
11 * Base class for all file backends.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
29 * @ingroup FileBackend
30 * @author Aaron Schulz
34 * @brief Base class for all file backend classes (including multi-write backends).
36 * This class defines the methods as abstract that subclasses must implement.
37 * Outside callers can assume that all backends will have these functions.
39 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
40 * The "<path>" portion is a relative path that uses UNIX file system (FS)
41 * notation, though any particular backend may not actually be using a local
42 * filesystem. Therefore, the relative paths are only virtual.
44 * Backend contents are stored under wiki-specific container names by default.
45 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
46 * segregation must be done by setting the container paths appropriately.
48 * FS-based backends are somewhat more restrictive due to the existence of real
49 * directory files; a regular file cannot have the same name as a directory. Other
50 * backends with virtual directories may not have this limitation. Callers should
51 * store files in such a way that no files and directories are under the same path.
53 * Methods of subclasses should avoid throwing exceptions at all costs.
54 * As a corollary, external dependencies should be kept to a minimum.
56 * @ingroup FileBackend
59 abstract class FileBackend
{
60 protected $name; // string; unique backend name
61 protected $wikiId; // string; unique wiki name
62 protected $readOnly; // string; read-only explanation message
63 protected $parallelize; // string; when to do operations in parallel
64 protected $concurrency; // integer; how many operations can be done in parallel
66 /** @var LockManager */
67 protected $lockManager;
68 /** @var FileJournal */
69 protected $fileJournal;
72 * Create a new backend instance from configuration.
73 * This should only be called from within FileBackendGroup.
76 * - name : The unique name of this backend.
77 * This should consist of alphanumberic, '-', and '_' characters.
78 * This name should not be changed after use.
79 * - wikiId : Prefix to container names that is unique to this wiki.
80 * It should only consist of alphanumberic, '-', and '_' characters.
81 * - lockManager : Registered name of a file lock manager to use.
82 * - fileJournal : File journal configuration; see FileJournal::factory().
83 * Journals simply log changes to files stored in the backend.
84 * - readOnly : Write operations are disallowed if this is a non-empty string.
85 * It should be an explanation for the backend being read-only.
86 * - parallelize : When to do file operations in parallel (when possible).
87 * Allowed values are "implicit", "explicit" and "off".
88 * - concurrency : How many file operations can be done in parallel.
90 * @param $config Array
93 public function __construct( array $config ) {
94 $this->name
= $config['name'];
95 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
96 throw new MWException( "Backend name `{$this->name}` is invalid." );
98 $this->wikiId
= isset( $config['wikiId'] )
100 : wfWikiID(); // e.g. "my_wiki-en_"
101 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
102 ?
$config['lockManager']
103 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
104 $this->fileJournal
= isset( $config['fileJournal'] )
105 ?
( ( $config['fileJournal'] instanceof FileJournal
)
106 ?
$config['fileJournal']
107 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
108 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
109 $this->readOnly
= isset( $config['readOnly'] )
110 ?
(string)$config['readOnly']
112 $this->parallelize
= isset( $config['parallelize'] )
113 ?
(string)$config['parallelize']
115 $this->concurrency
= isset( $config['concurrency'] )
116 ?
(int)$config['concurrency']
121 * Get the unique backend name.
122 * We may have multiple different backends of the same type.
123 * For example, we can have two Swift backends using different proxies.
127 final public function getName() {
132 * Check if this backend is read-only
136 final public function isReadOnly() {
137 return ( $this->readOnly
!= '' );
141 * Get an explanatory message if this backend is read-only
143 * @return string|bool Returns false if the backend is not read-only
145 final public function getReadOnlyReason() {
146 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
150 * This is the main entry point into the backend for write operations.
151 * Callers supply an ordered list of operations to perform as a transaction.
152 * Files will be locked, the stat cache cleared, and then the operations attempted.
153 * If any serious errors occur, all attempted operations will be rolled back.
155 * $ops is an array of arrays. The outer array holds a list of operations.
156 * Each inner array is a set of key value pairs that specify an operation.
158 * Supported operations and their parameters. The supported actions are:
166 * a) Create a new file in storage with the contents of a string
170 * 'dst' => <storage path>,
171 * 'content' => <string of new file contents>,
172 * 'overwrite' => <boolean>,
173 * 'overwriteSame' => <boolean>,
174 * 'disposition' => <Content-Disposition header value>
178 * b) Copy a file system file into storage
182 * 'src' => <file system path>,
183 * 'dst' => <storage path>,
184 * 'overwrite' => <boolean>,
185 * 'overwriteSame' => <boolean>,
186 * 'disposition' => <Content-Disposition header value>
190 * c) Copy a file within storage
194 * 'src' => <storage path>,
195 * 'dst' => <storage path>,
196 * 'overwrite' => <boolean>,
197 * 'overwriteSame' => <boolean>,
198 * 'disposition' => <Content-Disposition header value>
202 * d) Move a file within storage
206 * 'src' => <storage path>,
207 * 'dst' => <storage path>,
208 * 'overwrite' => <boolean>,
209 * 'overwriteSame' => <boolean>,
210 * 'disposition' => <Content-Disposition header value>
214 * e) Delete a file within storage
218 * 'src' => <storage path>,
219 * 'ignoreMissingSource' => <boolean>
223 * f) Do nothing (no-op)
230 * Boolean flags for operations (operation-specific):
231 * - ignoreMissingSource : The operation will simply succeed and do
232 * nothing if the source file does not exist.
233 * - overwrite : Any destination file will be overwritten.
234 * - overwriteSame : An error will not be given if a file already
235 * exists at the destination that has the same
236 * contents as the new contents to be written there.
237 * - disposition : When supplied, the backend will add a Content-Disposition
238 * header when GETs/HEADs of the destination file are made.
239 * Backends that don't support file metadata will ignore this.
240 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
242 * $opts is an associative of boolean flags, including:
243 * - force : Operation precondition errors no longer trigger an abort.
244 * Any remaining operations are still attempted. Unexpected
245 * failures may still cause remaning operations to be aborted.
246 * - nonLocking : No locks are acquired for the operations.
247 * This can increase performance for non-critical writes.
248 * This has no effect unless the 'force' flag is set.
249 * - allowStale : Don't require the latest available data.
250 * This can increase performance for non-critical writes.
251 * This has no effect unless the 'force' flag is set.
252 * - nonJournaled : Don't log this operation batch in the file journal.
253 * This limits the ability of recovery scripts.
254 * - parallelize : Try to do operations in parallel when possible.
255 * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
256 * - preserveCache : Don't clear the process cache before checking files.
257 * This should only be used if all entries in the process
258 * cache were added after the files were already locked (since 1.20).
260 * @remarks Remarks on locking:
261 * File system paths given to operations should refer to files that are
262 * already locked or otherwise safe from modification from other processes.
263 * Normally these files will be new temp files, which should be adequate.
267 * This returns a Status, which contains all warnings and fatals that occurred
268 * during the operation. The 'failCount', 'successCount', and 'success' members
269 * will reflect each operation attempted.
271 * The status will be "OK" unless:
272 * - a) unexpected operation errors occurred (network partitions, disk full...)
273 * - b) significant operation errors occurred and 'force' was not set
275 * @param $ops Array List of operations to execute in order
276 * @param $opts Array Batch operation options
279 final public function doOperations( array $ops, array $opts = array() ) {
280 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
281 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
283 if ( empty( $opts['force'] ) ) { // sanity
284 unset( $opts['nonLocking'] );
285 unset( $opts['allowStale'] );
287 return $this->doOperationsInternal( $ops, $opts );
291 * @see FileBackend::doOperations()
293 abstract protected function doOperationsInternal( array $ops, array $opts );
296 * Same as doOperations() except it takes a single operation.
297 * If you are doing a batch of operations that should either
298 * all succeed or all fail, then use that function instead.
300 * @see FileBackend::doOperations()
302 * @param $op Array Operation
303 * @param $opts Array Operation options
306 final public function doOperation( array $op, array $opts = array() ) {
307 return $this->doOperations( array( $op ), $opts );
311 * Performs a single create operation.
312 * This sets $params['op'] to 'create' and passes it to doOperation().
314 * @see FileBackend::doOperation()
316 * @param $params Array Operation parameters
317 * @param $opts Array Operation options
320 final public function create( array $params, array $opts = array() ) {
321 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
325 * Performs a single store operation.
326 * This sets $params['op'] to 'store' and passes it to doOperation().
328 * @see FileBackend::doOperation()
330 * @param $params Array Operation parameters
331 * @param $opts Array Operation options
334 final public function store( array $params, array $opts = array() ) {
335 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
339 * Performs a single copy operation.
340 * This sets $params['op'] to 'copy' and passes it to doOperation().
342 * @see FileBackend::doOperation()
344 * @param $params Array Operation parameters
345 * @param $opts Array Operation options
348 final public function copy( array $params, array $opts = array() ) {
349 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
353 * Performs a single move operation.
354 * This sets $params['op'] to 'move' and passes it to doOperation().
356 * @see FileBackend::doOperation()
358 * @param $params Array Operation parameters
359 * @param $opts Array Operation options
362 final public function move( array $params, array $opts = array() ) {
363 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
367 * Performs a single delete operation.
368 * This sets $params['op'] to 'delete' and passes it to doOperation().
370 * @see FileBackend::doOperation()
372 * @param $params Array Operation parameters
373 * @param $opts Array Operation options
376 final public function delete( array $params, array $opts = array() ) {
377 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
381 * Perform a set of independent file operations on some files.
383 * This does no locking, nor journaling, and possibly no stat calls.
384 * Any destination files that already exist will be overwritten.
385 * This should *only* be used on non-original files, like cache files.
387 * Supported operations and their parameters:
395 * a) Create a new file in storage with the contents of a string
399 * 'dst' => <storage path>,
400 * 'content' => <string of new file contents>,
401 * 'disposition' => <Content-Disposition header value>
404 * b) Copy a file system file into storage
408 * 'src' => <file system path>,
409 * 'dst' => <storage path>,
410 * 'disposition' => <Content-Disposition header value>
413 * c) Copy a file within storage
417 * 'src' => <storage path>,
418 * 'dst' => <storage path>,
419 * 'disposition' => <Content-Disposition header value>
422 * d) Move a file within storage
426 * 'src' => <storage path>,
427 * 'dst' => <storage path>,
428 * 'disposition' => <Content-Disposition header value>
431 * e) Delete a file within storage
435 * 'src' => <storage path>,
436 * 'ignoreMissingSource' => <boolean>
439 * f) Do nothing (no-op)
446 * @par Boolean flags for operations (operation-specific):
447 * - ignoreMissingSource : The operation will simply succeed and do
448 * nothing if the source file does not exist.
449 * - disposition : When supplied, the backend will add a Content-Disposition
450 * header when GETs/HEADs of the destination file are made.
451 * Backends that don't support file metadata will ignore this.
452 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
454 * $opts is an associative of boolean flags, including:
455 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
458 * This returns a Status, which contains all warnings and fatals that occurred
459 * during the operation. The 'failCount', 'successCount', and 'success' members
460 * will reflect each operation attempted for the given files. The status will be
461 * considered "OK" as long as no fatal errors occurred.
463 * @param $ops Array Set of operations to execute
464 * @param $opts Array Batch operation options
468 final public function doQuickOperations( array $ops, array $opts = array() ) {
469 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
470 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
472 foreach ( $ops as &$op ) {
473 $op['overwrite'] = true; // avoids RTTs in key/value stores
475 return $this->doQuickOperationsInternal( $ops );
479 * @see FileBackend::doQuickOperations()
482 abstract protected function doQuickOperationsInternal( array $ops );
485 * Same as doQuickOperations() except it takes a single operation.
486 * If you are doing a batch of operations, then use that function instead.
488 * @see FileBackend::doQuickOperations()
490 * @param $op Array Operation
494 final public function doQuickOperation( array $op ) {
495 return $this->doQuickOperations( array( $op ) );
499 * Performs a single quick create operation.
500 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
502 * @see FileBackend::doQuickOperation()
504 * @param $params Array Operation parameters
508 final public function quickCreate( array $params ) {
509 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
513 * Performs a single quick store operation.
514 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
516 * @see FileBackend::doQuickOperation()
518 * @param $params Array Operation parameters
522 final public function quickStore( array $params ) {
523 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
527 * Performs a single quick copy operation.
528 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
530 * @see FileBackend::doQuickOperation()
532 * @param $params Array Operation parameters
536 final public function quickCopy( array $params ) {
537 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
541 * Performs a single quick move operation.
542 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
544 * @see FileBackend::doQuickOperation()
546 * @param $params Array Operation parameters
550 final public function quickMove( array $params ) {
551 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
555 * Performs a single quick delete operation.
556 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
558 * @see FileBackend::doQuickOperation()
560 * @param $params Array Operation parameters
564 final public function quickDelete( array $params ) {
565 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
569 * Concatenate a list of storage files into a single file system file.
570 * The target path should refer to a file that is already locked or
571 * otherwise safe from modification from other processes. Normally,
572 * the file will be a new temp file, which should be adequate.
574 * @param $params Array Operation parameters
576 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
577 * - dst : file system path to 0-byte temp file
578 * - parallelize : try to do operations in parallel when possible
581 abstract public function concatenate( array $params );
584 * Prepare a storage directory for usage.
585 * This will create any required containers and parent directories.
586 * Backends using key/value stores only need to create the container.
588 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
589 * except they are only applied *if* the directory/container had to be created.
590 * These flags should always be set for directories that have private files.
592 * @param $params Array
594 * - dir : storage directory
595 * - noAccess : try to deny file access (since 1.20)
596 * - noListing : try to deny file listing (since 1.20)
597 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
600 final public function prepare( array $params ) {
601 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
602 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
604 return $this->doPrepare( $params );
608 * @see FileBackend::prepare()
610 abstract protected function doPrepare( array $params );
613 * Take measures to block web access to a storage directory and
614 * the container it belongs to. FS backends might add .htaccess
615 * files whereas key/value store backends might revoke container
616 * access to the storage user representing end-users in web requests.
617 * This is not guaranteed to actually do anything.
619 * @param $params Array
621 * - dir : storage directory
622 * - noAccess : try to deny file access
623 * - noListing : try to deny file listing
624 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
627 final public function secure( array $params ) {
628 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
629 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
631 return $this->doSecure( $params );
635 * @see FileBackend::secure()
637 abstract protected function doSecure( array $params );
640 * Remove measures to block web access to a storage directory and
641 * the container it belongs to. FS backends might remove .htaccess
642 * files whereas key/value store backends might grant container
643 * access to the storage user representing end-users in web requests.
644 * This essentially can undo the result of secure() calls.
646 * @param $params Array
648 * - dir : storage directory
649 * - access : try to allow file access
650 * - listing : try to allow file listing
651 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
655 final public function publish( array $params ) {
656 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
657 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
659 return $this->doPublish( $params );
663 * @see FileBackend::publish()
665 abstract protected function doPublish( array $params );
668 * Delete a storage directory if it is empty.
669 * Backends using key/value stores may do nothing unless the directory
670 * is that of an empty container, in which case it will be deleted.
672 * @param $params Array
674 * - dir : storage directory
675 * - recursive : recursively delete empty subdirectories first (since 1.20)
676 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
679 final public function clean( array $params ) {
680 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
681 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
683 return $this->doClean( $params );
687 * @see FileBackend::clean()
689 abstract protected function doClean( array $params );
692 * Check if a file exists at a storage path in the backend.
693 * This returns false if only a directory exists at the path.
695 * @param $params Array
697 * - src : source storage path
698 * - latest : use the latest available data
699 * @return bool|null Returns null on failure
701 abstract public function fileExists( array $params );
704 * Get the last-modified timestamp of the file at a storage path.
706 * @param $params Array
708 * - src : source storage path
709 * - latest : use the latest available data
710 * @return string|bool TS_MW timestamp or false on failure
712 abstract public function getFileTimestamp( array $params );
715 * Get the contents of a file at a storage path in the backend.
716 * This should be avoided for potentially large files.
718 * @param $params Array
720 * - src : source storage path
721 * - latest : use the latest available data
722 * @return string|bool Returns false on failure
724 final public function getFileContents( array $params ) {
725 $contents = $this->getFileContentsMulti(
726 array( 'srcs' => array( $params['src'] ) ) +
$params );
728 return $contents[$params['src']];
732 * Like getFileContents() except it takes an array of storage paths
733 * and returns a map of storage paths to strings (or null on failure).
734 * The map keys (paths) are in the same order as the provided list of paths.
736 * @see FileBackend::getFileContents()
738 * @param $params Array
740 * - srcs : list of source storage paths
741 * - latest : use the latest available data
742 * - parallelize : try to do operations in parallel when possible
743 * @return Array Map of (path name => string or false on failure)
746 abstract public function getFileContentsMulti( array $params );
749 * Get the size (bytes) of a file at a storage path in the backend.
751 * @param $params Array
753 * - src : source storage path
754 * - latest : use the latest available data
755 * @return integer|bool Returns false on failure
757 abstract public function getFileSize( array $params );
760 * Get quick information about a file at a storage path in the backend.
761 * If the file does not exist, then this returns false.
762 * Otherwise, the result is an associative array that includes:
763 * - mtime : the last-modified timestamp (TS_MW)
764 * - size : the file size (bytes)
765 * Additional values may be included for internal use only.
767 * @param $params Array
769 * - src : source storage path
770 * - latest : use the latest available data
771 * @return Array|bool|null Returns null on failure
773 abstract public function getFileStat( array $params );
776 * Get a SHA-1 hash of the file at a storage path in the backend.
778 * @param $params Array
780 * - src : source storage path
781 * - latest : use the latest available data
782 * @return string|bool Hash string or false on failure
784 abstract public function getFileSha1Base36( array $params );
787 * Get the properties of the file at a storage path in the backend.
788 * Returns FSFile::placeholderProps() on failure.
790 * @param $params Array
792 * - src : source storage path
793 * - latest : use the latest available data
796 abstract public function getFileProps( array $params );
799 * Stream the file at a storage path in the backend.
800 * If the file does not exists, an HTTP 404 error will be given.
801 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
802 * will be sent if streaming began, while none will be sent otherwise.
803 * Implementations should flush the output buffer before sending data.
805 * @param $params Array
807 * - src : source storage path
808 * - headers : list of additional HTTP headers to send on success
809 * - latest : use the latest available data
812 abstract public function streamFile( array $params );
815 * Returns a file system file, identical to the file at a storage path.
816 * The file returned is either:
817 * - a) A local copy of the file at a storage path in the backend.
818 * The temporary copy will have the same extension as the source.
819 * - b) An original of the file at a storage path in the backend.
820 * Temporary files may be purged when the file object falls out of scope.
822 * Write operations should *never* be done on this file as some backends
823 * may do internal tracking or may be instances of FileBackendMultiWrite.
824 * In that later case, there are copies of the file that must stay in sync.
825 * Additionally, further calls to this function may return the same file.
827 * @param $params Array
829 * - src : source storage path
830 * - latest : use the latest available data
831 * @return FSFile|null Returns null on failure
833 final public function getLocalReference( array $params ) {
834 $fsFiles = $this->getLocalReferenceMulti(
835 array( 'srcs' => array( $params['src'] ) ) +
$params );
837 return $fsFiles[$params['src']];
841 * Like getLocalReference() except it takes an array of storage paths
842 * and returns a map of storage paths to FSFile objects (or null on failure).
843 * The map keys (paths) are in the same order as the provided list of paths.
845 * @see FileBackend::getLocalReference()
847 * @param $params Array
849 * - srcs : list of source storage paths
850 * - latest : use the latest available data
851 * - parallelize : try to do operations in parallel when possible
852 * @return Array Map of (path name => FSFile or null on failure)
855 abstract public function getLocalReferenceMulti( array $params );
858 * Get a local copy on disk of the file at a storage path in the backend.
859 * The temporary copy will have the same file extension as the source.
860 * Temporary files may be purged when the file object falls out of scope.
862 * @param $params Array
864 * - src : source storage path
865 * - latest : use the latest available data
866 * @return TempFSFile|null Returns null on failure
868 final public function getLocalCopy( array $params ) {
869 $tmpFiles = $this->getLocalCopyMulti(
870 array( 'srcs' => array( $params['src'] ) ) +
$params );
872 return $tmpFiles[$params['src']];
876 * Like getLocalCopy() except it takes an array of storage paths and
877 * returns a map of storage paths to TempFSFile objects (or null on failure).
878 * The map keys (paths) are in the same order as the provided list of paths.
880 * @see FileBackend::getLocalCopy()
882 * @param $params Array
884 * - srcs : list of source storage paths
885 * - latest : use the latest available data
886 * - parallelize : try to do operations in parallel when possible
887 * @return Array Map of (path name => TempFSFile or null on failure)
890 abstract public function getLocalCopyMulti( array $params );
893 * Check if a directory exists at a given storage path.
894 * Backends using key/value stores will check if the path is a
895 * virtual directory, meaning there are files under the given directory.
897 * Storage backends with eventual consistency might return stale data.
899 * @param $params array
901 * - dir : storage directory
902 * @return bool|null Returns null on failure
905 abstract public function directoryExists( array $params );
908 * Get an iterator to list *all* directories under a storage directory.
909 * If the directory is of the form "mwstore://backend/container",
910 * then all directories in the container will be listed.
911 * If the directory is of form "mwstore://backend/container/dir",
912 * then all directories directly under that directory will be listed.
913 * Results will be storage directories relative to the given directory.
915 * Storage backends with eventual consistency might return stale data.
917 * @param $params array
919 * - dir : storage directory
920 * - topOnly : only return direct child dirs of the directory
921 * @return Traversable|Array|null Returns null on failure
924 abstract public function getDirectoryList( array $params );
927 * Same as FileBackend::getDirectoryList() except only lists
928 * directories that are immediately under the given directory.
930 * Storage backends with eventual consistency might return stale data.
932 * @param $params array
934 * - dir : storage directory
935 * @return Traversable|Array|null Returns null on failure
938 final public function getTopDirectoryList( array $params ) {
939 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
943 * Get an iterator to list *all* stored files under a storage directory.
944 * If the directory is of the form "mwstore://backend/container",
945 * then all files in the container will be listed.
946 * If the directory is of form "mwstore://backend/container/dir",
947 * then all files under that directory will be listed.
948 * Results will be storage paths relative to the given directory.
950 * Storage backends with eventual consistency might return stale data.
952 * @param $params array
954 * - dir : storage directory
955 * - topOnly : only return direct child files of the directory (since 1.20)
956 * @return Traversable|Array|null Returns null on failure
958 abstract public function getFileList( array $params );
961 * Same as FileBackend::getFileList() except only lists
962 * files that are immediately under the given directory.
964 * Storage backends with eventual consistency might return stale data.
966 * @param $params array
968 * - dir : storage directory
969 * @return Traversable|Array|null Returns null on failure
972 final public function getTopFileList( array $params ) {
973 return $this->getFileList( array( 'topOnly' => true ) +
$params );
977 * Preload persistent file stat and property cache into in-process cache.
978 * This should be used when stat calls will be made on a known list of a many files.
980 * @param $paths Array Storage paths
983 public function preloadCache( array $paths ) {}
986 * Invalidate any in-process file stat and property cache.
987 * If $paths is given, then only the cache for those files will be cleared.
989 * @param $paths Array Storage paths (optional)
992 public function clearCache( array $paths = null ) {}
995 * Lock the files at the given storage paths in the backend.
996 * This will either lock all the files or none (on failure).
998 * Callers should consider using getScopedFileLocks() instead.
1000 * @param $paths Array Storage paths
1001 * @param $type integer LockManager::LOCK_* constant
1004 final public function lockFiles( array $paths, $type ) {
1005 return $this->lockManager
->lock( $paths, $type );
1009 * Unlock the files at the given storage paths in the backend.
1011 * @param $paths Array Storage paths
1012 * @param $type integer LockManager::LOCK_* constant
1015 final public function unlockFiles( array $paths, $type ) {
1016 return $this->lockManager
->unlock( $paths, $type );
1020 * Lock the files at the given storage paths in the backend.
1021 * This will either lock all the files or none (on failure).
1022 * On failure, the status object will be updated with errors.
1024 * Once the return value goes out scope, the locks will be released and
1025 * the status updated. Unlock fatals will not change the status "OK" value.
1027 * @param $paths Array Storage paths
1028 * @param $type integer LockManager::LOCK_* constant
1029 * @param $status Status Status to update on lock/unlock
1030 * @return ScopedLock|null Returns null on failure
1032 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1033 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1037 * Get an array of scoped locks needed for a batch of file operations.
1039 * Normally, FileBackend::doOperations() handles locking, unless
1040 * the 'nonLocking' param is passed in. This function is useful if you
1041 * want the files to be locked for a broader scope than just when the
1042 * files are changing. For example, if you need to update DB metadata,
1043 * you may want to keep the files locked until finished.
1045 * @see FileBackend::doOperations()
1047 * @param $ops Array List of file operations to FileBackend::doOperations()
1048 * @param $status Status Status to update on lock/unlock
1049 * @return Array List of ScopedFileLocks or null values
1052 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1055 * Get the root storage path of this backend.
1056 * All container paths are "subdirectories" of this path.
1058 * @return string Storage path
1061 final public function getRootStoragePath() {
1062 return "mwstore://{$this->name}";
1066 * Get the file journal object for this backend
1068 * @return FileJournal
1070 final public function getJournal() {
1071 return $this->fileJournal
;
1075 * Check if a given path is a "mwstore://" path.
1076 * This does not do any further validation or any existence checks.
1078 * @param $path string
1081 final public static function isStoragePath( $path ) {
1082 return ( strpos( $path, 'mwstore://' ) === 0 );
1086 * Split a storage path into a backend name, a container name,
1087 * and a relative file path. The relative path may be the empty string.
1088 * This does not do any path normalization or traversal checks.
1090 * @param $storagePath string
1091 * @return Array (backend, container, rel object) or (null, null, null)
1093 final public static function splitStoragePath( $storagePath ) {
1094 if ( self
::isStoragePath( $storagePath ) ) {
1095 // Remove the "mwstore://" prefix and split the path
1096 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1097 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1098 if ( count( $parts ) == 3 ) {
1099 return $parts; // e.g. "backend/container/path"
1101 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1105 return array( null, null, null );
1109 * Normalize a storage path by cleaning up directory separators.
1110 * Returns null if the path is not of the format of a valid storage path.
1112 * @param $storagePath string
1113 * @return string|null
1115 final public static function normalizeStoragePath( $storagePath ) {
1116 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1117 if ( $relPath !== null ) { // must be for this backend
1118 $relPath = self
::normalizeContainerPath( $relPath );
1119 if ( $relPath !== null ) {
1120 return ( $relPath != '' )
1121 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1122 : "mwstore://{$backend}/{$container}";
1129 * Get the parent storage directory of a storage path.
1130 * This returns a path like "mwstore://backend/container",
1131 * "mwstore://backend/container/...", or null if there is no parent.
1133 * @param $storagePath string
1134 * @return string|null
1136 final public static function parentStoragePath( $storagePath ) {
1137 $storagePath = dirname( $storagePath );
1138 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1139 return ( $rel === null ) ?
null : $storagePath;
1143 * Get the final extension from a storage or FS path
1145 * @param $path string
1148 final public static function extensionFromPath( $path ) {
1149 $i = strrpos( $path, '.' );
1150 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1154 * Check if a relative path has no directory traversals
1156 * @param $path string
1160 final public static function isPathTraversalFree( $path ) {
1161 return ( self
::normalizeContainerPath( $path ) !== null );
1165 * Build a Content-Disposition header value per RFC 6266.
1167 * @param $type string One of (attachment, inline)
1168 * @param $filename string Suggested file name (should not contain slashes)
1172 final public static function makeContentDisposition( $type, $filename = '' ) {
1175 $type = strtolower( $type );
1176 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1177 throw new MWException( "Invalid Content-Disposition type '$type'." );
1181 if ( strlen( $filename ) ) {
1182 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1185 return implode( ';', $parts );
1189 * Validate and normalize a relative storage path.
1190 * Null is returned if the path involves directory traversal.
1191 * Traversal is insecure for FS backends and broken for others.
1193 * This uses the same traversal protection as Title::secureAndSplit().
1195 * @param $path string Storage path relative to a container
1196 * @return string|null
1198 final protected static function normalizeContainerPath( $path ) {
1199 // Normalize directory separators
1200 $path = strtr( $path, '\\', '/' );
1201 // Collapse any consecutive directory separators
1202 $path = preg_replace( '![/]{2,}!', '/', $path );
1203 // Remove any leading directory separator
1204 $path = ltrim( $path, '/' );
1205 // Use the same traversal protection as Title::secureAndSplit()
1206 if ( strpos( $path, '.' ) !== false ) {
1210 strpos( $path, './' ) === 0 ||
1211 strpos( $path, '../' ) === 0 ||
1212 strpos( $path, '/./' ) !== false ||
1213 strpos( $path, '/../' ) !== false