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