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 ?
( ( $config['fileJournal'] instanceof FileJournal
)
107 ?
$config['fileJournal']
108 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
109 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
110 $this->readOnly
= isset( $config['readOnly'] )
111 ?
(string)$config['readOnly']
113 $this->parallelize
= isset( $config['parallelize'] )
114 ?
(string)$config['parallelize']
116 $this->concurrency
= isset( $config['concurrency'] )
117 ?
(int)$config['concurrency']
122 * Get the unique backend name.
123 * We may have multiple different backends of the same type.
124 * For example, we can have two Swift backends using different proxies.
128 final public function getName() {
133 * Check if this backend is read-only
137 final public function isReadOnly() {
138 return ( $this->readOnly
!= '' );
142 * Get an explanatory message if this backend is read-only
144 * @return string|bool Returns false if the backend is not read-only
146 final public function getReadOnlyReason() {
147 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
151 * This is the main entry point into the backend for write operations.
152 * Callers supply an ordered list of operations to perform as a transaction.
153 * Files will be locked, the stat cache cleared, and then the operations attempted.
154 * If any serious errors occur, all attempted operations will be rolled back.
156 * $ops is an array of arrays. The outer array holds a list of operations.
157 * Each inner array is a set of key value pairs that specify an operation.
159 * Supported operations and their parameters. The supported actions are:
167 * a) Create a new file in storage with the contents of a string
171 * 'dst' => <storage path>,
172 * 'content' => <string of new file contents>,
173 * 'overwrite' => <boolean>,
174 * 'overwriteSame' => <boolean>
178 * b) Copy a file system file into storage
182 * 'src' => <file system path>,
183 * 'dst' => <storage path>,
184 * 'overwrite' => <boolean>,
185 * 'overwriteSame' => <boolean>
189 * c) Copy a file within storage
193 * 'src' => <storage path>,
194 * 'dst' => <storage path>,
195 * 'overwrite' => <boolean>,
196 * 'overwriteSame' => <boolean>
200 * d) Move a file within storage
204 * 'src' => <storage path>,
205 * 'dst' => <storage path>,
206 * 'overwrite' => <boolean>,
207 * 'overwriteSame' => <boolean>
211 * e) Delete a file within storage
215 * 'src' => <storage path>,
216 * 'ignoreMissingSource' => <boolean>
220 * f) Do nothing (no-op)
227 * Boolean flags for operations (operation-specific):
228 * - ignoreMissingSource : The operation will simply succeed and do
229 * nothing if the source file does not exist.
230 * - overwrite : Any destination file will be overwritten.
231 * - overwriteSame : An error will not be given if a file already
232 * exists at the destination that has the same
233 * contents as the new contents to be written there.
235 * $opts is an associative of boolean flags, including:
236 * - force : Operation precondition errors no longer trigger an abort.
237 * Any remaining operations are still attempted. Unexpected
238 * failures may still cause remaning operations to be aborted.
239 * - nonLocking : No locks are acquired for the operations.
240 * This can increase performance for non-critical writes.
241 * This has no effect unless the 'force' flag is set.
242 * - allowStale : Don't require the latest available data.
243 * This can increase performance for non-critical writes.
244 * This has no effect unless the 'force' flag is set.
245 * - preserveCache : Don't clear the process cache before checking files.
246 * This should only be used if all entries in the process
247 * cache were added after the files were already locked.
248 * - nonJournaled : Don't log this operation batch in the file journal.
249 * This limits the ability of recovery scripts.
250 * - parallelize : Try to do operations in parallel when possible.
251 * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
253 * @remarks Remarks on locking:
254 * File system paths given to operations should refer to files that are
255 * already locked or otherwise safe from modification from other processes.
256 * Normally these files will be new temp files, which should be adequate.
260 * This returns a Status, which contains all warnings and fatals that occurred
261 * during the operation. The 'failCount', 'successCount', and 'success' members
262 * will reflect each operation attempted.
264 * The status will be "OK" unless:
265 * - a) unexpected operation errors occurred (network partitions, disk full...)
266 * - b) significant operation errors occurred and 'force' was not set
268 * @param $ops Array List of operations to execute in order
269 * @param $opts Array Batch operation options
272 final public function doOperations( array $ops, array $opts = array() ) {
273 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
274 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
276 if ( empty( $opts['force'] ) ) { // sanity
277 unset( $opts['nonLocking'] );
278 unset( $opts['allowStale'] );
280 $opts['concurrency'] = 1; // off
281 if ( $this->parallelize
=== 'implicit' ) {
282 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
283 $opts['concurrency'] = $this->concurrency
;
285 } elseif ( $this->parallelize
=== 'explicit' ) {
286 if ( !empty( $opts['parallelize'] ) ) {
287 $opts['concurrency'] = $this->concurrency
;
290 return $this->doOperationsInternal( $ops, $opts );
294 * @see FileBackend::doOperations()
296 abstract protected function doOperationsInternal( array $ops, array $opts );
299 * Same as doOperations() except it takes a single operation.
300 * If you are doing a batch of operations that should either
301 * all succeed or all fail, then use that function instead.
303 * @see FileBackend::doOperations()
305 * @param $op Array Operation
306 * @param $opts Array Operation options
309 final public function doOperation( array $op, array $opts = array() ) {
310 return $this->doOperations( array( $op ), $opts );
314 * Performs a single create operation.
315 * This sets $params['op'] to 'create' and passes it to doOperation().
317 * @see FileBackend::doOperation()
319 * @param $params Array Operation parameters
320 * @param $opts Array Operation options
323 final public function create( array $params, array $opts = array() ) {
324 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
328 * Performs a single store operation.
329 * This sets $params['op'] to 'store' and passes it to doOperation().
331 * @see FileBackend::doOperation()
333 * @param $params Array Operation parameters
334 * @param $opts Array Operation options
337 final public function store( array $params, array $opts = array() ) {
338 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
342 * Performs a single copy operation.
343 * This sets $params['op'] to 'copy' and passes it to doOperation().
345 * @see FileBackend::doOperation()
347 * @param $params Array Operation parameters
348 * @param $opts Array Operation options
351 final public function copy( array $params, array $opts = array() ) {
352 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
356 * Performs a single move operation.
357 * This sets $params['op'] to 'move' and passes it to doOperation().
359 * @see FileBackend::doOperation()
361 * @param $params Array Operation parameters
362 * @param $opts Array Operation options
365 final public function move( array $params, array $opts = array() ) {
366 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
370 * Performs a single delete operation.
371 * This sets $params['op'] to 'delete' and passes it to doOperation().
373 * @see FileBackend::doOperation()
375 * @param $params Array Operation parameters
376 * @param $opts Array Operation options
379 final public function delete( array $params, array $opts = array() ) {
380 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
384 * Perform a set of independent file operations on some files.
386 * This does no locking, nor journaling, and possibly no stat calls.
387 * Any destination files that already exist will be overwritten.
388 * This should *only* be used on non-original files, like cache files.
390 * Supported operations and their parameters:
398 * a) Create a new file in storage with the contents of a string
402 * 'dst' => <storage path>,
403 * 'content' => <string of new file contents>
406 * b) Copy a file system file into storage
410 * 'src' => <file system path>,
411 * 'dst' => <storage path>
414 * c) Copy a file within storage
418 * 'src' => <storage path>,
419 * 'dst' => <storage path>
422 * d) Move a file within storage
426 * 'src' => <storage path>,
427 * 'dst' => <storage path>
430 * e) Delete a file within storage
434 * 'src' => <storage path>,
435 * 'ignoreMissingSource' => <boolean>
438 * f) Do nothing (no-op)
445 * @par Boolean flags for operations (operation-specific):
446 * - ignoreMissingSource : The operation will simply succeed and do
447 * nothing if the source file does not exist.
449 * $opts is an associative of boolean flags, including:
450 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
453 * This returns a Status, which contains all warnings and fatals that occurred
454 * during the operation. The 'failCount', 'successCount', and 'success' members
455 * will reflect each operation attempted for the given files. The status will be
456 * considered "OK" as long as no fatal errors occurred.
458 * @param $ops Array Set of operations to execute
459 * @param $opts Array Batch operation options
463 final public function doQuickOperations( array $ops, array $opts = array() ) {
464 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
465 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
467 foreach ( $ops as &$op ) {
468 $op['overwrite'] = true; // avoids RTTs in key/value stores
470 return $this->doQuickOperationsInternal( $ops );
474 * @see FileBackend::doQuickOperations()
477 abstract protected function doQuickOperationsInternal( array $ops );
480 * Same as doQuickOperations() except it takes a single operation.
481 * If you are doing a batch of operations, then use that function instead.
483 * @see FileBackend::doQuickOperations()
485 * @param $op Array Operation
489 final public function doQuickOperation( array $op ) {
490 return $this->doQuickOperations( array( $op ) );
494 * Performs a single quick create operation.
495 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
497 * @see FileBackend::doQuickOperation()
499 * @param $params Array Operation parameters
503 final public function quickCreate( array $params ) {
504 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
508 * Performs a single quick store operation.
509 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
511 * @see FileBackend::doQuickOperation()
513 * @param $params Array Operation parameters
517 final public function quickStore( array $params ) {
518 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
522 * Performs a single quick copy operation.
523 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
525 * @see FileBackend::doQuickOperation()
527 * @param $params Array Operation parameters
531 final public function quickCopy( array $params ) {
532 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
536 * Performs a single quick move operation.
537 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
539 * @see FileBackend::doQuickOperation()
541 * @param $params Array Operation parameters
545 final public function quickMove( array $params ) {
546 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
550 * Performs a single quick delete operation.
551 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
553 * @see FileBackend::doQuickOperation()
555 * @param $params Array Operation parameters
559 final public function quickDelete( array $params ) {
560 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
564 * Concatenate a list of storage files into a single file system file.
565 * The target path should refer to a file that is already locked or
566 * otherwise safe from modification from other processes. Normally,
567 * the file will be a new temp file, which should be adequate.
569 * @param $params Array Operation parameters
571 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
572 * - dst : file system path to 0-byte temp file
575 abstract public function concatenate( array $params );
578 * Prepare a storage directory for usage.
579 * This will create any required containers and parent directories.
580 * Backends using key/value stores only need to create the container.
582 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
583 * except they are only applied *if* the directory/container had to be created.
584 * These flags should always be set for directories that have private files.
586 * @param $params Array
588 * - dir : storage directory
589 * - noAccess : try to deny file access (since 1.20)
590 * - noListing : try to deny file listing (since 1.20)
591 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
594 final public function prepare( array $params ) {
595 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
596 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
598 return $this->doPrepare( $params );
602 * @see FileBackend::prepare()
604 abstract protected function doPrepare( array $params );
607 * Take measures to block web access to a storage directory and
608 * the container it belongs to. FS backends might add .htaccess
609 * files whereas key/value store backends might revoke container
610 * access to the storage user representing end-users in web requests.
611 * This is not guaranteed to actually do anything.
613 * @param $params Array
615 * - dir : storage directory
616 * - noAccess : try to deny file access
617 * - noListing : try to deny file listing
618 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
621 final public function secure( array $params ) {
622 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
623 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
625 return $this->doSecure( $params );
629 * @see FileBackend::secure()
631 abstract protected function doSecure( array $params );
634 * Remove measures to block web access to a storage directory and
635 * the container it belongs to. FS backends might remove .htaccess
636 * files whereas key/value store backends might grant container
637 * access to the storage user representing end-users in web requests.
638 * This essentially can undo the result of secure() calls.
640 * @param $params Array
642 * - dir : storage directory
643 * - access : try to allow file access
644 * - listing : try to allow file listing
645 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
649 final public function publish( array $params ) {
650 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
651 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
653 return $this->doPublish( $params );
657 * @see FileBackend::publish()
659 abstract protected function doPublish( array $params );
662 * Delete a storage directory if it is empty.
663 * Backends using key/value stores may do nothing unless the directory
664 * is that of an empty container, in which case it should be deleted.
666 * @param $params Array
668 * - dir : storage directory
669 * - recursive : recursively delete empty subdirectories first (since 1.20)
670 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
673 final public function clean( array $params ) {
674 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
675 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
677 return $this->doClean( $params );
681 * @see FileBackend::clean()
683 abstract protected function doClean( array $params );
686 * Check if a file exists at a storage path in the backend.
687 * This returns false if only a directory exists at the path.
689 * @param $params Array
691 * - src : source storage path
692 * - latest : use the latest available data
693 * @return bool|null Returns null on failure
695 abstract public function fileExists( array $params );
698 * Get the last-modified timestamp of the file at a storage path.
700 * @param $params Array
702 * - src : source storage path
703 * - latest : use the latest available data
704 * @return string|bool TS_MW timestamp or false on failure
706 abstract public function getFileTimestamp( array $params );
709 * Get the contents of a file at a storage path in the backend.
710 * This should be avoided for potentially large files.
712 * @param $params Array
714 * - src : source storage path
715 * - latest : use the latest available data
716 * @return string|bool Returns false on failure
718 abstract public function getFileContents( array $params );
721 * Get the size (bytes) of a file at a storage path in the backend.
723 * @param $params Array
725 * - src : source storage path
726 * - latest : use the latest available data
727 * @return integer|bool Returns false on failure
729 abstract public function getFileSize( array $params );
732 * Get quick information about a file at a storage path in the backend.
733 * If the file does not exist, then this returns false.
734 * Otherwise, the result is an associative array that includes:
735 * - mtime : the last-modified timestamp (TS_MW)
736 * - size : the file size (bytes)
737 * Additional values may be included for internal use only.
739 * @param $params Array
741 * - src : source storage path
742 * - latest : use the latest available data
743 * @return Array|bool|null Returns null on failure
745 abstract public function getFileStat( array $params );
748 * Get a SHA-1 hash of the file at a storage path in the backend.
750 * @param $params Array
752 * - src : source storage path
753 * - latest : use the latest available data
754 * @return string|bool Hash string or false on failure
756 abstract public function getFileSha1Base36( array $params );
759 * Get the properties of the file at a storage path in the backend.
760 * Returns FSFile::placeholderProps() on failure.
762 * @param $params Array
764 * - src : source storage path
765 * - latest : use the latest available data
768 abstract public function getFileProps( array $params );
771 * Stream the file at a storage path in the backend.
772 * If the file does not exists, a 404 error will be given.
773 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
774 * must be sent if streaming began, while none should be sent otherwise.
775 * Implementations should flush the output buffer before sending data.
777 * @param $params Array
779 * - src : source storage path
780 * - headers : additional HTTP headers to send on success
781 * - latest : use the latest available data
784 abstract public function streamFile( array $params );
787 * Returns a file system file, identical to the file at a storage path.
788 * The file returned is either:
789 * - a) A local copy of the file at a storage path in the backend.
790 * The temporary copy will have the same extension as the source.
791 * - b) An original of the file at a storage path in the backend.
792 * Temporary files may be purged when the file object falls out of scope.
794 * Write operations should *never* be done on this file as some backends
795 * may do internal tracking or may be instances of FileBackendMultiWrite.
796 * In that later case, there are copies of the file that must stay in sync.
797 * Additionally, further calls to this function may return the same file.
799 * @param $params Array
801 * - src : source storage path
802 * - latest : use the latest available data
803 * @return FSFile|null Returns null on failure
805 abstract public function getLocalReference( array $params );
808 * Get a local copy on disk of the file at a storage path in the backend.
809 * The temporary copy will have the same file extension as the source.
810 * Temporary files may be purged when the file object falls out of scope.
812 * @param $params Array
814 * - src : source storage path
815 * - latest : use the latest available data
816 * @return TempFSFile|null Returns null on failure
818 abstract public function getLocalCopy( array $params );
821 * Check if a directory exists at a given storage path.
822 * Backends using key/value stores will check if the path is a
823 * virtual directory, meaning there are files under the given directory.
825 * Storage backends with eventual consistency might return stale data.
827 * @param $params array
829 * - dir : storage directory
830 * @return bool|null Returns null on failure
833 abstract public function directoryExists( array $params );
836 * Get an iterator to list *all* directories under a storage directory.
837 * If the directory is of the form "mwstore://backend/container",
838 * then all directories in the container should be listed.
839 * If the directory is of form "mwstore://backend/container/dir",
840 * then all directories directly under that directory should be listed.
841 * Results should be storage directories relative to the given directory.
843 * Storage backends with eventual consistency might return stale data.
845 * @param $params array
847 * - dir : storage directory
848 * - topOnly : only return direct child dirs of the directory
849 * @return Traversable|Array|null Returns null on failure
852 abstract public function getDirectoryList( array $params );
855 * Same as FileBackend::getDirectoryList() except only lists
856 * directories that are immediately under the given directory.
858 * Storage backends with eventual consistency might return stale data.
860 * @param $params array
862 * - dir : storage directory
863 * @return Traversable|Array|null Returns null on failure
866 final public function getTopDirectoryList( array $params ) {
867 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
871 * Get an iterator to list *all* stored files under a storage directory.
872 * If the directory is of the form "mwstore://backend/container",
873 * then all files in the container should be listed.
874 * If the directory is of form "mwstore://backend/container/dir",
875 * then all files under that directory should be listed.
876 * Results should be storage paths relative to the given directory.
878 * Storage backends with eventual consistency might return stale data.
880 * @param $params array
882 * - dir : storage directory
883 * - topOnly : only return direct child files of the directory (since 1.20)
884 * @return Traversable|Array|null Returns null on failure
886 abstract public function getFileList( array $params );
889 * Same as FileBackend::getFileList() except only lists
890 * files that are immediately under the given directory.
892 * Storage backends with eventual consistency might return stale data.
894 * @param $params array
896 * - dir : storage directory
897 * @return Traversable|Array|null Returns null on failure
900 final public function getTopFileList( array $params ) {
901 return $this->getFileList( array( 'topOnly' => true ) +
$params );
905 * Preload persistent file stat and property cache into in-process cache.
906 * This should be used when stat calls will be made on a known list of a many files.
908 * @param $paths Array Storage paths
911 public function preloadCache( array $paths ) {}
914 * Invalidate any in-process file stat and property cache.
915 * If $paths is given, then only the cache for those files will be cleared.
917 * @param $paths Array Storage paths (optional)
920 public function clearCache( array $paths = null ) {}
923 * Lock the files at the given storage paths in the backend.
924 * This will either lock all the files or none (on failure).
926 * Callers should consider using getScopedFileLocks() instead.
928 * @param $paths Array Storage paths
929 * @param $type integer LockManager::LOCK_* constant
932 final public function lockFiles( array $paths, $type ) {
933 return $this->lockManager
->lock( $paths, $type );
937 * Unlock the files at the given storage paths in the backend.
939 * @param $paths Array Storage paths
940 * @param $type integer LockManager::LOCK_* constant
943 final public function unlockFiles( array $paths, $type ) {
944 return $this->lockManager
->unlock( $paths, $type );
948 * Lock the files at the given storage paths in the backend.
949 * This will either lock all the files or none (on failure).
950 * On failure, the status object will be updated with errors.
952 * Once the return value goes out scope, the locks will be released and
953 * the status updated. Unlock fatals will not change the status "OK" value.
955 * @param $paths Array Storage paths
956 * @param $type integer LockManager::LOCK_* constant
957 * @param $status Status Status to update on lock/unlock
958 * @return ScopedLock|null Returns null on failure
960 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
961 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
965 * Get an array of scoped locks needed for a batch of file operations.
967 * Normally, FileBackend::doOperations() handles locking, unless
968 * the 'nonLocking' param is passed in. This function is useful if you
969 * want the files to be locked for a broader scope than just when the
970 * files are changing. For example, if you need to update DB metadata,
971 * you may want to keep the files locked until finished.
973 * @see FileBackend::doOperations()
975 * @param $ops Array List of file operations to FileBackend::doOperations()
976 * @param $status Status Status to update on lock/unlock
977 * @return Array List of ScopedFileLocks or null values
980 abstract public function getScopedLocksForOps( array $ops, Status
$status );
983 * Get the root storage path of this backend.
984 * All container paths are "subdirectories" of this path.
986 * @return string Storage path
989 final public function getRootStoragePath() {
990 return "mwstore://{$this->name}";
994 * Get the file journal object for this backend
996 * @return FileJournal
998 final public function getJournal() {
999 return $this->fileJournal
;
1003 * Check if a given path is a "mwstore://" path.
1004 * This does not do any further validation or any existence checks.
1006 * @param $path string
1009 final public static function isStoragePath( $path ) {
1010 return ( strpos( $path, 'mwstore://' ) === 0 );
1014 * Split a storage path into a backend name, a container name,
1015 * and a relative file path. The relative path may be the empty string.
1016 * This does not do any path normalization or traversal checks.
1018 * @param $storagePath string
1019 * @return Array (backend, container, rel object) or (null, null, null)
1021 final public static function splitStoragePath( $storagePath ) {
1022 if ( self
::isStoragePath( $storagePath ) ) {
1023 // Remove the "mwstore://" prefix and split the path
1024 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1025 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1026 if ( count( $parts ) == 3 ) {
1027 return $parts; // e.g. "backend/container/path"
1029 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1033 return array( null, null, null );
1037 * Normalize a storage path by cleaning up directory separators.
1038 * Returns null if the path is not of the format of a valid storage path.
1040 * @param $storagePath string
1041 * @return string|null
1043 final public static function normalizeStoragePath( $storagePath ) {
1044 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1045 if ( $relPath !== null ) { // must be for this backend
1046 $relPath = self
::normalizeContainerPath( $relPath );
1047 if ( $relPath !== null ) {
1048 return ( $relPath != '' )
1049 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1050 : "mwstore://{$backend}/{$container}";
1057 * Get the parent storage directory of a storage path.
1058 * This returns a path like "mwstore://backend/container",
1059 * "mwstore://backend/container/...", or null if there is no parent.
1061 * @param $storagePath string
1062 * @return string|null
1064 final public static function parentStoragePath( $storagePath ) {
1065 $storagePath = dirname( $storagePath );
1066 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1067 return ( $rel === null ) ?
null : $storagePath;
1071 * Get the final extension from a storage or FS path
1073 * @param $path string
1076 final public static function extensionFromPath( $path ) {
1077 $i = strrpos( $path, '.' );
1078 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1082 * Check if a relative path has no directory traversals
1084 * @param $path string
1088 final public static function isPathTraversalFree( $path ) {
1089 return ( self
::normalizeContainerPath( $path ) !== null );
1093 * Validate and normalize a relative storage path.
1094 * Null is returned if the path involves directory traversal.
1095 * Traversal is insecure for FS backends and broken for others.
1097 * This uses the same traversal protection as Title::secureAndSplit().
1099 * @param $path string Storage path relative to a container
1100 * @return string|null
1102 final protected static function normalizeContainerPath( $path ) {
1103 // Normalize directory separators
1104 $path = strtr( $path, '\\', '/' );
1105 // Collapse any consecutive directory separators
1106 $path = preg_replace( '![/]{2,}!', '/', $path );
1107 // Remove any leading directory separator
1108 $path = ltrim( $path, '/' );
1109 // Use the same traversal protection as Title::secureAndSplit()
1110 if ( strpos( $path, '.' ) !== false ) {
1114 strpos( $path, './' ) === 0 ||
1115 strpos( $path, '../' ) === 0 ||
1116 strpos( $path, '/./' ) !== false ||
1117 strpos( $path, '/../' ) !== false