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