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
43 * Therefore, the relative paths are only virtual.
45 * Backend contents are stored under wiki-specific container names by default.
46 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
47 * segregation must be done by setting the container paths appropriately.
49 * FS-based backends are somewhat more restrictive due to the existence of real
50 * directory files; a regular file cannot have the same name as a directory. Other
51 * backends with virtual directories may not have this limitation. Callers should
52 * store files in such a way that no files and directories are under the same path.
54 * Methods should avoid throwing exceptions at all costs.
55 * As a corollary, external dependencies should be kept to a minimum.
57 * @ingroup FileBackend
60 abstract class FileBackend
{
61 protected $name; // string; unique backend name
62 protected $wikiId; // string; unique wiki name
63 protected $readOnly; // string; read-only explanation message
64 protected $parallelize; // string; when to do operations in parallel
65 protected $concurrency; // integer; how many operations can be done in parallel
67 /** @var LockManager */
68 protected $lockManager;
69 /** @var FileJournal */
70 protected $fileJournal;
73 * Create a new backend instance from configuration.
74 * This should only be called from within FileBackendGroup.
77 * - name : The unique name of this backend.
78 * This should consist of alphanumberic, '-', and '_' characters.
79 * This name should not be changed after use.
80 * - wikiId : Prefix to container names that is unique to this wiki.
81 * It should only consist of alphanumberic, '-', and '_' characters.
82 * - lockManager : Registered name of a file lock manager to use.
83 * - fileJournal : File journal configuration; see FileJournal::factory().
84 * Journals simply log changes to files stored in the backend.
85 * - readOnly : Write operations are disallowed if this is a non-empty string.
86 * It should be an explanation for the backend being read-only.
87 * - parallelize : When to do file operations in parallel (when possible).
88 * Allowed values are "implicit", "explicit" and "off".
89 * - concurrency : How many file operations can be done in parallel.
91 * @param $config Array
94 public function __construct( array $config ) {
95 $this->name
= $config['name'];
96 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
97 throw new MWException( "Backend name `{$this->name}` is invalid." );
99 $this->wikiId
= isset( $config['wikiId'] )
101 : wfWikiID(); // e.g. "my_wiki-en_"
102 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
103 ?
$config['lockManager']
104 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
105 $this->fileJournal
= isset( $config['fileJournal'] )
106 ? FileJournal
::factory( $config['fileJournal'], $this->name
)
107 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
108 $this->readOnly
= isset( $config['readOnly'] )
109 ?
(string)$config['readOnly']
111 $this->parallelize
= isset( $config['parallelize'] )
112 ?
(string)$config['parallelize']
114 $this->concurrency
= isset( $config['concurrency'] )
115 ?
(int)$config['concurrency']
120 * Get the unique backend name.
121 * We may have multiple different backends of the same type.
122 * For example, we can have two Swift backends using different proxies.
126 final public function getName() {
131 * Check if this backend is read-only
135 final public function isReadOnly() {
136 return ( $this->readOnly
!= '' );
140 * Get an explanatory message if this backend is read-only
142 * @return string|bool Returns false if the backend is not read-only
144 final public function getReadOnlyReason() {
145 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
149 * This is the main entry point into the backend for write operations.
150 * Callers supply an ordered list of operations to perform as a transaction.
151 * Files will be locked, the stat cache cleared, and then the operations attempted.
152 * If any serious errors occur, all attempted operations will be rolled back.
154 * $ops is an array of arrays. The outer array holds a list of operations.
155 * Each inner array is a set of key value pairs that specify an operation.
157 * Supported operations and their parameters. The supported actions are:
165 * a) Create a new file in storage with the contents of a string
169 * 'dst' => <storage path>,
170 * 'content' => <string of new file contents>,
171 * 'overwrite' => <boolean>,
172 * 'overwriteSame' => <boolean>
176 * b) Copy a file system file into storage
180 * 'src' => <file system path>,
181 * 'dst' => <storage path>,
182 * 'overwrite' => <boolean>,
183 * 'overwriteSame' => <boolean>
187 * c) Copy a file within storage
191 * 'src' => <storage path>,
192 * 'dst' => <storage path>,
193 * 'overwrite' => <boolean>,
194 * 'overwriteSame' => <boolean>
198 * d) Move a file within storage
202 * 'src' => <storage path>,
203 * 'dst' => <storage path>,
204 * 'overwrite' => <boolean>,
205 * 'overwriteSame' => <boolean>
209 * e) Delete a file within storage
213 * 'src' => <storage path>,
214 * 'ignoreMissingSource' => <boolean>
218 * f) Do nothing (no-op)
225 * Boolean flags for operations (operation-specific):
226 * - ignoreMissingSource : The operation will simply succeed and do
227 * nothing if the source file does not exist.
228 * - overwrite : Any destination file will be overwritten.
229 * - overwriteSame : An error will not be given if a file already
230 * exists at the destination that has the same
231 * contents as the new contents to be written there.
233 * $opts is an associative of boolean flags, including:
234 * - force : Operation precondition errors no longer trigger an abort.
235 * Any remaining operations are still attempted. Unexpected
236 * failures may still cause remaning operations to be aborted.
237 * - nonLocking : No locks are acquired for the operations.
238 * This can increase performance for non-critical writes.
239 * This has no effect unless the 'force' flag is set.
240 * - allowStale : Don't require the latest available data.
241 * This can increase performance for non-critical writes.
242 * This has no effect unless the 'force' flag is set.
243 * - nonJournaled : Don't log this operation batch in the file journal.
244 * This limits the ability of recovery scripts.
245 * - parallelize' : Try to do operations in parallel when possible.
247 * @remarks Remarks on locking:
248 * File system paths given to operations should refer to files that are
249 * already locked or otherwise safe from modification from other processes.
250 * Normally these files will be new temp files, which should be adequate.
254 * This returns a Status, which contains all warnings and fatals that occured
255 * during the operation. The 'failCount', 'successCount', and 'success' members
256 * will reflect each operation attempted.
258 * The status will be "OK" unless:
259 * a) unexpected operation errors occurred (network partitions, disk full...)
260 * b) significant operation errors occured and 'force' was not set
262 * @param $ops Array List of operations to execute in order
263 * @param $opts Array Batch operation options
266 final public function doOperations( array $ops, array $opts = array() ) {
267 if ( $this->isReadOnly() ) {
268 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
270 if ( empty( $opts['force'] ) ) { // sanity
271 unset( $opts['nonLocking'] );
272 unset( $opts['allowStale'] );
274 $opts['concurrency'] = 1; // off
275 if ( $this->parallelize
=== 'implicit' ) {
276 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
277 $opts['concurrency'] = $this->concurrency
;
279 } elseif ( $this->parallelize
=== 'explicit' ) {
280 if ( !empty( $opts['parallelize'] ) ) {
281 $opts['concurrency'] = $this->concurrency
;
284 return $this->doOperationsInternal( $ops, $opts );
288 * @see FileBackend::doOperations()
290 abstract protected function doOperationsInternal( array $ops, array $opts );
293 * Same as doOperations() except it takes a single operation.
294 * If you are doing a batch of operations that should either
295 * all succeed or all fail, then use that function instead.
297 * @see FileBackend::doOperations()
299 * @param $op Array Operation
300 * @param $opts Array Operation options
303 final public function doOperation( array $op, array $opts = array() ) {
304 return $this->doOperations( array( $op ), $opts );
308 * Performs a single create operation.
309 * This sets $params['op'] to 'create' and passes it to doOperation().
311 * @see FileBackend::doOperation()
313 * @param $params Array Operation parameters
314 * @param $opts Array Operation options
317 final public function create( array $params, array $opts = array() ) {
318 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
322 * Performs a single store operation.
323 * This sets $params['op'] to 'store' and passes it to doOperation().
325 * @see FileBackend::doOperation()
327 * @param $params Array Operation parameters
328 * @param $opts Array Operation options
331 final public function store( array $params, array $opts = array() ) {
332 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
336 * Performs a single copy operation.
337 * This sets $params['op'] to 'copy' and passes it to doOperation().
339 * @see FileBackend::doOperation()
341 * @param $params Array Operation parameters
342 * @param $opts Array Operation options
345 final public function copy( array $params, array $opts = array() ) {
346 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
350 * Performs a single move operation.
351 * This sets $params['op'] to 'move' and passes it to doOperation().
353 * @see FileBackend::doOperation()
355 * @param $params Array Operation parameters
356 * @param $opts Array Operation options
359 final public function move( array $params, array $opts = array() ) {
360 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
364 * Performs a single delete operation.
365 * This sets $params['op'] to 'delete' and passes it to doOperation().
367 * @see FileBackend::doOperation()
369 * @param $params Array Operation parameters
370 * @param $opts Array Operation options
373 final public function delete( array $params, array $opts = array() ) {
374 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
378 * Perform a set of independent file operations on some files.
380 * This does no locking, nor journaling, and possibly no stat calls.
381 * Any destination files that already exist will be overwritten.
382 * This should *only* be used on non-original files, like cache files.
384 * Supported operations and their parameters:
391 * a) Create a new file in storage with the contents of a string
395 * 'dst' => <storage path>,
396 * 'content' => <string of new file contents>
399 * b) Copy a file system file into storage
403 * 'src' => <file system path>,
404 * 'dst' => <storage path>
407 * c) Copy a file within storage
411 * 'src' => <storage path>,
412 * 'dst' => <storage path>
415 * d) Move a file within storage
419 * 'src' => <storage path>,
420 * 'dst' => <storage path>
423 * e) Delete a file within storage
427 * 'src' => <storage path>,
428 * 'ignoreMissingSource' => <boolean>
431 * f) Do nothing (no-op)
438 * @par Boolean flags for operations (operation-specific):
439 * - ignoreMissingSource : The operation will simply succeed and do
440 * nothing if the source file does not exist.
443 * This returns a Status, which contains all warnings and fatals that occured
444 * during the operation. The 'failCount', 'successCount', and 'success' members
445 * will reflect each operation attempted for the given files. The status will be
446 * considered "OK" as long as no fatal errors occured.
448 * @param $ops Array Set of operations to execute
452 final public function doQuickOperations( array $ops ) {
453 if ( $this->isReadOnly() ) {
454 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
456 foreach ( $ops as &$op ) {
457 $op['overwrite'] = true; // avoids RTTs in key/value stores
459 return $this->doQuickOperationsInternal( $ops );
463 * @see FileBackend::doQuickOperations()
466 abstract protected function doQuickOperationsInternal( array $ops );
469 * Same as doQuickOperations() except it takes a single operation.
470 * If you are doing a batch of operations, then use that function instead.
472 * @see FileBackend::doQuickOperations()
474 * @param $op Array Operation
478 final public function doQuickOperation( array $op ) {
479 return $this->doQuickOperations( array( $op ) );
483 * Performs a single quick create operation.
484 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
486 * @see FileBackend::doQuickOperation()
488 * @param $params Array Operation parameters
492 final public function quickCreate( array $params ) {
493 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
497 * Performs a single quick store operation.
498 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
500 * @see FileBackend::doQuickOperation()
502 * @param $params Array Operation parameters
506 final public function quickStore( array $params ) {
507 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
511 * Performs a single quick copy operation.
512 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
514 * @see FileBackend::doQuickOperation()
516 * @param $params Array Operation parameters
520 final public function quickCopy( array $params ) {
521 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
525 * Performs a single quick move operation.
526 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
528 * @see FileBackend::doQuickOperation()
530 * @param $params Array Operation parameters
534 final public function quickMove( array $params ) {
535 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
539 * Performs a single quick delete operation.
540 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
542 * @see FileBackend::doQuickOperation()
544 * @param $params Array Operation parameters
548 final public function quickDelete( array $params ) {
549 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
553 * Concatenate a list of storage files into a single file system file.
554 * The target path should refer to a file that is already locked or
555 * otherwise safe from modification from other processes. Normally,
556 * the file will be a new temp file, which should be adequate.
558 * @param $params Array Operation parameters
560 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
561 * - dst : file system path to 0-byte temp file
564 abstract public function concatenate( array $params );
567 * Prepare a storage directory for usage.
568 * This will create any required containers and parent directories.
569 * Backends using key/value stores only need to create the container.
571 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
572 * except they are only applied *if* the directory/container had to be created.
573 * These flags should always be set for directories that have private files.
576 * - dir : storage directory
577 * - noAccess : try to deny file access (@since 1.20)
578 * - noListing : try to deny file listing (@since 1.20)
580 * @param $params Array
583 final public function prepare( array $params ) {
584 if ( $this->isReadOnly() ) {
585 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
587 return $this->doPrepare( $params );
591 * @see FileBackend::prepare()
593 abstract protected function doPrepare( array $params );
596 * Take measures to block web access to a storage directory and
597 * the container it belongs to. FS backends might add .htaccess
598 * files whereas key/value store backends might revoke container
599 * access to the storage user representing end-users in web requests.
600 * This is not guaranteed to actually do anything.
602 * @param $params Array
604 * - dir : storage directory
605 * - noAccess : try to deny file access
606 * - noListing : try to deny file listing
609 final public function secure( array $params ) {
610 if ( $this->isReadOnly() ) {
611 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
613 return $this->doSecure( $params );
617 * @see FileBackend::secure()
619 abstract protected function doSecure( array $params );
622 * Remove measures to block web access to a storage directory and
623 * the container it belongs to. FS backends might remove .htaccess
624 * files whereas key/value store backends might grant container
625 * access to the storage user representing end-users in web requests.
626 * This essentially can undo the result of secure() calls.
629 * - dir : storage directory
630 * - access : try to allow file access
631 * - listing : try to allow file listing
633 * @param $params Array
637 final public function publish( array $params ) {
638 if ( $this->isReadOnly() ) {
639 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
641 return $this->doPublish( $params );
645 * @see FileBackend::publish()
647 abstract protected function doPublish( array $params );
650 * Delete a storage directory if it is empty.
651 * Backends using key/value stores may do nothing unless the directory
652 * is that of an empty container, in which case it should be deleted.
654 * @param $params Array
656 * - dir : storage directory
657 * - recursive : recursively delete empty subdirectories first (@since 1.20)
660 final public function clean( array $params ) {
661 if ( $this->isReadOnly() ) {
662 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
664 return $this->doClean( $params );
668 * @see FileBackend::clean()
670 abstract protected function doClean( array $params );
673 * Check if a file exists at a storage path in the backend.
674 * This returns false if only a directory exists at the path.
676 * @param $params Array
678 * - src : source storage path
679 * - latest : use the latest available data
680 * @return bool|null Returns null on failure
682 abstract public function fileExists( array $params );
685 * Get the last-modified timestamp of the file at a storage path.
687 * @param $params Array
689 * - src : source storage path
690 * - latest : use the latest available data
691 * @return string|bool TS_MW timestamp or false on failure
693 abstract public function getFileTimestamp( array $params );
696 * Get the contents of a file at a storage path in the backend.
697 * This should be avoided for potentially large files.
699 * @param $params Array
701 * - src : source storage path
702 * - latest : use the latest available data
703 * @return string|bool Returns false on failure
705 abstract public function getFileContents( array $params );
708 * Get the size (bytes) of a file at a storage path in the backend.
710 * @param $params Array
712 * - src : source storage path
713 * - latest : use the latest available data
714 * @return integer|bool Returns false on failure
716 abstract public function getFileSize( array $params );
719 * Get quick information about a file at a storage path in the backend.
720 * If the file does not exist, then this returns false.
721 * Otherwise, the result is an associative array that includes:
722 * - mtime : the last-modified timestamp (TS_MW)
723 * - size : the file size (bytes)
724 * Additional values may be included for internal use only.
726 * @param $params Array
728 * - src : source storage path
729 * - latest : use the latest available data
730 * @return Array|bool|null Returns null on failure
732 abstract public function getFileStat( array $params );
735 * Get a SHA-1 hash of the file at a storage path in the backend.
737 * @param $params Array
739 * - src : source storage path
740 * - latest : use the latest available data
741 * @return string|bool Hash string or false on failure
743 abstract public function getFileSha1Base36( array $params );
746 * Get the properties of the file at a storage path in the backend.
747 * Returns FSFile::placeholderProps() on failure.
749 * @param $params Array
751 * - src : source storage path
752 * - latest : use the latest available data
755 abstract public function getFileProps( array $params );
758 * Stream the file at a storage path in the backend.
759 * If the file does not exists, a 404 error will be given.
760 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
761 * must be sent if streaming began, while none should be sent otherwise.
762 * Implementations should flush the output buffer before sending data.
764 * @param $params Array
766 * - src : source storage path
767 * - headers : additional HTTP headers to send on success
768 * - latest : use the latest available data
771 abstract public function streamFile( array $params );
774 * Returns a file system file, identical to the file at a storage path.
775 * The file returned is either:
776 * a) A local copy of the file at a storage path in the backend.
777 * The temporary copy will have the same extension as the source.
778 * b) An original of the file at a storage path in the backend.
779 * Temporary files may be purged when the file object falls out of scope.
781 * Write operations should *never* be done on this file as some backends
782 * may do internal tracking or may be instances of FileBackendMultiWrite.
783 * In that later case, there are copies of the file that must stay in sync.
784 * Additionally, further calls to this function may return the same file.
786 * @param $params Array
788 * - src : source storage path
789 * - latest : use the latest available data
790 * @return FSFile|null Returns null on failure
792 abstract public function getLocalReference( array $params );
795 * Get a local copy on disk of the file at a storage path in the backend.
796 * The temporary copy will have the same file extension as the source.
797 * Temporary files may be purged when the file object falls out of scope.
799 * @param $params Array
801 * - src : source storage path
802 * - latest : use the latest available data
803 * @return TempFSFile|null Returns null on failure
805 abstract public function getLocalCopy( array $params );
808 * Check if a directory exists at a given storage path.
809 * Backends using key/value stores will check if the path is a
810 * virtual directory, meaning there are files under the given directory.
812 * Storage backends with eventual consistency might return stale data.
814 * @param $params array
816 * - dir : storage directory
817 * @return bool|null Returns null on failure
820 abstract public function directoryExists( array $params );
823 * Get an iterator to list *all* directories under a storage directory.
824 * If the directory is of the form "mwstore://backend/container",
825 * then all directories in the container should be listed.
826 * If the directory is of form "mwstore://backend/container/dir",
827 * then all directories directly under that directory should be listed.
828 * Results should be storage directories relative to the given directory.
830 * Storage backends with eventual consistency might return stale data.
832 * @param $params array
834 * - dir : storage directory
835 * - topOnly : only return direct child dirs of the directory
836 * @return Traversable|Array|null Returns null on failure
839 abstract public function getDirectoryList( array $params );
842 * Same as FileBackend::getDirectoryList() except only lists
843 * directories that are immediately under the given directory.
845 * Storage backends with eventual consistency might return stale data.
847 * @param $params array
849 * - dir : storage directory
850 * @return Traversable|Array|null Returns null on failure
853 final public function getTopDirectoryList( array $params ) {
854 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
858 * Get an iterator to list *all* stored files under a storage directory.
859 * If the directory is of the form "mwstore://backend/container",
860 * then all files in the container should be listed.
861 * If the directory is of form "mwstore://backend/container/dir",
862 * then all files under that directory should be listed.
863 * Results should be storage paths relative to the given directory.
865 * Storage backends with eventual consistency might return stale data.
867 * @param $params array
869 * - dir : storage directory
870 * - topOnly : only return direct child files of the directory (@since 1.20)
871 * @return Traversable|Array|null Returns null on failure
873 abstract public function getFileList( array $params );
876 * Same as FileBackend::getFileList() except only lists
877 * files that are immediately under the given directory.
879 * Storage backends with eventual consistency might return stale data.
881 * @param $params array
883 * - dir : storage directory
884 * @return Traversable|Array|null Returns null on failure
887 final public function getTopFileList( array $params ) {
888 return $this->getFileList( array( 'topOnly' => true ) +
$params );
892 * Invalidate any in-process file existence and property cache.
893 * If $paths is given, then only the cache for those files will be cleared.
895 * @param $paths Array Storage paths (optional)
898 public function clearCache( array $paths = null ) {}
901 * Lock the files at the given storage paths in the backend.
902 * This will either lock all the files or none (on failure).
904 * Callers should consider using getScopedFileLocks() instead.
906 * @param $paths Array Storage paths
907 * @param $type integer LockManager::LOCK_* constant
910 final public function lockFiles( array $paths, $type ) {
911 return $this->lockManager
->lock( $paths, $type );
915 * Unlock the files at the given storage paths in the backend.
917 * @param $paths Array Storage paths
918 * @param $type integer LockManager::LOCK_* constant
921 final public function unlockFiles( array $paths, $type ) {
922 return $this->lockManager
->unlock( $paths, $type );
926 * Lock the files at the given storage paths in the backend.
927 * This will either lock all the files or none (on failure).
928 * On failure, the status object will be updated with errors.
930 * Once the return value goes out scope, the locks will be released and
931 * the status updated. Unlock fatals will not change the status "OK" value.
933 * @param $paths Array Storage paths
934 * @param $type integer LockManager::LOCK_* constant
935 * @param $status Status Status to update on lock/unlock
936 * @return ScopedLock|null Returns null on failure
938 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
939 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
943 * Get an array of scoped locks needed for a batch of file operations.
945 * Normally, FileBackend::doOperations() handles locking, unless
946 * the 'nonLocking' param is passed in. This function is useful if you
947 * want the files to be locked for a broader scope than just when the
948 * files are changing. For example, if you need to update DB metadata,
949 * you may want to keep the files locked until finished.
951 * @see FileBackend::doOperations()
953 * @param $ops Array List of file operations to FileBackend::doOperations()
954 * @param $status Status Status to update on lock/unlock
955 * @return Array List of ScopedFileLocks or null values
958 abstract public function getScopedLocksForOps( array $ops, Status
$status );
961 * Get the root storage path of this backend.
962 * All container paths are "subdirectories" of this path.
964 * @return string Storage path
967 final public function getRootStoragePath() {
968 return "mwstore://{$this->name}";
972 * Get the file journal object for this backend
974 * @return FileJournal
976 final public function getJournal() {
977 return $this->fileJournal
;
981 * Check if a given path is a "mwstore://" path.
982 * This does not do any further validation or any existence checks.
984 * @param $path string
987 final public static function isStoragePath( $path ) {
988 return ( strpos( $path, 'mwstore://' ) === 0 );
992 * Split a storage path into a backend name, a container name,
993 * and a relative file path. The relative path may be the empty string.
994 * This does not do any path normalization or traversal checks.
996 * @param $storagePath string
997 * @return Array (backend, container, rel object) or (null, null, null)
999 final public static function splitStoragePath( $storagePath ) {
1000 if ( self
::isStoragePath( $storagePath ) ) {
1001 // Remove the "mwstore://" prefix and split the path
1002 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1003 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1004 if ( count( $parts ) == 3 ) {
1005 return $parts; // e.g. "backend/container/path"
1007 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1011 return array( null, null, null );
1015 * Normalize a storage path by cleaning up directory separators.
1016 * Returns null if the path is not of the format of a valid storage path.
1018 * @param $storagePath string
1019 * @return string|null
1021 final public static function normalizeStoragePath( $storagePath ) {
1022 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1023 if ( $relPath !== null ) { // must be for this backend
1024 $relPath = self
::normalizeContainerPath( $relPath );
1025 if ( $relPath !== null ) {
1026 return ( $relPath != '' )
1027 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1028 : "mwstore://{$backend}/{$container}";
1035 * Get the parent storage directory of a storage path.
1036 * This returns a path like "mwstore://backend/container",
1037 * "mwstore://backend/container/...", or null if there is no parent.
1039 * @param $storagePath string
1040 * @return string|null
1042 final public static function parentStoragePath( $storagePath ) {
1043 $storagePath = dirname( $storagePath );
1044 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1045 return ( $rel === null ) ?
null : $storagePath;
1049 * Get the final extension from a storage or FS path
1051 * @param $path string
1054 final public static function extensionFromPath( $path ) {
1055 $i = strrpos( $path, '.' );
1056 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1060 * Check if a relative path has no directory traversals
1062 * @param $path string
1066 final public static function isPathTraversalFree( $path ) {
1067 return ( self
::normalizeContainerPath( $path ) !== null );
1071 * Validate and normalize a relative storage path.
1072 * Null is returned if the path involves directory traversal.
1073 * Traversal is insecure for FS backends and broken for others.
1075 * This uses the same traversal protection as Title::secureAndSplit().
1077 * @param $path string Storage path relative to a container
1078 * @return string|null
1080 final protected static function normalizeContainerPath( $path ) {
1081 // Normalize directory separators
1082 $path = strtr( $path, '\\', '/' );
1083 // Collapse any consecutive directory separators
1084 $path = preg_replace( '![/]{2,}!', '/', $path );
1085 // Remove any leading directory separator
1086 $path = ltrim( $path, '/' );
1087 // Use the same traversal protection as Title::secureAndSplit()
1088 if ( strpos( $path, '.' ) !== false ) {
1092 strpos( $path, './' ) === 0 ||
1093 strpos( $path, '../' ) === 0 ||
1094 strpos( $path, '/./' ) !== false ||
1095 strpos( $path, '/../' ) !== false