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