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