Merge "[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 * If a callback function is given, it will be called each time a segment is
664 * appended and when the overall concatenate operation completes or fails.
665 * The arguments passed in are:
666 * - 1) A Status object containing errors if any problems occurred.
667 * - 2) The index of the relevant segment (starting at 1) if a segment was appended
668 * (including the last one) or null in the case of overall success or failure.
669 * When a good Status is returned with a null segment, then the operation completed.
670 * Callbacks should generally avoid throwing exceptions.
671 *
672 * @param $params Array Operation parameters
673 * $params include:
674 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
675 * - dst : file system path to 0-byte temp file
676 * - parallelize : try to do operations in parallel when possible
677 * - callback : closure called when chunks are appended and on success/failure
678 * @return Status
679 */
680 abstract public function concatenate( array $params );
681
682 /**
683 * Prepare a storage directory for usage.
684 * This will create any required containers and parent directories.
685 * Backends using key/value stores only need to create the container.
686 *
687 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
688 * except they are only applied *if* the directory/container had to be created.
689 * These flags should always be set for directories that have private files.
690 *
691 * @param $params Array
692 * $params include:
693 * - dir : storage directory
694 * - noAccess : try to deny file access (since 1.20)
695 * - noListing : try to deny file listing (since 1.20)
696 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
697 * @return Status
698 */
699 final public function prepare( array $params ) {
700 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
701 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
702 }
703 return $this->doPrepare( $params );
704 }
705
706 /**
707 * @see FileBackend::prepare()
708 */
709 abstract protected function doPrepare( array $params );
710
711 /**
712 * Take measures to block web access to a storage directory and
713 * the container it belongs to. FS backends might add .htaccess
714 * files whereas key/value store backends might revoke container
715 * access to the storage user representing end-users in web requests.
716 * This is not guaranteed to actually do anything.
717 *
718 * @param $params Array
719 * $params include:
720 * - dir : storage directory
721 * - noAccess : try to deny file access
722 * - noListing : try to deny file listing
723 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
724 * @return Status
725 */
726 final public function secure( array $params ) {
727 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
728 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
729 }
730 return $this->doSecure( $params );
731 }
732
733 /**
734 * @see FileBackend::secure()
735 */
736 abstract protected function doSecure( array $params );
737
738 /**
739 * Remove measures to block web access to a storage directory and
740 * the container it belongs to. FS backends might remove .htaccess
741 * files whereas key/value store backends might grant container
742 * access to the storage user representing end-users in web requests.
743 * This essentially can undo the result of secure() calls.
744 *
745 * @param $params Array
746 * $params include:
747 * - dir : storage directory
748 * - access : try to allow file access
749 * - listing : try to allow file listing
750 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
751 * @return Status
752 * @since 1.20
753 */
754 final public function publish( array $params ) {
755 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
756 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
757 }
758 return $this->doPublish( $params );
759 }
760
761 /**
762 * @see FileBackend::publish()
763 */
764 abstract protected function doPublish( array $params );
765
766 /**
767 * Delete a storage directory if it is empty.
768 * Backends using key/value stores may do nothing unless the directory
769 * is that of an empty container, in which case it will be deleted.
770 *
771 * @param $params Array
772 * $params include:
773 * - dir : storage directory
774 * - recursive : recursively delete empty subdirectories first (since 1.20)
775 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
776 * @return Status
777 */
778 final public function clean( array $params ) {
779 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
780 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
781 }
782 return $this->doClean( $params );
783 }
784
785 /**
786 * @see FileBackend::clean()
787 */
788 abstract protected function doClean( array $params );
789
790 /**
791 * Check if a file exists at a storage path in the backend.
792 * This returns false if only a directory exists at the path.
793 *
794 * @param $params Array
795 * $params include:
796 * - src : source storage path
797 * - latest : use the latest available data
798 * @return bool|null Returns null on failure
799 */
800 abstract public function fileExists( array $params );
801
802 /**
803 * Get the last-modified timestamp of the file at a storage path.
804 *
805 * @param $params Array
806 * $params include:
807 * - src : source storage path
808 * - latest : use the latest available data
809 * @return string|bool TS_MW timestamp or false on failure
810 */
811 abstract public function getFileTimestamp( array $params );
812
813 /**
814 * Get the contents of a file at a storage path in the backend.
815 * This should be avoided for potentially large files.
816 *
817 * @param $params Array
818 * $params include:
819 * - src : source storage path
820 * - latest : use the latest available data
821 * @return string|bool Returns false on failure
822 */
823 final public function getFileContents( array $params ) {
824 $contents = $this->getFileContentsMulti(
825 array( 'srcs' => array( $params['src'] ) ) + $params );
826
827 return $contents[$params['src']];
828 }
829
830 /**
831 * Like getFileContents() except it takes an array of storage paths
832 * and returns a map of storage paths to strings (or null on failure).
833 * The map keys (paths) are in the same order as the provided list of paths.
834 *
835 * @see FileBackend::getFileContents()
836 *
837 * @param $params Array
838 * $params include:
839 * - srcs : list of source storage paths
840 * - latest : use the latest available data
841 * - parallelize : try to do operations in parallel when possible
842 * @return Array Map of (path name => string or false on failure)
843 * @since 1.20
844 */
845 abstract public function getFileContentsMulti( array $params );
846
847 /**
848 * Get the size (bytes) of a file at a storage path in the backend.
849 *
850 * @param $params Array
851 * $params include:
852 * - src : source storage path
853 * - latest : use the latest available data
854 * @return integer|bool Returns false on failure
855 */
856 abstract public function getFileSize( array $params );
857
858 /**
859 * Get quick information about a file at a storage path in the backend.
860 * If the file does not exist, then this returns false.
861 * Otherwise, the result is an associative array that includes:
862 * - mtime : the last-modified timestamp (TS_MW)
863 * - size : the file size (bytes)
864 * Additional values may be included for internal use only.
865 *
866 * @param $params Array
867 * $params include:
868 * - src : source storage path
869 * - latest : use the latest available data
870 * @return Array|bool|null Returns null on failure
871 */
872 abstract public function getFileStat( array $params );
873
874 /**
875 * Get a SHA-1 hash of the file at a storage path in the backend.
876 *
877 * @param $params Array
878 * $params include:
879 * - src : source storage path
880 * - latest : use the latest available data
881 * @return string|bool Hash string or false on failure
882 */
883 abstract public function getFileSha1Base36( array $params );
884
885 /**
886 * Get the properties of the file at a storage path in the backend.
887 * Returns FSFile::placeholderProps() on failure.
888 *
889 * @param $params Array
890 * $params include:
891 * - src : source storage path
892 * - latest : use the latest available data
893 * @return Array
894 */
895 abstract public function getFileProps( array $params );
896
897 /**
898 * Stream the file at a storage path in the backend.
899 * If the file does not exists, an HTTP 404 error will be given.
900 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
901 * will be sent if streaming began, while none will be sent otherwise.
902 * Implementations should flush the output buffer before sending data.
903 *
904 * @param $params Array
905 * $params include:
906 * - src : source storage path
907 * - headers : list of additional HTTP headers to send on success
908 * - latest : use the latest available data
909 * @return Status
910 */
911 abstract public function streamFile( array $params );
912
913 /**
914 * Returns a file system file, identical to the file at a storage path.
915 * The file returned is either:
916 * - a) A local copy of the file at a storage path in the backend.
917 * The temporary copy will have the same extension as the source.
918 * - b) An original of the file at a storage path in the backend.
919 * Temporary files may be purged when the file object falls out of scope.
920 *
921 * Write operations should *never* be done on this file as some backends
922 * may do internal tracking or may be instances of FileBackendMultiWrite.
923 * In that later case, there are copies of the file that must stay in sync.
924 * Additionally, further calls to this function may return the same file.
925 *
926 * @param $params Array
927 * $params include:
928 * - src : source storage path
929 * - latest : use the latest available data
930 * @return FSFile|null Returns null on failure
931 */
932 final public function getLocalReference( array $params ) {
933 $fsFiles = $this->getLocalReferenceMulti(
934 array( 'srcs' => array( $params['src'] ) ) + $params );
935
936 return $fsFiles[$params['src']];
937 }
938
939 /**
940 * Like getLocalReference() except it takes an array of storage paths
941 * and returns a map of storage paths to FSFile objects (or null on failure).
942 * The map keys (paths) are in the same order as the provided list of paths.
943 *
944 * @see FileBackend::getLocalReference()
945 *
946 * @param $params Array
947 * $params include:
948 * - srcs : list of source storage paths
949 * - latest : use the latest available data
950 * - parallelize : try to do operations in parallel when possible
951 * @return Array Map of (path name => FSFile or null on failure)
952 * @since 1.20
953 */
954 abstract public function getLocalReferenceMulti( array $params );
955
956 /**
957 * Get a local copy on disk of the file at a storage path in the backend.
958 * The temporary copy will have the same file extension as the source.
959 * Temporary files may be purged when the file object falls out of scope.
960 *
961 * @param $params Array
962 * $params include:
963 * - src : source storage path
964 * - latest : use the latest available data
965 * @return TempFSFile|null Returns null on failure
966 */
967 final public function getLocalCopy( array $params ) {
968 $tmpFiles = $this->getLocalCopyMulti(
969 array( 'srcs' => array( $params['src'] ) ) + $params );
970
971 return $tmpFiles[$params['src']];
972 }
973
974 /**
975 * Like getLocalCopy() except it takes an array of storage paths and
976 * returns a map of storage paths to TempFSFile objects (or null on failure).
977 * The map keys (paths) are in the same order as the provided list of paths.
978 *
979 * @see FileBackend::getLocalCopy()
980 *
981 * @param $params Array
982 * $params include:
983 * - srcs : list of source storage paths
984 * - latest : use the latest available data
985 * - parallelize : try to do operations in parallel when possible
986 * @return Array Map of (path name => TempFSFile or null on failure)
987 * @since 1.20
988 */
989 abstract public function getLocalCopyMulti( array $params );
990
991 /**
992 * Return an HTTP URL to a given file that requires no authentication to use.
993 * The URL may be pre-authenticated (via some token in the URL) and temporary.
994 * This will return null if the backend cannot make an HTTP URL for the file.
995 *
996 * This is useful for key/value stores when using scripts that seek around
997 * large files and those scripts (and the backend) support HTTP Range headers.
998 * Otherwise, one would need to use getLocalReference(), which involves loading
999 * the entire file on to local disk.
1000 *
1001 * @param $params Array
1002 * $params include:
1003 * - src : source storage path
1004 * @return string|null
1005 * @since 1.21
1006 */
1007 abstract public function getFileHttpUrl( array $params );
1008
1009 /**
1010 * Check if a directory exists at a given storage path.
1011 * Backends using key/value stores will check if the path is a
1012 * virtual directory, meaning there are files under the given directory.
1013 *
1014 * Storage backends with eventual consistency might return stale data.
1015 *
1016 * @param $params array
1017 * $params include:
1018 * - dir : storage directory
1019 * @return bool|null Returns null on failure
1020 * @since 1.20
1021 */
1022 abstract public function directoryExists( array $params );
1023
1024 /**
1025 * Get an iterator to list *all* directories under a storage directory.
1026 * If the directory is of the form "mwstore://backend/container",
1027 * then all directories in the container will be listed.
1028 * If the directory is of form "mwstore://backend/container/dir",
1029 * then all directories directly under that directory will be listed.
1030 * Results will be storage directories relative to the given directory.
1031 *
1032 * Storage backends with eventual consistency might return stale data.
1033 *
1034 * @param $params array
1035 * $params include:
1036 * - dir : storage directory
1037 * - topOnly : only return direct child dirs of the directory
1038 * @return Traversable|Array|null Returns null on failure
1039 * @since 1.20
1040 */
1041 abstract public function getDirectoryList( array $params );
1042
1043 /**
1044 * Same as FileBackend::getDirectoryList() except only lists
1045 * directories that are immediately under the given directory.
1046 *
1047 * Storage backends with eventual consistency might return stale data.
1048 *
1049 * @param $params array
1050 * $params include:
1051 * - dir : storage directory
1052 * @return Traversable|Array|null Returns null on failure
1053 * @since 1.20
1054 */
1055 final public function getTopDirectoryList( array $params ) {
1056 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
1057 }
1058
1059 /**
1060 * Get an iterator to list *all* stored files under a storage directory.
1061 * If the directory is of the form "mwstore://backend/container",
1062 * then all files in the container will be listed.
1063 * If the directory is of form "mwstore://backend/container/dir",
1064 * then all files under that directory will be listed.
1065 * Results will be storage paths relative to the given directory.
1066 *
1067 * Storage backends with eventual consistency might return stale data.
1068 *
1069 * @param $params array
1070 * $params include:
1071 * - dir : storage directory
1072 * - topOnly : only return direct child files of the directory (since 1.20)
1073 * @return Traversable|Array|null Returns null on failure
1074 */
1075 abstract public function getFileList( array $params );
1076
1077 /**
1078 * Same as FileBackend::getFileList() except only lists
1079 * files that are immediately under the given directory.
1080 *
1081 * Storage backends with eventual consistency might return stale data.
1082 *
1083 * @param $params array
1084 * $params include:
1085 * - dir : storage directory
1086 * @return Traversable|Array|null Returns null on failure
1087 * @since 1.20
1088 */
1089 final public function getTopFileList( array $params ) {
1090 return $this->getFileList( array( 'topOnly' => true ) + $params );
1091 }
1092
1093 /**
1094 * Preload persistent file stat and property cache into in-process cache.
1095 * This should be used when stat calls will be made on a known list of a many files.
1096 *
1097 * @param $paths Array Storage paths
1098 * @return void
1099 */
1100 public function preloadCache( array $paths ) {}
1101
1102 /**
1103 * Invalidate any in-process file stat and property cache.
1104 * If $paths is given, then only the cache for those files will be cleared.
1105 *
1106 * @param $paths Array Storage paths (optional)
1107 * @return void
1108 */
1109 public function clearCache( array $paths = null ) {}
1110
1111 /**
1112 * Lock the files at the given storage paths in the backend.
1113 * This will either lock all the files or none (on failure).
1114 *
1115 * Callers should consider using getScopedFileLocks() instead.
1116 *
1117 * @param $paths Array Storage paths
1118 * @param $type integer LockManager::LOCK_* constant
1119 * @return Status
1120 */
1121 final public function lockFiles( array $paths, $type ) {
1122 return $this->lockManager->lock( $paths, $type );
1123 }
1124
1125 /**
1126 * Unlock the files at the given storage paths in the backend.
1127 *
1128 * @param $paths Array Storage paths
1129 * @param $type integer LockManager::LOCK_* constant
1130 * @return Status
1131 */
1132 final public function unlockFiles( array $paths, $type ) {
1133 return $this->lockManager->unlock( $paths, $type );
1134 }
1135
1136 /**
1137 * Lock the files at the given storage paths in the backend.
1138 * This will either lock all the files or none (on failure).
1139 * On failure, the status object will be updated with errors.
1140 *
1141 * Once the return value goes out scope, the locks will be released and
1142 * the status updated. Unlock fatals will not change the status "OK" value.
1143 *
1144 * @param $paths Array Storage paths
1145 * @param $type integer LockManager::LOCK_* constant
1146 * @param $status Status Status to update on lock/unlock
1147 * @return ScopedLock|null Returns null on failure
1148 */
1149 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
1150 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
1151 }
1152
1153 /**
1154 * Get an array of scoped locks needed for a batch of file operations.
1155 *
1156 * Normally, FileBackend::doOperations() handles locking, unless
1157 * the 'nonLocking' param is passed in. This function is useful if you
1158 * want the files to be locked for a broader scope than just when the
1159 * files are changing. For example, if you need to update DB metadata,
1160 * you may want to keep the files locked until finished.
1161 *
1162 * @see FileBackend::doOperations()
1163 *
1164 * @param $ops Array List of file operations to FileBackend::doOperations()
1165 * @param $status Status Status to update on lock/unlock
1166 * @return Array List of ScopedFileLocks or null values
1167 * @since 1.20
1168 */
1169 abstract public function getScopedLocksForOps( array $ops, Status $status );
1170
1171 /**
1172 * Get the root storage path of this backend.
1173 * All container paths are "subdirectories" of this path.
1174 *
1175 * @return string Storage path
1176 * @since 1.20
1177 */
1178 final public function getRootStoragePath() {
1179 return "mwstore://{$this->name}";
1180 }
1181
1182 /**
1183 * Get the storage path for the given container for this backend
1184 *
1185 * @param $container string Container name
1186 * @return string Storage path
1187 * @since 1.21
1188 */
1189 final public function getContainerStoragePath( $container ) {
1190 return $this->getRootStoragePath() . "/{$container}";
1191 }
1192
1193 /**
1194 * Get the file journal object for this backend
1195 *
1196 * @return FileJournal
1197 */
1198 final public function getJournal() {
1199 return $this->fileJournal;
1200 }
1201
1202 /**
1203 * Check if a given path is a "mwstore://" path.
1204 * This does not do any further validation or any existence checks.
1205 *
1206 * @param $path string
1207 * @return bool
1208 */
1209 final public static function isStoragePath( $path ) {
1210 return ( strpos( $path, 'mwstore://' ) === 0 );
1211 }
1212
1213 /**
1214 * Split a storage path into a backend name, a container name,
1215 * and a relative file path. The relative path may be the empty string.
1216 * This does not do any path normalization or traversal checks.
1217 *
1218 * @param $storagePath string
1219 * @return Array (backend, container, rel object) or (null, null, null)
1220 */
1221 final public static function splitStoragePath( $storagePath ) {
1222 if ( self::isStoragePath( $storagePath ) ) {
1223 // Remove the "mwstore://" prefix and split the path
1224 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1225 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1226 if ( count( $parts ) == 3 ) {
1227 return $parts; // e.g. "backend/container/path"
1228 } else {
1229 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1230 }
1231 }
1232 }
1233 return array( null, null, null );
1234 }
1235
1236 /**
1237 * Normalize a storage path by cleaning up directory separators.
1238 * Returns null if the path is not of the format of a valid storage path.
1239 *
1240 * @param $storagePath string
1241 * @return string|null
1242 */
1243 final public static function normalizeStoragePath( $storagePath ) {
1244 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1245 if ( $relPath !== null ) { // must be for this backend
1246 $relPath = self::normalizeContainerPath( $relPath );
1247 if ( $relPath !== null ) {
1248 return ( $relPath != '' )
1249 ? "mwstore://{$backend}/{$container}/{$relPath}"
1250 : "mwstore://{$backend}/{$container}";
1251 }
1252 }
1253 return null;
1254 }
1255
1256 /**
1257 * Get the parent storage directory of a storage path.
1258 * This returns a path like "mwstore://backend/container",
1259 * "mwstore://backend/container/...", or null if there is no parent.
1260 *
1261 * @param $storagePath string
1262 * @return string|null
1263 */
1264 final public static function parentStoragePath( $storagePath ) {
1265 $storagePath = dirname( $storagePath );
1266 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
1267 return ( $rel === null ) ? null : $storagePath;
1268 }
1269
1270 /**
1271 * Get the final extension from a storage or FS path
1272 *
1273 * @param $path string
1274 * @return string
1275 */
1276 final public static function extensionFromPath( $path ) {
1277 $i = strrpos( $path, '.' );
1278 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1279 }
1280
1281 /**
1282 * Check if a relative path has no directory traversals
1283 *
1284 * @param $path string
1285 * @return bool
1286 * @since 1.20
1287 */
1288 final public static function isPathTraversalFree( $path ) {
1289 return ( self::normalizeContainerPath( $path ) !== null );
1290 }
1291
1292 /**
1293 * Build a Content-Disposition header value per RFC 6266.
1294 *
1295 * @param $type string One of (attachment, inline)
1296 * @param $filename string Suggested file name (should not contain slashes)
1297 * @throws MWException
1298 * @return string
1299 * @since 1.20
1300 */
1301 final public static function makeContentDisposition( $type, $filename = '' ) {
1302 $parts = array();
1303
1304 $type = strtolower( $type );
1305 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1306 throw new MWException( "Invalid Content-Disposition type '$type'." );
1307 }
1308 $parts[] = $type;
1309
1310 if ( strlen( $filename ) ) {
1311 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1312 }
1313
1314 return implode( ';', $parts );
1315 }
1316
1317 /**
1318 * Validate and normalize a relative storage path.
1319 * Null is returned if the path involves directory traversal.
1320 * Traversal is insecure for FS backends and broken for others.
1321 *
1322 * This uses the same traversal protection as Title::secureAndSplit().
1323 *
1324 * @param $path string Storage path relative to a container
1325 * @return string|null
1326 */
1327 final protected static function normalizeContainerPath( $path ) {
1328 // Normalize directory separators
1329 $path = strtr( $path, '\\', '/' );
1330 // Collapse any consecutive directory separators
1331 $path = preg_replace( '![/]{2,}!', '/', $path );
1332 // Remove any leading directory separator
1333 $path = ltrim( $path, '/' );
1334 // Use the same traversal protection as Title::secureAndSplit()
1335 if ( strpos( $path, '.' ) !== false ) {
1336 if (
1337 $path === '.' ||
1338 $path === '..' ||
1339 strpos( $path, './' ) === 0 ||
1340 strpos( $path, '../' ) === 0 ||
1341 strpos( $path, '/./' ) !== false ||
1342 strpos( $path, '/../' ) !== false
1343 ) {
1344 return null;
1345 }
1346 }
1347 return $path;
1348 }
1349 }