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