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