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