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