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 * Get the wiki identifier used for this backend (possibly empty).
133 * Note that this might *not* be in the same format as wfWikiID().
138 final public function getWikiId() {
139 return $this->wikiId
;
143 * Check if this backend is read-only
147 final public function isReadOnly() {
148 return ( $this->readOnly
!= '' );
152 * Get an explanatory message if this backend is read-only
154 * @return string|bool Returns false if the backend is not read-only
156 final public function getReadOnlyReason() {
157 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
161 * This is the main entry point into the backend for write operations.
162 * Callers supply an ordered list of operations to perform as a transaction.
163 * Files will be locked, the stat cache cleared, and then the operations attempted.
164 * If any serious errors occur, all attempted operations will be rolled back.
166 * $ops is an array of arrays. The outer array holds a list of operations.
167 * Each inner array is a set of key value pairs that specify an operation.
169 * Supported operations and their parameters. The supported actions are:
177 * a) Create a new file in storage with the contents of a string
181 * 'dst' => <storage path>,
182 * 'content' => <string of new file contents>,
183 * 'overwrite' => <boolean>,
184 * 'overwriteSame' => <boolean>,
185 * 'disposition' => <Content-Disposition header value>
189 * b) Copy a file system file into storage
193 * 'src' => <file system path>,
194 * 'dst' => <storage path>,
195 * 'overwrite' => <boolean>,
196 * 'overwriteSame' => <boolean>,
197 * 'disposition' => <Content-Disposition header value>
201 * c) Copy a file within storage
205 * 'src' => <storage path>,
206 * 'dst' => <storage path>,
207 * 'overwrite' => <boolean>,
208 * 'overwriteSame' => <boolean>,
209 * 'ignoreMissingSource' => <boolean>, # since 1.21
210 * 'disposition' => <Content-Disposition header value>
214 * d) Move a file within storage
218 * 'src' => <storage path>,
219 * 'dst' => <storage path>,
220 * 'overwrite' => <boolean>,
221 * 'overwriteSame' => <boolean>,
222 * 'ignoreMissingSource' => <boolean>, # since 1.21
223 * 'disposition' => <Content-Disposition header value>
227 * e) Delete a file within storage
231 * 'src' => <storage path>,
232 * 'ignoreMissingSource' => <boolean>
236 * f) Do nothing (no-op)
243 * Boolean flags for operations (operation-specific):
244 * - ignoreMissingSource : The operation will simply succeed and do
245 * nothing if the source file does not exist.
246 * - overwrite : Any destination file will be overwritten.
247 * - overwriteSame : An error will not be given if a file already
248 * exists at the destination that has the same
249 * contents as the new contents to be written there.
250 * - disposition : When supplied, the backend will add a Content-Disposition
251 * header when GETs/HEADs of the destination file are made.
252 * Backends that don't support file metadata will ignore this.
253 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
255 * $opts is an associative of boolean flags, including:
256 * - force : Operation precondition errors no longer trigger an abort.
257 * Any remaining operations are still attempted. Unexpected
258 * failures may still cause remaning operations to be aborted.
259 * - nonLocking : No locks are acquired for the operations.
260 * This can increase performance for non-critical writes.
261 * This has no effect unless the 'force' flag is set.
262 * - allowStale : Don't require the latest available data.
263 * This can increase performance for non-critical writes.
264 * This has no effect unless the 'force' flag is set.
265 * - nonJournaled : Don't log this operation batch in the file journal.
266 * This limits the ability of recovery scripts.
267 * - parallelize : Try to do operations in parallel when possible.
268 * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
269 * - preserveCache : Don't clear the process cache before checking files.
270 * This should only be used if all entries in the process
271 * cache were added after the files were already locked (since 1.20).
273 * @remarks Remarks on locking:
274 * File system paths given to operations should refer to files that are
275 * already locked or otherwise safe from modification from other processes.
276 * Normally these files will be new temp files, which should be adequate.
280 * This returns a Status, which contains all warnings and fatals that occurred
281 * during the operation. The 'failCount', 'successCount', and 'success' members
282 * will reflect each operation attempted.
284 * The status will be "OK" unless:
285 * - a) unexpected operation errors occurred (network partitions, disk full...)
286 * - b) significant operation errors occurred and 'force' was not set
288 * @param $ops Array List of operations to execute in order
289 * @param $opts Array Batch operation options
292 final public function doOperations( array $ops, array $opts = array() ) {
293 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
294 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
296 if ( empty( $opts['force'] ) ) { // sanity
297 unset( $opts['nonLocking'] );
298 unset( $opts['allowStale'] );
300 return $this->doOperationsInternal( $ops, $opts );
304 * @see FileBackend::doOperations()
306 abstract protected function doOperationsInternal( array $ops, array $opts );
309 * Same as doOperations() except it takes a single operation.
310 * If you are doing a batch of operations that should either
311 * all succeed or all fail, then use that function instead.
313 * @see FileBackend::doOperations()
315 * @param $op Array Operation
316 * @param $opts Array Operation options
319 final public function doOperation( array $op, array $opts = array() ) {
320 return $this->doOperations( array( $op ), $opts );
324 * Performs a single create operation.
325 * This sets $params['op'] to 'create' and passes it to doOperation().
327 * @see FileBackend::doOperation()
329 * @param $params Array Operation parameters
330 * @param $opts Array Operation options
333 final public function create( array $params, array $opts = array() ) {
334 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
338 * Performs a single store operation.
339 * This sets $params['op'] to 'store' and passes it to doOperation().
341 * @see FileBackend::doOperation()
343 * @param $params Array Operation parameters
344 * @param $opts Array Operation options
347 final public function store( array $params, array $opts = array() ) {
348 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
352 * Performs a single copy operation.
353 * This sets $params['op'] to 'copy' and passes it to doOperation().
355 * @see FileBackend::doOperation()
357 * @param $params Array Operation parameters
358 * @param $opts Array Operation options
361 final public function copy( array $params, array $opts = array() ) {
362 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
366 * Performs a single move operation.
367 * This sets $params['op'] to 'move' and passes it to doOperation().
369 * @see FileBackend::doOperation()
371 * @param $params Array Operation parameters
372 * @param $opts Array Operation options
375 final public function move( array $params, array $opts = array() ) {
376 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
380 * Performs a single delete operation.
381 * This sets $params['op'] to 'delete' and passes it to doOperation().
383 * @see FileBackend::doOperation()
385 * @param $params Array Operation parameters
386 * @param $opts Array Operation options
389 final public function delete( array $params, array $opts = array() ) {
390 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
394 * Perform a set of independent file operations on some files.
396 * This does no locking, nor journaling, and possibly no stat calls.
397 * Any destination files that already exist will be overwritten.
398 * This should *only* be used on non-original files, like cache files.
400 * Supported operations and their parameters:
408 * a) Create a new file in storage with the contents of a string
412 * 'dst' => <storage path>,
413 * 'content' => <string of new file contents>,
414 * 'disposition' => <Content-Disposition header value>
417 * b) Copy a file system file into storage
421 * 'src' => <file system path>,
422 * 'dst' => <storage path>,
423 * 'disposition' => <Content-Disposition header value>
426 * c) Copy a file within storage
430 * 'src' => <storage path>,
431 * 'dst' => <storage path>,
432 * 'ignoreMissingSource' => <boolean>, # since 1.21
433 * 'disposition' => <Content-Disposition header value>
436 * d) Move a file within storage
440 * 'src' => <storage path>,
441 * 'dst' => <storage path>,
442 * 'ignoreMissingSource' => <boolean>, # since 1.21
443 * 'disposition' => <Content-Disposition header value>
446 * e) Delete a file within storage
450 * 'src' => <storage path>,
451 * 'ignoreMissingSource' => <boolean>
454 * f) Do nothing (no-op)
461 * @par Boolean flags for operations (operation-specific):
462 * - ignoreMissingSource : The operation will simply succeed and do
463 * nothing if the source file does not exist.
464 * - disposition : When supplied, the backend will add a Content-Disposition
465 * header when GETs/HEADs of the destination file are made.
466 * Backends that don't support file metadata will ignore this.
467 * See http://tools.ietf.org/html/rfc6266 (since 1.20).
469 * $opts is an associative of boolean flags, including:
470 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
473 * This returns a Status, which contains all warnings and fatals that occurred
474 * during the operation. The 'failCount', 'successCount', and 'success' members
475 * will reflect each operation attempted for the given files. The status will be
476 * considered "OK" as long as no fatal errors occurred.
478 * @param $ops Array Set of operations to execute
479 * @param $opts Array Batch operation options
483 final public function doQuickOperations( array $ops, array $opts = array() ) {
484 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
485 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
487 foreach ( $ops as &$op ) {
488 $op['overwrite'] = true; // avoids RTTs in key/value stores
490 return $this->doQuickOperationsInternal( $ops );
494 * @see FileBackend::doQuickOperations()
497 abstract protected function doQuickOperationsInternal( array $ops );
500 * Same as doQuickOperations() except it takes a single operation.
501 * If you are doing a batch of operations, then use that function instead.
503 * @see FileBackend::doQuickOperations()
505 * @param $op Array Operation
509 final public function doQuickOperation( array $op ) {
510 return $this->doQuickOperations( array( $op ) );
514 * Performs a single quick create operation.
515 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
517 * @see FileBackend::doQuickOperation()
519 * @param $params Array Operation parameters
523 final public function quickCreate( array $params ) {
524 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
528 * Performs a single quick store operation.
529 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
531 * @see FileBackend::doQuickOperation()
533 * @param $params Array Operation parameters
537 final public function quickStore( array $params ) {
538 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
542 * Performs a single quick copy operation.
543 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
545 * @see FileBackend::doQuickOperation()
547 * @param $params Array Operation parameters
551 final public function quickCopy( array $params ) {
552 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
556 * Performs a single quick move operation.
557 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
559 * @see FileBackend::doQuickOperation()
561 * @param $params Array Operation parameters
565 final public function quickMove( array $params ) {
566 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
570 * Performs a single quick delete operation.
571 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
573 * @see FileBackend::doQuickOperation()
575 * @param $params Array Operation parameters
579 final public function quickDelete( array $params ) {
580 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
584 * Concatenate a list of storage files into a single file system file.
585 * The target path should refer to a file that is already locked or
586 * otherwise safe from modification from other processes. Normally,
587 * the file will be a new temp file, which should be adequate.
589 * @param $params Array Operation parameters
591 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
592 * - dst : file system path to 0-byte temp file
593 * - parallelize : try to do operations in parallel when possible
596 abstract public function concatenate( array $params );
599 * Prepare a storage directory for usage.
600 * This will create any required containers and parent directories.
601 * Backends using key/value stores only need to create the container.
603 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
604 * except they are only applied *if* the directory/container had to be created.
605 * These flags should always be set for directories that have private files.
607 * @param $params Array
609 * - dir : storage directory
610 * - noAccess : try to deny file access (since 1.20)
611 * - noListing : try to deny file listing (since 1.20)
612 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
615 final public function prepare( array $params ) {
616 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
617 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
619 return $this->doPrepare( $params );
623 * @see FileBackend::prepare()
625 abstract protected function doPrepare( array $params );
628 * Take measures to block web access to a storage directory and
629 * the container it belongs to. FS backends might add .htaccess
630 * files whereas key/value store backends might revoke container
631 * access to the storage user representing end-users in web requests.
632 * This is not guaranteed to actually do anything.
634 * @param $params Array
636 * - dir : storage directory
637 * - noAccess : try to deny file access
638 * - noListing : try to deny file listing
639 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
642 final public function secure( array $params ) {
643 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
644 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
646 return $this->doSecure( $params );
650 * @see FileBackend::secure()
652 abstract protected function doSecure( array $params );
655 * Remove measures to block web access to a storage directory and
656 * the container it belongs to. FS backends might remove .htaccess
657 * files whereas key/value store backends might grant container
658 * access to the storage user representing end-users in web requests.
659 * This essentially can undo the result of secure() calls.
661 * @param $params Array
663 * - dir : storage directory
664 * - access : try to allow file access
665 * - listing : try to allow file listing
666 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
670 final public function publish( array $params ) {
671 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
672 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
674 return $this->doPublish( $params );
678 * @see FileBackend::publish()
680 abstract protected function doPublish( array $params );
683 * Delete a storage directory if it is empty.
684 * Backends using key/value stores may do nothing unless the directory
685 * is that of an empty container, in which case it will be deleted.
687 * @param $params Array
689 * - dir : storage directory
690 * - recursive : recursively delete empty subdirectories first (since 1.20)
691 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
694 final public function clean( array $params ) {
695 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
696 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
698 return $this->doClean( $params );
702 * @see FileBackend::clean()
704 abstract protected function doClean( array $params );
707 * Check if a file exists at a storage path in the backend.
708 * This returns false if only a directory exists at the path.
710 * @param $params Array
712 * - src : source storage path
713 * - latest : use the latest available data
714 * @return bool|null Returns null on failure
716 abstract public function fileExists( array $params );
719 * Get the last-modified timestamp of the file at a storage path.
721 * @param $params Array
723 * - src : source storage path
724 * - latest : use the latest available data
725 * @return string|bool TS_MW timestamp or false on failure
727 abstract public function getFileTimestamp( array $params );
730 * Get the contents of a file at a storage path in the backend.
731 * This should be avoided for potentially large files.
733 * @param $params Array
735 * - src : source storage path
736 * - latest : use the latest available data
737 * @return string|bool Returns false on failure
739 final public function getFileContents( array $params ) {
740 $contents = $this->getFileContentsMulti(
741 array( 'srcs' => array( $params['src'] ) ) +
$params );
743 return $contents[$params['src']];
747 * Like getFileContents() except it takes an array of storage paths
748 * and returns a map of storage paths to strings (or null on failure).
749 * The map keys (paths) are in the same order as the provided list of paths.
751 * @see FileBackend::getFileContents()
753 * @param $params Array
755 * - srcs : list of source storage paths
756 * - latest : use the latest available data
757 * - parallelize : try to do operations in parallel when possible
758 * @return Array Map of (path name => string or false on failure)
761 abstract public function getFileContentsMulti( array $params );
764 * Get the size (bytes) of a file at a storage path in the backend.
766 * @param $params Array
768 * - src : source storage path
769 * - latest : use the latest available data
770 * @return integer|bool Returns false on failure
772 abstract public function getFileSize( array $params );
775 * Get quick information about a file at a storage path in the backend.
776 * If the file does not exist, then this returns false.
777 * Otherwise, the result is an associative array that includes:
778 * - mtime : the last-modified timestamp (TS_MW)
779 * - size : the file size (bytes)
780 * Additional values may be included for internal use only.
782 * @param $params Array
784 * - src : source storage path
785 * - latest : use the latest available data
786 * @return Array|bool|null Returns null on failure
788 abstract public function getFileStat( array $params );
791 * Get a SHA-1 hash of the file at a storage path in the backend.
793 * @param $params Array
795 * - src : source storage path
796 * - latest : use the latest available data
797 * @return string|bool Hash string or false on failure
799 abstract public function getFileSha1Base36( array $params );
802 * Get the properties of the file at a storage path in the backend.
803 * Returns FSFile::placeholderProps() on failure.
805 * @param $params Array
807 * - src : source storage path
808 * - latest : use the latest available data
811 abstract public function getFileProps( array $params );
814 * Stream the file at a storage path in the backend.
815 * If the file does not exists, an HTTP 404 error will be given.
816 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
817 * will be sent if streaming began, while none will be sent otherwise.
818 * Implementations should flush the output buffer before sending data.
820 * @param $params Array
822 * - src : source storage path
823 * - headers : list of additional HTTP headers to send on success
824 * - latest : use the latest available data
827 abstract public function streamFile( array $params );
830 * Returns a file system file, identical to the file at a storage path.
831 * The file returned is either:
832 * - a) A local copy of the file at a storage path in the backend.
833 * The temporary copy will have the same extension as the source.
834 * - b) An original of the file at a storage path in the backend.
835 * Temporary files may be purged when the file object falls out of scope.
837 * Write operations should *never* be done on this file as some backends
838 * may do internal tracking or may be instances of FileBackendMultiWrite.
839 * In that later case, there are copies of the file that must stay in sync.
840 * Additionally, further calls to this function may return the same file.
842 * @param $params Array
844 * - src : source storage path
845 * - latest : use the latest available data
846 * @return FSFile|null Returns null on failure
848 final public function getLocalReference( array $params ) {
849 $fsFiles = $this->getLocalReferenceMulti(
850 array( 'srcs' => array( $params['src'] ) ) +
$params );
852 return $fsFiles[$params['src']];
856 * Like getLocalReference() except it takes an array of storage paths
857 * and returns a map of storage paths to FSFile objects (or null on failure).
858 * The map keys (paths) are in the same order as the provided list of paths.
860 * @see FileBackend::getLocalReference()
862 * @param $params Array
864 * - srcs : list of source storage paths
865 * - latest : use the latest available data
866 * - parallelize : try to do operations in parallel when possible
867 * @return Array Map of (path name => FSFile or null on failure)
870 abstract public function getLocalReferenceMulti( array $params );
873 * Get a local copy on disk of the file at a storage path in the backend.
874 * The temporary copy will have the same file extension as the source.
875 * Temporary files may be purged when the file object falls out of scope.
877 * @param $params Array
879 * - src : source storage path
880 * - latest : use the latest available data
881 * @return TempFSFile|null Returns null on failure
883 final public function getLocalCopy( array $params ) {
884 $tmpFiles = $this->getLocalCopyMulti(
885 array( 'srcs' => array( $params['src'] ) ) +
$params );
887 return $tmpFiles[$params['src']];
891 * Like getLocalCopy() except it takes an array of storage paths and
892 * returns a map of storage paths to TempFSFile objects (or null on failure).
893 * The map keys (paths) are in the same order as the provided list of paths.
895 * @see FileBackend::getLocalCopy()
897 * @param $params Array
899 * - srcs : list of source storage paths
900 * - latest : use the latest available data
901 * - parallelize : try to do operations in parallel when possible
902 * @return Array Map of (path name => TempFSFile or null on failure)
905 abstract public function getLocalCopyMulti( array $params );
908 * Check if a directory exists at a given storage path.
909 * Backends using key/value stores will check if the path is a
910 * virtual directory, meaning there are files under the given directory.
912 * Storage backends with eventual consistency might return stale data.
914 * @param $params array
916 * - dir : storage directory
917 * @return bool|null Returns null on failure
920 abstract public function directoryExists( array $params );
923 * Get an iterator to list *all* directories under a storage directory.
924 * If the directory is of the form "mwstore://backend/container",
925 * then all directories in the container will be listed.
926 * If the directory is of form "mwstore://backend/container/dir",
927 * then all directories directly under that directory will be listed.
928 * Results will be storage directories relative to the given directory.
930 * Storage backends with eventual consistency might return stale data.
932 * @param $params array
934 * - dir : storage directory
935 * - topOnly : only return direct child dirs of the directory
936 * @return Traversable|Array|null Returns null on failure
939 abstract public function getDirectoryList( array $params );
942 * Same as FileBackend::getDirectoryList() except only lists
943 * directories that are immediately under the given directory.
945 * Storage backends with eventual consistency might return stale data.
947 * @param $params array
949 * - dir : storage directory
950 * @return Traversable|Array|null Returns null on failure
953 final public function getTopDirectoryList( array $params ) {
954 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
958 * Get an iterator to list *all* stored files under a storage directory.
959 * If the directory is of the form "mwstore://backend/container",
960 * then all files in the container will be listed.
961 * If the directory is of form "mwstore://backend/container/dir",
962 * then all files under that directory will be listed.
963 * Results will be storage paths relative to the given directory.
965 * Storage backends with eventual consistency might return stale data.
967 * @param $params array
969 * - dir : storage directory
970 * - topOnly : only return direct child files of the directory (since 1.20)
971 * @return Traversable|Array|null Returns null on failure
973 abstract public function getFileList( array $params );
976 * Same as FileBackend::getFileList() except only lists
977 * files that are immediately under the given directory.
979 * Storage backends with eventual consistency might return stale data.
981 * @param $params array
983 * - dir : storage directory
984 * @return Traversable|Array|null Returns null on failure
987 final public function getTopFileList( array $params ) {
988 return $this->getFileList( array( 'topOnly' => true ) +
$params );
992 * Preload persistent file stat and property cache into in-process cache.
993 * This should be used when stat calls will be made on a known list of a many files.
995 * @param $paths Array Storage paths
998 public function preloadCache( array $paths ) {}
1001 * Invalidate any in-process file stat and property cache.
1002 * If $paths is given, then only the cache for those files will be cleared.
1004 * @param $paths Array Storage paths (optional)
1007 public function clearCache( array $paths = null ) {}
1010 * Lock the files at the given storage paths in the backend.
1011 * This will either lock all the files or none (on failure).
1013 * Callers should consider using getScopedFileLocks() instead.
1015 * @param $paths Array Storage paths
1016 * @param $type integer LockManager::LOCK_* constant
1019 final public function lockFiles( array $paths, $type ) {
1020 return $this->lockManager
->lock( $paths, $type );
1024 * Unlock the files at the given storage paths in the backend.
1026 * @param $paths Array Storage paths
1027 * @param $type integer LockManager::LOCK_* constant
1030 final public function unlockFiles( array $paths, $type ) {
1031 return $this->lockManager
->unlock( $paths, $type );
1035 * Lock the files at the given storage paths in the backend.
1036 * This will either lock all the files or none (on failure).
1037 * On failure, the status object will be updated with errors.
1039 * Once the return value goes out scope, the locks will be released and
1040 * the status updated. Unlock fatals will not change the status "OK" value.
1042 * @param $paths Array Storage paths
1043 * @param $type integer LockManager::LOCK_* constant
1044 * @param $status Status Status to update on lock/unlock
1045 * @return ScopedLock|null Returns null on failure
1047 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
1048 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
1052 * Get an array of scoped locks needed for a batch of file operations.
1054 * Normally, FileBackend::doOperations() handles locking, unless
1055 * the 'nonLocking' param is passed in. This function is useful if you
1056 * want the files to be locked for a broader scope than just when the
1057 * files are changing. For example, if you need to update DB metadata,
1058 * you may want to keep the files locked until finished.
1060 * @see FileBackend::doOperations()
1062 * @param $ops Array List of file operations to FileBackend::doOperations()
1063 * @param $status Status Status to update on lock/unlock
1064 * @return Array List of ScopedFileLocks or null values
1067 abstract public function getScopedLocksForOps( array $ops, Status
$status );
1070 * Get the root storage path of this backend.
1071 * All container paths are "subdirectories" of this path.
1073 * @return string Storage path
1076 final public function getRootStoragePath() {
1077 return "mwstore://{$this->name}";
1081 * Get the storage path for the given container for this backend
1083 * @param $container string Container name
1084 * @return string Storage path
1087 final public function getContainerStoragePath( $container ) {
1088 return $this->getRootStoragePath() . "/{$container}";
1092 * Get the file journal object for this backend
1094 * @return FileJournal
1096 final public function getJournal() {
1097 return $this->fileJournal
;
1101 * Check if a given path is a "mwstore://" path.
1102 * This does not do any further validation or any existence checks.
1104 * @param $path string
1107 final public static function isStoragePath( $path ) {
1108 return ( strpos( $path, 'mwstore://' ) === 0 );
1112 * Split a storage path into a backend name, a container name,
1113 * and a relative file path. The relative path may be the empty string.
1114 * This does not do any path normalization or traversal checks.
1116 * @param $storagePath string
1117 * @return Array (backend, container, rel object) or (null, null, null)
1119 final public static function splitStoragePath( $storagePath ) {
1120 if ( self
::isStoragePath( $storagePath ) ) {
1121 // Remove the "mwstore://" prefix and split the path
1122 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1123 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1124 if ( count( $parts ) == 3 ) {
1125 return $parts; // e.g. "backend/container/path"
1127 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1131 return array( null, null, null );
1135 * Normalize a storage path by cleaning up directory separators.
1136 * Returns null if the path is not of the format of a valid storage path.
1138 * @param $storagePath string
1139 * @return string|null
1141 final public static function normalizeStoragePath( $storagePath ) {
1142 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1143 if ( $relPath !== null ) { // must be for this backend
1144 $relPath = self
::normalizeContainerPath( $relPath );
1145 if ( $relPath !== null ) {
1146 return ( $relPath != '' )
1147 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1148 : "mwstore://{$backend}/{$container}";
1155 * Get the parent storage directory of a storage path.
1156 * This returns a path like "mwstore://backend/container",
1157 * "mwstore://backend/container/...", or null if there is no parent.
1159 * @param $storagePath string
1160 * @return string|null
1162 final public static function parentStoragePath( $storagePath ) {
1163 $storagePath = dirname( $storagePath );
1164 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1165 return ( $rel === null ) ?
null : $storagePath;
1169 * Get the final extension from a storage or FS path
1171 * @param $path string
1174 final public static function extensionFromPath( $path ) {
1175 $i = strrpos( $path, '.' );
1176 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1180 * Check if a relative path has no directory traversals
1182 * @param $path string
1186 final public static function isPathTraversalFree( $path ) {
1187 return ( self
::normalizeContainerPath( $path ) !== null );
1191 * Build a Content-Disposition header value per RFC 6266.
1193 * @param $type string One of (attachment, inline)
1194 * @param $filename string Suggested file name (should not contain slashes)
1195 * @throws MWException
1199 final public static function makeContentDisposition( $type, $filename = '' ) {
1202 $type = strtolower( $type );
1203 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1204 throw new MWException( "Invalid Content-Disposition type '$type'." );
1208 if ( strlen( $filename ) ) {
1209 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1212 return implode( ';', $parts );
1216 * Validate and normalize a relative storage path.
1217 * Null is returned if the path involves directory traversal.
1218 * Traversal is insecure for FS backends and broken for others.
1220 * This uses the same traversal protection as Title::secureAndSplit().
1222 * @param $path string Storage path relative to a container
1223 * @return string|null
1225 final protected static function normalizeContainerPath( $path ) {
1226 // Normalize directory separators
1227 $path = strtr( $path, '\\', '/' );
1228 // Collapse any consecutive directory separators
1229 $path = preg_replace( '![/]{2,}!', '/', $path );
1230 // Remove any leading directory separator
1231 $path = ltrim( $path, '/' );
1232 // Use the same traversal protection as Title::secureAndSplit()
1233 if ( strpos( $path, '.' ) !== false ) {
1237 strpos( $path, './' ) === 0 ||
1238 strpos( $path, '../' ) === 0 ||
1239 strpos( $path, '/./' ) !== false ||
1240 strpos( $path, '/../' ) !== false