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