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