Merge "No need to call parseTitle() directly in MediaWiki::__construct()."
[lhc/web/wiklou.git] / includes / filerepo / backend / 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 * - nonJournaled : Don't log this operation batch in the file journal.
246 * This limits the ability of recovery scripts.
247 * - parallelize : Try to do operations in parallel when possible.
248 * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
249 *
250 * @remarks Remarks on locking:
251 * File system paths given to operations should refer to files that are
252 * already locked or otherwise safe from modification from other processes.
253 * Normally these files will be new temp files, which should be adequate.
254 *
255 * @par Return value:
256 *
257 * This returns a Status, which contains all warnings and fatals that occured
258 * during the operation. The 'failCount', 'successCount', and 'success' members
259 * will reflect each operation attempted.
260 *
261 * The status will be "OK" unless:
262 * - a) unexpected operation errors occurred (network partitions, disk full...)
263 * - b) significant operation errors occured and 'force' was not set
264 *
265 * @param $ops Array List of operations to execute in order
266 * @param $opts Array Batch operation options
267 * @return Status
268 */
269 final public function doOperations( array $ops, array $opts = array() ) {
270 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
271 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
272 }
273 if ( empty( $opts['force'] ) ) { // sanity
274 unset( $opts['nonLocking'] );
275 unset( $opts['allowStale'] );
276 }
277 $opts['concurrency'] = 1; // off
278 if ( $this->parallelize === 'implicit' ) {
279 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
280 $opts['concurrency'] = $this->concurrency;
281 }
282 } elseif ( $this->parallelize === 'explicit' ) {
283 if ( !empty( $opts['parallelize'] ) ) {
284 $opts['concurrency'] = $this->concurrency;
285 }
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 * )
402 * @endcode
403 * b) Copy a file system file into storage
404 * @code
405 * array(
406 * 'op' => 'store',
407 * 'src' => <file system path>,
408 * 'dst' => <storage path>
409 * )
410 * @endcode
411 * c) Copy a file within storage
412 * @code
413 * array(
414 * 'op' => 'copy',
415 * 'src' => <storage path>,
416 * 'dst' => <storage path>
417 * )
418 * @endcode
419 * d) Move a file within storage
420 * @code
421 * array(
422 * 'op' => 'move',
423 * 'src' => <storage path>,
424 * 'dst' => <storage path>
425 * )
426 * @endcode
427 * e) Delete a file within storage
428 * @code
429 * array(
430 * 'op' => 'delete',
431 * 'src' => <storage path>,
432 * 'ignoreMissingSource' => <boolean>
433 * )
434 * @endcode
435 * f) Do nothing (no-op)
436 * @code
437 * array(
438 * 'op' => 'null',
439 * )
440 * @endcode
441 *
442 * @par Boolean flags for operations (operation-specific):
443 * - ignoreMissingSource : The operation will simply succeed and do
444 * nothing if the source file does not exist.
445 *
446 * $opts is an associative of boolean flags, including:
447 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
448 *
449 * @par Return value:
450 * This returns a Status, which contains all warnings and fatals that occured
451 * during the operation. The 'failCount', 'successCount', and 'success' members
452 * will reflect each operation attempted for the given files. The status will be
453 * considered "OK" as long as no fatal errors occured.
454 *
455 * @param $ops Array Set of operations to execute
456 * @param $opts Array Batch operation options
457 * @return Status
458 * @since 1.20
459 */
460 final public function doQuickOperations( array $ops, array $opts = array() ) {
461 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
462 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
463 }
464 foreach ( $ops as &$op ) {
465 $op['overwrite'] = true; // avoids RTTs in key/value stores
466 }
467 return $this->doQuickOperationsInternal( $ops );
468 }
469
470 /**
471 * @see FileBackend::doQuickOperations()
472 * @since 1.20
473 */
474 abstract protected function doQuickOperationsInternal( array $ops );
475
476 /**
477 * Same as doQuickOperations() except it takes a single operation.
478 * If you are doing a batch of operations, then use that function instead.
479 *
480 * @see FileBackend::doQuickOperations()
481 *
482 * @param $op Array Operation
483 * @return Status
484 * @since 1.20
485 */
486 final public function doQuickOperation( array $op ) {
487 return $this->doQuickOperations( array( $op ) );
488 }
489
490 /**
491 * Performs a single quick create operation.
492 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
493 *
494 * @see FileBackend::doQuickOperation()
495 *
496 * @param $params Array Operation parameters
497 * @return Status
498 * @since 1.20
499 */
500 final public function quickCreate( array $params ) {
501 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
502 }
503
504 /**
505 * Performs a single quick store operation.
506 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
507 *
508 * @see FileBackend::doQuickOperation()
509 *
510 * @param $params Array Operation parameters
511 * @return Status
512 * @since 1.20
513 */
514 final public function quickStore( array $params ) {
515 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
516 }
517
518 /**
519 * Performs a single quick copy operation.
520 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
521 *
522 * @see FileBackend::doQuickOperation()
523 *
524 * @param $params Array Operation parameters
525 * @return Status
526 * @since 1.20
527 */
528 final public function quickCopy( array $params ) {
529 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
530 }
531
532 /**
533 * Performs a single quick move operation.
534 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
535 *
536 * @see FileBackend::doQuickOperation()
537 *
538 * @param $params Array Operation parameters
539 * @return Status
540 * @since 1.20
541 */
542 final public function quickMove( array $params ) {
543 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
544 }
545
546 /**
547 * Performs a single quick delete operation.
548 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
549 *
550 * @see FileBackend::doQuickOperation()
551 *
552 * @param $params Array Operation parameters
553 * @return Status
554 * @since 1.20
555 */
556 final public function quickDelete( array $params ) {
557 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
558 }
559
560 /**
561 * Concatenate a list of storage files into a single file system file.
562 * The target path should refer to a file that is already locked or
563 * otherwise safe from modification from other processes. Normally,
564 * the file will be a new temp file, which should be adequate.
565 *
566 * @param $params Array Operation parameters
567 * $params include:
568 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
569 * - dst : file system path to 0-byte temp file
570 * @return Status
571 */
572 abstract public function concatenate( array $params );
573
574 /**
575 * Prepare a storage directory for usage.
576 * This will create any required containers and parent directories.
577 * Backends using key/value stores only need to create the container.
578 *
579 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
580 * except they are only applied *if* the directory/container had to be created.
581 * These flags should always be set for directories that have private files.
582 *
583 * @param $params Array
584 * $params include:
585 * - dir : storage directory
586 * - noAccess : try to deny file access (since 1.20)
587 * - noListing : try to deny file listing (since 1.20)
588 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
589 * @return Status
590 */
591 final public function prepare( array $params ) {
592 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
593 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
594 }
595 return $this->doPrepare( $params );
596 }
597
598 /**
599 * @see FileBackend::prepare()
600 */
601 abstract protected function doPrepare( array $params );
602
603 /**
604 * Take measures to block web access to a storage directory and
605 * the container it belongs to. FS backends might add .htaccess
606 * files whereas key/value store backends might revoke container
607 * access to the storage user representing end-users in web requests.
608 * This is not guaranteed to actually do anything.
609 *
610 * @param $params Array
611 * $params include:
612 * - dir : storage directory
613 * - noAccess : try to deny file access
614 * - noListing : try to deny file listing
615 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
616 * @return Status
617 */
618 final public function secure( array $params ) {
619 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
620 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
621 }
622 return $this->doSecure( $params );
623 }
624
625 /**
626 * @see FileBackend::secure()
627 */
628 abstract protected function doSecure( array $params );
629
630 /**
631 * Remove measures to block web access to a storage directory and
632 * the container it belongs to. FS backends might remove .htaccess
633 * files whereas key/value store backends might grant container
634 * access to the storage user representing end-users in web requests.
635 * This essentially can undo the result of secure() calls.
636 *
637 * @param $params Array
638 * $params include:
639 * - dir : storage directory
640 * - access : try to allow file access
641 * - listing : try to allow file listing
642 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
643 * @return Status
644 * @since 1.20
645 */
646 final public function publish( array $params ) {
647 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
648 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
649 }
650 return $this->doPublish( $params );
651 }
652
653 /**
654 * @see FileBackend::publish()
655 */
656 abstract protected function doPublish( array $params );
657
658 /**
659 * Delete a storage directory if it is empty.
660 * Backends using key/value stores may do nothing unless the directory
661 * is that of an empty container, in which case it should be deleted.
662 *
663 * @param $params Array
664 * $params include:
665 * - dir : storage directory
666 * - recursive : recursively delete empty subdirectories first (since 1.20)
667 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
668 * @return Status
669 */
670 final public function clean( array $params ) {
671 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
672 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
673 }
674 return $this->doClean( $params );
675 }
676
677 /**
678 * @see FileBackend::clean()
679 */
680 abstract protected function doClean( array $params );
681
682 /**
683 * Check if a file exists at a storage path in the backend.
684 * This returns false if only a directory exists at the path.
685 *
686 * @param $params Array
687 * $params include:
688 * - src : source storage path
689 * - latest : use the latest available data
690 * @return bool|null Returns null on failure
691 */
692 abstract public function fileExists( array $params );
693
694 /**
695 * Get the last-modified timestamp of the file at a storage path.
696 *
697 * @param $params Array
698 * $params include:
699 * - src : source storage path
700 * - latest : use the latest available data
701 * @return string|bool TS_MW timestamp or false on failure
702 */
703 abstract public function getFileTimestamp( array $params );
704
705 /**
706 * Get the contents of a file at a storage path in the backend.
707 * This should be avoided for potentially large files.
708 *
709 * @param $params Array
710 * $params include:
711 * - src : source storage path
712 * - latest : use the latest available data
713 * @return string|bool Returns false on failure
714 */
715 abstract public function getFileContents( array $params );
716
717 /**
718 * Get the size (bytes) of a file at a storage path in the backend.
719 *
720 * @param $params Array
721 * $params include:
722 * - src : source storage path
723 * - latest : use the latest available data
724 * @return integer|bool Returns false on failure
725 */
726 abstract public function getFileSize( array $params );
727
728 /**
729 * Get quick information about a file at a storage path in the backend.
730 * If the file does not exist, then this returns false.
731 * Otherwise, the result is an associative array that includes:
732 * - mtime : the last-modified timestamp (TS_MW)
733 * - size : the file size (bytes)
734 * Additional values may be included for internal use only.
735 *
736 * @param $params Array
737 * $params include:
738 * - src : source storage path
739 * - latest : use the latest available data
740 * @return Array|bool|null Returns null on failure
741 */
742 abstract public function getFileStat( array $params );
743
744 /**
745 * Get a SHA-1 hash of the file at a storage path in the backend.
746 *
747 * @param $params Array
748 * $params include:
749 * - src : source storage path
750 * - latest : use the latest available data
751 * @return string|bool Hash string or false on failure
752 */
753 abstract public function getFileSha1Base36( array $params );
754
755 /**
756 * Get the properties of the file at a storage path in the backend.
757 * Returns FSFile::placeholderProps() on failure.
758 *
759 * @param $params Array
760 * $params include:
761 * - src : source storage path
762 * - latest : use the latest available data
763 * @return Array
764 */
765 abstract public function getFileProps( array $params );
766
767 /**
768 * Stream the file at a storage path in the backend.
769 * If the file does not exists, a 404 error will be given.
770 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
771 * must be sent if streaming began, while none should be sent otherwise.
772 * Implementations should flush the output buffer before sending data.
773 *
774 * @param $params Array
775 * $params include:
776 * - src : source storage path
777 * - headers : additional HTTP headers to send on success
778 * - latest : use the latest available data
779 * @return Status
780 */
781 abstract public function streamFile( array $params );
782
783 /**
784 * Returns a file system file, identical to the file at a storage path.
785 * The file returned is either:
786 * - a) A local copy of the file at a storage path in the backend.
787 * The temporary copy will have the same extension as the source.
788 * - b) An original of the file at a storage path in the backend.
789 * Temporary files may be purged when the file object falls out of scope.
790 *
791 * Write operations should *never* be done on this file as some backends
792 * may do internal tracking or may be instances of FileBackendMultiWrite.
793 * In that later case, there are copies of the file that must stay in sync.
794 * Additionally, further calls to this function may return the same file.
795 *
796 * @param $params Array
797 * $params include:
798 * - src : source storage path
799 * - latest : use the latest available data
800 * @return FSFile|null Returns null on failure
801 */
802 abstract public function getLocalReference( array $params );
803
804 /**
805 * Get a local copy on disk of the file at a storage path in the backend.
806 * The temporary copy will have the same file extension as the source.
807 * Temporary files may be purged when the file object falls out of scope.
808 *
809 * @param $params Array
810 * $params include:
811 * - src : source storage path
812 * - latest : use the latest available data
813 * @return TempFSFile|null Returns null on failure
814 */
815 abstract public function getLocalCopy( array $params );
816
817 /**
818 * Check if a directory exists at a given storage path.
819 * Backends using key/value stores will check if the path is a
820 * virtual directory, meaning there are files under the given directory.
821 *
822 * Storage backends with eventual consistency might return stale data.
823 *
824 * @param $params array
825 * $params include:
826 * - dir : storage directory
827 * @return bool|null Returns null on failure
828 * @since 1.20
829 */
830 abstract public function directoryExists( array $params );
831
832 /**
833 * Get an iterator to list *all* directories under a storage directory.
834 * If the directory is of the form "mwstore://backend/container",
835 * then all directories in the container should be listed.
836 * If the directory is of form "mwstore://backend/container/dir",
837 * then all directories directly under that directory should be listed.
838 * Results should be storage directories relative to the given directory.
839 *
840 * Storage backends with eventual consistency might return stale data.
841 *
842 * @param $params array
843 * $params include:
844 * - dir : storage directory
845 * - topOnly : only return direct child dirs of the directory
846 * @return Traversable|Array|null Returns null on failure
847 * @since 1.20
848 */
849 abstract public function getDirectoryList( array $params );
850
851 /**
852 * Same as FileBackend::getDirectoryList() except only lists
853 * directories that are immediately under the given directory.
854 *
855 * Storage backends with eventual consistency might return stale data.
856 *
857 * @param $params array
858 * $params include:
859 * - dir : storage directory
860 * @return Traversable|Array|null Returns null on failure
861 * @since 1.20
862 */
863 final public function getTopDirectoryList( array $params ) {
864 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
865 }
866
867 /**
868 * Get an iterator to list *all* stored files under a storage directory.
869 * If the directory is of the form "mwstore://backend/container",
870 * then all files in the container should be listed.
871 * If the directory is of form "mwstore://backend/container/dir",
872 * then all files under that directory should be listed.
873 * Results should be storage paths relative to the given directory.
874 *
875 * Storage backends with eventual consistency might return stale data.
876 *
877 * @param $params array
878 * $params include:
879 * - dir : storage directory
880 * - topOnly : only return direct child files of the directory (since 1.20)
881 * @return Traversable|Array|null Returns null on failure
882 */
883 abstract public function getFileList( array $params );
884
885 /**
886 * Same as FileBackend::getFileList() except only lists
887 * files that are immediately under the given directory.
888 *
889 * Storage backends with eventual consistency might return stale data.
890 *
891 * @param $params array
892 * $params include:
893 * - dir : storage directory
894 * @return Traversable|Array|null Returns null on failure
895 * @since 1.20
896 */
897 final public function getTopFileList( array $params ) {
898 return $this->getFileList( array( 'topOnly' => true ) + $params );
899 }
900
901 /**
902 * Invalidate any in-process file existence and property cache.
903 * If $paths is given, then only the cache for those files will be cleared.
904 *
905 * @param $paths Array Storage paths (optional)
906 * @return void
907 */
908 public function clearCache( array $paths = null ) {}
909
910 /**
911 * Lock the files at the given storage paths in the backend.
912 * This will either lock all the files or none (on failure).
913 *
914 * Callers should consider using getScopedFileLocks() instead.
915 *
916 * @param $paths Array Storage paths
917 * @param $type integer LockManager::LOCK_* constant
918 * @return Status
919 */
920 final public function lockFiles( array $paths, $type ) {
921 return $this->lockManager->lock( $paths, $type );
922 }
923
924 /**
925 * Unlock the files at the given storage paths in the backend.
926 *
927 * @param $paths Array Storage paths
928 * @param $type integer LockManager::LOCK_* constant
929 * @return Status
930 */
931 final public function unlockFiles( array $paths, $type ) {
932 return $this->lockManager->unlock( $paths, $type );
933 }
934
935 /**
936 * Lock the files at the given storage paths in the backend.
937 * This will either lock all the files or none (on failure).
938 * On failure, the status object will be updated with errors.
939 *
940 * Once the return value goes out scope, the locks will be released and
941 * the status updated. Unlock fatals will not change the status "OK" value.
942 *
943 * @param $paths Array Storage paths
944 * @param $type integer LockManager::LOCK_* constant
945 * @param $status Status Status to update on lock/unlock
946 * @return ScopedLock|null Returns null on failure
947 */
948 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
949 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
950 }
951
952 /**
953 * Get an array of scoped locks needed for a batch of file operations.
954 *
955 * Normally, FileBackend::doOperations() handles locking, unless
956 * the 'nonLocking' param is passed in. This function is useful if you
957 * want the files to be locked for a broader scope than just when the
958 * files are changing. For example, if you need to update DB metadata,
959 * you may want to keep the files locked until finished.
960 *
961 * @see FileBackend::doOperations()
962 *
963 * @param $ops Array List of file operations to FileBackend::doOperations()
964 * @param $status Status Status to update on lock/unlock
965 * @return Array List of ScopedFileLocks or null values
966 * @since 1.20
967 */
968 abstract public function getScopedLocksForOps( array $ops, Status $status );
969
970 /**
971 * Get the root storage path of this backend.
972 * All container paths are "subdirectories" of this path.
973 *
974 * @return string Storage path
975 * @since 1.20
976 */
977 final public function getRootStoragePath() {
978 return "mwstore://{$this->name}";
979 }
980
981 /**
982 * Get the file journal object for this backend
983 *
984 * @return FileJournal
985 */
986 final public function getJournal() {
987 return $this->fileJournal;
988 }
989
990 /**
991 * Check if a given path is a "mwstore://" path.
992 * This does not do any further validation or any existence checks.
993 *
994 * @param $path string
995 * @return bool
996 */
997 final public static function isStoragePath( $path ) {
998 return ( strpos( $path, 'mwstore://' ) === 0 );
999 }
1000
1001 /**
1002 * Split a storage path into a backend name, a container name,
1003 * and a relative file path. The relative path may be the empty string.
1004 * This does not do any path normalization or traversal checks.
1005 *
1006 * @param $storagePath string
1007 * @return Array (backend, container, rel object) or (null, null, null)
1008 */
1009 final public static function splitStoragePath( $storagePath ) {
1010 if ( self::isStoragePath( $storagePath ) ) {
1011 // Remove the "mwstore://" prefix and split the path
1012 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1013 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1014 if ( count( $parts ) == 3 ) {
1015 return $parts; // e.g. "backend/container/path"
1016 } else {
1017 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1018 }
1019 }
1020 }
1021 return array( null, null, null );
1022 }
1023
1024 /**
1025 * Normalize a storage path by cleaning up directory separators.
1026 * Returns null if the path is not of the format of a valid storage path.
1027 *
1028 * @param $storagePath string
1029 * @return string|null
1030 */
1031 final public static function normalizeStoragePath( $storagePath ) {
1032 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1033 if ( $relPath !== null ) { // must be for this backend
1034 $relPath = self::normalizeContainerPath( $relPath );
1035 if ( $relPath !== null ) {
1036 return ( $relPath != '' )
1037 ? "mwstore://{$backend}/{$container}/{$relPath}"
1038 : "mwstore://{$backend}/{$container}";
1039 }
1040 }
1041 return null;
1042 }
1043
1044 /**
1045 * Get the parent storage directory of a storage path.
1046 * This returns a path like "mwstore://backend/container",
1047 * "mwstore://backend/container/...", or null if there is no parent.
1048 *
1049 * @param $storagePath string
1050 * @return string|null
1051 */
1052 final public static function parentStoragePath( $storagePath ) {
1053 $storagePath = dirname( $storagePath );
1054 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
1055 return ( $rel === null ) ? null : $storagePath;
1056 }
1057
1058 /**
1059 * Get the final extension from a storage or FS path
1060 *
1061 * @param $path string
1062 * @return string
1063 */
1064 final public static function extensionFromPath( $path ) {
1065 $i = strrpos( $path, '.' );
1066 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1067 }
1068
1069 /**
1070 * Check if a relative path has no directory traversals
1071 *
1072 * @param $path string
1073 * @return bool
1074 * @since 1.20
1075 */
1076 final public static function isPathTraversalFree( $path ) {
1077 return ( self::normalizeContainerPath( $path ) !== null );
1078 }
1079
1080 /**
1081 * Validate and normalize a relative storage path.
1082 * Null is returned if the path involves directory traversal.
1083 * Traversal is insecure for FS backends and broken for others.
1084 *
1085 * This uses the same traversal protection as Title::secureAndSplit().
1086 *
1087 * @param $path string Storage path relative to a container
1088 * @return string|null
1089 */
1090 final protected static function normalizeContainerPath( $path ) {
1091 // Normalize directory separators
1092 $path = strtr( $path, '\\', '/' );
1093 // Collapse any consecutive directory separators
1094 $path = preg_replace( '![/]{2,}!', '/', $path );
1095 // Remove any leading directory separator
1096 $path = ltrim( $path, '/' );
1097 // Use the same traversal protection as Title::secureAndSplit()
1098 if ( strpos( $path, '.' ) !== false ) {
1099 if (
1100 $path === '.' ||
1101 $path === '..' ||
1102 strpos( $path, './' ) === 0 ||
1103 strpos( $path, '../' ) === 0 ||
1104 strpos( $path, '/./' ) !== false ||
1105 strpos( $path, '/../' ) !== false
1106 ) {
1107 return null;
1108 }
1109 }
1110 return $path;
1111 }
1112 }