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