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