PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / filebackend / FileBackend.php
blob8d76e96b7adfc2d1a811130fa6d55fd142ae875c
1 <?php
2 /**
3 * @defgroup FileBackend File backend
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
7 */
9 /**
10 * Base class for all file backends.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
27 * @file
28 * @ingroup FileBackend
29 * @author Aaron Schulz
32 /**
33 * @brief Base class for all file backend classes (including multi-write backends).
35 * This class defines the methods as abstract that subclasses must implement.
36 * Outside callers can assume that all backends will have these functions.
38 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
39 * The "backend" portion is unique name for MediaWiki to refer to a backend, while
40 * the "container" portion is a top-level directory of the backend. The "path" portion
41 * is a relative path that uses UNIX file system (FS) notation, though any particular
42 * backend may not actually be using a local filesystem. Therefore, the relative paths
43 * are only virtual.
45 * Backend contents are stored under wiki-specific container names by default.
46 * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
47 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
48 * containers to ones that do not respect the "wiki ID".
50 * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
51 * FS-based backends are somewhat more restrictive due to the existence of real
52 * directory files; a regular file cannot have the same name as a directory. Other
53 * backends with virtual directories may not have this limitation. Callers should
54 * store files in such a way that no files and directories are under the same path.
56 * In general, this class allows for callers to access storage through the same
57 * interface, without regard to the underlying storage system. However, calling code
58 * must follow certain patterns and be aware of certain things to ensure compatibility:
59 * - a) Always call prepare() on the parent directory before trying to put a file there;
60 * key/value stores only need the container to exist first, but filesystems need
61 * all the parent directories to exist first (prepare() is aware of all this)
62 * - b) Always call clean() on a directory when it might become empty to avoid empty
63 * directory buildup on filesystems; key/value stores never have empty directories,
64 * so doing this helps preserve consistency in both cases
65 * - c) Likewise, do not rely on the existence of empty directories for anything;
66 * calling directoryExists() on a path that prepare() was previously called on
67 * will return false for key/value stores if there are no files under that path
68 * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
69 * either be a copy of the source file in /tmp or the original source file itself
70 * - e) Use a file layout that results in never attempting to store files over directories
71 * or directories over files; key/value stores allow this but filesystems do not
72 * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
73 * - g) Do not assume that move operations are atomic (difficult with key/value stores)
74 * - h) Do not assume that file stat or read operations always have immediate consistency;
75 * various methods have a "latest" flag that should always be used if up-to-date
76 * information is required (this trades performance for correctness as needed)
77 * - i) Do not assume that directory listings have immediate consistency
79 * Methods of subclasses should avoid throwing exceptions at all costs.
80 * As a corollary, external dependencies should be kept to a minimum.
82 * @ingroup FileBackend
83 * @since 1.19
85 abstract class FileBackend {
86 /** @var string Unique backend name */
87 protected $name;
89 /** @var string Unique wiki name */
90 protected $wikiId;
92 /** @var string Read-only explanation message */
93 protected $readOnly;
95 /** @var string When to do operations in parallel */
96 protected $parallelize;
98 /** @var int How many operations can be done in parallel */
99 protected $concurrency;
101 /** @var LockManager */
102 protected $lockManager;
104 /** @var FileJournal */
105 protected $fileJournal;
107 /** Bitfield flags for supported features */
108 const ATTR_HEADERS = 1; // files can be tagged with standard HTTP headers
109 const ATTR_METADATA = 2; // files can be stored with metadata key/values
110 const ATTR_UNICODE_PATHS = 4; // files can have Unicode paths (not just ASCII)
113 * Create a new backend instance from configuration.
114 * This should only be called from within FileBackendGroup.
116 * @param array $config Parameters include:
117 * - name : The unique name of this backend.
118 * This should consist of alphanumberic, '-', and '_' characters.
119 * This name should not be changed after use (e.g. with journaling).
120 * Note that the name is *not* used in actual container names.
121 * - wikiId : Prefix to container names that is unique to this backend.
122 * It should only consist of alphanumberic, '-', and '_' characters.
123 * This ID is what avoids collisions if multiple logical backends
124 * use the same storage system, so this should be set carefully.
125 * - lockManager : LockManager object to use for any file locking.
126 * If not provided, then no file locking will be enforced.
127 * - fileJournal : FileJournal object to use for logging changes to files.
128 * If not provided, then change journaling will be disabled.
129 * - readOnly : Write operations are disallowed if this is a non-empty string.
130 * It should be an explanation for the backend being read-only.
131 * - parallelize : When to do file operations in parallel (when possible).
132 * Allowed values are "implicit", "explicit" and "off".
133 * - concurrency : How many file operations can be done in parallel.
134 * @throws FileBackendException
136 public function __construct( array $config ) {
137 $this->name = $config['name'];
138 $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
139 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
140 throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
141 } elseif ( !is_string( $this->wikiId ) ) {
142 throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
144 $this->lockManager = isset( $config['lockManager'] )
145 ? $config['lockManager']
146 : new NullLockManager( array() );
147 $this->fileJournal = isset( $config['fileJournal'] )
148 ? $config['fileJournal']
149 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
150 $this->readOnly = isset( $config['readOnly'] )
151 ? (string)$config['readOnly']
152 : '';
153 $this->parallelize = isset( $config['parallelize'] )
154 ? (string)$config['parallelize']
155 : 'off';
156 $this->concurrency = isset( $config['concurrency'] )
157 ? (int)$config['concurrency']
158 : 50;
162 * Get the unique backend name.
163 * We may have multiple different backends of the same type.
164 * For example, we can have two Swift backends using different proxies.
166 * @return string
168 final public function getName() {
169 return $this->name;
173 * Get the wiki identifier used for this backend (possibly empty).
174 * Note that this might *not* be in the same format as wfWikiID().
176 * @return string
177 * @since 1.20
179 final public function getWikiId() {
180 return $this->wikiId;
184 * Check if this backend is read-only
186 * @return bool
188 final public function isReadOnly() {
189 return ( $this->readOnly != '' );
193 * Get an explanatory message if this backend is read-only
195 * @return string|bool Returns false if the backend is not read-only
197 final public function getReadOnlyReason() {
198 return ( $this->readOnly != '' ) ? $this->readOnly : false;
202 * Get the a bitfield of extra features supported by the backend medium
204 * @return int Bitfield of FileBackend::ATTR_* flags
205 * @since 1.23
207 public function getFeatures() {
208 return self::ATTR_UNICODE_PATHS;
212 * Check if the backend medium supports a field of extra features
214 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
215 * @return bool
216 * @since 1.23
218 final public function hasFeatures( $bitfield ) {
219 return ( $this->getFeatures() & $bitfield ) === $bitfield;
223 * This is the main entry point into the backend for write operations.
224 * Callers supply an ordered list of operations to perform as a transaction.
225 * Files will be locked, the stat cache cleared, and then the operations attempted.
226 * If any serious errors occur, all attempted operations will be rolled back.
228 * $ops is an array of arrays. The outer array holds a list of operations.
229 * Each inner array is a set of key value pairs that specify an operation.
231 * Supported operations and their parameters. The supported actions are:
232 * - create
233 * - store
234 * - copy
235 * - move
236 * - delete
237 * - describe (since 1.21)
238 * - null
240 * a) Create a new file in storage with the contents of a string
241 * @code
242 * array(
243 * 'op' => 'create',
244 * 'dst' => <storage path>,
245 * 'content' => <string of new file contents>,
246 * 'overwrite' => <boolean>,
247 * 'overwriteSame' => <boolean>,
248 * 'headers' => <HTTP header name/value map> # since 1.21
249 * );
250 * @endcode
252 * b) Copy a file system file into storage
253 * @code
254 * array(
255 * 'op' => 'store',
256 * 'src' => <file system path>,
257 * 'dst' => <storage path>,
258 * 'overwrite' => <boolean>,
259 * 'overwriteSame' => <boolean>,
260 * 'headers' => <HTTP header name/value map> # since 1.21
262 * @endcode
264 * c) Copy a file within storage
265 * @code
266 * array(
267 * 'op' => 'copy',
268 * 'src' => <storage path>,
269 * 'dst' => <storage path>,
270 * 'overwrite' => <boolean>,
271 * 'overwriteSame' => <boolean>,
272 * 'ignoreMissingSource' => <boolean>, # since 1.21
273 * 'headers' => <HTTP header name/value map> # since 1.21
275 * @endcode
277 * d) Move a file within storage
278 * @code
279 * array(
280 * 'op' => 'move',
281 * 'src' => <storage path>,
282 * 'dst' => <storage path>,
283 * 'overwrite' => <boolean>,
284 * 'overwriteSame' => <boolean>,
285 * 'ignoreMissingSource' => <boolean>, # since 1.21
286 * 'headers' => <HTTP header name/value map> # since 1.21
288 * @endcode
290 * e) Delete a file within storage
291 * @code
292 * array(
293 * 'op' => 'delete',
294 * 'src' => <storage path>,
295 * 'ignoreMissingSource' => <boolean>
297 * @endcode
299 * f) Update metadata for a file within storage
300 * @code
301 * array(
302 * 'op' => 'describe',
303 * 'src' => <storage path>,
304 * 'headers' => <HTTP header name/value map>
306 * @endcode
308 * g) Do nothing (no-op)
309 * @code
310 * array(
311 * 'op' => 'null',
313 * @endcode
315 * Boolean flags for operations (operation-specific):
316 * - ignoreMissingSource : The operation will simply succeed and do
317 * nothing if the source file does not exist.
318 * - overwrite : Any destination file will be overwritten.
319 * - overwriteSame : If a file already exists at the destination with the
320 * same contents, then do nothing to the destination file
321 * instead of giving an error. This does not compare headers.
322 * This option is ignored if 'overwrite' is already provided.
323 * - headers : If supplied, the result of merging these headers with any
324 * existing source file headers (replacing conflicting ones)
325 * will be set as the destination file headers. Headers are
326 * deleted if their value is set to the empty string. When a
327 * file has headers they are included in responses to GET and
328 * HEAD requests to the backing store for that file.
329 * Header values should be no larger than 255 bytes, except for
330 * Content-Disposition. The system might ignore or truncate any
331 * headers that are too long to store (exact limits will vary).
332 * Backends that don't support metadata ignore this. (since 1.21)
334 * $opts is an associative of boolean flags, including:
335 * - force : Operation precondition errors no longer trigger an abort.
336 * Any remaining operations are still attempted. Unexpected
337 * failures may still cause remaining operations to be aborted.
338 * - nonLocking : No locks are acquired for the operations.
339 * This can increase performance for non-critical writes.
340 * This has no effect unless the 'force' flag is set.
341 * - nonJournaled : Don't log this operation batch in the file journal.
342 * This limits the ability of recovery scripts.
343 * - parallelize : Try to do operations in parallel when possible.
344 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
345 * - preserveCache : Don't clear the process cache before checking files.
346 * This should only be used if all entries in the process
347 * cache were added after the files were already locked. (since 1.20)
349 * @remarks Remarks on locking:
350 * File system paths given to operations should refer to files that are
351 * already locked or otherwise safe from modification from other processes.
352 * Normally these files will be new temp files, which should be adequate.
354 * @par Return value:
356 * This returns a Status, which contains all warnings and fatals that occurred
357 * during the operation. The 'failCount', 'successCount', and 'success' members
358 * will reflect each operation attempted.
360 * The status will be "OK" unless:
361 * - a) unexpected operation errors occurred (network partitions, disk full...)
362 * - b) significant operation errors occurred and 'force' was not set
364 * @param array $ops List of operations to execute in order
365 * @param array $opts Batch operation options
366 * @return Status
368 final public function doOperations( array $ops, array $opts = array() ) {
369 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
370 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
372 if ( !count( $ops ) ) {
373 return Status::newGood(); // nothing to do
375 if ( empty( $opts['force'] ) ) { // sanity
376 unset( $opts['nonLocking'] );
378 /** @noinspection PhpUnusedLocalVariableInspection */
379 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
380 return $this->doOperationsInternal( $ops, $opts );
384 * @see FileBackend::doOperations()
385 * @param array $ops
386 * @param array $opts
388 abstract protected function doOperationsInternal( array $ops, array $opts );
391 * Same as doOperations() except it takes a single operation.
392 * If you are doing a batch of operations that should either
393 * all succeed or all fail, then use that function instead.
395 * @see FileBackend::doOperations()
397 * @param array $op Operation
398 * @param array $opts Operation options
399 * @return Status
401 final public function doOperation( array $op, array $opts = array() ) {
402 return $this->doOperations( array( $op ), $opts );
406 * Performs a single create operation.
407 * This sets $params['op'] to 'create' and passes it to doOperation().
409 * @see FileBackend::doOperation()
411 * @param array $params Operation parameters
412 * @param array $opts Operation options
413 * @return Status
415 final public function create( array $params, array $opts = array() ) {
416 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
420 * Performs a single store operation.
421 * This sets $params['op'] to 'store' and passes it to doOperation().
423 * @see FileBackend::doOperation()
425 * @param array $params Operation parameters
426 * @param array $opts Operation options
427 * @return Status
429 final public function store( array $params, array $opts = array() ) {
430 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
434 * Performs a single copy operation.
435 * This sets $params['op'] to 'copy' and passes it to doOperation().
437 * @see FileBackend::doOperation()
439 * @param array $params Operation parameters
440 * @param array $opts Operation options
441 * @return Status
443 final public function copy( array $params, array $opts = array() ) {
444 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
448 * Performs a single move operation.
449 * This sets $params['op'] to 'move' and passes it to doOperation().
451 * @see FileBackend::doOperation()
453 * @param array $params Operation parameters
454 * @param array $opts Operation options
455 * @return Status
457 final public function move( array $params, array $opts = array() ) {
458 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
462 * Performs a single delete operation.
463 * This sets $params['op'] to 'delete' and passes it to doOperation().
465 * @see FileBackend::doOperation()
467 * @param array $params Operation parameters
468 * @param array $opts Operation options
469 * @return Status
471 final public function delete( array $params, array $opts = array() ) {
472 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
476 * Performs a single describe operation.
477 * This sets $params['op'] to 'describe' and passes it to doOperation().
479 * @see FileBackend::doOperation()
481 * @param array $params Operation parameters
482 * @param array $opts Operation options
483 * @return Status
484 * @since 1.21
486 final public function describe( array $params, array $opts = array() ) {
487 return $this->doOperation( array( 'op' => 'describe' ) + $params, $opts );
491 * Perform a set of independent file operations on some files.
493 * This does no locking, nor journaling, and possibly no stat calls.
494 * Any destination files that already exist will be overwritten.
495 * This should *only* be used on non-original files, like cache files.
497 * Supported operations and their parameters:
498 * - create
499 * - store
500 * - copy
501 * - move
502 * - delete
503 * - describe (since 1.21)
504 * - null
506 * a) Create a new file in storage with the contents of a string
507 * @code
508 * array(
509 * 'op' => 'create',
510 * 'dst' => <storage path>,
511 * 'content' => <string of new file contents>,
512 * 'headers' => <HTTP header name/value map> # since 1.21
514 * @endcode
516 * b) Copy a file system file into storage
517 * @code
518 * array(
519 * 'op' => 'store',
520 * 'src' => <file system path>,
521 * 'dst' => <storage path>,
522 * 'headers' => <HTTP header name/value map> # since 1.21
524 * @endcode
526 * c) Copy a file within storage
527 * @code
528 * array(
529 * 'op' => 'copy',
530 * 'src' => <storage path>,
531 * 'dst' => <storage path>,
532 * 'ignoreMissingSource' => <boolean>, # since 1.21
533 * 'headers' => <HTTP header name/value map> # since 1.21
535 * @endcode
537 * d) Move a file within storage
538 * @code
539 * array(
540 * 'op' => 'move',
541 * 'src' => <storage path>,
542 * 'dst' => <storage path>,
543 * 'ignoreMissingSource' => <boolean>, # since 1.21
544 * 'headers' => <HTTP header name/value map> # since 1.21
546 * @endcode
548 * e) Delete a file within storage
549 * @code
550 * array(
551 * 'op' => 'delete',
552 * 'src' => <storage path>,
553 * 'ignoreMissingSource' => <boolean>
555 * @endcode
557 * f) Update metadata for a file within storage
558 * @code
559 * array(
560 * 'op' => 'describe',
561 * 'src' => <storage path>,
562 * 'headers' => <HTTP header name/value map>
564 * @endcode
566 * g) Do nothing (no-op)
567 * @code
568 * array(
569 * 'op' => 'null',
571 * @endcode
573 * @par Boolean flags for operations (operation-specific):
574 * - ignoreMissingSource : The operation will simply succeed and do
575 * nothing if the source file does not exist.
576 * - headers : If supplied with a header name/value map, the backend will
577 * reply with these headers when GETs/HEADs of the destination
578 * file are made. Header values should be smaller than 256 bytes.
579 * Content-Disposition headers can be longer, though the system
580 * might ignore or truncate ones that are too long to store.
581 * Existing headers will remain, but these will replace any
582 * conflicting previous headers, and headers will be removed
583 * if they are set to an empty string.
584 * Backends that don't support metadata ignore this. (since 1.21)
586 * $opts is an associative of boolean flags, including:
587 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
589 * @par Return value:
590 * This returns a Status, which contains all warnings and fatals that occurred
591 * during the operation. The 'failCount', 'successCount', and 'success' members
592 * will reflect each operation attempted for the given files. The status will be
593 * considered "OK" as long as no fatal errors occurred.
595 * @param array $ops Set of operations to execute
596 * @param array $opts Batch operation options
597 * @return Status
598 * @since 1.20
600 final public function doQuickOperations( array $ops, array $opts = array() ) {
601 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
602 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
604 if ( !count( $ops ) ) {
605 return Status::newGood(); // nothing to do
607 foreach ( $ops as &$op ) {
608 $op['overwrite'] = true; // avoids RTTs in key/value stores
610 /** @noinspection PhpUnusedLocalVariableInspection */
611 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
612 return $this->doQuickOperationsInternal( $ops );
616 * @see FileBackend::doQuickOperations()
617 * @param array $ops
618 * @since 1.20
620 abstract protected function doQuickOperationsInternal( array $ops );
623 * Same as doQuickOperations() except it takes a single operation.
624 * If you are doing a batch of operations, then use that function instead.
626 * @see FileBackend::doQuickOperations()
628 * @param array $op Operation
629 * @return Status
630 * @since 1.20
632 final public function doQuickOperation( array $op ) {
633 return $this->doQuickOperations( array( $op ) );
637 * Performs a single quick create operation.
638 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
640 * @see FileBackend::doQuickOperation()
642 * @param array $params Operation parameters
643 * @return Status
644 * @since 1.20
646 final public function quickCreate( array $params ) {
647 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
651 * Performs a single quick store operation.
652 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
654 * @see FileBackend::doQuickOperation()
656 * @param array $params Operation parameters
657 * @return Status
658 * @since 1.20
660 final public function quickStore( array $params ) {
661 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
665 * Performs a single quick copy operation.
666 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
668 * @see FileBackend::doQuickOperation()
670 * @param array $params Operation parameters
671 * @return Status
672 * @since 1.20
674 final public function quickCopy( array $params ) {
675 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
679 * Performs a single quick move operation.
680 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
682 * @see FileBackend::doQuickOperation()
684 * @param array $params Operation parameters
685 * @return Status
686 * @since 1.20
688 final public function quickMove( array $params ) {
689 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
693 * Performs a single quick delete operation.
694 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
696 * @see FileBackend::doQuickOperation()
698 * @param array $params Operation parameters
699 * @return Status
700 * @since 1.20
702 final public function quickDelete( array $params ) {
703 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
707 * Performs a single quick describe operation.
708 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
710 * @see FileBackend::doQuickOperation()
712 * @param array $params Operation parameters
713 * @return Status
714 * @since 1.21
716 final public function quickDescribe( array $params ) {
717 return $this->doQuickOperation( array( 'op' => 'describe' ) + $params );
721 * Concatenate a list of storage files into a single file system file.
722 * The target path should refer to a file that is already locked or
723 * otherwise safe from modification from other processes. Normally,
724 * the file will be a new temp file, which should be adequate.
726 * @param array $params Operation parameters, include:
727 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
728 * - dst : file system path to 0-byte temp file
729 * - parallelize : try to do operations in parallel when possible
730 * @return Status
732 abstract public function concatenate( array $params );
735 * Prepare a storage directory for usage.
736 * This will create any required containers and parent directories.
737 * Backends using key/value stores only need to create the container.
739 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
740 * except they are only applied *if* the directory/container had to be created.
741 * These flags should always be set for directories that have private files.
742 * However, setting them is not guaranteed to actually do anything.
743 * Additional server configuration may be needed to achieve the desired effect.
745 * @param array $params Parameters include:
746 * - dir : storage directory
747 * - noAccess : try to deny file access (since 1.20)
748 * - noListing : try to deny file listing (since 1.20)
749 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
750 * @return Status
752 final public function prepare( array $params ) {
753 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
754 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
756 /** @noinspection PhpUnusedLocalVariableInspection */
757 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
758 return $this->doPrepare( $params );
762 * @see FileBackend::prepare()
763 * @param array $params
765 abstract protected function doPrepare( array $params );
768 * Take measures to block web access to a storage directory and
769 * the container it belongs to. FS backends might add .htaccess
770 * files whereas key/value store backends might revoke container
771 * access to the storage user representing end-users in web requests.
773 * This is not guaranteed to actually make files or listings publically hidden.
774 * Additional server configuration may be needed to achieve the desired effect.
776 * @param array $params Parameters include:
777 * - dir : storage directory
778 * - noAccess : try to deny file access
779 * - noListing : try to deny file listing
780 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
781 * @return Status
783 final public function secure( array $params ) {
784 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
785 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
787 /** @noinspection PhpUnusedLocalVariableInspection */
788 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
789 return $this->doSecure( $params );
793 * @see FileBackend::secure()
794 * @param array $params
796 abstract protected function doSecure( array $params );
799 * Remove measures to block web access to a storage directory and
800 * the container it belongs to. FS backends might remove .htaccess
801 * files whereas key/value store backends might grant container
802 * access to the storage user representing end-users in web requests.
803 * This essentially can undo the result of secure() calls.
805 * This is not guaranteed to actually make files or listings publically viewable.
806 * Additional server configuration may be needed to achieve the desired effect.
808 * @param array $params Parameters include:
809 * - dir : storage directory
810 * - access : try to allow file access
811 * - listing : try to allow file listing
812 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
813 * @return Status
814 * @since 1.20
816 final public function publish( array $params ) {
817 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
818 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
820 /** @noinspection PhpUnusedLocalVariableInspection */
821 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
822 return $this->doPublish( $params );
826 * @see FileBackend::publish()
827 * @param array $params
829 abstract protected function doPublish( array $params );
832 * Delete a storage directory if it is empty.
833 * Backends using key/value stores may do nothing unless the directory
834 * is that of an empty container, in which case it will be deleted.
836 * @param array $params Parameters include:
837 * - dir : storage directory
838 * - recursive : recursively delete empty subdirectories first (since 1.20)
839 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
840 * @return Status
842 final public function clean( array $params ) {
843 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
844 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
846 /** @noinspection PhpUnusedLocalVariableInspection */
847 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
848 return $this->doClean( $params );
852 * @see FileBackend::clean()
853 * @param array $params
855 abstract protected function doClean( array $params );
858 * Enter file operation scope.
859 * This just makes PHP ignore user aborts/disconnects until the return
860 * value leaves scope. This returns null and does nothing in CLI mode.
862 * @return ScopedCallback|null
864 final protected function getScopedPHPBehaviorForOps() {
865 if ( PHP_SAPI != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
866 $old = ignore_user_abort( true ); // avoid half-finished operations
867 return new ScopedCallback( function () use ( $old ) {
868 ignore_user_abort( $old );
869 } );
872 return null;
876 * Check if a file exists at a storage path in the backend.
877 * This returns false if only a directory exists at the path.
879 * @param array $params Parameters include:
880 * - src : source storage path
881 * - latest : use the latest available data
882 * @return bool|null Returns null on failure
884 abstract public function fileExists( array $params );
887 * Get the last-modified timestamp of the file at a storage path.
889 * @param array $params Parameters include:
890 * - src : source storage path
891 * - latest : use the latest available data
892 * @return string|bool TS_MW timestamp or false on failure
894 abstract public function getFileTimestamp( array $params );
897 * Get the contents of a file at a storage path in the backend.
898 * This should be avoided for potentially large files.
900 * @param array $params Parameters include:
901 * - src : source storage path
902 * - latest : use the latest available data
903 * @return string|bool Returns false on failure
905 final public function getFileContents( array $params ) {
906 $contents = $this->getFileContentsMulti(
907 array( 'srcs' => array( $params['src'] ) ) + $params );
909 return $contents[$params['src']];
913 * Like getFileContents() except it takes an array of storage paths
914 * and returns a map of storage paths to strings (or null on failure).
915 * The map keys (paths) are in the same order as the provided list of paths.
917 * @see FileBackend::getFileContents()
919 * @param array $params Parameters include:
920 * - srcs : list of source storage paths
921 * - latest : use the latest available data
922 * - parallelize : try to do operations in parallel when possible
923 * @return array Map of (path name => string or false on failure)
924 * @since 1.20
926 abstract public function getFileContentsMulti( array $params );
929 * Get metadata about a file at a storage path in the backend.
930 * If the file does not exist, then this returns false.
931 * Otherwise, the result is an associative array that includes:
932 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
933 * - metadata : map of file metadata (name => value)
934 * Metadata keys and headers names will be returned in all lower-case.
935 * Additional values may be included for internal use only.
937 * Use FileBackend::hasFeatures() to check how well this is supported.
939 * @param array $params
940 * $params include:
941 * - src : source storage path
942 * - latest : use the latest available data
943 * @return array|bool Returns false on failure
944 * @since 1.23
946 abstract public function getFileXAttributes( array $params );
949 * Get the size (bytes) of a file at a storage path in the backend.
951 * @param array $params Parameters include:
952 * - src : source storage path
953 * - latest : use the latest available data
954 * @return int|bool Returns false on failure
956 abstract public function getFileSize( array $params );
959 * Get quick information about a file at a storage path in the backend.
960 * If the file does not exist, then this returns false.
961 * Otherwise, the result is an associative array that includes:
962 * - mtime : the last-modified timestamp (TS_MW)
963 * - size : the file size (bytes)
964 * Additional values may be included for internal use only.
966 * @param array $params Parameters include:
967 * - src : source storage path
968 * - latest : use the latest available data
969 * @return array|bool|null Returns null on failure
971 abstract public function getFileStat( array $params );
974 * Get a SHA-1 hash of the file at a storage path in the backend.
976 * @param array $params Parameters include:
977 * - src : source storage path
978 * - latest : use the latest available data
979 * @return string|bool Hash string or false on failure
981 abstract public function getFileSha1Base36( array $params );
984 * Get the properties of the file at a storage path in the backend.
985 * This gives the result of FSFile::getProps() on a local copy of the file.
987 * @param array $params Parameters include:
988 * - src : source storage path
989 * - latest : use the latest available data
990 * @return array Returns FSFile::placeholderProps() on failure
992 abstract public function getFileProps( array $params );
995 * Stream the file at a storage path in the backend.
996 * If the file does not exists, an HTTP 404 error will be given.
997 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
998 * will be sent if streaming began, while none will be sent otherwise.
999 * Implementations should flush the output buffer before sending data.
1001 * @param array $params Parameters include:
1002 * - src : source storage path
1003 * - headers : list of additional HTTP headers to send on success
1004 * - latest : use the latest available data
1005 * @return Status
1007 abstract public function streamFile( array $params );
1010 * Returns a file system file, identical to the file at a storage path.
1011 * The file returned is either:
1012 * - a) A local copy of the file at a storage path in the backend.
1013 * The temporary copy will have the same extension as the source.
1014 * - b) An original of the file at a storage path in the backend.
1015 * Temporary files may be purged when the file object falls out of scope.
1017 * Write operations should *never* be done on this file as some backends
1018 * may do internal tracking or may be instances of FileBackendMultiWrite.
1019 * In that later case, there are copies of the file that must stay in sync.
1020 * Additionally, further calls to this function may return the same file.
1022 * @param array $params Parameters include:
1023 * - src : source storage path
1024 * - latest : use the latest available data
1025 * @return FSFile|null Returns null on failure
1027 final public function getLocalReference( array $params ) {
1028 $fsFiles = $this->getLocalReferenceMulti(
1029 array( 'srcs' => array( $params['src'] ) ) + $params );
1031 return $fsFiles[$params['src']];
1035 * Like getLocalReference() except it takes an array of storage paths
1036 * and returns a map of storage paths to FSFile objects (or null on failure).
1037 * The map keys (paths) are in the same order as the provided list of paths.
1039 * @see FileBackend::getLocalReference()
1041 * @param array $params Parameters include:
1042 * - srcs : list of source storage paths
1043 * - latest : use the latest available data
1044 * - parallelize : try to do operations in parallel when possible
1045 * @return array Map of (path name => FSFile or null on failure)
1046 * @since 1.20
1048 abstract public function getLocalReferenceMulti( array $params );
1051 * Get a local copy on disk of the file at a storage path in the backend.
1052 * The temporary copy will have the same file extension as the source.
1053 * Temporary files may be purged when the file object falls out of scope.
1055 * @param array $params Parameters include:
1056 * - src : source storage path
1057 * - latest : use the latest available data
1058 * @return TempFSFile|null Returns null on failure
1060 final public function getLocalCopy( array $params ) {
1061 $tmpFiles = $this->getLocalCopyMulti(
1062 array( 'srcs' => array( $params['src'] ) ) + $params );
1064 return $tmpFiles[$params['src']];
1068 * Like getLocalCopy() except it takes an array of storage paths and
1069 * returns a map of storage paths to TempFSFile objects (or null on failure).
1070 * The map keys (paths) are in the same order as the provided list of paths.
1072 * @see FileBackend::getLocalCopy()
1074 * @param array $params Parameters include:
1075 * - srcs : list of source storage paths
1076 * - latest : use the latest available data
1077 * - parallelize : try to do operations in parallel when possible
1078 * @return array Map of (path name => TempFSFile or null on failure)
1079 * @since 1.20
1081 abstract public function getLocalCopyMulti( array $params );
1084 * Return an HTTP URL to a given file that requires no authentication to use.
1085 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1086 * This will return null if the backend cannot make an HTTP URL for the file.
1088 * This is useful for key/value stores when using scripts that seek around
1089 * large files and those scripts (and the backend) support HTTP Range headers.
1090 * Otherwise, one would need to use getLocalReference(), which involves loading
1091 * the entire file on to local disk.
1093 * @param array $params Parameters include:
1094 * - src : source storage path
1095 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1096 * @return string|null
1097 * @since 1.21
1099 abstract public function getFileHttpUrl( array $params );
1102 * Check if a directory exists at a given storage path.
1103 * Backends using key/value stores will check if the path is a
1104 * virtual directory, meaning there are files under the given directory.
1106 * Storage backends with eventual consistency might return stale data.
1108 * @param array $params Parameters include:
1109 * - dir : storage directory
1110 * @return bool|null Returns null on failure
1111 * @since 1.20
1113 abstract public function directoryExists( array $params );
1116 * Get an iterator to list *all* directories under a storage directory.
1117 * If the directory is of the form "mwstore://backend/container",
1118 * then all directories in the container will be listed.
1119 * If the directory is of form "mwstore://backend/container/dir",
1120 * then all directories directly under that directory will be listed.
1121 * Results will be storage directories relative to the given directory.
1123 * Storage backends with eventual consistency might return stale data.
1125 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1127 * @param array $params Parameters include:
1128 * - dir : storage directory
1129 * - topOnly : only return direct child dirs of the directory
1130 * @return Traversable|array|null Returns null on failure
1131 * @since 1.20
1133 abstract public function getDirectoryList( array $params );
1136 * Same as FileBackend::getDirectoryList() except only lists
1137 * directories that are immediately under the given directory.
1139 * Storage backends with eventual consistency might return stale data.
1141 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1143 * @param array $params Parameters include:
1144 * - dir : storage directory
1145 * @return Traversable|array|null Returns null on failure
1146 * @since 1.20
1148 final public function getTopDirectoryList( array $params ) {
1149 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
1153 * Get an iterator to list *all* stored files under a storage directory.
1154 * If the directory is of the form "mwstore://backend/container",
1155 * then all files in the container will be listed.
1156 * If the directory is of form "mwstore://backend/container/dir",
1157 * then all files under that directory will be listed.
1158 * Results will be storage paths relative to the given directory.
1160 * Storage backends with eventual consistency might return stale data.
1162 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1164 * @param array $params Parameters include:
1165 * - dir : storage directory
1166 * - topOnly : only return direct child files of the directory (since 1.20)
1167 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1168 * @return Traversable|array|null Returns null on failure
1170 abstract public function getFileList( array $params );
1173 * Same as FileBackend::getFileList() except only lists
1174 * files that are immediately under the given directory.
1176 * Storage backends with eventual consistency might return stale data.
1178 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1180 * @param array $params Parameters include:
1181 * - dir : storage directory
1182 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1183 * @return Traversable|array|null Returns null on failure
1184 * @since 1.20
1186 final public function getTopFileList( array $params ) {
1187 return $this->getFileList( array( 'topOnly' => true ) + $params );
1191 * Preload persistent file stat cache and property cache into in-process cache.
1192 * This should be used when stat calls will be made on a known list of a many files.
1194 * @see FileBackend::getFileStat()
1196 * @param array $paths Storage paths
1198 abstract public function preloadCache( array $paths );
1201 * Invalidate any in-process file stat and property cache.
1202 * If $paths is given, then only the cache for those files will be cleared.
1204 * @see FileBackend::getFileStat()
1206 * @param array $paths Storage paths (optional)
1208 abstract public function clearCache( array $paths = null );
1211 * Preload file stat information (concurrently if possible) into in-process cache.
1213 * This should be used when stat calls will be made on a known list of a many files.
1214 * This does not make use of the persistent file stat cache.
1216 * @see FileBackend::getFileStat()
1218 * @param array $params Parameters include:
1219 * - srcs : list of source storage paths
1220 * - latest : use the latest available data
1221 * @return bool All requests proceeded without I/O errors (since 1.24)
1222 * @since 1.23
1224 abstract public function preloadFileStat( array $params );
1227 * Lock the files at the given storage paths in the backend.
1228 * This will either lock all the files or none (on failure).
1230 * Callers should consider using getScopedFileLocks() instead.
1232 * @param array $paths Storage paths
1233 * @param int $type LockManager::LOCK_* constant
1234 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1235 * @return Status
1237 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1238 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1240 return $this->lockManager->lock( $paths, $type, $timeout );
1244 * Unlock the files at the given storage paths in the backend.
1246 * @param array $paths Storage paths
1247 * @param int $type LockManager::LOCK_* constant
1248 * @return Status
1250 final public function unlockFiles( array $paths, $type ) {
1251 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1253 return $this->lockManager->unlock( $paths, $type );
1257 * Lock the files at the given storage paths in the backend.
1258 * This will either lock all the files or none (on failure).
1259 * On failure, the status object will be updated with errors.
1261 * Once the return value goes out scope, the locks will be released and
1262 * the status updated. Unlock fatals will not change the status "OK" value.
1264 * @see ScopedLock::factory()
1266 * @param array $paths List of storage paths or map of lock types to path lists
1267 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1268 * @param Status $status Status to update on lock/unlock
1269 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1270 * @return ScopedLock|null Returns null on failure
1272 final public function getScopedFileLocks( array $paths, $type, Status $status, $timeout = 0 ) {
1273 if ( $type === 'mixed' ) {
1274 foreach ( $paths as &$typePaths ) {
1275 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1277 } else {
1278 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1281 return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
1285 * Get an array of scoped locks needed for a batch of file operations.
1287 * Normally, FileBackend::doOperations() handles locking, unless
1288 * the 'nonLocking' param is passed in. This function is useful if you
1289 * want the files to be locked for a broader scope than just when the
1290 * files are changing. For example, if you need to update DB metadata,
1291 * you may want to keep the files locked until finished.
1293 * @see FileBackend::doOperations()
1295 * @param array $ops List of file operations to FileBackend::doOperations()
1296 * @param Status $status Status to update on lock/unlock
1297 * @return ScopedLock|null
1298 * @since 1.20
1300 abstract public function getScopedLocksForOps( array $ops, Status $status );
1303 * Get the root storage path of this backend.
1304 * All container paths are "subdirectories" of this path.
1306 * @return string Storage path
1307 * @since 1.20
1309 final public function getRootStoragePath() {
1310 return "mwstore://{$this->name}";
1314 * Get the storage path for the given container for this backend
1316 * @param string $container Container name
1317 * @return string Storage path
1318 * @since 1.21
1320 final public function getContainerStoragePath( $container ) {
1321 return $this->getRootStoragePath() . "/{$container}";
1325 * Get the file journal object for this backend
1327 * @return FileJournal
1329 final public function getJournal() {
1330 return $this->fileJournal;
1334 * Check if a given path is a "mwstore://" path.
1335 * This does not do any further validation or any existence checks.
1337 * @param string $path
1338 * @return bool
1340 final public static function isStoragePath( $path ) {
1341 return ( strpos( $path, 'mwstore://' ) === 0 );
1345 * Split a storage path into a backend name, a container name,
1346 * and a relative file path. The relative path may be the empty string.
1347 * This does not do any path normalization or traversal checks.
1349 * @param string $storagePath
1350 * @return array (backend, container, rel object) or (null, null, null)
1352 final public static function splitStoragePath( $storagePath ) {
1353 if ( self::isStoragePath( $storagePath ) ) {
1354 // Remove the "mwstore://" prefix and split the path
1355 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1356 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1357 if ( count( $parts ) == 3 ) {
1358 return $parts; // e.g. "backend/container/path"
1359 } else {
1360 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1365 return array( null, null, null );
1369 * Normalize a storage path by cleaning up directory separators.
1370 * Returns null if the path is not of the format of a valid storage path.
1372 * @param string $storagePath
1373 * @return string|null
1375 final public static function normalizeStoragePath( $storagePath ) {
1376 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1377 if ( $relPath !== null ) { // must be for this backend
1378 $relPath = self::normalizeContainerPath( $relPath );
1379 if ( $relPath !== null ) {
1380 return ( $relPath != '' )
1381 ? "mwstore://{$backend}/{$container}/{$relPath}"
1382 : "mwstore://{$backend}/{$container}";
1386 return null;
1390 * Get the parent storage directory of a storage path.
1391 * This returns a path like "mwstore://backend/container",
1392 * "mwstore://backend/container/...", or null if there is no parent.
1394 * @param string $storagePath
1395 * @return string|null
1397 final public static function parentStoragePath( $storagePath ) {
1398 $storagePath = dirname( $storagePath );
1399 list( , , $rel ) = self::splitStoragePath( $storagePath );
1401 return ( $rel === null ) ? null : $storagePath;
1405 * Get the final extension from a storage or FS path
1407 * @param string $path
1408 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1409 * @return string
1411 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1412 $i = strrpos( $path, '.' );
1413 $ext = $i ? substr( $path, $i + 1 ) : '';
1415 if ( $case === 'lowercase' ) {
1416 $ext = strtolower( $ext );
1417 } elseif ( $case === 'uppercase' ) {
1418 $ext = strtoupper( $ext );
1421 return $ext;
1425 * Check if a relative path has no directory traversals
1427 * @param string $path
1428 * @return bool
1429 * @since 1.20
1431 final public static function isPathTraversalFree( $path ) {
1432 return ( self::normalizeContainerPath( $path ) !== null );
1436 * Build a Content-Disposition header value per RFC 6266.
1438 * @param string $type One of (attachment, inline)
1439 * @param string $filename Suggested file name (should not contain slashes)
1440 * @throws FileBackendError
1441 * @return string
1442 * @since 1.20
1444 final public static function makeContentDisposition( $type, $filename = '' ) {
1445 $parts = array();
1447 $type = strtolower( $type );
1448 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1449 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1451 $parts[] = $type;
1453 if ( strlen( $filename ) ) {
1454 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1457 return implode( ';', $parts );
1461 * Validate and normalize a relative storage path.
1462 * Null is returned if the path involves directory traversal.
1463 * Traversal is insecure for FS backends and broken for others.
1465 * This uses the same traversal protection as Title::secureAndSplit().
1467 * @param string $path Storage path relative to a container
1468 * @return string|null
1470 final protected static function normalizeContainerPath( $path ) {
1471 // Normalize directory separators
1472 $path = strtr( $path, '\\', '/' );
1473 // Collapse any consecutive directory separators
1474 $path = preg_replace( '![/]{2,}!', '/', $path );
1475 // Remove any leading directory separator
1476 $path = ltrim( $path, '/' );
1477 // Use the same traversal protection as Title::secureAndSplit()
1478 if ( strpos( $path, '.' ) !== false ) {
1479 if (
1480 $path === '.' ||
1481 $path === '..' ||
1482 strpos( $path, './' ) === 0 ||
1483 strpos( $path, '../' ) === 0 ||
1484 strpos( $path, '/./' ) !== false ||
1485 strpos( $path, '/../' ) !== false
1487 return null;
1491 return $path;
1496 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1498 * @ingroup FileBackend
1499 * @since 1.23
1501 class FileBackendException extends Exception {
1505 * File backend exception for checked exceptions (e.g. I/O errors)
1507 * @ingroup FileBackend
1508 * @since 1.22
1510 class FileBackendError extends FileBackendException {