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