Merge "$wgUseSquid unused since parent commit (fa1a8d5)"
[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 */
405 final public function doQuickOperations( array $ops ) {
406 if ( $this->isReadOnly() ) {
407 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
408 }
409 foreach ( $ops as &$op ) {
410 $op['overwrite'] = true; // avoids RTTs in key/value stores
411 }
412 return $this->doQuickOperationsInternal( $ops );
413 }
414
415 /**
416 * @see FileBackend::doQuickOperations()
417 */
418 abstract protected function doQuickOperationsInternal( array $ops );
419
420 /**
421 * Concatenate a list of storage files into a single file system file.
422 * The target path should refer to a file that is already locked or
423 * otherwise safe from modification from other processes. Normally,
424 * the file will be a new temp file, which should be adequate.
425 * $params include:
426 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
427 * dst : file system path to 0-byte temp file
428 *
429 * @param $params Array Operation parameters
430 * @return Status
431 */
432 abstract public function concatenate( array $params );
433
434 /**
435 * Prepare a storage directory for usage.
436 * This will create any required containers and parent directories.
437 * Backends using key/value stores only need to create the container.
438 *
439 * $params include:
440 * dir : storage directory
441 *
442 * @param $params Array
443 * @return Status
444 */
445 final public function prepare( array $params ) {
446 if ( $this->isReadOnly() ) {
447 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
448 }
449 return $this->doPrepare( $params );
450 }
451
452 /**
453 * @see FileBackend::prepare()
454 */
455 abstract protected function doPrepare( array $params );
456
457 /**
458 * Take measures to block web access to a storage directory and
459 * the container it belongs to. FS backends might add .htaccess
460 * files whereas key/value store backends might restrict container
461 * access to the auth user that represents end-users in web request.
462 * This is not guaranteed to actually do anything.
463 *
464 * $params include:
465 * dir : storage directory
466 * noAccess : try to deny file access
467 * noListing : try to deny file listing
468 *
469 * @param $params Array
470 * @return Status
471 */
472 final public function secure( array $params ) {
473 if ( $this->isReadOnly() ) {
474 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
475 }
476 $status = $this->doPrepare( $params ); // dir must exist to restrict it
477 if ( $status->isOK() ) {
478 $status->merge( $this->doSecure( $params ) );
479 }
480 return $status;
481 }
482
483 /**
484 * @see FileBackend::secure()
485 */
486 abstract protected function doSecure( array $params );
487
488 /**
489 * Delete a storage directory if it is empty.
490 * Backends using key/value stores may do nothing unless the directory
491 * is that of an empty container, in which case it should be deleted.
492 *
493 * $params include:
494 * dir : storage directory
495 * recursive : recursively delete empty subdirectories first (@since 1.20)
496 *
497 * @param $params Array
498 * @return Status
499 */
500 final public function clean( array $params ) {
501 if ( $this->isReadOnly() ) {
502 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
503 }
504 return $this->doClean( $params );
505 }
506
507 /**
508 * @see FileBackend::clean()
509 */
510 abstract protected function doClean( array $params );
511
512 /**
513 * Check if a file exists at a storage path in the backend.
514 * This returns false if only a directory exists at the path.
515 *
516 * $params include:
517 * src : source storage path
518 * latest : use the latest available data
519 *
520 * @param $params Array
521 * @return bool|null Returns null on failure
522 */
523 abstract public function fileExists( array $params );
524
525 /**
526 * Get the last-modified timestamp of the file at a storage path.
527 *
528 * $params include:
529 * src : source storage path
530 * latest : use the latest available data
531 *
532 * @param $params Array
533 * @return string|bool TS_MW timestamp or false on failure
534 */
535 abstract public function getFileTimestamp( array $params );
536
537 /**
538 * Get the contents of a file at a storage path in the backend.
539 * This should be avoided for potentially large files.
540 *
541 * $params include:
542 * src : source storage path
543 * latest : use the latest available data
544 *
545 * @param $params Array
546 * @return string|bool Returns false on failure
547 */
548 abstract public function getFileContents( array $params );
549
550 /**
551 * Get the size (bytes) of a file at a storage path in the backend.
552 *
553 * $params include:
554 * src : source storage path
555 * latest : use the latest available data
556 *
557 * @param $params Array
558 * @return integer|bool Returns false on failure
559 */
560 abstract public function getFileSize( array $params );
561
562 /**
563 * Get quick information about a file at a storage path in the backend.
564 * If the file does not exist, then this returns false.
565 * Otherwise, the result is an associative array that includes:
566 * mtime : the last-modified timestamp (TS_MW)
567 * size : the file size (bytes)
568 * Additional values may be included for internal use only.
569 *
570 * $params include:
571 * src : source storage path
572 * latest : use the latest available data
573 *
574 * @param $params Array
575 * @return Array|bool|null Returns null on failure
576 */
577 abstract public function getFileStat( array $params );
578
579 /**
580 * Get a SHA-1 hash of the file at a storage path in the backend.
581 *
582 * $params include:
583 * src : source storage path
584 * latest : use the latest available data
585 *
586 * @param $params Array
587 * @return string|bool Hash string or false on failure
588 */
589 abstract public function getFileSha1Base36( array $params );
590
591 /**
592 * Get the properties of the file at a storage path in the backend.
593 * Returns FSFile::placeholderProps() on failure.
594 *
595 * $params include:
596 * src : source storage path
597 * latest : use the latest available data
598 *
599 * @param $params Array
600 * @return Array
601 */
602 abstract public function getFileProps( array $params );
603
604 /**
605 * Stream the file at a storage path in the backend.
606 * If the file does not exists, a 404 error will be given.
607 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
608 * must be sent if streaming began, while none should be sent otherwise.
609 * Implementations should flush the output buffer before sending data.
610 *
611 * $params include:
612 * src : source storage path
613 * headers : additional HTTP headers to send on success
614 * latest : use the latest available data
615 *
616 * @param $params Array
617 * @return Status
618 */
619 abstract public function streamFile( array $params );
620
621 /**
622 * Returns a file system file, identical to the file at a storage path.
623 * The file returned is either:
624 * a) A local copy of the file at a storage path in the backend.
625 * The temporary copy will have the same extension as the source.
626 * b) An original of the file at a storage path in the backend.
627 * Temporary files may be purged when the file object falls out of scope.
628 *
629 * Write operations should *never* be done on this file as some backends
630 * may do internal tracking or may be instances of FileBackendMultiWrite.
631 * In that later case, there are copies of the file that must stay in sync.
632 * Additionally, further calls to this function may return the same file.
633 *
634 * $params include:
635 * src : source storage path
636 * latest : use the latest available data
637 *
638 * @param $params Array
639 * @return FSFile|null Returns null on failure
640 */
641 abstract public function getLocalReference( array $params );
642
643 /**
644 * Get a local copy on disk of the file at a storage path in the backend.
645 * The temporary copy will have the same file extension as the source.
646 * Temporary files may be purged when the file object falls out of scope.
647 *
648 * $params include:
649 * src : source storage path
650 * latest : use the latest available data
651 *
652 * @param $params Array
653 * @return TempFSFile|null Returns null on failure
654 */
655 abstract public function getLocalCopy( array $params );
656
657 /**
658 * Check if a directory exists at a given storage path.
659 * Backends using key/value stores will check if the path is a
660 * virtual directory, meaning there are files under the given directory.
661 *
662 * Storage backends with eventual consistency might return stale data.
663 *
664 * $params include:
665 * dir : storage directory
666 *
667 * @param $params array
668 * @return bool|null Returns null on failure
669 * @since 1.20
670 */
671 abstract public function directoryExists( array $params );
672
673 /**
674 * Get an iterator to list *all* directories under a storage directory.
675 * If the directory is of the form "mwstore://backend/container",
676 * then all directories in the container should be listed.
677 * If the directory is of form "mwstore://backend/container/dir",
678 * then all directories directly under that directory should be listed.
679 * Results should be storage directories relative to the given directory.
680 *
681 * Storage backends with eventual consistency might return stale data.
682 *
683 * $params include:
684 * dir : storage directory
685 * topOnly : only return direct child dirs of the directory
686 *
687 * @param $params array
688 * @return Traversable|Array|null Returns null on failure
689 * @since 1.20
690 */
691 abstract public function getDirectoryList( array $params );
692
693 /**
694 * Same as FileBackend::getDirectoryList() except only lists
695 * directories that are immediately under the given directory.
696 *
697 * Storage backends with eventual consistency might return stale data.
698 *
699 * $params include:
700 * dir : storage directory
701 *
702 * @param $params array
703 * @return Traversable|Array|null Returns null on failure
704 * @since 1.20
705 */
706 final public function getTopDirectoryList( array $params ) {
707 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
708 }
709
710 /**
711 * Get an iterator to list *all* stored files under a storage directory.
712 * If the directory is of the form "mwstore://backend/container",
713 * then all files in the container should be listed.
714 * If the directory is of form "mwstore://backend/container/dir",
715 * then all files under that directory should be listed.
716 * Results should be storage paths relative to the given directory.
717 *
718 * Storage backends with eventual consistency might return stale data.
719 *
720 * $params include:
721 * dir : storage directory
722 * topOnly : only return direct child files of the directory (@since 1.20)
723 *
724 * @param $params array
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 * @param $params array
739 * @return Traversable|Array|null Returns null on failure
740 * @since 1.20
741 */
742 final public function getTopFileList( array $params ) {
743 return $this->getFileList( array( 'topOnly' => true ) + $params );
744 }
745
746 /**
747 * Invalidate any in-process file existence and property cache.
748 * If $paths is given, then only the cache for those files will be cleared.
749 *
750 * @param $paths Array Storage paths (optional)
751 * @return void
752 */
753 public function clearCache( array $paths = null ) {}
754
755 /**
756 * Lock the files at the given storage paths in the backend.
757 * This will either lock all the files or none (on failure).
758 *
759 * Callers should consider using getScopedFileLocks() instead.
760 *
761 * @param $paths Array Storage paths
762 * @param $type integer LockManager::LOCK_* constant
763 * @return Status
764 */
765 final public function lockFiles( array $paths, $type ) {
766 return $this->lockManager->lock( $paths, $type );
767 }
768
769 /**
770 * Unlock the files at the given storage paths in the backend.
771 *
772 * @param $paths Array Storage paths
773 * @param $type integer LockManager::LOCK_* constant
774 * @return Status
775 */
776 final public function unlockFiles( array $paths, $type ) {
777 return $this->lockManager->unlock( $paths, $type );
778 }
779
780 /**
781 * Lock the files at the given storage paths in the backend.
782 * This will either lock all the files or none (on failure).
783 * On failure, the status object will be updated with errors.
784 *
785 * Once the return value goes out scope, the locks will be released and
786 * the status updated. Unlock fatals will not change the status "OK" value.
787 *
788 * @param $paths Array Storage paths
789 * @param $type integer LockManager::LOCK_* constant
790 * @param $status Status Status to update on lock/unlock
791 * @return ScopedLock|null Returns null on failure
792 */
793 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
794 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
795 }
796
797 /**
798 * Get an array of scoped locks needed for a batch of file operations.
799 *
800 * Normally, FileBackend::doOperations() handles locking, unless
801 * the 'nonLocking' param is passed in. This function is useful if you
802 * want the files to be locked for a broader scope than just when the
803 * files are changing. For example, if you need to update DB metadata,
804 * you may want to keep the files locked until finished.
805 *
806 * @see FileBackend::doOperations()
807 *
808 * @param $ops Array List of file operations to FileBackend::doOperations()
809 * @param $status Status Status to update on lock/unlock
810 * @return Array List of ScopedFileLocks or null values
811 * @since 1.20
812 */
813 abstract public function getScopedLocksForOps( array $ops, Status $status );
814
815 /**
816 * Get the root storage path of this backend.
817 * All container paths are "subdirectories" of this path.
818 *
819 * @return string Storage path
820 * @since 1.20
821 */
822 final public function getRootStoragePath() {
823 return "mwstore://{$this->name}";
824 }
825
826 /**
827 * Get the file journal object for this backend
828 *
829 * @return FileJournal
830 */
831 final public function getJournal() {
832 return $this->fileJournal;
833 }
834
835 /**
836 * Check if a given path is a "mwstore://" path.
837 * This does not do any further validation or any existence checks.
838 *
839 * @param $path string
840 * @return bool
841 */
842 final public static function isStoragePath( $path ) {
843 return ( strpos( $path, 'mwstore://' ) === 0 );
844 }
845
846 /**
847 * Split a storage path into a backend name, a container name,
848 * and a relative file path. The relative path may be the empty string.
849 * This does not do any path normalization or traversal checks.
850 *
851 * @param $storagePath string
852 * @return Array (backend, container, rel object) or (null, null, null)
853 */
854 final public static function splitStoragePath( $storagePath ) {
855 if ( self::isStoragePath( $storagePath ) ) {
856 // Remove the "mwstore://" prefix and split the path
857 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
858 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
859 if ( count( $parts ) == 3 ) {
860 return $parts; // e.g. "backend/container/path"
861 } else {
862 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
863 }
864 }
865 }
866 return array( null, null, null );
867 }
868
869 /**
870 * Normalize a storage path by cleaning up directory separators.
871 * Returns null if the path is not of the format of a valid storage path.
872 *
873 * @param $storagePath string
874 * @return string|null
875 */
876 final public static function normalizeStoragePath( $storagePath ) {
877 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
878 if ( $relPath !== null ) { // must be for this backend
879 $relPath = self::normalizeContainerPath( $relPath );
880 if ( $relPath !== null ) {
881 return ( $relPath != '' )
882 ? "mwstore://{$backend}/{$container}/{$relPath}"
883 : "mwstore://{$backend}/{$container}";
884 }
885 }
886 return null;
887 }
888
889 /**
890 * Get the parent storage directory of a storage path.
891 * This returns a path like "mwstore://backend/container",
892 * "mwstore://backend/container/...", or null if there is no parent.
893 *
894 * @param $storagePath string
895 * @return string|null
896 */
897 final public static function parentStoragePath( $storagePath ) {
898 $storagePath = dirname( $storagePath );
899 list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
900 return ( $rel === null ) ? null : $storagePath;
901 }
902
903 /**
904 * Get the final extension from a storage or FS path
905 *
906 * @param $path string
907 * @return string
908 */
909 final public static function extensionFromPath( $path ) {
910 $i = strrpos( $path, '.' );
911 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
912 }
913
914 /**
915 * Check if a relative path has no directory traversals
916 *
917 * @param $path string
918 * @return bool
919 * @since 1.20
920 */
921 final public static function isPathTraversalFree( $path ) {
922 return ( self::normalizeContainerPath( $path ) !== null );
923 }
924
925 /**
926 * Validate and normalize a relative storage path.
927 * Null is returned if the path involves directory traversal.
928 * Traversal is insecure for FS backends and broken for others.
929 *
930 * This uses the same traversal protection as Title::secureAndSplit().
931 *
932 * @param $path string Storage path relative to a container
933 * @return string|null
934 */
935 final protected static function normalizeContainerPath( $path ) {
936 // Normalize directory separators
937 $path = strtr( $path, '\\', '/' );
938 // Collapse any consecutive directory separators
939 $path = preg_replace( '![/]{2,}!', '/', $path );
940 // Remove any leading directory separator
941 $path = ltrim( $path, '/' );
942 // Use the same traversal protection as Title::secureAndSplit()
943 if ( strpos( $path, '.' ) !== false ) {
944 if (
945 $path === '.' ||
946 $path === '..' ||
947 strpos( $path, './' ) === 0 ||
948 strpos( $path, '../' ) === 0 ||
949 strpos( $path, '/./' ) !== false ||
950 strpos( $path, '/../' ) !== false
951 ) {
952 return null;
953 }
954 }
955 return $path;
956 }
957 }