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