(bug 35060) more allowed params to Special:MyPage, Special:MyTalk
[mediawiki.git] / includes / filerepo / backend / FileBackend.php
blob21261fa8c3602b26631db827372b2d5927081ef9
1 <?php
2 /**
3 * @defgroup FileBackend File backend
4 * @ingroup FileRepo
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
8 */
10 /**
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
28 * @file
29 * @ingroup FileBackend
30 * @author Aaron Schulz
33 /**
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.
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
58 * @since 1.19
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;
72 /**
73 * Create a new backend instance from configuration.
74 * This should only be called from within FileBackendGroup.
76 * $config includes:
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
92 * @throws MWException
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'] )
100 ? $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']
112 : '';
113 $this->parallelize = isset( $config['parallelize'] )
114 ? (string)$config['parallelize']
115 : 'off';
116 $this->concurrency = isset( $config['concurrency'] )
117 ? (int)$config['concurrency']
118 : 50;
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.
126 * @return string
128 final public function getName() {
129 return $this->name;
133 * Check if this backend is read-only
135 * @return bool
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:
160 * - create
161 * - store
162 * - copy
163 * - move
164 * - delete
165 * - null
167 * a) Create a new file in storage with the contents of a string
168 * @code
169 * array(
170 * 'op' => 'create',
171 * 'dst' => <storage path>,
172 * 'content' => <string of new file contents>,
173 * 'overwrite' => <boolean>,
174 * 'overwriteSame' => <boolean>
175 * );
176 * @endcode
178 * b) Copy a file system file into storage
179 * @code
180 * array(
181 * 'op' => 'store',
182 * 'src' => <file system path>,
183 * 'dst' => <storage path>,
184 * 'overwrite' => <boolean>,
185 * 'overwriteSame' => <boolean>
187 * @endcode
189 * c) Copy a file within storage
190 * @code
191 * array(
192 * 'op' => 'copy',
193 * 'src' => <storage path>,
194 * 'dst' => <storage path>,
195 * 'overwrite' => <boolean>,
196 * 'overwriteSame' => <boolean>
198 * @endcode
200 * d) Move a file within storage
201 * @code
202 * array(
203 * 'op' => 'move',
204 * 'src' => <storage path>,
205 * 'dst' => <storage path>,
206 * 'overwrite' => <boolean>,
207 * 'overwriteSame' => <boolean>
209 * @endcode
211 * e) Delete a file within storage
212 * @code
213 * array(
214 * 'op' => 'delete',
215 * 'src' => <storage path>,
216 * 'ignoreMissingSource' => <boolean>
218 * @endcode
220 * f) Do nothing (no-op)
221 * @code
222 * array(
223 * 'op' => 'null',
225 * @endcode
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 * - nonJournaled : Don't log this operation batch in the file journal.
246 * This limits the ability of recovery scripts.
247 * - parallelize : Try to do operations in parallel when possible.
248 * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
250 * @remarks Remarks on locking:
251 * File system paths given to operations should refer to files that are
252 * already locked or otherwise safe from modification from other processes.
253 * Normally these files will be new temp files, which should be adequate.
255 * @par Return value:
257 * This returns a Status, which contains all warnings and fatals that occured
258 * during the operation. The 'failCount', 'successCount', and 'success' members
259 * will reflect each operation attempted.
261 * The status will be "OK" unless:
262 * - a) unexpected operation errors occurred (network partitions, disk full...)
263 * - b) significant operation errors occured and 'force' was not set
265 * @param $ops Array List of operations to execute in order
266 * @param $opts Array Batch operation options
267 * @return Status
269 final public function doOperations( array $ops, array $opts = array() ) {
270 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
271 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
273 if ( empty( $opts['force'] ) ) { // sanity
274 unset( $opts['nonLocking'] );
275 unset( $opts['allowStale'] );
277 $opts['concurrency'] = 1; // off
278 if ( $this->parallelize === 'implicit' ) {
279 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
280 $opts['concurrency'] = $this->concurrency;
282 } elseif ( $this->parallelize === 'explicit' ) {
283 if ( !empty( $opts['parallelize'] ) ) {
284 $opts['concurrency'] = $this->concurrency;
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
304 * @return Status
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
318 * @return Status
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
332 * @return Status
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
346 * @return Status
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
360 * @return Status
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
374 * @return Status
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:
388 * - create
389 * - store
390 * - copy
391 * - move
392 * - delete
393 * - null
395 * a) Create a new file in storage with the contents of a string
396 * @code
397 * array(
398 * 'op' => 'create',
399 * 'dst' => <storage path>,
400 * 'content' => <string of new file contents>
402 * @endcode
403 * b) Copy a file system file into storage
404 * @code
405 * array(
406 * 'op' => 'store',
407 * 'src' => <file system path>,
408 * 'dst' => <storage path>
410 * @endcode
411 * c) Copy a file within storage
412 * @code
413 * array(
414 * 'op' => 'copy',
415 * 'src' => <storage path>,
416 * 'dst' => <storage path>
418 * @endcode
419 * d) Move a file within storage
420 * @code
421 * array(
422 * 'op' => 'move',
423 * 'src' => <storage path>,
424 * 'dst' => <storage path>
426 * @endcode
427 * e) Delete a file within storage
428 * @code
429 * array(
430 * 'op' => 'delete',
431 * 'src' => <storage path>,
432 * 'ignoreMissingSource' => <boolean>
434 * @endcode
435 * f) Do nothing (no-op)
436 * @code
437 * array(
438 * 'op' => 'null',
440 * @endcode
442 * @par Boolean flags for operations (operation-specific):
443 * - ignoreMissingSource : The operation will simply succeed and do
444 * nothing if the source file does not exist.
446 * $opts is an associative of boolean flags, including:
447 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
449 * @par Return value:
450 * This returns a Status, which contains all warnings and fatals that occured
451 * during the operation. The 'failCount', 'successCount', and 'success' members
452 * will reflect each operation attempted for the given files. The status will be
453 * considered "OK" as long as no fatal errors occured.
455 * @param $ops Array Set of operations to execute
456 * @param $opts Array Batch operation options
457 * @return Status
458 * @since 1.20
460 final public function doQuickOperations( array $ops, array $opts = array() ) {
461 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
462 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
464 foreach ( $ops as &$op ) {
465 $op['overwrite'] = true; // avoids RTTs in key/value stores
467 return $this->doQuickOperationsInternal( $ops );
471 * @see FileBackend::doQuickOperations()
472 * @since 1.20
474 abstract protected function doQuickOperationsInternal( array $ops );
477 * Same as doQuickOperations() except it takes a single operation.
478 * If you are doing a batch of operations, then use that function instead.
480 * @see FileBackend::doQuickOperations()
482 * @param $op Array Operation
483 * @return Status
484 * @since 1.20
486 final public function doQuickOperation( array $op ) {
487 return $this->doQuickOperations( array( $op ) );
491 * Performs a single quick create operation.
492 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
494 * @see FileBackend::doQuickOperation()
496 * @param $params Array Operation parameters
497 * @return Status
498 * @since 1.20
500 final public function quickCreate( array $params ) {
501 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
505 * Performs a single quick store operation.
506 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
508 * @see FileBackend::doQuickOperation()
510 * @param $params Array Operation parameters
511 * @return Status
512 * @since 1.20
514 final public function quickStore( array $params ) {
515 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
519 * Performs a single quick copy operation.
520 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
522 * @see FileBackend::doQuickOperation()
524 * @param $params Array Operation parameters
525 * @return Status
526 * @since 1.20
528 final public function quickCopy( array $params ) {
529 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
533 * Performs a single quick move operation.
534 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
536 * @see FileBackend::doQuickOperation()
538 * @param $params Array Operation parameters
539 * @return Status
540 * @since 1.20
542 final public function quickMove( array $params ) {
543 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
547 * Performs a single quick delete operation.
548 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
550 * @see FileBackend::doQuickOperation()
552 * @param $params Array Operation parameters
553 * @return Status
554 * @since 1.20
556 final public function quickDelete( array $params ) {
557 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
561 * Concatenate a list of storage files into a single file system file.
562 * The target path should refer to a file that is already locked or
563 * otherwise safe from modification from other processes. Normally,
564 * the file will be a new temp file, which should be adequate.
566 * @param $params Array Operation parameters
567 * $params include:
568 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
569 * - dst : file system path to 0-byte temp file
570 * @return Status
572 abstract public function concatenate( array $params );
575 * Prepare a storage directory for usage.
576 * This will create any required containers and parent directories.
577 * Backends using key/value stores only need to create the container.
579 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
580 * except they are only applied *if* the directory/container had to be created.
581 * These flags should always be set for directories that have private files.
583 * $params include:
584 * - dir : storage directory
585 * - noAccess : try to deny file access (since 1.20)
586 * - noListing : try to deny file listing (since 1.20)
587 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
589 * @param $params Array
590 * @return Status
592 final public function prepare( array $params ) {
593 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
594 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
596 return $this->doPrepare( $params );
600 * @see FileBackend::prepare()
602 abstract protected function doPrepare( array $params );
605 * Take measures to block web access to a storage directory and
606 * the container it belongs to. FS backends might add .htaccess
607 * files whereas key/value store backends might revoke container
608 * access to the storage user representing end-users in web requests.
609 * This is not guaranteed to actually do anything.
611 * @param $params Array
612 * $params include:
613 * - dir : storage directory
614 * - noAccess : try to deny file access
615 * - noListing : try to deny file listing
616 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
617 * @return Status
619 final public function secure( array $params ) {
620 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
621 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
623 return $this->doSecure( $params );
627 * @see FileBackend::secure()
629 abstract protected function doSecure( array $params );
632 * Remove measures to block web access to a storage directory and
633 * the container it belongs to. FS backends might remove .htaccess
634 * files whereas key/value store backends might grant container
635 * access to the storage user representing end-users in web requests.
636 * This essentially can undo the result of secure() calls.
638 * $params include:
639 * - dir : storage directory
640 * - access : try to allow file access
641 * - listing : try to allow file listing
642 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
644 * @param $params Array
645 * @return Status
646 * @since 1.20
648 final public function publish( array $params ) {
649 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
650 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
652 return $this->doPublish( $params );
656 * @see FileBackend::publish()
658 abstract protected function doPublish( array $params );
661 * Delete a storage directory if it is empty.
662 * Backends using key/value stores may do nothing unless the directory
663 * is that of an empty container, in which case it should be deleted.
665 * @param $params Array
666 * $params include:
667 * - dir : storage directory
668 * - recursive : recursively delete empty subdirectories first (since 1.20)
669 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
670 * @return Status
672 final public function clean( array $params ) {
673 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
674 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
676 return $this->doClean( $params );
680 * @see FileBackend::clean()
682 abstract protected function doClean( array $params );
685 * Check if a file exists at a storage path in the backend.
686 * This returns false if only a directory exists at the path.
688 * @param $params Array
689 * $params include:
690 * - src : source storage path
691 * - latest : use the latest available data
692 * @return bool|null Returns null on failure
694 abstract public function fileExists( array $params );
697 * Get the last-modified timestamp of the file at a storage path.
699 * @param $params Array
700 * $params include:
701 * - src : source storage path
702 * - latest : use the latest available data
703 * @return string|bool TS_MW timestamp or false on failure
705 abstract public function getFileTimestamp( array $params );
708 * Get the contents of a file at a storage path in the backend.
709 * This should be avoided for potentially large files.
711 * @param $params Array
712 * $params include:
713 * - src : source storage path
714 * - latest : use the latest available data
715 * @return string|bool Returns false on failure
717 abstract public function getFileContents( array $params );
720 * Get the size (bytes) of a file at a storage path in the backend.
722 * @param $params Array
723 * $params include:
724 * - src : source storage path
725 * - latest : use the latest available data
726 * @return integer|bool Returns false on failure
728 abstract public function getFileSize( array $params );
731 * Get quick information about a file at a storage path in the backend.
732 * If the file does not exist, then this returns false.
733 * Otherwise, the result is an associative array that includes:
734 * - mtime : the last-modified timestamp (TS_MW)
735 * - size : the file size (bytes)
736 * Additional values may be included for internal use only.
738 * @param $params Array
739 * $params include:
740 * - src : source storage path
741 * - latest : use the latest available data
742 * @return Array|bool|null Returns null on failure
744 abstract public function getFileStat( array $params );
747 * Get a SHA-1 hash of the file at a storage path in the backend.
749 * @param $params Array
750 * $params include:
751 * - src : source storage path
752 * - latest : use the latest available data
753 * @return string|bool Hash string or false on failure
755 abstract public function getFileSha1Base36( array $params );
758 * Get the properties of the file at a storage path in the backend.
759 * Returns FSFile::placeholderProps() on failure.
761 * @param $params Array
762 * $params include:
763 * - src : source storage path
764 * - latest : use the latest available data
765 * @return Array
767 abstract public function getFileProps( array $params );
770 * Stream the file at a storage path in the backend.
771 * If the file does not exists, a 404 error will be given.
772 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
773 * must be sent if streaming began, while none should be sent otherwise.
774 * Implementations should flush the output buffer before sending data.
776 * @param $params Array
777 * $params include:
778 * - src : source storage path
779 * - headers : additional HTTP headers to send on success
780 * - latest : use the latest available data
781 * @return Status
783 abstract public function streamFile( array $params );
786 * Returns a file system file, identical to the file at a storage path.
787 * The file returned is either:
788 * a) A local copy of the file at a storage path in the backend.
789 * The temporary copy will have the same extension as the source.
790 * b) An original of the file at a storage path in the backend.
791 * Temporary files may be purged when the file object falls out of scope.
793 * Write operations should *never* be done on this file as some backends
794 * may do internal tracking or may be instances of FileBackendMultiWrite.
795 * In that later case, there are copies of the file that must stay in sync.
796 * Additionally, further calls to this function may return the same file.
798 * @param $params Array
799 * $params include:
800 * - src : source storage path
801 * - latest : use the latest available data
802 * @return FSFile|null Returns null on failure
804 abstract public function getLocalReference( array $params );
807 * Get a local copy on disk of the file at a storage path in the backend.
808 * The temporary copy will have the same file extension as the source.
809 * Temporary files may be purged when the file object falls out of scope.
811 * @param $params Array
812 * $params include:
813 * - src : source storage path
814 * - latest : use the latest available data
815 * @return TempFSFile|null Returns null on failure
817 abstract public function getLocalCopy( array $params );
820 * Check if a directory exists at a given storage path.
821 * Backends using key/value stores will check if the path is a
822 * virtual directory, meaning there are files under the given directory.
824 * Storage backends with eventual consistency might return stale data.
826 * @param $params array
827 * $params include:
828 * - dir : storage directory
829 * @return bool|null Returns null on failure
830 * @since 1.20
832 abstract public function directoryExists( array $params );
835 * Get an iterator to list *all* directories under a storage directory.
836 * If the directory is of the form "mwstore://backend/container",
837 * then all directories in the container should be listed.
838 * If the directory is of form "mwstore://backend/container/dir",
839 * then all directories directly under that directory should be listed.
840 * Results should be storage directories relative to the given directory.
842 * Storage backends with eventual consistency might return stale data.
844 * @param $params array
845 * $params include:
846 * - dir : storage directory
847 * - topOnly : only return direct child dirs of the directory
848 * @return Traversable|Array|null Returns null on failure
849 * @since 1.20
851 abstract public function getDirectoryList( array $params );
854 * Same as FileBackend::getDirectoryList() except only lists
855 * directories that are immediately under the given directory.
857 * Storage backends with eventual consistency might return stale data.
859 * @param $params array
860 * $params include:
861 * - dir : storage directory
862 * @return Traversable|Array|null Returns null on failure
863 * @since 1.20
865 final public function getTopDirectoryList( array $params ) {
866 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
870 * Get an iterator to list *all* stored files under a storage directory.
871 * If the directory is of the form "mwstore://backend/container",
872 * then all files in the container should be listed.
873 * If the directory is of form "mwstore://backend/container/dir",
874 * then all files under that directory should be listed.
875 * Results should be storage paths relative to the given directory.
877 * Storage backends with eventual consistency might return stale data.
879 * @param $params array
880 * $params include:
881 * - dir : storage directory
882 * - topOnly : only return direct child files of the directory (since 1.20)
883 * @return Traversable|Array|null Returns null on failure
885 abstract public function getFileList( array $params );
888 * Same as FileBackend::getFileList() except only lists
889 * files that are immediately under the given directory.
891 * Storage backends with eventual consistency might return stale data.
893 * @param $params array
894 * $params include:
895 * - dir : storage directory
896 * @return Traversable|Array|null Returns null on failure
897 * @since 1.20
899 final public function getTopFileList( array $params ) {
900 return $this->getFileList( array( 'topOnly' => true ) + $params );
904 * Invalidate any in-process file existence and property cache.
905 * If $paths is given, then only the cache for those files will be cleared.
907 * @param $paths Array Storage paths (optional)
908 * @return void
910 public function clearCache( array $paths = null ) {}
913 * Lock the files at the given storage paths in the backend.
914 * This will either lock all the files or none (on failure).
916 * Callers should consider using getScopedFileLocks() instead.
918 * @param $paths Array Storage paths
919 * @param $type integer LockManager::LOCK_* constant
920 * @return Status
922 final public function lockFiles( array $paths, $type ) {
923 return $this->lockManager->lock( $paths, $type );
927 * Unlock the files at the given storage paths in the backend.
929 * @param $paths Array Storage paths
930 * @param $type integer LockManager::LOCK_* constant
931 * @return Status
933 final public function unlockFiles( array $paths, $type ) {
934 return $this->lockManager->unlock( $paths, $type );
938 * Lock the files at the given storage paths in the backend.
939 * This will either lock all the files or none (on failure).
940 * On failure, the status object will be updated with errors.
942 * Once the return value goes out scope, the locks will be released and
943 * the status updated. Unlock fatals will not change the status "OK" value.
945 * @param $paths Array Storage paths
946 * @param $type integer LockManager::LOCK_* constant
947 * @param $status Status Status to update on lock/unlock
948 * @return ScopedLock|null Returns null on failure
950 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
951 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
955 * Get an array of scoped locks needed for a batch of file operations.
957 * Normally, FileBackend::doOperations() handles locking, unless
958 * the 'nonLocking' param is passed in. This function is useful if you
959 * want the files to be locked for a broader scope than just when the
960 * files are changing. For example, if you need to update DB metadata,
961 * you may want to keep the files locked until finished.
963 * @see FileBackend::doOperations()
965 * @param $ops Array List of file operations to FileBackend::doOperations()
966 * @param $status Status Status to update on lock/unlock
967 * @return Array List of ScopedFileLocks or null values
968 * @since 1.20
970 abstract public function getScopedLocksForOps( array $ops, Status $status );
973 * Get the root storage path of this backend.
974 * All container paths are "subdirectories" of this path.
976 * @return string Storage path
977 * @since 1.20
979 final public function getRootStoragePath() {
980 return "mwstore://{$this->name}";
984 * Get the file journal object for this backend
986 * @return FileJournal
988 final public function getJournal() {
989 return $this->fileJournal;
993 * Check if a given path is a "mwstore://" path.
994 * This does not do any further validation or any existence checks.
996 * @param $path string
997 * @return bool
999 final public static function isStoragePath( $path ) {
1000 return ( strpos( $path, 'mwstore://' ) === 0 );
1004 * Split a storage path into a backend name, a container name,
1005 * and a relative file path. The relative path may be the empty string.
1006 * This does not do any path normalization or traversal checks.
1008 * @param $storagePath string
1009 * @return Array (backend, container, rel object) or (null, null, null)
1011 final public static function splitStoragePath( $storagePath ) {
1012 if ( self::isStoragePath( $storagePath ) ) {
1013 // Remove the "mwstore://" prefix and split the path
1014 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1015 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1016 if ( count( $parts ) == 3 ) {
1017 return $parts; // e.g. "backend/container/path"
1018 } else {
1019 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1023 return array( null, null, null );
1027 * Normalize a storage path by cleaning up directory separators.
1028 * Returns null if the path is not of the format of a valid storage path.
1030 * @param $storagePath string
1031 * @return string|null
1033 final public static function normalizeStoragePath( $storagePath ) {
1034 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1035 if ( $relPath !== null ) { // must be for this backend
1036 $relPath = self::normalizeContainerPath( $relPath );
1037 if ( $relPath !== null ) {
1038 return ( $relPath != '' )
1039 ? "mwstore://{$backend}/{$container}/{$relPath}"
1040 : "mwstore://{$backend}/{$container}";
1043 return null;
1047 * Get the parent storage directory of a storage path.
1048 * This returns a path like "mwstore://backend/container",
1049 * "mwstore://backend/container/...", or null if there is no parent.
1051 * @param $storagePath string
1052 * @return string|null
1054 final public static function parentStoragePath( $storagePath ) {
1055 $storagePath = dirname( $storagePath );
1056 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
1057 return ( $rel === null ) ? null : $storagePath;
1061 * Get the final extension from a storage or FS path
1063 * @param $path string
1064 * @return string
1066 final public static function extensionFromPath( $path ) {
1067 $i = strrpos( $path, '.' );
1068 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1072 * Check if a relative path has no directory traversals
1074 * @param $path string
1075 * @return bool
1076 * @since 1.20
1078 final public static function isPathTraversalFree( $path ) {
1079 return ( self::normalizeContainerPath( $path ) !== null );
1083 * Validate and normalize a relative storage path.
1084 * Null is returned if the path involves directory traversal.
1085 * Traversal is insecure for FS backends and broken for others.
1087 * This uses the same traversal protection as Title::secureAndSplit().
1089 * @param $path string Storage path relative to a container
1090 * @return string|null
1092 final protected static function normalizeContainerPath( $path ) {
1093 // Normalize directory separators
1094 $path = strtr( $path, '\\', '/' );
1095 // Collapse any consecutive directory separators
1096 $path = preg_replace( '![/]{2,}!', '/', $path );
1097 // Remove any leading directory separator
1098 $path = ltrim( $path, '/' );
1099 // Use the same traversal protection as Title::secureAndSplit()
1100 if ( strpos( $path, '.' ) !== false ) {
1101 if (
1102 $path === '.' ||
1103 $path === '..' ||
1104 strpos( $path, './' ) === 0 ||
1105 strpos( $path, '../' ) === 0 ||
1106 strpos( $path, '/./' ) !== false ||
1107 strpos( $path, '/../' ) !== false
1109 return null;
1112 return $path;