Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / filerepo / backend / FileBackend.php
blob3cc902194544f61a9704c2a258c0925f9cfff79c
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) notation,
41 * though any particular backend may not actually be using a local filesystem.
42 * Therefore, the relative paths are only virtual.
44 * Backend contents are stored under wiki-specific container names by default.
45 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
46 * segregation must be done by setting the container paths appropriately.
48 * FS-based backends are somewhat more restrictive due to the existence of real
49 * directory files; a regular file cannot have the same name as a directory. Other
50 * backends with virtual directories may not have this limitation. Callers should
51 * store files in such a way that no files and directories are under the same path.
53 * Methods should avoid throwing exceptions at all costs.
54 * As a corollary, external dependencies should be kept to a minimum.
56 * @ingroup FileBackend
57 * @since 1.19
59 abstract class FileBackend {
60 protected $name; // string; unique backend name
61 protected $wikiId; // string; unique wiki name
62 protected $readOnly; // string; read-only explanation message
63 protected $parallelize; // string; when to do operations in parallel
64 protected $concurrency; // integer; how many operations can be done in parallel
66 /** @var LockManager */
67 protected $lockManager;
68 /** @var FileJournal */
69 protected $fileJournal;
71 /**
72 * Create a new backend instance from configuration.
73 * This should only be called from within FileBackendGroup.
75 * $config includes:
76 * 'name' : The unique name of this backend.
77 * This should consist of alphanumberic, '-', and '_' characters.
78 * This name should not be changed after use.
79 * 'wikiId' : Prefix to container names that is unique to this wiki.
80 * It should only consist of alphanumberic, '-', and '_' characters.
81 * 'lockManager' : Registered name of a file lock manager to use.
82 * 'fileJournal' : File journal configuration; see FileJournal::factory().
83 * Journals simply log changes to files stored in the backend.
84 * 'readOnly' : Write operations are disallowed if this is a non-empty string.
85 * It should be an explanation for the backend being read-only.
86 * 'parallelize' : When to do file operations in parallel (when possible).
87 * Allowed values are "implicit", "explicit" and "off".
88 * 'concurrency' : How many file operations can be done in parallel.
90 * @param $config Array
91 * @throws MWException
93 public function __construct( array $config ) {
94 $this->name = $config['name'];
95 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
96 throw new MWException( "Backend name `{$this->name}` is invalid." );
98 $this->wikiId = isset( $config['wikiId'] )
99 ? $config['wikiId']
100 : wfWikiID(); // e.g. "my_wiki-en_"
101 $this->lockManager = ( $config['lockManager'] instanceof LockManager )
102 ? $config['lockManager']
103 : LockManagerGroup::singleton()->get( $config['lockManager'] );
104 $this->fileJournal = isset( $config['fileJournal'] )
105 ? FileJournal::factory( $config['fileJournal'], $this->name )
106 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
107 $this->readOnly = isset( $config['readOnly'] )
108 ? (string)$config['readOnly']
109 : '';
110 $this->parallelize = isset( $config['parallelize'] )
111 ? (string)$config['parallelize']
112 : 'off';
113 $this->concurrency = isset( $config['concurrency'] )
114 ? (int)$config['concurrency']
115 : 50;
119 * Get the unique backend name.
120 * We may have multiple different backends of the same type.
121 * For example, we can have two Swift backends using different proxies.
123 * @return string
125 final public function getName() {
126 return $this->name;
130 * Check if this backend is read-only
132 * @return bool
134 final public function isReadOnly() {
135 return ( $this->readOnly != '' );
139 * Get an explanatory message if this backend is read-only
141 * @return string|bool Returns false if the backend is not read-only
143 final public function getReadOnlyReason() {
144 return ( $this->readOnly != '' ) ? $this->readOnly : false;
148 * This is the main entry point into the backend for write operations.
149 * Callers supply an ordered list of operations to perform as a transaction.
150 * Files will be locked, the stat cache cleared, and then the operations attempted.
151 * If any serious errors occur, all attempted operations will be rolled back.
153 * $ops is an array of arrays. The outer array holds a list of operations.
154 * Each inner array is a set of key value pairs that specify an operation.
156 * Supported operations and their parameters:
157 * a) Create a new file in storage with the contents of a string
158 * array(
159 * 'op' => 'create',
160 * 'dst' => <storage path>,
161 * 'content' => <string of new file contents>,
162 * 'overwrite' => <boolean>,
163 * 'overwriteSame' => <boolean>
165 * b) Copy a file system file into storage
166 * array(
167 * 'op' => 'store',
168 * 'src' => <file system path>,
169 * 'dst' => <storage path>,
170 * 'overwrite' => <boolean>,
171 * 'overwriteSame' => <boolean>
173 * c) Copy a file within storage
174 * array(
175 * 'op' => 'copy',
176 * 'src' => <storage path>,
177 * 'dst' => <storage path>,
178 * 'overwrite' => <boolean>,
179 * 'overwriteSame' => <boolean>
181 * d) Move a file within storage
182 * array(
183 * 'op' => 'move',
184 * 'src' => <storage path>,
185 * 'dst' => <storage path>,
186 * 'overwrite' => <boolean>,
187 * 'overwriteSame' => <boolean>
189 * e) Delete a file within storage
190 * array(
191 * 'op' => 'delete',
192 * 'src' => <storage path>,
193 * 'ignoreMissingSource' => <boolean>
195 * f) Do nothing (no-op)
196 * array(
197 * 'op' => 'null',
200 * Boolean flags for operations (operation-specific):
201 * 'ignoreMissingSource' : The operation will simply succeed and do
202 * nothing if the source file does not exist.
203 * 'overwrite' : Any destination file will be overwritten.
204 * 'overwriteSame' : An error will not be given if a file already
205 * exists at the destination that has the same
206 * contents as the new contents to be written there.
208 * $opts is an associative of boolean flags, including:
209 * 'force' : Operation precondition errors no longer trigger an abort.
210 * Any remaining operations are still attempted. Unexpected
211 * failures may still cause remaning operations to be aborted.
212 * 'nonLocking' : No locks are acquired for the operations.
213 * This can increase performance for non-critical writes.
214 * This has no effect unless the 'force' flag is set.
215 * 'allowStale' : Don't require the latest available data.
216 * This can increase performance for non-critical writes.
217 * This has no effect unless the 'force' flag is set.
218 * 'nonJournaled' : Don't log this operation batch in the file journal.
219 * This limits the ability of recovery scripts.
220 * 'parallelize' : Try to do operations in parallel when possible.
222 * Remarks on locking:
223 * File system paths given to operations should refer to files that are
224 * already locked or otherwise safe from modification from other processes.
225 * Normally these files will be new temp files, which should be adequate.
227 * Return value:
228 * This returns a Status, which contains all warnings and fatals that occured
229 * during the operation. The 'failCount', 'successCount', and 'success' members
230 * will reflect each operation attempted. The status will be "OK" unless:
231 * a) unexpected operation errors occurred (network partitions, disk full...)
232 * b) significant operation errors occured and 'force' was not set
234 * @param $ops Array List of operations to execute in order
235 * @param $opts Array Batch operation options
236 * @return Status
238 final public function doOperations( array $ops, array $opts = array() ) {
239 if ( $this->isReadOnly() ) {
240 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
242 if ( empty( $opts['force'] ) ) { // sanity
243 unset( $opts['nonLocking'] );
244 unset( $opts['allowStale'] );
246 $opts['concurrency'] = 1; // off
247 if ( $this->parallelize === 'implicit' ) {
248 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
249 $opts['concurrency'] = $this->concurrency;
251 } elseif ( $this->parallelize === 'explicit' ) {
252 if ( !empty( $opts['parallelize'] ) ) {
253 $opts['concurrency'] = $this->concurrency;
256 return $this->doOperationsInternal( $ops, $opts );
260 * @see FileBackend::doOperations()
262 abstract protected function doOperationsInternal( array $ops, array $opts );
265 * Same as doOperations() except it takes a single operation.
266 * If you are doing a batch of operations that should either
267 * all succeed or all fail, then use that function instead.
269 * @see FileBackend::doOperations()
271 * @param $op Array Operation
272 * @param $opts Array Operation options
273 * @return Status
275 final public function doOperation( array $op, array $opts = array() ) {
276 return $this->doOperations( array( $op ), $opts );
280 * Performs a single create operation.
281 * This sets $params['op'] to 'create' and passes it to doOperation().
283 * @see FileBackend::doOperation()
285 * @param $params Array Operation parameters
286 * @param $opts Array Operation options
287 * @return Status
289 final public function create( array $params, array $opts = array() ) {
290 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
294 * Performs a single store operation.
295 * This sets $params['op'] to 'store' and passes it to doOperation().
297 * @see FileBackend::doOperation()
299 * @param $params Array Operation parameters
300 * @param $opts Array Operation options
301 * @return Status
303 final public function store( array $params, array $opts = array() ) {
304 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
308 * Performs a single copy operation.
309 * This sets $params['op'] to 'copy' and passes it to doOperation().
311 * @see FileBackend::doOperation()
313 * @param $params Array Operation parameters
314 * @param $opts Array Operation options
315 * @return Status
317 final public function copy( array $params, array $opts = array() ) {
318 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
322 * Performs a single move operation.
323 * This sets $params['op'] to 'move' and passes it to doOperation().
325 * @see FileBackend::doOperation()
327 * @param $params Array Operation parameters
328 * @param $opts Array Operation options
329 * @return Status
331 final public function move( array $params, array $opts = array() ) {
332 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
336 * Performs a single delete operation.
337 * This sets $params['op'] to 'delete' and passes it to doOperation().
339 * @see FileBackend::doOperation()
341 * @param $params Array Operation parameters
342 * @param $opts Array Operation options
343 * @return Status
345 final public function delete( array $params, array $opts = array() ) {
346 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
350 * Perform a set of independent file operations on some files.
352 * This does no locking, nor journaling, and possibly no stat calls.
353 * Any destination files that already exist will be overwritten.
354 * This should *only* be used on non-original files, like cache files.
356 * Supported operations and their parameters:
357 * a) Create a new file in storage with the contents of a string
358 * array(
359 * 'op' => 'create',
360 * 'dst' => <storage path>,
361 * 'content' => <string of new file contents>
363 * b) Copy a file system file into storage
364 * array(
365 * 'op' => 'store',
366 * 'src' => <file system path>,
367 * 'dst' => <storage path>
369 * c) Copy a file within storage
370 * array(
371 * 'op' => 'copy',
372 * 'src' => <storage path>,
373 * 'dst' => <storage path>
375 * d) Move a file within storage
376 * array(
377 * 'op' => 'move',
378 * 'src' => <storage path>,
379 * 'dst' => <storage path>
381 * e) Delete a file within storage
382 * array(
383 * 'op' => 'delete',
384 * 'src' => <storage path>,
385 * 'ignoreMissingSource' => <boolean>
387 * f) Do nothing (no-op)
388 * array(
389 * 'op' => 'null',
392 * Boolean flags for operations (operation-specific):
393 * 'ignoreMissingSource' : The operation will simply succeed and do
394 * nothing if the source file does not exist.
396 * Return value:
397 * This returns a Status, which contains all warnings and fatals that occured
398 * during the operation. The 'failCount', 'successCount', and 'success' members
399 * will reflect each operation attempted for the given files. The status will be
400 * considered "OK" as long as no fatal errors occured.
402 * @param $ops Array Set of operations to execute
403 * @return Status
404 * @since 1.20
406 final public function doQuickOperations( array $ops ) {
407 if ( $this->isReadOnly() ) {
408 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
410 foreach ( $ops as &$op ) {
411 $op['overwrite'] = true; // avoids RTTs in key/value stores
413 return $this->doQuickOperationsInternal( $ops );
417 * @see FileBackend::doQuickOperations()
418 * @since 1.20
420 abstract protected function doQuickOperationsInternal( array $ops );
423 * Same as doQuickOperations() except it takes a single operation.
424 * If you are doing a batch of operations, then use that function instead.
426 * @see FileBackend::doQuickOperations()
428 * @param $op Array Operation
429 * @return Status
430 * @since 1.20
432 final public function doQuickOperation( array $op ) {
433 return $this->doQuickOperations( array( $op ) );
437 * Performs a single quick create operation.
438 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
440 * @see FileBackend::doQuickOperation()
442 * @param $params Array Operation parameters
443 * @return Status
444 * @since 1.20
446 final public function quickCreate( array $params ) {
447 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
451 * Performs a single quick store operation.
452 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
454 * @see FileBackend::doQuickOperation()
456 * @param $params Array Operation parameters
457 * @return Status
458 * @since 1.20
460 final public function quickStore( array $params ) {
461 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
465 * Performs a single quick copy operation.
466 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
468 * @see FileBackend::doQuickOperation()
470 * @param $params Array Operation parameters
471 * @return Status
472 * @since 1.20
474 final public function quickCopy( array $params ) {
475 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
479 * Performs a single quick move operation.
480 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
482 * @see FileBackend::doQuickOperation()
484 * @param $params Array Operation parameters
485 * @return Status
486 * @since 1.20
488 final public function quickMove( array $params ) {
489 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
493 * Performs a single quick delete operation.
494 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
496 * @see FileBackend::doQuickOperation()
498 * @param $params Array Operation parameters
499 * @return Status
500 * @since 1.20
502 final public function quickDelete( array $params ) {
503 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
507 * Concatenate a list of storage files into a single file system file.
508 * The target path should refer to a file that is already locked or
509 * otherwise safe from modification from other processes. Normally,
510 * the file will be a new temp file, which should be adequate.
511 * $params include:
512 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
513 * dst : file system path to 0-byte temp file
515 * @param $params Array Operation parameters
516 * @return Status
518 abstract public function concatenate( array $params );
521 * Prepare a storage directory for usage.
522 * This will create any required containers and parent directories.
523 * Backends using key/value stores only need to create the container.
525 * $params include:
526 * dir : storage directory
528 * @param $params Array
529 * @return Status
531 final public function prepare( array $params ) {
532 if ( $this->isReadOnly() ) {
533 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
535 return $this->doPrepare( $params );
539 * @see FileBackend::prepare()
541 abstract protected function doPrepare( array $params );
544 * Take measures to block web access to a storage directory and
545 * the container it belongs to. FS backends might add .htaccess
546 * files whereas key/value store backends might restrict container
547 * access to the auth user that represents end-users in web request.
548 * This is not guaranteed to actually do anything.
550 * $params include:
551 * dir : storage directory
552 * noAccess : try to deny file access
553 * noListing : try to deny file listing
555 * @param $params Array
556 * @return Status
558 final public function secure( array $params ) {
559 if ( $this->isReadOnly() ) {
560 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
562 $status = $this->doPrepare( $params ); // dir must exist to restrict it
563 if ( $status->isOK() ) {
564 $status->merge( $this->doSecure( $params ) );
566 return $status;
570 * @see FileBackend::secure()
572 abstract protected function doSecure( array $params );
575 * Delete a storage directory if it is empty.
576 * Backends using key/value stores may do nothing unless the directory
577 * is that of an empty container, in which case it should be deleted.
579 * $params include:
580 * dir : storage directory
581 * recursive : recursively delete empty subdirectories first (@since 1.20)
583 * @param $params Array
584 * @return Status
586 final public function clean( array $params ) {
587 if ( $this->isReadOnly() ) {
588 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
590 return $this->doClean( $params );
594 * @see FileBackend::clean()
596 abstract protected function doClean( array $params );
599 * Check if a file exists at a storage path in the backend.
600 * This returns false if only a directory exists at the path.
602 * $params include:
603 * src : source storage path
604 * latest : use the latest available data
606 * @param $params Array
607 * @return bool|null Returns null on failure
609 abstract public function fileExists( array $params );
612 * Get the last-modified timestamp of the file at a storage path.
614 * $params include:
615 * src : source storage path
616 * latest : use the latest available data
618 * @param $params Array
619 * @return string|bool TS_MW timestamp or false on failure
621 abstract public function getFileTimestamp( array $params );
624 * Get the contents of a file at a storage path in the backend.
625 * This should be avoided for potentially large files.
627 * $params include:
628 * src : source storage path
629 * latest : use the latest available data
631 * @param $params Array
632 * @return string|bool Returns false on failure
634 abstract public function getFileContents( array $params );
637 * Get the size (bytes) of a file at a storage path in the backend.
639 * $params include:
640 * src : source storage path
641 * latest : use the latest available data
643 * @param $params Array
644 * @return integer|bool Returns false on failure
646 abstract public function getFileSize( array $params );
649 * Get quick information about a file at a storage path in the backend.
650 * If the file does not exist, then this returns false.
651 * Otherwise, the result is an associative array that includes:
652 * mtime : the last-modified timestamp (TS_MW)
653 * size : the file size (bytes)
654 * Additional values may be included for internal use only.
656 * $params include:
657 * src : source storage path
658 * latest : use the latest available data
660 * @param $params Array
661 * @return Array|bool|null Returns null on failure
663 abstract public function getFileStat( array $params );
666 * Get a SHA-1 hash of the file at a storage path in the backend.
668 * $params include:
669 * src : source storage path
670 * latest : use the latest available data
672 * @param $params Array
673 * @return string|bool Hash string or false on failure
675 abstract public function getFileSha1Base36( array $params );
678 * Get the properties of the file at a storage path in the backend.
679 * Returns FSFile::placeholderProps() on failure.
681 * $params include:
682 * src : source storage path
683 * latest : use the latest available data
685 * @param $params Array
686 * @return Array
688 abstract public function getFileProps( array $params );
691 * Stream the file at a storage path in the backend.
692 * If the file does not exists, a 404 error will be given.
693 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
694 * must be sent if streaming began, while none should be sent otherwise.
695 * Implementations should flush the output buffer before sending data.
697 * $params include:
698 * src : source storage path
699 * headers : additional HTTP headers to send on success
700 * latest : use the latest available data
702 * @param $params Array
703 * @return Status
705 abstract public function streamFile( array $params );
708 * Returns a file system file, identical to the file at a storage path.
709 * The file returned is either:
710 * a) A local copy of the file at a storage path in the backend.
711 * The temporary copy will have the same extension as the source.
712 * b) An original of the file at a storage path in the backend.
713 * Temporary files may be purged when the file object falls out of scope.
715 * Write operations should *never* be done on this file as some backends
716 * may do internal tracking or may be instances of FileBackendMultiWrite.
717 * In that later case, there are copies of the file that must stay in sync.
718 * Additionally, further calls to this function may return the same file.
720 * $params include:
721 * src : source storage path
722 * latest : use the latest available data
724 * @param $params Array
725 * @return FSFile|null Returns null on failure
727 abstract public function getLocalReference( array $params );
730 * Get a local copy on disk of the file at a storage path in the backend.
731 * The temporary copy will have the same file extension as the source.
732 * Temporary files may be purged when the file object falls out of scope.
734 * $params include:
735 * src : source storage path
736 * latest : use the latest available data
738 * @param $params Array
739 * @return TempFSFile|null Returns null on failure
741 abstract public function getLocalCopy( array $params );
744 * Check if a directory exists at a given storage path.
745 * Backends using key/value stores will check if the path is a
746 * virtual directory, meaning there are files under the given directory.
748 * Storage backends with eventual consistency might return stale data.
750 * $params include:
751 * dir : storage directory
753 * @param $params array
754 * @return bool|null Returns null on failure
755 * @since 1.20
757 abstract public function directoryExists( array $params );
760 * Get an iterator to list *all* directories under a storage directory.
761 * If the directory is of the form "mwstore://backend/container",
762 * then all directories in the container should be listed.
763 * If the directory is of form "mwstore://backend/container/dir",
764 * then all directories directly under that directory should be listed.
765 * Results should be storage directories relative to the given directory.
767 * Storage backends with eventual consistency might return stale data.
769 * $params include:
770 * dir : storage directory
771 * topOnly : only return direct child dirs of the directory
773 * @param $params array
774 * @return Traversable|Array|null Returns null on failure
775 * @since 1.20
777 abstract public function getDirectoryList( array $params );
780 * Same as FileBackend::getDirectoryList() except only lists
781 * directories that are immediately under the given directory.
783 * Storage backends with eventual consistency might return stale data.
785 * $params include:
786 * dir : storage directory
788 * @param $params array
789 * @return Traversable|Array|null Returns null on failure
790 * @since 1.20
792 final public function getTopDirectoryList( array $params ) {
793 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
797 * Get an iterator to list *all* stored files under a storage directory.
798 * If the directory is of the form "mwstore://backend/container",
799 * then all files in the container should be listed.
800 * If the directory is of form "mwstore://backend/container/dir",
801 * then all files under that directory should be listed.
802 * Results should be storage paths relative to the given directory.
804 * Storage backends with eventual consistency might return stale data.
806 * $params include:
807 * dir : storage directory
808 * topOnly : only return direct child files of the directory (@since 1.20)
810 * @param $params array
811 * @return Traversable|Array|null Returns null on failure
813 abstract public function getFileList( array $params );
816 * Same as FileBackend::getFileList() except only lists
817 * files that are immediately under the given directory.
819 * Storage backends with eventual consistency might return stale data.
821 * $params include:
822 * dir : storage directory
824 * @param $params array
825 * @return Traversable|Array|null Returns null on failure
826 * @since 1.20
828 final public function getTopFileList( array $params ) {
829 return $this->getFileList( array( 'topOnly' => true ) + $params );
833 * Invalidate any in-process file existence and property cache.
834 * If $paths is given, then only the cache for those files will be cleared.
836 * @param $paths Array Storage paths (optional)
837 * @return void
839 public function clearCache( array $paths = null ) {}
842 * Lock the files at the given storage paths in the backend.
843 * This will either lock all the files or none (on failure).
845 * Callers should consider using getScopedFileLocks() instead.
847 * @param $paths Array Storage paths
848 * @param $type integer LockManager::LOCK_* constant
849 * @return Status
851 final public function lockFiles( array $paths, $type ) {
852 return $this->lockManager->lock( $paths, $type );
856 * Unlock the files at the given storage paths in the backend.
858 * @param $paths Array Storage paths
859 * @param $type integer LockManager::LOCK_* constant
860 * @return Status
862 final public function unlockFiles( array $paths, $type ) {
863 return $this->lockManager->unlock( $paths, $type );
867 * Lock the files at the given storage paths in the backend.
868 * This will either lock all the files or none (on failure).
869 * On failure, the status object will be updated with errors.
871 * Once the return value goes out scope, the locks will be released and
872 * the status updated. Unlock fatals will not change the status "OK" value.
874 * @param $paths Array Storage paths
875 * @param $type integer LockManager::LOCK_* constant
876 * @param $status Status Status to update on lock/unlock
877 * @return ScopedLock|null Returns null on failure
879 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
880 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
884 * Get an array of scoped locks needed for a batch of file operations.
886 * Normally, FileBackend::doOperations() handles locking, unless
887 * the 'nonLocking' param is passed in. This function is useful if you
888 * want the files to be locked for a broader scope than just when the
889 * files are changing. For example, if you need to update DB metadata,
890 * you may want to keep the files locked until finished.
892 * @see FileBackend::doOperations()
894 * @param $ops Array List of file operations to FileBackend::doOperations()
895 * @param $status Status Status to update on lock/unlock
896 * @return Array List of ScopedFileLocks or null values
897 * @since 1.20
899 abstract public function getScopedLocksForOps( array $ops, Status $status );
902 * Get the root storage path of this backend.
903 * All container paths are "subdirectories" of this path.
905 * @return string Storage path
906 * @since 1.20
908 final public function getRootStoragePath() {
909 return "mwstore://{$this->name}";
913 * Get the file journal object for this backend
915 * @return FileJournal
917 final public function getJournal() {
918 return $this->fileJournal;
922 * Check if a given path is a "mwstore://" path.
923 * This does not do any further validation or any existence checks.
925 * @param $path string
926 * @return bool
928 final public static function isStoragePath( $path ) {
929 return ( strpos( $path, 'mwstore://' ) === 0 );
933 * Split a storage path into a backend name, a container name,
934 * and a relative file path. The relative path may be the empty string.
935 * This does not do any path normalization or traversal checks.
937 * @param $storagePath string
938 * @return Array (backend, container, rel object) or (null, null, null)
940 final public static function splitStoragePath( $storagePath ) {
941 if ( self::isStoragePath( $storagePath ) ) {
942 // Remove the "mwstore://" prefix and split the path
943 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
944 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
945 if ( count( $parts ) == 3 ) {
946 return $parts; // e.g. "backend/container/path"
947 } else {
948 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
952 return array( null, null, null );
956 * Normalize a storage path by cleaning up directory separators.
957 * Returns null if the path is not of the format of a valid storage path.
959 * @param $storagePath string
960 * @return string|null
962 final public static function normalizeStoragePath( $storagePath ) {
963 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
964 if ( $relPath !== null ) { // must be for this backend
965 $relPath = self::normalizeContainerPath( $relPath );
966 if ( $relPath !== null ) {
967 return ( $relPath != '' )
968 ? "mwstore://{$backend}/{$container}/{$relPath}"
969 : "mwstore://{$backend}/{$container}";
972 return null;
976 * Get the parent storage directory of a storage path.
977 * This returns a path like "mwstore://backend/container",
978 * "mwstore://backend/container/...", or null if there is no parent.
980 * @param $storagePath string
981 * @return string|null
983 final public static function parentStoragePath( $storagePath ) {
984 $storagePath = dirname( $storagePath );
985 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
986 return ( $rel === null ) ? null : $storagePath;
990 * Get the final extension from a storage or FS path
992 * @param $path string
993 * @return string
995 final public static function extensionFromPath( $path ) {
996 $i = strrpos( $path, '.' );
997 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1001 * Check if a relative path has no directory traversals
1003 * @param $path string
1004 * @return bool
1005 * @since 1.20
1007 final public static function isPathTraversalFree( $path ) {
1008 return ( self::normalizeContainerPath( $path ) !== null );
1012 * Validate and normalize a relative storage path.
1013 * Null is returned if the path involves directory traversal.
1014 * Traversal is insecure for FS backends and broken for others.
1016 * This uses the same traversal protection as Title::secureAndSplit().
1018 * @param $path string Storage path relative to a container
1019 * @return string|null
1021 final protected static function normalizeContainerPath( $path ) {
1022 // Normalize directory separators
1023 $path = strtr( $path, '\\', '/' );
1024 // Collapse any consecutive directory separators
1025 $path = preg_replace( '![/]{2,}!', '/', $path );
1026 // Remove any leading directory separator
1027 $path = ltrim( $path, '/' );
1028 // Use the same traversal protection as Title::secureAndSplit()
1029 if ( strpos( $path, '.' ) !== false ) {
1030 if (
1031 $path === '.' ||
1032 $path === '..' ||
1033 strpos( $path, './' ) === 0 ||
1034 strpos( $path, '../' ) === 0 ||
1035 strpos( $path, '/./' ) !== false ||
1036 strpos( $path, '/../' ) !== false
1038 return null;
1041 return $path;