filebackend: cleaned up the FileBackend constructor
[lhc/web/wiklou.git] / includes / filebackend / FileBackend.php
1 <?php
2 /**
3 * @defgroup FileBackend File backend
4 *
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
7 */
8
9 /**
10 * Base class for all file backends.
11 *
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.
16 *
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.
21 *
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
26 *
27 * @file
28 * @ingroup FileBackend
29 * @author Aaron Schulz
30 */
31
32 /**
33 * @brief Base class for all file backend classes (including multi-write backends).
34 *
35 * This class defines the methods as abstract that subclasses must implement.
36 * Outside callers can assume that all backends will have these functions.
37 *
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.
44 *
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".
49 *
50 * In key/value stores, the container is 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.
55 *
56 * Methods of subclasses should avoid throwing exceptions at all costs.
57 * As a corollary, external dependencies should be kept to a minimum.
58 *
59 * @ingroup FileBackend
60 * @since 1.19
61 */
62 abstract class FileBackend {
63 /** @var string Unique backend name */
64 protected $name;
65
66 /** @var string Unique wiki name */
67 protected $wikiId;
68
69 /** @var string Read-only explanation message */
70 protected $readOnly;
71
72 /** @var string When to do operations in parallel */
73 protected $parallelize;
74
75 /** @var int How many operations can be done in parallel */
76 protected $concurrency;
77
78 /** @var LockManager */
79 protected $lockManager;
80
81 /** @var FileJournal */
82 protected $fileJournal;
83
84 /**
85 * Create a new backend instance from configuration.
86 * This should only be called from within FileBackendGroup.
87 *
88 * @param array $config Parameters include:
89 * - name : The unique name of this backend.
90 * This should consist of alphanumberic, '-', and '_' characters.
91 * This name should not be changed after use (e.g. with journaling).
92 * Note that the name is *not* used in actual container names.
93 * - wikiId : Prefix to container names that is unique to this backend.
94 * It should only consist of alphanumberic, '-', and '_' characters.
95 * This ID is what avoids collisions if multiple logical backends
96 * use the same storage system, so this should be set carefully.
97 * - lockManager : LockManager object to use for any file locking.
98 * If not provided, then no file locking will be enforced.
99 * - fileJournal : FileJournal object to use for logging changes to files.
100 * If not provided, then change journaling will be disabled.
101 * - readOnly : Write operations are disallowed if this is a non-empty string.
102 * It should be an explanation for the backend being read-only.
103 * - parallelize : When to do file operations in parallel (when possible).
104 * Allowed values are "implicit", "explicit" and "off".
105 * - concurrency : How many file operations can be done in parallel.
106 * @throws MWException
107 */
108 public function __construct( array $config ) {
109 $this->name = $config['name'];
110 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
111 throw new MWException( "Backend name `{$this->name}` is invalid." );
112 }
113 if ( !isset( $config['wikiId'] ) ) {
114 $config['wikiId'] = wfWikiID();
115 wfDeprecated( __METHOD__ . ' called without "wikiID".', '1.23' );
116 }
117 if ( isset( $config['lockManager'] ) && !is_object( $config['lockManager'] ) ) {
118 $config['lockManager'] =
119 LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
120 wfDeprecated( __METHOD__ . ' called with non-object "lockManager".', '1.23' );
121 }
122 $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
123 $this->lockManager = isset( $config['lockManager'] )
124 ? $config['lockManager']
125 : new NullLockManager( array() );
126 $this->fileJournal = isset( $config['fileJournal'] )
127 ? $config['fileJournal']
128 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
129 $this->readOnly = isset( $config['readOnly'] )
130 ? (string)$config['readOnly']
131 : '';
132 $this->parallelize = isset( $config['parallelize'] )
133 ? (string)$config['parallelize']
134 : 'off';
135 $this->concurrency = isset( $config['concurrency'] )
136 ? (int)$config['concurrency']
137 : 50;
138 }
139
140 /**
141 * Get the unique backend name.
142 * We may have multiple different backends of the same type.
143 * For example, we can have two Swift backends using different proxies.
144 *
145 * @return string
146 */
147 final public function getName() {
148 return $this->name;
149 }
150
151 /**
152 * Get the wiki identifier used for this backend (possibly empty).
153 * Note that this might *not* be in the same format as wfWikiID().
154 *
155 * @return string
156 * @since 1.20
157 */
158 final public function getWikiId() {
159 return $this->wikiId;
160 }
161
162 /**
163 * Check if this backend is read-only
164 *
165 * @return bool
166 */
167 final public function isReadOnly() {
168 return ( $this->readOnly != '' );
169 }
170
171 /**
172 * Get an explanatory message if this backend is read-only
173 *
174 * @return string|bool Returns false if the backend is not read-only
175 */
176 final public function getReadOnlyReason() {
177 return ( $this->readOnly != '' ) ? $this->readOnly : false;
178 }
179
180 /**
181 * This is the main entry point into the backend for write operations.
182 * Callers supply an ordered list of operations to perform as a transaction.
183 * Files will be locked, the stat cache cleared, and then the operations attempted.
184 * If any serious errors occur, all attempted operations will be rolled back.
185 *
186 * $ops is an array of arrays. The outer array holds a list of operations.
187 * Each inner array is a set of key value pairs that specify an operation.
188 *
189 * Supported operations and their parameters. The supported actions are:
190 * - create
191 * - store
192 * - copy
193 * - move
194 * - delete
195 * - describe (since 1.21)
196 * - null
197 *
198 * a) Create a new file in storage with the contents of a string
199 * @code
200 * array(
201 * 'op' => 'create',
202 * 'dst' => <storage path>,
203 * 'content' => <string of new file contents>,
204 * 'overwrite' => <boolean>,
205 * 'overwriteSame' => <boolean>,
206 * 'headers' => <HTTP header name/value map> # since 1.21
207 * );
208 * @endcode
209 *
210 * b) Copy a file system file into storage
211 * @code
212 * array(
213 * 'op' => 'store',
214 * 'src' => <file system path>,
215 * 'dst' => <storage path>,
216 * 'overwrite' => <boolean>,
217 * 'overwriteSame' => <boolean>,
218 * 'headers' => <HTTP header name/value map> # since 1.21
219 * )
220 * @endcode
221 *
222 * c) Copy a file within storage
223 * @code
224 * array(
225 * 'op' => 'copy',
226 * 'src' => <storage path>,
227 * 'dst' => <storage path>,
228 * 'overwrite' => <boolean>,
229 * 'overwriteSame' => <boolean>,
230 * 'ignoreMissingSource' => <boolean>, # since 1.21
231 * 'headers' => <HTTP header name/value map> # since 1.21
232 * )
233 * @endcode
234 *
235 * d) Move a file within storage
236 * @code
237 * array(
238 * 'op' => 'move',
239 * 'src' => <storage path>,
240 * 'dst' => <storage path>,
241 * 'overwrite' => <boolean>,
242 * 'overwriteSame' => <boolean>,
243 * 'ignoreMissingSource' => <boolean>, # since 1.21
244 * 'headers' => <HTTP header name/value map> # since 1.21
245 * )
246 * @endcode
247 *
248 * e) Delete a file within storage
249 * @code
250 * array(
251 * 'op' => 'delete',
252 * 'src' => <storage path>,
253 * 'ignoreMissingSource' => <boolean>
254 * )
255 * @endcode
256 *
257 * f) Update metadata for a file within storage
258 * @code
259 * array(
260 * 'op' => 'describe',
261 * 'src' => <storage path>,
262 * 'headers' => <HTTP header name/value map>
263 * )
264 * @endcode
265 *
266 * g) Do nothing (no-op)
267 * @code
268 * array(
269 * 'op' => 'null',
270 * )
271 * @endcode
272 *
273 * Boolean flags for operations (operation-specific):
274 * - ignoreMissingSource : The operation will simply succeed and do
275 * nothing if the source file does not exist.
276 * - overwrite : Any destination file will be overwritten.
277 * - overwriteSame : If a file already exists at the destination with the
278 * same contents, then do nothing to the destination file
279 * instead of giving an error. This does not compare headers.
280 * This option is ignored if 'overwrite' is already provided.
281 * - headers : If supplied, the result of merging these headers with any
282 * existing source file headers (replacing conflicting ones)
283 * will be set as the destination file headers. Headers are
284 * deleted if their value is set to the empty string. When a
285 * file has headers they are included in responses to GET and
286 * HEAD requests to the backing store for that file.
287 * Header values should be no larger than 255 bytes, except for
288 * Content-Disposition. The system might ignore or truncate any
289 * headers that are too long to store (exact limits will vary).
290 * Backends that don't support metadata ignore this. (since 1.21)
291 *
292 * $opts is an associative of boolean flags, including:
293 * - force : Operation precondition errors no longer trigger an abort.
294 * Any remaining operations are still attempted. Unexpected
295 * failures may still cause remaining operations to be aborted.
296 * - nonLocking : No locks are acquired for the operations.
297 * This can increase performance for non-critical writes.
298 * This has no effect unless the 'force' flag is set.
299 * - nonJournaled : Don't log this operation batch in the file journal.
300 * This limits the ability of recovery scripts.
301 * - parallelize : Try to do operations in parallel when possible.
302 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
303 * - preserveCache : Don't clear the process cache before checking files.
304 * This should only be used if all entries in the process
305 * cache were added after the files were already locked. (since 1.20)
306 *
307 * @remarks Remarks on locking:
308 * File system paths given to operations should refer to files that are
309 * already locked or otherwise safe from modification from other processes.
310 * Normally these files will be new temp files, which should be adequate.
311 *
312 * @par Return value:
313 *
314 * This returns a Status, which contains all warnings and fatals that occurred
315 * during the operation. The 'failCount', 'successCount', and 'success' members
316 * will reflect each operation attempted.
317 *
318 * The status will be "OK" unless:
319 * - a) unexpected operation errors occurred (network partitions, disk full...)
320 * - b) significant operation errors occurred and 'force' was not set
321 *
322 * @param array $ops List of operations to execute in order
323 * @param array $opts Batch operation options
324 * @return Status
325 */
326 final public function doOperations( array $ops, array $opts = array() ) {
327 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
328 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
329 }
330 if ( !count( $ops ) ) {
331 return Status::newGood(); // nothing to do
332 }
333 if ( empty( $opts['force'] ) ) { // sanity
334 unset( $opts['nonLocking'] );
335 }
336 foreach ( $ops as &$op ) {
337 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
338 $op['headers']['Content-Disposition'] = $op['disposition'];
339 }
340 }
341 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
342 return $this->doOperationsInternal( $ops, $opts );
343 }
344
345 /**
346 * @see FileBackend::doOperations()
347 */
348 abstract protected function doOperationsInternal( array $ops, array $opts );
349
350 /**
351 * Same as doOperations() except it takes a single operation.
352 * If you are doing a batch of operations that should either
353 * all succeed or all fail, then use that function instead.
354 *
355 * @see FileBackend::doOperations()
356 *
357 * @param array $op Operation
358 * @param array $opts Operation options
359 * @return Status
360 */
361 final public function doOperation( array $op, array $opts = array() ) {
362 return $this->doOperations( array( $op ), $opts );
363 }
364
365 /**
366 * Performs a single create operation.
367 * This sets $params['op'] to 'create' and passes it to doOperation().
368 *
369 * @see FileBackend::doOperation()
370 *
371 * @param array $params Operation parameters
372 * @param array $opts Operation options
373 * @return Status
374 */
375 final public function create( array $params, array $opts = array() ) {
376 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
377 }
378
379 /**
380 * Performs a single store operation.
381 * This sets $params['op'] to 'store' and passes it to doOperation().
382 *
383 * @see FileBackend::doOperation()
384 *
385 * @param array $params Operation parameters
386 * @param array $opts Operation options
387 * @return Status
388 */
389 final public function store( array $params, array $opts = array() ) {
390 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
391 }
392
393 /**
394 * Performs a single copy operation.
395 * This sets $params['op'] to 'copy' and passes it to doOperation().
396 *
397 * @see FileBackend::doOperation()
398 *
399 * @param array $params Operation parameters
400 * @param array $opts Operation options
401 * @return Status
402 */
403 final public function copy( array $params, array $opts = array() ) {
404 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
405 }
406
407 /**
408 * Performs a single move operation.
409 * This sets $params['op'] to 'move' and passes it to doOperation().
410 *
411 * @see FileBackend::doOperation()
412 *
413 * @param array $params Operation parameters
414 * @param array $opts Operation options
415 * @return Status
416 */
417 final public function move( array $params, array $opts = array() ) {
418 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
419 }
420
421 /**
422 * Performs a single delete operation.
423 * This sets $params['op'] to 'delete' and passes it to doOperation().
424 *
425 * @see FileBackend::doOperation()
426 *
427 * @param array $params Operation parameters
428 * @param array $opts Operation options
429 * @return Status
430 */
431 final public function delete( array $params, array $opts = array() ) {
432 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
433 }
434
435 /**
436 * Performs a single describe operation.
437 * This sets $params['op'] to 'describe' and passes it to doOperation().
438 *
439 * @see FileBackend::doOperation()
440 *
441 * @param array $params Operation parameters
442 * @param array $opts Operation options
443 * @return Status
444 * @since 1.21
445 */
446 final public function describe( array $params, array $opts = array() ) {
447 return $this->doOperation( array( 'op' => 'describe' ) + $params, $opts );
448 }
449
450 /**
451 * Perform a set of independent file operations on some files.
452 *
453 * This does no locking, nor journaling, and possibly no stat calls.
454 * Any destination files that already exist will be overwritten.
455 * This should *only* be used on non-original files, like cache files.
456 *
457 * Supported operations and their parameters:
458 * - create
459 * - store
460 * - copy
461 * - move
462 * - delete
463 * - describe (since 1.21)
464 * - null
465 *
466 * a) Create a new file in storage with the contents of a string
467 * @code
468 * array(
469 * 'op' => 'create',
470 * 'dst' => <storage path>,
471 * 'content' => <string of new file contents>,
472 * 'headers' => <HTTP header name/value map> # since 1.21
473 * )
474 * @endcode
475 *
476 * b) Copy a file system file into storage
477 * @code
478 * array(
479 * 'op' => 'store',
480 * 'src' => <file system path>,
481 * 'dst' => <storage path>,
482 * 'headers' => <HTTP header name/value map> # since 1.21
483 * )
484 * @endcode
485 *
486 * c) Copy a file within storage
487 * @code
488 * array(
489 * 'op' => 'copy',
490 * 'src' => <storage path>,
491 * 'dst' => <storage path>,
492 * 'ignoreMissingSource' => <boolean>, # since 1.21
493 * 'headers' => <HTTP header name/value map> # since 1.21
494 * )
495 * @endcode
496 *
497 * d) Move a file within storage
498 * @code
499 * array(
500 * 'op' => 'move',
501 * 'src' => <storage path>,
502 * 'dst' => <storage path>,
503 * 'ignoreMissingSource' => <boolean>, # since 1.21
504 * 'headers' => <HTTP header name/value map> # since 1.21
505 * )
506 * @endcode
507 *
508 * e) Delete a file within storage
509 * @code
510 * array(
511 * 'op' => 'delete',
512 * 'src' => <storage path>,
513 * 'ignoreMissingSource' => <boolean>
514 * )
515 * @endcode
516 *
517 * f) Update metadata for a file within storage
518 * @code
519 * array(
520 * 'op' => 'describe',
521 * 'src' => <storage path>,
522 * 'headers' => <HTTP header name/value map>
523 * )
524 * @endcode
525 *
526 * g) Do nothing (no-op)
527 * @code
528 * array(
529 * 'op' => 'null',
530 * )
531 * @endcode
532 *
533 * @par Boolean flags for operations (operation-specific):
534 * - ignoreMissingSource : The operation will simply succeed and do
535 * nothing if the source file does not exist.
536 * - headers : If supplied with a header name/value map, the backend will
537 * reply with these headers when GETs/HEADs of the destination
538 * file are made. Header values should be smaller than 256 bytes.
539 * Content-Disposition headers can be longer, though the system
540 * might ignore or truncate ones that are too long to store.
541 * Existing headers will remain, but these will replace any
542 * conflicting previous headers, and headers will be removed
543 * if they are set to an empty string.
544 * Backends that don't support metadata ignore this. (since 1.21)
545 *
546 * $opts is an associative of boolean flags, including:
547 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
548 *
549 * @par Return value:
550 * This returns a Status, which contains all warnings and fatals that occurred
551 * during the operation. The 'failCount', 'successCount', and 'success' members
552 * will reflect each operation attempted for the given files. The status will be
553 * considered "OK" as long as no fatal errors occurred.
554 *
555 * @param array $ops Set of operations to execute
556 * @param array $opts Batch operation options
557 * @return Status
558 * @since 1.20
559 */
560 final public function doQuickOperations( array $ops, array $opts = array() ) {
561 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
562 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
563 }
564 if ( !count( $ops ) ) {
565 return Status::newGood(); // nothing to do
566 }
567 foreach ( $ops as &$op ) {
568 $op['overwrite'] = true; // avoids RTTs in key/value stores
569 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
570 $op['headers']['Content-Disposition'] = $op['disposition'];
571 }
572 }
573 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
574 return $this->doQuickOperationsInternal( $ops );
575 }
576
577 /**
578 * @see FileBackend::doQuickOperations()
579 * @since 1.20
580 */
581 abstract protected function doQuickOperationsInternal( array $ops );
582
583 /**
584 * Same as doQuickOperations() except it takes a single operation.
585 * If you are doing a batch of operations, then use that function instead.
586 *
587 * @see FileBackend::doQuickOperations()
588 *
589 * @param array $op Operation
590 * @return Status
591 * @since 1.20
592 */
593 final public function doQuickOperation( array $op ) {
594 return $this->doQuickOperations( array( $op ) );
595 }
596
597 /**
598 * Performs a single quick create operation.
599 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
600 *
601 * @see FileBackend::doQuickOperation()
602 *
603 * @param array $params Operation parameters
604 * @return Status
605 * @since 1.20
606 */
607 final public function quickCreate( array $params ) {
608 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
609 }
610
611 /**
612 * Performs a single quick store operation.
613 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
614 *
615 * @see FileBackend::doQuickOperation()
616 *
617 * @param array $params Operation parameters
618 * @return Status
619 * @since 1.20
620 */
621 final public function quickStore( array $params ) {
622 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
623 }
624
625 /**
626 * Performs a single quick copy operation.
627 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
628 *
629 * @see FileBackend::doQuickOperation()
630 *
631 * @param array $params Operation parameters
632 * @return Status
633 * @since 1.20
634 */
635 final public function quickCopy( array $params ) {
636 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
637 }
638
639 /**
640 * Performs a single quick move operation.
641 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
642 *
643 * @see FileBackend::doQuickOperation()
644 *
645 * @param array $params Operation parameters
646 * @return Status
647 * @since 1.20
648 */
649 final public function quickMove( array $params ) {
650 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
651 }
652
653 /**
654 * Performs a single quick delete operation.
655 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
656 *
657 * @see FileBackend::doQuickOperation()
658 *
659 * @param array $params Operation parameters
660 * @return Status
661 * @since 1.20
662 */
663 final public function quickDelete( array $params ) {
664 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
665 }
666
667 /**
668 * Performs a single quick describe operation.
669 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
670 *
671 * @see FileBackend::doQuickOperation()
672 *
673 * @param array $params Operation parameters
674 * @return Status
675 * @since 1.21
676 */
677 final public function quickDescribe( array $params ) {
678 return $this->doQuickOperation( array( 'op' => 'describe' ) + $params );
679 }
680
681 /**
682 * Concatenate a list of storage files into a single file system file.
683 * The target path should refer to a file that is already locked or
684 * otherwise safe from modification from other processes. Normally,
685 * the file will be a new temp file, which should be adequate.
686 *
687 * @param array $params Operation parameters, include:
688 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
689 * - dst : file system path to 0-byte temp file
690 * - parallelize : try to do operations in parallel when possible
691 * @return Status
692 */
693 abstract public function concatenate( array $params );
694
695 /**
696 * Prepare a storage directory for usage.
697 * This will create any required containers and parent directories.
698 * Backends using key/value stores only need to create the container.
699 *
700 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
701 * except they are only applied *if* the directory/container had to be created.
702 * These flags should always be set for directories that have private files.
703 * However, setting them is not guaranteed to actually do anything.
704 * Additional server configuration may be needed to achieve the desired effect.
705 *
706 * @param array $params Parameters include:
707 * - dir : storage directory
708 * - noAccess : try to deny file access (since 1.20)
709 * - noListing : try to deny file listing (since 1.20)
710 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
711 * @return Status
712 */
713 final public function prepare( array $params ) {
714 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
715 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
716 }
717 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
718 return $this->doPrepare( $params );
719 }
720
721 /**
722 * @see FileBackend::prepare()
723 */
724 abstract protected function doPrepare( array $params );
725
726 /**
727 * Take measures to block web access to a storage directory and
728 * the container it belongs to. FS backends might add .htaccess
729 * files whereas key/value store backends might revoke container
730 * access to the storage user representing end-users in web requests.
731 *
732 * This is not guaranteed to actually make files or listings publically hidden.
733 * Additional server configuration may be needed to achieve the desired effect.
734 *
735 * @param array $params Parameters include:
736 * - dir : storage directory
737 * - noAccess : try to deny file access
738 * - noListing : try to deny file listing
739 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
740 * @return Status
741 */
742 final public function secure( array $params ) {
743 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
744 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
745 }
746 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
747 return $this->doSecure( $params );
748 }
749
750 /**
751 * @see FileBackend::secure()
752 */
753 abstract protected function doSecure( array $params );
754
755 /**
756 * Remove measures to block web access to a storage directory and
757 * the container it belongs to. FS backends might remove .htaccess
758 * files whereas key/value store backends might grant container
759 * access to the storage user representing end-users in web requests.
760 * This essentially can undo the result of secure() calls.
761 *
762 * This is not guaranteed to actually make files or listings publically viewable.
763 * Additional server configuration may be needed to achieve the desired effect.
764 *
765 * @param array $params Parameters include:
766 * - dir : storage directory
767 * - access : try to allow file access
768 * - listing : try to allow file listing
769 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
770 * @return Status
771 * @since 1.20
772 */
773 final public function publish( array $params ) {
774 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
775 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
776 }
777 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
778 return $this->doPublish( $params );
779 }
780
781 /**
782 * @see FileBackend::publish()
783 */
784 abstract protected function doPublish( array $params );
785
786 /**
787 * Delete a storage directory if it is empty.
788 * Backends using key/value stores may do nothing unless the directory
789 * is that of an empty container, in which case it will be deleted.
790 *
791 * @param array $params Parameters include:
792 * - dir : storage directory
793 * - recursive : recursively delete empty subdirectories first (since 1.20)
794 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
795 * @return Status
796 */
797 final public function clean( array $params ) {
798 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
799 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
800 }
801 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
802 return $this->doClean( $params );
803 }
804
805 /**
806 * @see FileBackend::clean()
807 */
808 abstract protected function doClean( array $params );
809
810 /**
811 * Enter file operation scope.
812 * This just makes PHP ignore user aborts/disconnects until the return
813 * value leaves scope. This returns null and does nothing in CLI mode.
814 *
815 * @return ScopedCallback|null
816 */
817 final protected function getScopedPHPBehaviorForOps() {
818 if ( PHP_SAPI != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
819 $old = ignore_user_abort( true ); // avoid half-finished operations
820 return new ScopedCallback( function () use ( $old ) {
821 ignore_user_abort( $old );
822 } );
823 }
824
825 return null;
826 }
827
828 /**
829 * Check if a file exists at a storage path in the backend.
830 * This returns false if only a directory exists at the path.
831 *
832 * @param array $params Parameters include:
833 * - src : source storage path
834 * - latest : use the latest available data
835 * @return bool|null Returns null on failure
836 */
837 abstract public function fileExists( array $params );
838
839 /**
840 * Get the last-modified timestamp of the file at a storage path.
841 *
842 * @param array $params Parameters include:
843 * - src : source storage path
844 * - latest : use the latest available data
845 * @return string|bool TS_MW timestamp or false on failure
846 */
847 abstract public function getFileTimestamp( array $params );
848
849 /**
850 * Get the contents of a file at a storage path in the backend.
851 * This should be avoided for potentially large files.
852 *
853 * @param array $params Parameters include:
854 * - src : source storage path
855 * - latest : use the latest available data
856 * @return string|bool Returns false on failure
857 */
858 final public function getFileContents( array $params ) {
859 $contents = $this->getFileContentsMulti(
860 array( 'srcs' => array( $params['src'] ) ) + $params );
861
862 return $contents[$params['src']];
863 }
864
865 /**
866 * Like getFileContents() except it takes an array of storage paths
867 * and returns a map of storage paths to strings (or null on failure).
868 * The map keys (paths) are in the same order as the provided list of paths.
869 *
870 * @see FileBackend::getFileContents()
871 *
872 * @param array $params Parameters include:
873 * - srcs : list of source storage paths
874 * - latest : use the latest available data
875 * - parallelize : try to do operations in parallel when possible
876 * @return array Map of (path name => string or false on failure)
877 * @since 1.20
878 */
879 abstract public function getFileContentsMulti( array $params );
880
881 /**
882 * Get the size (bytes) of a file at a storage path in the backend.
883 *
884 * @param array $params Parameters include:
885 * - src : source storage path
886 * - latest : use the latest available data
887 * @return int|bool Returns false on failure
888 */
889 abstract public function getFileSize( array $params );
890
891 /**
892 * Get quick information about a file at a storage path in the backend.
893 * If the file does not exist, then this returns false.
894 * Otherwise, the result is an associative array that includes:
895 * - mtime : the last-modified timestamp (TS_MW)
896 * - size : the file size (bytes)
897 * Additional values may be included for internal use only.
898 *
899 * @param array $params Parameters include:
900 * - src : source storage path
901 * - latest : use the latest available data
902 * @return array|bool|null Returns null on failure
903 */
904 abstract public function getFileStat( array $params );
905
906 /**
907 * Get a SHA-1 hash of the file at a storage path in the backend.
908 *
909 * @param array $params Parameters include:
910 * - src : source storage path
911 * - latest : use the latest available data
912 * @return string|bool Hash string or false on failure
913 */
914 abstract public function getFileSha1Base36( array $params );
915
916 /**
917 * Get the properties of the file at a storage path in the backend.
918 * This gives the result of FSFile::getProps() on a local copy of the file.
919 *
920 * @param array $params Parameters include:
921 * - src : source storage path
922 * - latest : use the latest available data
923 * @return array Returns FSFile::placeholderProps() on failure
924 */
925 abstract public function getFileProps( array $params );
926
927 /**
928 * Stream the file at a storage path in the backend.
929 * If the file does not exists, an HTTP 404 error will be given.
930 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
931 * will be sent if streaming began, while none will be sent otherwise.
932 * Implementations should flush the output buffer before sending data.
933 *
934 * @param array $params Parameters include:
935 * - src : source storage path
936 * - headers : list of additional HTTP headers to send on success
937 * - latest : use the latest available data
938 * @return Status
939 */
940 abstract public function streamFile( array $params );
941
942 /**
943 * Returns a file system file, identical to the file at a storage path.
944 * The file returned is either:
945 * - a) A local copy of the file at a storage path in the backend.
946 * The temporary copy will have the same extension as the source.
947 * - b) An original of the file at a storage path in the backend.
948 * Temporary files may be purged when the file object falls out of scope.
949 *
950 * Write operations should *never* be done on this file as some backends
951 * may do internal tracking or may be instances of FileBackendMultiWrite.
952 * In that later case, there are copies of the file that must stay in sync.
953 * Additionally, further calls to this function may return the same file.
954 *
955 * @param array $params Parameters include:
956 * - src : source storage path
957 * - latest : use the latest available data
958 * @return FSFile|null Returns null on failure
959 */
960 final public function getLocalReference( array $params ) {
961 $fsFiles = $this->getLocalReferenceMulti(
962 array( 'srcs' => array( $params['src'] ) ) + $params );
963
964 return $fsFiles[$params['src']];
965 }
966
967 /**
968 * Like getLocalReference() except it takes an array of storage paths
969 * and returns a map of storage paths to FSFile objects (or null on failure).
970 * The map keys (paths) are in the same order as the provided list of paths.
971 *
972 * @see FileBackend::getLocalReference()
973 *
974 * @param array $params Parameters include:
975 * - srcs : list of source storage paths
976 * - latest : use the latest available data
977 * - parallelize : try to do operations in parallel when possible
978 * @return array Map of (path name => FSFile or null on failure)
979 * @since 1.20
980 */
981 abstract public function getLocalReferenceMulti( array $params );
982
983 /**
984 * Get a local copy on disk of the file at a storage path in the backend.
985 * The temporary copy will have the same file extension as the source.
986 * Temporary files may be purged when the file object falls out of scope.
987 *
988 * @param array $params Parameters include:
989 * - src : source storage path
990 * - latest : use the latest available data
991 * @return TempFSFile|null Returns null on failure
992 */
993 final public function getLocalCopy( array $params ) {
994 $tmpFiles = $this->getLocalCopyMulti(
995 array( 'srcs' => array( $params['src'] ) ) + $params );
996
997 return $tmpFiles[$params['src']];
998 }
999
1000 /**
1001 * Like getLocalCopy() except it takes an array of storage paths and
1002 * returns a map of storage paths to TempFSFile objects (or null on failure).
1003 * The map keys (paths) are in the same order as the provided list of paths.
1004 *
1005 * @see FileBackend::getLocalCopy()
1006 *
1007 * @param array $params Parameters include:
1008 * - srcs : list of source storage paths
1009 * - latest : use the latest available data
1010 * - parallelize : try to do operations in parallel when possible
1011 * @return array Map of (path name => TempFSFile or null on failure)
1012 * @since 1.20
1013 */
1014 abstract public function getLocalCopyMulti( array $params );
1015
1016 /**
1017 * Return an HTTP URL to a given file that requires no authentication to use.
1018 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1019 * This will return null if the backend cannot make an HTTP URL for the file.
1020 *
1021 * This is useful for key/value stores when using scripts that seek around
1022 * large files and those scripts (and the backend) support HTTP Range headers.
1023 * Otherwise, one would need to use getLocalReference(), which involves loading
1024 * the entire file on to local disk.
1025 *
1026 * @param array $params Parameters include:
1027 * - src : source storage path
1028 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1029 * @return string|null
1030 * @since 1.21
1031 */
1032 abstract public function getFileHttpUrl( array $params );
1033
1034 /**
1035 * Check if a directory exists at a given storage path.
1036 * Backends using key/value stores will check if the path is a
1037 * virtual directory, meaning there are files under the given directory.
1038 *
1039 * Storage backends with eventual consistency might return stale data.
1040 *
1041 * @param array $params Parameters include:
1042 * - dir : storage directory
1043 * @return bool|null Returns null on failure
1044 * @since 1.20
1045 */
1046 abstract public function directoryExists( array $params );
1047
1048 /**
1049 * Get an iterator to list *all* directories under a storage directory.
1050 * If the directory is of the form "mwstore://backend/container",
1051 * then all directories in the container will be listed.
1052 * If the directory is of form "mwstore://backend/container/dir",
1053 * then all directories directly under that directory will be listed.
1054 * Results will be storage directories relative to the given directory.
1055 *
1056 * Storage backends with eventual consistency might return stale data.
1057 *
1058 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1059 *
1060 * @param array $params Parameters include:
1061 * - dir : storage directory
1062 * - topOnly : only return direct child dirs of the directory
1063 * @return Traversable|Array|null Returns null on failure
1064 * @since 1.20
1065 */
1066 abstract public function getDirectoryList( array $params );
1067
1068 /**
1069 * Same as FileBackend::getDirectoryList() except only lists
1070 * directories that are immediately under the given directory.
1071 *
1072 * Storage backends with eventual consistency might return stale data.
1073 *
1074 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1075 *
1076 * @param array $params Parameters include:
1077 * - dir : storage directory
1078 * @return Traversable|Array|null Returns null on failure
1079 * @since 1.20
1080 */
1081 final public function getTopDirectoryList( array $params ) {
1082 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
1083 }
1084
1085 /**
1086 * Get an iterator to list *all* stored files under a storage directory.
1087 * If the directory is of the form "mwstore://backend/container",
1088 * then all files in the container will be listed.
1089 * If the directory is of form "mwstore://backend/container/dir",
1090 * then all files under that directory will be listed.
1091 * Results will be storage paths relative to the given directory.
1092 *
1093 * Storage backends with eventual consistency might return stale data.
1094 *
1095 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1096 *
1097 * @param array $params Parameters include:
1098 * - dir : storage directory
1099 * - topOnly : only return direct child files of the directory (since 1.20)
1100 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1101 * @return Traversable|Array|null Returns null on failure
1102 */
1103 abstract public function getFileList( array $params );
1104
1105 /**
1106 * Same as FileBackend::getFileList() except only lists
1107 * files that are immediately under the given directory.
1108 *
1109 * Storage backends with eventual consistency might return stale data.
1110 *
1111 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1112 *
1113 * @param array $params Parameters include:
1114 * - dir : storage directory
1115 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1116 * @return Traversable|Array|null Returns null on failure
1117 * @since 1.20
1118 */
1119 final public function getTopFileList( array $params ) {
1120 return $this->getFileList( array( 'topOnly' => true ) + $params );
1121 }
1122
1123 /**
1124 * Preload persistent file stat and property cache into in-process cache.
1125 * This should be used when stat calls will be made on a known list of a many files.
1126 *
1127 * @param array $paths Storage paths
1128 */
1129 public function preloadCache( array $paths ) {
1130 }
1131
1132 /**
1133 * Invalidate any in-process file stat and property cache.
1134 * If $paths is given, then only the cache for those files will be cleared.
1135 *
1136 * @param array $paths Storage paths (optional)
1137 */
1138 public function clearCache( array $paths = null ) {
1139 }
1140
1141 /**
1142 * Lock the files at the given storage paths in the backend.
1143 * This will either lock all the files or none (on failure).
1144 *
1145 * Callers should consider using getScopedFileLocks() instead.
1146 *
1147 * @param array $paths Storage paths
1148 * @param int $type LockManager::LOCK_* constant
1149 * @return Status
1150 */
1151 final public function lockFiles( array $paths, $type ) {
1152 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1153
1154 return $this->lockManager->lock( $paths, $type );
1155 }
1156
1157 /**
1158 * Unlock the files at the given storage paths in the backend.
1159 *
1160 * @param array $paths Storage paths
1161 * @param int $type LockManager::LOCK_* constant
1162 * @return Status
1163 */
1164 final public function unlockFiles( array $paths, $type ) {
1165 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1166
1167 return $this->lockManager->unlock( $paths, $type );
1168 }
1169
1170 /**
1171 * Lock the files at the given storage paths in the backend.
1172 * This will either lock all the files or none (on failure).
1173 * On failure, the status object will be updated with errors.
1174 *
1175 * Once the return value goes out scope, the locks will be released and
1176 * the status updated. Unlock fatals will not change the status "OK" value.
1177 *
1178 * @see ScopedLock::factory()
1179 *
1180 * @param array $paths List of storage paths or map of lock types to path lists
1181 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1182 * @param Status $status Status to update on lock/unlock
1183 * @return ScopedLock|null Returns null on failure
1184 */
1185 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
1186 if ( $type === 'mixed' ) {
1187 foreach ( $paths as &$typePaths ) {
1188 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1189 }
1190 } else {
1191 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1192 }
1193
1194 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
1195 }
1196
1197 /**
1198 * Get an array of scoped locks needed for a batch of file operations.
1199 *
1200 * Normally, FileBackend::doOperations() handles locking, unless
1201 * the 'nonLocking' param is passed in. This function is useful if you
1202 * want the files to be locked for a broader scope than just when the
1203 * files are changing. For example, if you need to update DB metadata,
1204 * you may want to keep the files locked until finished.
1205 *
1206 * @see FileBackend::doOperations()
1207 *
1208 * @param array $ops List of file operations to FileBackend::doOperations()
1209 * @param Status $status Status to update on lock/unlock
1210 * @return array List of ScopedFileLocks or null values
1211 * @since 1.20
1212 */
1213 abstract public function getScopedLocksForOps( array $ops, Status $status );
1214
1215 /**
1216 * Get the root storage path of this backend.
1217 * All container paths are "subdirectories" of this path.
1218 *
1219 * @return string Storage path
1220 * @since 1.20
1221 */
1222 final public function getRootStoragePath() {
1223 return "mwstore://{$this->name}";
1224 }
1225
1226 /**
1227 * Get the storage path for the given container for this backend
1228 *
1229 * @param string $container Container name
1230 * @return string Storage path
1231 * @since 1.21
1232 */
1233 final public function getContainerStoragePath( $container ) {
1234 return $this->getRootStoragePath() . "/{$container}";
1235 }
1236
1237 /**
1238 * Get the file journal object for this backend
1239 *
1240 * @return FileJournal
1241 */
1242 final public function getJournal() {
1243 return $this->fileJournal;
1244 }
1245
1246 /**
1247 * Check if a given path is a "mwstore://" path.
1248 * This does not do any further validation or any existence checks.
1249 *
1250 * @param string $path
1251 * @return bool
1252 */
1253 final public static function isStoragePath( $path ) {
1254 return ( strpos( $path, 'mwstore://' ) === 0 );
1255 }
1256
1257 /**
1258 * Split a storage path into a backend name, a container name,
1259 * and a relative file path. The relative path may be the empty string.
1260 * This does not do any path normalization or traversal checks.
1261 *
1262 * @param string $storagePath
1263 * @return array (backend, container, rel object) or (null, null, null)
1264 */
1265 final public static function splitStoragePath( $storagePath ) {
1266 if ( self::isStoragePath( $storagePath ) ) {
1267 // Remove the "mwstore://" prefix and split the path
1268 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1269 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1270 if ( count( $parts ) == 3 ) {
1271 return $parts; // e.g. "backend/container/path"
1272 } else {
1273 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1274 }
1275 }
1276 }
1277
1278 return array( null, null, null );
1279 }
1280
1281 /**
1282 * Normalize a storage path by cleaning up directory separators.
1283 * Returns null if the path is not of the format of a valid storage path.
1284 *
1285 * @param string $storagePath
1286 * @return string|null
1287 */
1288 final public static function normalizeStoragePath( $storagePath ) {
1289 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1290 if ( $relPath !== null ) { // must be for this backend
1291 $relPath = self::normalizeContainerPath( $relPath );
1292 if ( $relPath !== null ) {
1293 return ( $relPath != '' )
1294 ? "mwstore://{$backend}/{$container}/{$relPath}"
1295 : "mwstore://{$backend}/{$container}";
1296 }
1297 }
1298
1299 return null;
1300 }
1301
1302 /**
1303 * Get the parent storage directory of a storage path.
1304 * This returns a path like "mwstore://backend/container",
1305 * "mwstore://backend/container/...", or null if there is no parent.
1306 *
1307 * @param string $storagePath
1308 * @return string|null
1309 */
1310 final public static function parentStoragePath( $storagePath ) {
1311 $storagePath = dirname( $storagePath );
1312 list( , , $rel ) = self::splitStoragePath( $storagePath );
1313
1314 return ( $rel === null ) ? null : $storagePath;
1315 }
1316
1317 /**
1318 * Get the final extension from a storage or FS path
1319 *
1320 * @param string $path
1321 * @return string
1322 */
1323 final public static function extensionFromPath( $path ) {
1324 $i = strrpos( $path, '.' );
1325
1326 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1327 }
1328
1329 /**
1330 * Check if a relative path has no directory traversals
1331 *
1332 * @param string $path
1333 * @return bool
1334 * @since 1.20
1335 */
1336 final public static function isPathTraversalFree( $path ) {
1337 return ( self::normalizeContainerPath( $path ) !== null );
1338 }
1339
1340 /**
1341 * Build a Content-Disposition header value per RFC 6266.
1342 *
1343 * @param string $type One of (attachment, inline)
1344 * @param string $filename Suggested file name (should not contain slashes)
1345 * @throws MWException
1346 * @return string
1347 * @since 1.20
1348 */
1349 final public static function makeContentDisposition( $type, $filename = '' ) {
1350 $parts = array();
1351
1352 $type = strtolower( $type );
1353 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1354 throw new MWException( "Invalid Content-Disposition type '$type'." );
1355 }
1356 $parts[] = $type;
1357
1358 if ( strlen( $filename ) ) {
1359 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1360 }
1361
1362 return implode( ';', $parts );
1363 }
1364
1365 /**
1366 * Validate and normalize a relative storage path.
1367 * Null is returned if the path involves directory traversal.
1368 * Traversal is insecure for FS backends and broken for others.
1369 *
1370 * This uses the same traversal protection as Title::secureAndSplit().
1371 *
1372 * @param string $path Storage path relative to a container
1373 * @return string|null
1374 */
1375 final protected static function normalizeContainerPath( $path ) {
1376 // Normalize directory separators
1377 $path = strtr( $path, '\\', '/' );
1378 // Collapse any consecutive directory separators
1379 $path = preg_replace( '![/]{2,}!', '/', $path );
1380 // Remove any leading directory separator
1381 $path = ltrim( $path, '/' );
1382 // Use the same traversal protection as Title::secureAndSplit()
1383 if ( strpos( $path, '.' ) !== false ) {
1384 if (
1385 $path === '.' ||
1386 $path === '..' ||
1387 strpos( $path, './' ) === 0 ||
1388 strpos( $path, '../' ) === 0 ||
1389 strpos( $path, '/./' ) !== false ||
1390 strpos( $path, '/../' ) !== false
1391 ) {
1392 return null;
1393 }
1394 }
1395
1396 return $path;
1397 }
1398 }
1399
1400 /**
1401 * @ingroup FileBackend
1402 * @since 1.22
1403 */
1404 class FileBackendError extends MWException {
1405 }