Big oops - merged to wrong branch.
[lhc/web/wiklou.git] / includes / filerepo / backend / 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) notation,
41 * though any particular backend may not actually be using a local filesystem.
42 * 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 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 ? FileJournal::factory( $config['fileJournal'], $this->name )
106 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
107 $this->readOnly = isset( $config['readOnly'] )
108 ? (string)$config['readOnly']
109 : '';
110 $this->parallelize = isset( $config['parallelize'] )
111 ? (string)$config['parallelize']
112 : 'off';
113 $this->concurrency = isset( $config['concurrency'] )
114 ? (int)$config['concurrency']
115 : 50;
116 }
117
118 /**
119 * Get the unique backend name.
120 * We may have multiple different backends of the same type.
121 * For example, we can have two Swift backends using different proxies.
122 *
123 * @return string
124 */
125 final public function getName() {
126 return $this->name;
127 }
128
129 /**
130 * Check if this backend is read-only
131 *
132 * @return bool
133 */
134 final public function isReadOnly() {
135 return ( $this->readOnly != '' );
136 }
137
138 /**
139 * Get an explanatory message if this backend is read-only
140 *
141 * @return string|bool Returns false if the backend is not read-only
142 */
143 final public function getReadOnlyReason() {
144 return ( $this->readOnly != '' ) ? $this->readOnly : false;
145 }
146
147 /**
148 * This is the main entry point into the backend for write operations.
149 * Callers supply an ordered list of operations to perform as a transaction.
150 * Files will be locked, the stat cache cleared, and then the operations attempted.
151 * If any serious errors occur, all attempted operations will be rolled back.
152 *
153 * $ops is an array of arrays. The outer array holds a list of operations.
154 * Each inner array is a set of key value pairs that specify an operation.
155 *
156 * Supported operations and their parameters:
157 * a) Create a new file in storage with the contents of a string
158 * array(
159 * 'op' => 'create',
160 * 'dst' => <storage path>,
161 * 'content' => <string of new file contents>,
162 * 'overwrite' => <boolean>,
163 * 'overwriteSame' => <boolean>
164 * )
165 * b) Copy a file system file into storage
166 * array(
167 * 'op' => 'store',
168 * 'src' => <file system path>,
169 * 'dst' => <storage path>,
170 * 'overwrite' => <boolean>,
171 * 'overwriteSame' => <boolean>
172 * )
173 * c) Copy a file within storage
174 * array(
175 * 'op' => 'copy',
176 * 'src' => <storage path>,
177 * 'dst' => <storage path>,
178 * 'overwrite' => <boolean>,
179 * 'overwriteSame' => <boolean>
180 * )
181 * d) Move a file within storage
182 * array(
183 * 'op' => 'move',
184 * 'src' => <storage path>,
185 * 'dst' => <storage path>,
186 * 'overwrite' => <boolean>,
187 * 'overwriteSame' => <boolean>
188 * )
189 * e) Delete a file within storage
190 * array(
191 * 'op' => 'delete',
192 * 'src' => <storage path>,
193 * 'ignoreMissingSource' => <boolean>
194 * )
195 * f) Do nothing (no-op)
196 * array(
197 * 'op' => 'null',
198 * )
199 *
200 * Boolean flags for operations (operation-specific):
201 * 'ignoreMissingSource' : The operation will simply succeed and do
202 * nothing if the source file does not exist.
203 * 'overwrite' : Any destination file will be overwritten.
204 * 'overwriteSame' : An error will not be given if a file already
205 * exists at the destination that has the same
206 * contents as the new contents to be written there.
207 *
208 * $opts is an associative of boolean flags, including:
209 * 'force' : Operation precondition errors no longer trigger an abort.
210 * Any remaining operations are still attempted. Unexpected
211 * failures may still cause remaning operations to be aborted.
212 * 'nonLocking' : No locks are acquired for the operations.
213 * This can increase performance for non-critical writes.
214 * This has no effect unless the 'force' flag is set.
215 * 'allowStale' : Don't require the latest available data.
216 * This can increase performance for non-critical writes.
217 * This has no effect unless the 'force' flag is set.
218 * 'nonJournaled' : Don't log this operation batch in the file journal.
219 * This limits the ability of recovery scripts.
220 * 'parallelize' : Try to do operations in parallel when possible.
221 *
222 * Remarks on locking:
223 * File system paths given to operations should refer to files that are
224 * already locked or otherwise safe from modification from other processes.
225 * Normally these files will be new temp files, which should be adequate.
226 *
227 * Return value:
228 * This returns a Status, which contains all warnings and fatals that occured
229 * during the operation. The 'failCount', 'successCount', and 'success' members
230 * will reflect each operation attempted. The status will be "OK" unless:
231 * a) unexpected operation errors occurred (network partitions, disk full...)
232 * b) significant operation errors occured and 'force' was not set
233 *
234 * @param $ops Array List of operations to execute in order
235 * @param $opts Array Batch operation options
236 * @return Status
237 */
238 final public function doOperations( array $ops, array $opts = array() ) {
239 if ( $this->isReadOnly() ) {
240 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
241 }
242 if ( empty( $opts['force'] ) ) { // sanity
243 unset( $opts['nonLocking'] );
244 unset( $opts['allowStale'] );
245 }
246 $opts['concurrency'] = 1; // off
247 if ( $this->parallelize === 'implicit' ) {
248 if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
249 $opts['concurrency'] = $this->concurrency;
250 }
251 } elseif ( $this->parallelize === 'explicit' ) {
252 if ( !empty( $opts['parallelize'] ) ) {
253 $opts['concurrency'] = $this->concurrency;
254 }
255 }
256 return $this->doOperationsInternal( $ops, $opts );
257 }
258
259 /**
260 * @see FileBackend::doOperations()
261 */
262 abstract protected function doOperationsInternal( array $ops, array $opts );
263
264 /**
265 * Same as doOperations() except it takes a single operation.
266 * If you are doing a batch of operations that should either
267 * all succeed or all fail, then use that function instead.
268 *
269 * @see FileBackend::doOperations()
270 *
271 * @param $op Array Operation
272 * @param $opts Array Operation options
273 * @return Status
274 */
275 final public function doOperation( array $op, array $opts = array() ) {
276 return $this->doOperations( array( $op ), $opts );
277 }
278
279 /**
280 * Performs a single create operation.
281 * This sets $params['op'] to 'create' and passes it to doOperation().
282 *
283 * @see FileBackend::doOperation()
284 *
285 * @param $params Array Operation parameters
286 * @param $opts Array Operation options
287 * @return Status
288 */
289 final public function create( array $params, array $opts = array() ) {
290 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
291 }
292
293 /**
294 * Performs a single store operation.
295 * This sets $params['op'] to 'store' and passes it to doOperation().
296 *
297 * @see FileBackend::doOperation()
298 *
299 * @param $params Array Operation parameters
300 * @param $opts Array Operation options
301 * @return Status
302 */
303 final public function store( array $params, array $opts = array() ) {
304 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
305 }
306
307 /**
308 * Performs a single copy operation.
309 * This sets $params['op'] to 'copy' and passes it to doOperation().
310 *
311 * @see FileBackend::doOperation()
312 *
313 * @param $params Array Operation parameters
314 * @param $opts Array Operation options
315 * @return Status
316 */
317 final public function copy( array $params, array $opts = array() ) {
318 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
319 }
320
321 /**
322 * Performs a single move operation.
323 * This sets $params['op'] to 'move' and passes it to doOperation().
324 *
325 * @see FileBackend::doOperation()
326 *
327 * @param $params Array Operation parameters
328 * @param $opts Array Operation options
329 * @return Status
330 */
331 final public function move( array $params, array $opts = array() ) {
332 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
333 }
334
335 /**
336 * Performs a single delete operation.
337 * This sets $params['op'] to 'delete' and passes it to doOperation().
338 *
339 * @see FileBackend::doOperation()
340 *
341 * @param $params Array Operation parameters
342 * @param $opts Array Operation options
343 * @return Status
344 */
345 final public function delete( array $params, array $opts = array() ) {
346 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
347 }
348
349 /**
350 * Perform a set of independent file operations on some files.
351 *
352 * This does no locking, nor journaling, and possibly no stat calls.
353 * Any destination files that already exist will be overwritten.
354 * This should *only* be used on non-original files, like cache files.
355 *
356 * Supported operations and their parameters:
357 * a) Create a new file in storage with the contents of a string
358 * array(
359 * 'op' => 'create',
360 * 'dst' => <storage path>,
361 * 'content' => <string of new file contents>
362 * )
363 * b) Copy a file system file into storage
364 * array(
365 * 'op' => 'store',
366 * 'src' => <file system path>,
367 * 'dst' => <storage path>
368 * )
369 * c) Copy a file within storage
370 * array(
371 * 'op' => 'copy',
372 * 'src' => <storage path>,
373 * 'dst' => <storage path>
374 * )
375 * d) Move a file within storage
376 * array(
377 * 'op' => 'move',
378 * 'src' => <storage path>,
379 * 'dst' => <storage path>
380 * )
381 * e) Delete a file within storage
382 * array(
383 * 'op' => 'delete',
384 * 'src' => <storage path>,
385 * 'ignoreMissingSource' => <boolean>
386 * )
387 * f) Do nothing (no-op)
388 * array(
389 * 'op' => 'null',
390 * )
391 *
392 * Boolean flags for operations (operation-specific):
393 * 'ignoreMissingSource' : The operation will simply succeed and do
394 * nothing if the source file does not exist.
395 *
396 * Return value:
397 * This returns a Status, which contains all warnings and fatals that occured
398 * during the operation. The 'failCount', 'successCount', and 'success' members
399 * will reflect each operation attempted for the given files. The status will be
400 * considered "OK" as long as no fatal errors occured.
401 *
402 * @param $ops Array Set of operations to execute
403 * @return Status
404 * @since 1.20
405 */
406 final public function doQuickOperations( array $ops ) {
407 if ( $this->isReadOnly() ) {
408 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
409 }
410 foreach ( $ops as &$op ) {
411 $op['overwrite'] = true; // avoids RTTs in key/value stores
412 }
413 return $this->doQuickOperationsInternal( $ops );
414 }
415
416 /**
417 * @see FileBackend::doQuickOperations()
418 * @since 1.20
419 */
420 abstract protected function doQuickOperationsInternal( array $ops );
421
422 /**
423 * Same as doQuickOperations() except it takes a single operation.
424 * If you are doing a batch of operations, then use that function instead.
425 *
426 * @see FileBackend::doQuickOperations()
427 *
428 * @param $op Array Operation
429 * @return Status
430 * @since 1.20
431 */
432 final public function doQuickOperation( array $op ) {
433 return $this->doQuickOperations( array( $op ) );
434 }
435
436 /**
437 * Performs a single quick create operation.
438 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
439 *
440 * @see FileBackend::doQuickOperation()
441 *
442 * @param $params Array Operation parameters
443 * @return Status
444 * @since 1.20
445 */
446 final public function quickCreate( array $params ) {
447 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
448 }
449
450 /**
451 * Performs a single quick store operation.
452 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
453 *
454 * @see FileBackend::doQuickOperation()
455 *
456 * @param $params Array Operation parameters
457 * @return Status
458 * @since 1.20
459 */
460 final public function quickStore( array $params ) {
461 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
462 }
463
464 /**
465 * Performs a single quick copy operation.
466 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
467 *
468 * @see FileBackend::doQuickOperation()
469 *
470 * @param $params Array Operation parameters
471 * @return Status
472 * @since 1.20
473 */
474 final public function quickCopy( array $params ) {
475 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
476 }
477
478 /**
479 * Performs a single quick move operation.
480 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
481 *
482 * @see FileBackend::doQuickOperation()
483 *
484 * @param $params Array Operation parameters
485 * @return Status
486 * @since 1.20
487 */
488 final public function quickMove( array $params ) {
489 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
490 }
491
492 /**
493 * Performs a single quick delete operation.
494 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
495 *
496 * @see FileBackend::doQuickOperation()
497 *
498 * @param $params Array Operation parameters
499 * @return Status
500 * @since 1.20
501 */
502 final public function quickDelete( array $params ) {
503 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
504 }
505
506 /**
507 * Concatenate a list of storage files into a single file system file.
508 * The target path should refer to a file that is already locked or
509 * otherwise safe from modification from other processes. Normally,
510 * the file will be a new temp file, which should be adequate.
511 * $params include:
512 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
513 * dst : file system path to 0-byte temp file
514 *
515 * @param $params Array Operation parameters
516 * @return Status
517 */
518 abstract public function concatenate( array $params );
519
520 /**
521 * Prepare a storage directory for usage.
522 * This will create any required containers and parent directories.
523 * Backends using key/value stores only need to create the container.
524 *
525 * $params include:
526 * dir : storage directory
527 *
528 * @param $params Array
529 * @return Status
530 */
531 final public function prepare( array $params ) {
532 if ( $this->isReadOnly() ) {
533 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
534 }
535 return $this->doPrepare( $params );
536 }
537
538 /**
539 * @see FileBackend::prepare()
540 */
541 abstract protected function doPrepare( array $params );
542
543 /**
544 * Take measures to block web access to a storage directory and
545 * the container it belongs to. FS backends might add .htaccess
546 * files whereas key/value store backends might restrict container
547 * access to the auth user that represents end-users in web request.
548 * This is not guaranteed to actually do anything.
549 *
550 * $params include:
551 * dir : storage directory
552 * noAccess : try to deny file access
553 * noListing : try to deny file listing
554 *
555 * @param $params Array
556 * @return Status
557 */
558 final public function secure( array $params ) {
559 if ( $this->isReadOnly() ) {
560 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
561 }
562 $status = $this->doPrepare( $params ); // dir must exist to restrict it
563 if ( $status->isOK() ) {
564 $status->merge( $this->doSecure( $params ) );
565 }
566 return $status;
567 }
568
569 /**
570 * @see FileBackend::secure()
571 */
572 abstract protected function doSecure( array $params );
573
574 /**
575 * Delete a storage directory if it is empty.
576 * Backends using key/value stores may do nothing unless the directory
577 * is that of an empty container, in which case it should be deleted.
578 *
579 * $params include:
580 * dir : storage directory
581 * recursive : recursively delete empty subdirectories first (@since 1.20)
582 *
583 * @param $params Array
584 * @return Status
585 */
586 final public function clean( array $params ) {
587 if ( $this->isReadOnly() ) {
588 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
589 }
590 return $this->doClean( $params );
591 }
592
593 /**
594 * @see FileBackend::clean()
595 */
596 abstract protected function doClean( array $params );
597
598 /**
599 * Check if a file exists at a storage path in the backend.
600 * This returns false if only a directory exists at the path.
601 *
602 * $params include:
603 * src : source storage path
604 * latest : use the latest available data
605 *
606 * @param $params Array
607 * @return bool|null Returns null on failure
608 */
609 abstract public function fileExists( array $params );
610
611 /**
612 * Get the last-modified timestamp of the file at a storage path.
613 *
614 * $params include:
615 * src : source storage path
616 * latest : use the latest available data
617 *
618 * @param $params Array
619 * @return string|bool TS_MW timestamp or false on failure
620 */
621 abstract public function getFileTimestamp( array $params );
622
623 /**
624 * Get the contents of a file at a storage path in the backend.
625 * This should be avoided for potentially large files.
626 *
627 * $params include:
628 * src : source storage path
629 * latest : use the latest available data
630 *
631 * @param $params Array
632 * @return string|bool Returns false on failure
633 */
634 abstract public function getFileContents( array $params );
635
636 /**
637 * Get the size (bytes) of a file at a storage path in the backend.
638 *
639 * $params include:
640 * src : source storage path
641 * latest : use the latest available data
642 *
643 * @param $params Array
644 * @return integer|bool Returns false on failure
645 */
646 abstract public function getFileSize( array $params );
647
648 /**
649 * Get quick information about a file at a storage path in the backend.
650 * If the file does not exist, then this returns false.
651 * Otherwise, the result is an associative array that includes:
652 * mtime : the last-modified timestamp (TS_MW)
653 * size : the file size (bytes)
654 * Additional values may be included for internal use only.
655 *
656 * $params include:
657 * src : source storage path
658 * latest : use the latest available data
659 *
660 * @param $params Array
661 * @return Array|bool|null Returns null on failure
662 */
663 abstract public function getFileStat( array $params );
664
665 /**
666 * Get a SHA-1 hash of the file at a storage path in the backend.
667 *
668 * $params include:
669 * src : source storage path
670 * latest : use the latest available data
671 *
672 * @param $params Array
673 * @return string|bool Hash string or false on failure
674 */
675 abstract public function getFileSha1Base36( array $params );
676
677 /**
678 * Get the properties of the file at a storage path in the backend.
679 * Returns FSFile::placeholderProps() on failure.
680 *
681 * $params include:
682 * src : source storage path
683 * latest : use the latest available data
684 *
685 * @param $params Array
686 * @return Array
687 */
688 abstract public function getFileProps( array $params );
689
690 /**
691 * Stream the file at a storage path in the backend.
692 * If the file does not exists, a 404 error will be given.
693 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
694 * must be sent if streaming began, while none should be sent otherwise.
695 * Implementations should flush the output buffer before sending data.
696 *
697 * $params include:
698 * src : source storage path
699 * headers : additional HTTP headers to send on success
700 * latest : use the latest available data
701 *
702 * @param $params Array
703 * @return Status
704 */
705 abstract public function streamFile( array $params );
706
707 /**
708 * Returns a file system file, identical to the file at a storage path.
709 * The file returned is either:
710 * a) A local copy of the file at a storage path in the backend.
711 * The temporary copy will have the same extension as the source.
712 * b) An original of the file at a storage path in the backend.
713 * Temporary files may be purged when the file object falls out of scope.
714 *
715 * Write operations should *never* be done on this file as some backends
716 * may do internal tracking or may be instances of FileBackendMultiWrite.
717 * In that later case, there are copies of the file that must stay in sync.
718 * Additionally, further calls to this function may return the same file.
719 *
720 * $params include:
721 * src : source storage path
722 * latest : use the latest available data
723 *
724 * @param $params Array
725 * @return FSFile|null Returns null on failure
726 */
727 abstract public function getLocalReference( array $params );
728
729 /**
730 * Get a local copy on disk of the file at a storage path in the backend.
731 * The temporary copy will have the same file extension as the source.
732 * Temporary files may be purged when the file object falls out of scope.
733 *
734 * $params include:
735 * src : source storage path
736 * latest : use the latest available data
737 *
738 * @param $params Array
739 * @return TempFSFile|null Returns null on failure
740 */
741 abstract public function getLocalCopy( array $params );
742
743 /**
744 * Check if a directory exists at a given storage path.
745 * Backends using key/value stores will check if the path is a
746 * virtual directory, meaning there are files under the given directory.
747 *
748 * Storage backends with eventual consistency might return stale data.
749 *
750 * $params include:
751 * dir : storage directory
752 *
753 * @param $params array
754 * @return bool|null Returns null on failure
755 * @since 1.20
756 */
757 abstract public function directoryExists( array $params );
758
759 /**
760 * Get an iterator to list *all* directories under a storage directory.
761 * If the directory is of the form "mwstore://backend/container",
762 * then all directories in the container should be listed.
763 * If the directory is of form "mwstore://backend/container/dir",
764 * then all directories directly under that directory should be listed.
765 * Results should be storage directories relative to the given directory.
766 *
767 * Storage backends with eventual consistency might return stale data.
768 *
769 * $params include:
770 * dir : storage directory
771 * topOnly : only return direct child dirs of the directory
772 *
773 * @param $params array
774 * @return Traversable|Array|null Returns null on failure
775 * @since 1.20
776 */
777 abstract public function getDirectoryList( array $params );
778
779 /**
780 * Same as FileBackend::getDirectoryList() except only lists
781 * directories that are immediately under the given directory.
782 *
783 * Storage backends with eventual consistency might return stale data.
784 *
785 * $params include:
786 * dir : storage directory
787 *
788 * @param $params array
789 * @return Traversable|Array|null Returns null on failure
790 * @since 1.20
791 */
792 final public function getTopDirectoryList( array $params ) {
793 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
794 }
795
796 /**
797 * Get an iterator to list *all* stored files under a storage directory.
798 * If the directory is of the form "mwstore://backend/container",
799 * then all files in the container should be listed.
800 * If the directory is of form "mwstore://backend/container/dir",
801 * then all files under that directory should be listed.
802 * Results should be storage paths relative to the given directory.
803 *
804 * Storage backends with eventual consistency might return stale data.
805 *
806 * $params include:
807 * dir : storage directory
808 * topOnly : only return direct child files of the directory (@since 1.20)
809 *
810 * @param $params array
811 * @return Traversable|Array|null Returns null on failure
812 */
813 abstract public function getFileList( array $params );
814
815 /**
816 * Same as FileBackend::getFileList() except only lists
817 * files that are immediately under the given directory.
818 *
819 * Storage backends with eventual consistency might return stale data.
820 *
821 * $params include:
822 * dir : storage directory
823 *
824 * @param $params array
825 * @return Traversable|Array|null Returns null on failure
826 * @since 1.20
827 */
828 final public function getTopFileList( array $params ) {
829 return $this->getFileList( array( 'topOnly' => true ) + $params );
830 }
831
832 /**
833 * Invalidate any in-process file existence and property cache.
834 * If $paths is given, then only the cache for those files will be cleared.
835 *
836 * @param $paths Array Storage paths (optional)
837 * @return void
838 */
839 public function clearCache( array $paths = null ) {}
840
841 /**
842 * Lock the files at the given storage paths in the backend.
843 * This will either lock all the files or none (on failure).
844 *
845 * Callers should consider using getScopedFileLocks() instead.
846 *
847 * @param $paths Array Storage paths
848 * @param $type integer LockManager::LOCK_* constant
849 * @return Status
850 */
851 final public function lockFiles( array $paths, $type ) {
852 return $this->lockManager->lock( $paths, $type );
853 }
854
855 /**
856 * Unlock the files at the given storage paths in the backend.
857 *
858 * @param $paths Array Storage paths
859 * @param $type integer LockManager::LOCK_* constant
860 * @return Status
861 */
862 final public function unlockFiles( array $paths, $type ) {
863 return $this->lockManager->unlock( $paths, $type );
864 }
865
866 /**
867 * Lock the files at the given storage paths in the backend.
868 * This will either lock all the files or none (on failure).
869 * On failure, the status object will be updated with errors.
870 *
871 * Once the return value goes out scope, the locks will be released and
872 * the status updated. Unlock fatals will not change the status "OK" value.
873 *
874 * @param $paths Array Storage paths
875 * @param $type integer LockManager::LOCK_* constant
876 * @param $status Status Status to update on lock/unlock
877 * @return ScopedLock|null Returns null on failure
878 */
879 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
880 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
881 }
882
883 /**
884 * Get an array of scoped locks needed for a batch of file operations.
885 *
886 * Normally, FileBackend::doOperations() handles locking, unless
887 * the 'nonLocking' param is passed in. This function is useful if you
888 * want the files to be locked for a broader scope than just when the
889 * files are changing. For example, if you need to update DB metadata,
890 * you may want to keep the files locked until finished.
891 *
892 * @see FileBackend::doOperations()
893 *
894 * @param $ops Array List of file operations to FileBackend::doOperations()
895 * @param $status Status Status to update on lock/unlock
896 * @return Array List of ScopedFileLocks or null values
897 * @since 1.20
898 */
899 abstract public function getScopedLocksForOps( array $ops, Status $status );
900
901 /**
902 * Get the root storage path of this backend.
903 * All container paths are "subdirectories" of this path.
904 *
905 * @return string Storage path
906 * @since 1.20
907 */
908 final public function getRootStoragePath() {
909 return "mwstore://{$this->name}";
910 }
911
912 /**
913 * Get the file journal object for this backend
914 *
915 * @return FileJournal
916 */
917 final public function getJournal() {
918 return $this->fileJournal;
919 }
920
921 /**
922 * Check if a given path is a "mwstore://" path.
923 * This does not do any further validation or any existence checks.
924 *
925 * @param $path string
926 * @return bool
927 */
928 final public static function isStoragePath( $path ) {
929 return ( strpos( $path, 'mwstore://' ) === 0 );
930 }
931
932 /**
933 * Split a storage path into a backend name, a container name,
934 * and a relative file path. The relative path may be the empty string.
935 * This does not do any path normalization or traversal checks.
936 *
937 * @param $storagePath string
938 * @return Array (backend, container, rel object) or (null, null, null)
939 */
940 final public static function splitStoragePath( $storagePath ) {
941 if ( self::isStoragePath( $storagePath ) ) {
942 // Remove the "mwstore://" prefix and split the path
943 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
944 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
945 if ( count( $parts ) == 3 ) {
946 return $parts; // e.g. "backend/container/path"
947 } else {
948 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
949 }
950 }
951 }
952 return array( null, null, null );
953 }
954
955 /**
956 * Normalize a storage path by cleaning up directory separators.
957 * Returns null if the path is not of the format of a valid storage path.
958 *
959 * @param $storagePath string
960 * @return string|null
961 */
962 final public static function normalizeStoragePath( $storagePath ) {
963 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
964 if ( $relPath !== null ) { // must be for this backend
965 $relPath = self::normalizeContainerPath( $relPath );
966 if ( $relPath !== null ) {
967 return ( $relPath != '' )
968 ? "mwstore://{$backend}/{$container}/{$relPath}"
969 : "mwstore://{$backend}/{$container}";
970 }
971 }
972 return null;
973 }
974
975 /**
976 * Get the parent storage directory of a storage path.
977 * This returns a path like "mwstore://backend/container",
978 * "mwstore://backend/container/...", or null if there is no parent.
979 *
980 * @param $storagePath string
981 * @return string|null
982 */
983 final public static function parentStoragePath( $storagePath ) {
984 $storagePath = dirname( $storagePath );
985 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
986 return ( $rel === null ) ? null : $storagePath;
987 }
988
989 /**
990 * Get the final extension from a storage or FS path
991 *
992 * @param $path string
993 * @return string
994 */
995 final public static function extensionFromPath( $path ) {
996 $i = strrpos( $path, '.' );
997 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
998 }
999
1000 /**
1001 * Check if a relative path has no directory traversals
1002 *
1003 * @param $path string
1004 * @return bool
1005 * @since 1.20
1006 */
1007 final public static function isPathTraversalFree( $path ) {
1008 return ( self::normalizeContainerPath( $path ) !== null );
1009 }
1010
1011 /**
1012 * Validate and normalize a relative storage path.
1013 * Null is returned if the path involves directory traversal.
1014 * Traversal is insecure for FS backends and broken for others.
1015 *
1016 * This uses the same traversal protection as Title::secureAndSplit().
1017 *
1018 * @param $path string Storage path relative to a container
1019 * @return string|null
1020 */
1021 final protected static function normalizeContainerPath( $path ) {
1022 // Normalize directory separators
1023 $path = strtr( $path, '\\', '/' );
1024 // Collapse any consecutive directory separators
1025 $path = preg_replace( '![/]{2,}!', '/', $path );
1026 // Remove any leading directory separator
1027 $path = ltrim( $path, '/' );
1028 // Use the same traversal protection as Title::secureAndSplit()
1029 if ( strpos( $path, '.' ) !== false ) {
1030 if (
1031 $path === '.' ||
1032 $path === '..' ||
1033 strpos( $path, './' ) === 0 ||
1034 strpos( $path, '../' ) === 0 ||
1035 strpos( $path, '/./' ) !== false ||
1036 strpos( $path, '/../' ) !== false
1037 ) {
1038 return null;
1039 }
1040 }
1041 return $path;
1042 }
1043 }