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