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
580 abstract public function concatenate( array $params );
583 * Prepare a storage directory for usage.
584 * This will create any required containers and parent directories.
585 * Backends using key/value stores only need to create the container.
587 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
588 * except they are only applied *if* the directory/container had to be created.
589 * These flags should always be set for directories that have private files.
591 * @param $params Array
593 * - dir : storage directory
594 * - noAccess : try to deny file access (since 1.20)
595 * - noListing : try to deny file listing (since 1.20)
596 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
599 final public function prepare( array $params ) {
600 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
601 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
603 return $this->doPrepare( $params );
607 * @see FileBackend::prepare()
609 abstract protected function doPrepare( array $params );
612 * Take measures to block web access to a storage directory and
613 * the container it belongs to. FS backends might add .htaccess
614 * files whereas key/value store backends might revoke container
615 * access to the storage user representing end-users in web requests.
616 * This is not guaranteed to actually do anything.
618 * @param $params Array
620 * - dir : storage directory
621 * - noAccess : try to deny file access
622 * - noListing : try to deny file listing
623 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
626 final public function secure( array $params ) {
627 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
628 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
630 return $this->doSecure( $params );
634 * @see FileBackend::secure()
636 abstract protected function doSecure( array $params );
639 * Remove measures to block web access to a storage directory and
640 * the container it belongs to. FS backends might remove .htaccess
641 * files whereas key/value store backends might grant container
642 * access to the storage user representing end-users in web requests.
643 * This essentially can undo the result of secure() calls.
645 * @param $params Array
647 * - dir : storage directory
648 * - access : try to allow file access
649 * - listing : try to allow file listing
650 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
654 final public function publish( array $params ) {
655 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
656 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
658 return $this->doPublish( $params );
662 * @see FileBackend::publish()
664 abstract protected function doPublish( array $params );
667 * Delete a storage directory if it is empty.
668 * Backends using key/value stores may do nothing unless the directory
669 * is that of an empty container, in which case it will be deleted.
671 * @param $params Array
673 * - dir : storage directory
674 * - recursive : recursively delete empty subdirectories first (since 1.20)
675 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
678 final public function clean( array $params ) {
679 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
680 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
682 return $this->doClean( $params );
686 * @see FileBackend::clean()
688 abstract protected function doClean( array $params );
691 * Check if a file exists at a storage path in the backend.
692 * This returns false if only a directory exists at the path.
694 * @param $params Array
696 * - src : source storage path
697 * - latest : use the latest available data
698 * @return bool|null Returns null on failure
700 abstract public function fileExists( array $params );
703 * Get the last-modified timestamp of the file at a storage path.
705 * @param $params Array
707 * - src : source storage path
708 * - latest : use the latest available data
709 * @return string|bool TS_MW timestamp or false on failure
711 abstract public function getFileTimestamp( array $params );
714 * Get the contents of a file at a storage path in the backend.
715 * This should be avoided for potentially large files.
717 * @param $params Array
719 * - src : source storage path
720 * - latest : use the latest available data
721 * @return string|bool Returns false on failure
723 abstract public function getFileContents( array $params );
726 * Get the size (bytes) of a file at a storage path in the backend.
728 * @param $params Array
730 * - src : source storage path
731 * - latest : use the latest available data
732 * @return integer|bool Returns false on failure
734 abstract public function getFileSize( array $params );
737 * Get quick information about a file at a storage path in the backend.
738 * If the file does not exist, then this returns false.
739 * Otherwise, the result is an associative array that includes:
740 * - mtime : the last-modified timestamp (TS_MW)
741 * - size : the file size (bytes)
742 * Additional values may be included for internal use only.
744 * @param $params Array
746 * - src : source storage path
747 * - latest : use the latest available data
748 * @return Array|bool|null Returns null on failure
750 abstract public function getFileStat( array $params );
753 * Get a SHA-1 hash of the file at a storage path in the backend.
755 * @param $params Array
757 * - src : source storage path
758 * - latest : use the latest available data
759 * @return string|bool Hash string or false on failure
761 abstract public function getFileSha1Base36( array $params );
764 * Get the properties of the file at a storage path in the backend.
765 * Returns FSFile::placeholderProps() on failure.
767 * @param $params Array
769 * - src : source storage path
770 * - latest : use the latest available data
773 abstract public function getFileProps( array $params );
776 * Stream the file at a storage path in the backend.
777 * If the file does not exists, an HTTP 404 error will be given.
778 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
779 * will be sent if streaming began, while none will be sent otherwise.
780 * Implementations should flush the output buffer before sending data.
782 * @param $params Array
784 * - src : source storage path
785 * - headers : list of additional HTTP headers to send on success
786 * - latest : use the latest available data
789 abstract public function streamFile( array $params );
792 * Returns a file system file, identical to the file at a storage path.
793 * The file returned is either:
794 * - a) A local copy of the file at a storage path in the backend.
795 * The temporary copy will have the same extension as the source.
796 * - b) An original of the file at a storage path in the backend.
797 * Temporary files may be purged when the file object falls out of scope.
799 * Write operations should *never* be done on this file as some backends
800 * may do internal tracking or may be instances of FileBackendMultiWrite.
801 * In that later case, there are copies of the file that must stay in sync.
802 * Additionally, further calls to this function may return the same file.
804 * @param $params Array
806 * - src : source storage path
807 * - latest : use the latest available data
808 * @return FSFile|null Returns null on failure
810 abstract public function getLocalReference( array $params );
813 * Get a local copy on disk of the file at a storage path in the backend.
814 * The temporary copy will have the same file extension as the source.
815 * Temporary files may be purged when the file object falls out of scope.
817 * @param $params Array
819 * - src : source storage path
820 * - latest : use the latest available data
821 * @return TempFSFile|null Returns null on failure
823 abstract public function getLocalCopy( array $params );
826 * Check if a directory exists at a given storage path.
827 * Backends using key/value stores will check if the path is a
828 * virtual directory, meaning there are files under the given directory.
830 * Storage backends with eventual consistency might return stale data.
832 * @param $params array
834 * - dir : storage directory
835 * @return bool|null Returns null on failure
838 abstract public function directoryExists( array $params );
841 * Get an iterator to list *all* directories under a storage directory.
842 * If the directory is of the form "mwstore://backend/container",
843 * then all directories in the container will be listed.
844 * If the directory is of form "mwstore://backend/container/dir",
845 * then all directories directly under that directory will be listed.
846 * Results will be storage directories relative to the given directory.
848 * Storage backends with eventual consistency might return stale data.
850 * @param $params array
852 * - dir : storage directory
853 * - topOnly : only return direct child dirs of the directory
854 * @return Traversable|Array|null Returns null on failure
857 abstract public function getDirectoryList( array $params );
860 * Same as FileBackend::getDirectoryList() except only lists
861 * directories that are immediately under the given directory.
863 * Storage backends with eventual consistency might return stale data.
865 * @param $params array
867 * - dir : storage directory
868 * @return Traversable|Array|null Returns null on failure
871 final public function getTopDirectoryList( array $params ) {
872 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
876 * Get an iterator to list *all* stored files under a storage directory.
877 * If the directory is of the form "mwstore://backend/container",
878 * then all files in the container will be listed.
879 * If the directory is of form "mwstore://backend/container/dir",
880 * then all files under that directory will be listed.
881 * Results will be storage paths relative to the given directory.
883 * Storage backends with eventual consistency might return stale data.
885 * @param $params array
887 * - dir : storage directory
888 * - topOnly : only return direct child files of the directory (since 1.20)
889 * @return Traversable|Array|null Returns null on failure
891 abstract public function getFileList( array $params );
894 * Same as FileBackend::getFileList() except only lists
895 * files that are immediately under the given directory.
897 * Storage backends with eventual consistency might return stale data.
899 * @param $params array
901 * - dir : storage directory
902 * @return Traversable|Array|null Returns null on failure
905 final public function getTopFileList( array $params ) {
906 return $this->getFileList( array( 'topOnly' => true ) +
$params );
910 * Preload persistent file stat and property cache into in-process cache.
911 * This should be used when stat calls will be made on a known list of a many files.
913 * @param $paths Array Storage paths
916 public function preloadCache( array $paths ) {}
919 * Invalidate any in-process file stat and property cache.
920 * If $paths is given, then only the cache for those files will be cleared.
922 * @param $paths Array Storage paths (optional)
925 public function clearCache( array $paths = null ) {}
928 * Lock the files at the given storage paths in the backend.
929 * This will either lock all the files or none (on failure).
931 * Callers should consider using getScopedFileLocks() instead.
933 * @param $paths Array Storage paths
934 * @param $type integer LockManager::LOCK_* constant
937 final public function lockFiles( array $paths, $type ) {
938 return $this->lockManager
->lock( $paths, $type );
942 * Unlock the files at the given storage paths in the backend.
944 * @param $paths Array Storage paths
945 * @param $type integer LockManager::LOCK_* constant
948 final public function unlockFiles( array $paths, $type ) {
949 return $this->lockManager
->unlock( $paths, $type );
953 * Lock the files at the given storage paths in the backend.
954 * This will either lock all the files or none (on failure).
955 * On failure, the status object will be updated with errors.
957 * Once the return value goes out scope, the locks will be released and
958 * the status updated. Unlock fatals will not change the status "OK" value.
960 * @param $paths Array Storage paths
961 * @param $type integer LockManager::LOCK_* constant
962 * @param $status Status Status to update on lock/unlock
963 * @return ScopedLock|null Returns null on failure
965 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
966 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
970 * Get an array of scoped locks needed for a batch of file operations.
972 * Normally, FileBackend::doOperations() handles locking, unless
973 * the 'nonLocking' param is passed in. This function is useful if you
974 * want the files to be locked for a broader scope than just when the
975 * files are changing. For example, if you need to update DB metadata,
976 * you may want to keep the files locked until finished.
978 * @see FileBackend::doOperations()
980 * @param $ops Array List of file operations to FileBackend::doOperations()
981 * @param $status Status Status to update on lock/unlock
982 * @return Array List of ScopedFileLocks or null values
985 abstract public function getScopedLocksForOps( array $ops, Status
$status );
988 * Get the root storage path of this backend.
989 * All container paths are "subdirectories" of this path.
991 * @return string Storage path
994 final public function getRootStoragePath() {
995 return "mwstore://{$this->name}";
999 * Get the file journal object for this backend
1001 * @return FileJournal
1003 final public function getJournal() {
1004 return $this->fileJournal
;
1008 * Check if a given path is a "mwstore://" path.
1009 * This does not do any further validation or any existence checks.
1011 * @param $path string
1014 final public static function isStoragePath( $path ) {
1015 return ( strpos( $path, 'mwstore://' ) === 0 );
1019 * Split a storage path into a backend name, a container name,
1020 * and a relative file path. The relative path may be the empty string.
1021 * This does not do any path normalization or traversal checks.
1023 * @param $storagePath string
1024 * @return Array (backend, container, rel object) or (null, null, null)
1026 final public static function splitStoragePath( $storagePath ) {
1027 if ( self
::isStoragePath( $storagePath ) ) {
1028 // Remove the "mwstore://" prefix and split the path
1029 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1030 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1031 if ( count( $parts ) == 3 ) {
1032 return $parts; // e.g. "backend/container/path"
1034 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1038 return array( null, null, null );
1042 * Normalize a storage path by cleaning up directory separators.
1043 * Returns null if the path is not of the format of a valid storage path.
1045 * @param $storagePath string
1046 * @return string|null
1048 final public static function normalizeStoragePath( $storagePath ) {
1049 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1050 if ( $relPath !== null ) { // must be for this backend
1051 $relPath = self
::normalizeContainerPath( $relPath );
1052 if ( $relPath !== null ) {
1053 return ( $relPath != '' )
1054 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1055 : "mwstore://{$backend}/{$container}";
1062 * Get the parent storage directory of a storage path.
1063 * This returns a path like "mwstore://backend/container",
1064 * "mwstore://backend/container/...", or null if there is no parent.
1066 * @param $storagePath string
1067 * @return string|null
1069 final public static function parentStoragePath( $storagePath ) {
1070 $storagePath = dirname( $storagePath );
1071 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1072 return ( $rel === null ) ?
null : $storagePath;
1076 * Get the final extension from a storage or FS path
1078 * @param $path string
1081 final public static function extensionFromPath( $path ) {
1082 $i = strrpos( $path, '.' );
1083 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1087 * Check if a relative path has no directory traversals
1089 * @param $path string
1093 final public static function isPathTraversalFree( $path ) {
1094 return ( self
::normalizeContainerPath( $path ) !== null );
1098 * Build a Content-Disposition header value per RFC 6266.
1100 * @param $type string One of (attachment, inline)
1101 * @param $filename string Suggested file name (should not contain slashes)
1105 final public static function makeContentDisposition( $type, $filename = '' ) {
1108 $type = strtolower( $type );
1109 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1110 throw new MWException( "Invalid Content-Disposition type '$type'." );
1114 if ( strlen( $filename ) ) {
1115 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1118 return implode( ';', $parts );
1122 * Validate and normalize a relative storage path.
1123 * Null is returned if the path involves directory traversal.
1124 * Traversal is insecure for FS backends and broken for others.
1126 * This uses the same traversal protection as Title::secureAndSplit().
1128 * @param $path string Storage path relative to a container
1129 * @return string|null
1131 final protected static function normalizeContainerPath( $path ) {
1132 // Normalize directory separators
1133 $path = strtr( $path, '\\', '/' );
1134 // Collapse any consecutive directory separators
1135 $path = preg_replace( '![/]{2,}!', '/', $path );
1136 // Remove any leading directory separator
1137 $path = ltrim( $path, '/' );
1138 // Use the same traversal protection as Title::secureAndSplit()
1139 if ( strpos( $path, '.' ) !== false ) {
1143 strpos( $path, './' ) === 0 ||
1144 strpos( $path, '../' ) === 0 ||
1145 strpos( $path, '/./' ) !== false ||
1146 strpos( $path, '/../' ) !== false