94e509ec62b56e089a2343c4328466769ac2281f
3 * @defgroup FileBackend File backend
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
11 * Base class for all file backends.
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.
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.
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
29 * @ingroup FileBackend
30 * @author Aaron Schulz
34 * @brief Base class for all file backend classes (including multi-write backends).
36 * This class defines the methods as abstract that subclasses must implement.
37 * Outside callers can assume that all backends will have these functions.
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.
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.
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.
53 * Methods should avoid throwing exceptions at all costs.
54 * As a corollary, external dependencies should be kept to a minimum.
56 * @ingroup FileBackend
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
66 /** @var LockManager */
67 protected $lockManager;
68 /** @var FileJournal */
69 protected $fileJournal;
72 * Create a new backend instance from configuration.
73 * This should only be called from within FileBackendGroup.
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.
90 * @param $config Array
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." );
97 $this->wikiId
= isset( $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']
109 $this->parallelize
= isset( $config['parallelize'] )
110 ?
(string)$config['parallelize']
112 $this->concurrency
= isset( $config['concurrency'] )
113 ?
(int)$config['concurrency']
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.
124 final public function getName() {
129 * Check if this backend is read-only
133 final public function isReadOnly() {
134 return ( $this->readOnly
!= '' );
138 * Get an explanatory message if this backend is read-only
140 * @return string|bool Returns false if the backend is not read-only
142 final public function getReadOnlyReason() {
143 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
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.
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.
155 * Supported operations and their parameters:
156 * a) Create a new file in storage with the contents of a string
159 * 'dst' => <storage path>,
160 * 'content' => <string of new file contents>,
161 * 'overwrite' => <boolean>,
162 * 'overwriteSame' => <boolean>
164 * b) Copy a file system file into storage
167 * 'src' => <file system path>,
168 * 'dst' => <storage path>,
169 * 'overwrite' => <boolean>,
170 * 'overwriteSame' => <boolean>
172 * c) Copy a file within storage
175 * 'src' => <storage path>,
176 * 'dst' => <storage path>,
177 * 'overwrite' => <boolean>,
178 * 'overwriteSame' => <boolean>
180 * d) Move a file within storage
183 * 'src' => <storage path>,
184 * 'dst' => <storage path>,
185 * 'overwrite' => <boolean>,
186 * 'overwriteSame' => <boolean>
188 * e) Delete a file within storage
191 * 'src' => <storage path>,
192 * 'ignoreMissingSource' => <boolean>
194 * f) Do nothing (no-op)
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.
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.
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.
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
233 * @param $ops Array List of operations to execute in order
234 * @param $opts Array Batch operation options
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
);
241 if ( empty( $opts['force'] ) ) { // sanity
242 unset( $opts['nonLocking'] );
243 unset( $opts['allowStale'] );
245 $opts['concurrency'] = 1; // off
246 if ( $this->parallelize
=== 'implicit' ) {
247 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
248 $opts['concurrency'] = $this->concurrency
;
250 } elseif ( $this->parallelize
=== 'explicit' ) {
251 if ( !empty( $opts['parallelize'] ) ) {
252 $opts['concurrency'] = $this->concurrency
;
255 return $this->doOperationsInternal( $ops, $opts );
259 * @see FileBackend::doOperations()
261 abstract protected function doOperationsInternal( array $ops, array $opts );
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.
268 * @see FileBackend::doOperations()
270 * @param $op Array Operation
271 * @param $opts Array Operation options
274 final public function doOperation( array $op, array $opts = array() ) {
275 return $this->doOperations( array( $op ), $opts );
279 * Performs a single create operation.
280 * This sets $params['op'] to 'create' and passes it to doOperation().
282 * @see FileBackend::doOperation()
284 * @param $params Array Operation parameters
285 * @param $opts Array Operation options
288 final public function create( array $params, array $opts = array() ) {
289 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
293 * Performs a single store operation.
294 * This sets $params['op'] to 'store' and passes it to doOperation().
296 * @see FileBackend::doOperation()
298 * @param $params Array Operation parameters
299 * @param $opts Array Operation options
302 final public function store( array $params, array $opts = array() ) {
303 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
307 * Performs a single copy operation.
308 * This sets $params['op'] to 'copy' and passes it to doOperation().
310 * @see FileBackend::doOperation()
312 * @param $params Array Operation parameters
313 * @param $opts Array Operation options
316 final public function copy( array $params, array $opts = array() ) {
317 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
321 * Performs a single move operation.
322 * This sets $params['op'] to 'move' and passes it to doOperation().
324 * @see FileBackend::doOperation()
326 * @param $params Array Operation parameters
327 * @param $opts Array Operation options
330 final public function move( array $params, array $opts = array() ) {
331 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
335 * Performs a single delete operation.
336 * This sets $params['op'] to 'delete' and passes it to doOperation().
338 * @see FileBackend::doOperation()
340 * @param $params Array Operation parameters
341 * @param $opts Array Operation options
344 final public function delete( array $params, array $opts = array() ) {
345 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
349 * Perform a set of independent file operations on some files.
351 * This does no locking, nor journaling, and possibly no stat calls.
352 * Any destination files that already exist will be overwritten.
353 * This should *only* be used on non-original files, like cache files.
355 * Supported operations and their parameters:
356 * a) Create a new file in storage with the contents of a string
359 * 'dst' => <storage path>,
360 * 'content' => <string of new file contents>
362 * b) Copy a file system file into storage
365 * 'src' => <file system path>,
366 * 'dst' => <storage path>
368 * c) Copy a file within storage
371 * 'src' => <storage path>,
372 * 'dst' => <storage path>
374 * d) Move a file within storage
377 * 'src' => <storage path>,
378 * 'dst' => <storage path>
380 * e) Delete a file within storage
383 * 'src' => <storage path>,
384 * 'ignoreMissingSource' => <boolean>
386 * f) Do nothing (no-op)
391 * Boolean flags for operations (operation-specific):
392 * 'ignoreMissingSource' : The operation will simply succeed and do
393 * nothing if the source file does not exist.
396 * This returns a Status, which contains all warnings and fatals that occured
397 * during the operation. The 'failCount', 'successCount', and 'success' members
398 * will reflect each operation attempted for the given files. The status will be
399 * considered "OK" as long as no fatal errors occured.
401 * @param $ops Array Set of operations to execute
404 final public function doQuickOperations( array $ops ) {
405 if ( $this->isReadOnly() ) {
406 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
408 foreach ( $ops as &$op ) {
409 $op['overwrite'] = true; // avoids RTTs in key/value stores
411 return $this->doQuickOperationsInternal( $ops );
415 * @see FileBackend::doQuickOperations()
417 abstract protected function doQuickOperationsInternal( array $ops );
420 * Concatenate a list of storage files into a single file system file.
421 * The target path should refer to a file that is already locked or
422 * otherwise safe from modification from other processes. Normally,
423 * the file will be a new temp file, which should be adequate.
425 * srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
426 * dst : file system path to 0-byte temp file
428 * @param $params Array Operation parameters
431 abstract public function concatenate( array $params );
434 * Prepare a storage directory for usage.
435 * This will create any required containers and parent directories.
436 * Backends using key/value stores only need to create the container.
439 * dir : storage directory
441 * @param $params Array
444 final public function prepare( array $params ) {
445 if ( $this->isReadOnly() ) {
446 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
448 return $this->doPrepare( $params );
452 * @see FileBackend::prepare()
454 abstract protected function doPrepare( array $params );
457 * Take measures to block web access to a storage directory and
458 * the container it belongs to. FS backends might add .htaccess
459 * files whereas key/value store backends might restrict container
460 * access to the auth user that represents end-users in web request.
461 * This is not guaranteed to actually do anything.
464 * dir : storage directory
465 * noAccess : try to deny file access
466 * noListing : try to deny file listing
468 * @param $params Array
471 final public function secure( array $params ) {
472 if ( $this->isReadOnly() ) {
473 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
475 $status = $this->doPrepare( $params ); // dir must exist to restrict it
476 if ( $status->isOK() ) {
477 $status->merge( $this->doSecure( $params ) );
483 * @see FileBackend::secure()
485 abstract protected function doSecure( array $params );
488 * Delete a storage directory if it is empty.
489 * Backends using key/value stores may do nothing unless the directory
490 * is that of an empty container, in which case it should be deleted.
493 * dir : storage directory
494 * recursive : recursively delete empty subdirectories first (@since 1.20)
496 * @param $params Array
499 final public function clean( array $params ) {
500 if ( $this->isReadOnly() ) {
501 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
503 return $this->doClean( $params );
507 * @see FileBackend::clean()
509 abstract protected function doClean( array $params );
512 * Check if a file exists at a storage path in the backend.
513 * This returns false if only a directory exists at the path.
516 * src : source storage path
517 * latest : use the latest available data
519 * @param $params Array
520 * @return bool|null Returns null on failure
522 abstract public function fileExists( array $params );
525 * Get the last-modified timestamp of the file at a storage path.
528 * src : source storage path
529 * latest : use the latest available data
531 * @param $params Array
532 * @return string|bool TS_MW timestamp or false on failure
534 abstract public function getFileTimestamp( array $params );
537 * Get the contents of a file at a storage path in the backend.
538 * This should be avoided for potentially large files.
541 * src : source storage path
542 * latest : use the latest available data
544 * @param $params Array
545 * @return string|bool Returns false on failure
547 abstract public function getFileContents( array $params );
550 * Get the size (bytes) of a file at a storage path in the backend.
553 * src : source storage path
554 * latest : use the latest available data
556 * @param $params Array
557 * @return integer|bool Returns false on failure
559 abstract public function getFileSize( array $params );
562 * Get quick information about a file at a storage path in the backend.
563 * If the file does not exist, then this returns false.
564 * Otherwise, the result is an associative array that includes:
565 * mtime : the last-modified timestamp (TS_MW)
566 * size : the file size (bytes)
567 * Additional values may be included for internal use only.
570 * src : source storage path
571 * latest : use the latest available data
573 * @param $params Array
574 * @return Array|bool|null Returns null on failure
576 abstract public function getFileStat( array $params );
579 * Get a SHA-1 hash of the file at a storage path in the backend.
582 * src : source storage path
583 * latest : use the latest available data
585 * @param $params Array
586 * @return string|bool Hash string or false on failure
588 abstract public function getFileSha1Base36( array $params );
591 * Get the properties of the file at a storage path in the backend.
592 * Returns FSFile::placeholderProps() on failure.
595 * src : source storage path
596 * latest : use the latest available data
598 * @param $params Array
601 abstract public function getFileProps( array $params );
604 * Stream the file at a storage path in the backend.
605 * If the file does not exists, a 404 error will be given.
606 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
607 * must be sent if streaming began, while none should be sent otherwise.
608 * Implementations should flush the output buffer before sending data.
611 * src : source storage path
612 * headers : additional HTTP headers to send on success
613 * latest : use the latest available data
615 * @param $params Array
618 abstract public function streamFile( array $params );
621 * Returns a file system file, identical to the file at a storage path.
622 * The file returned is either:
623 * a) A local copy of the file at a storage path in the backend.
624 * The temporary copy will have the same extension as the source.
625 * b) An original of the file at a storage path in the backend.
626 * Temporary files may be purged when the file object falls out of scope.
628 * Write operations should *never* be done on this file as some backends
629 * may do internal tracking or may be instances of FileBackendMultiWrite.
630 * In that later case, there are copies of the file that must stay in sync.
631 * Additionally, further calls to this function may return the same file.
634 * src : source storage path
635 * latest : use the latest available data
637 * @param $params Array
638 * @return FSFile|null Returns null on failure
640 abstract public function getLocalReference( array $params );
643 * Get a local copy on disk of the file at a storage path in the backend.
644 * The temporary copy will have the same file extension as the source.
645 * Temporary files may be purged when the file object falls out of scope.
648 * src : source storage path
649 * latest : use the latest available data
651 * @param $params Array
652 * @return TempFSFile|null Returns null on failure
654 abstract public function getLocalCopy( array $params );
657 * Check if a directory exists at a given storage path.
658 * Backends using key/value stores will check if the path is a
659 * virtual directory, meaning there are files under the given directory.
661 * Storage backends with eventual consistency might return stale data.
664 * dir : storage directory
666 * @return bool|null Returns null on failure
669 abstract public function directoryExists( array $params );
672 * Get an iterator to list *all* directories under a storage directory.
673 * If the directory is of the form "mwstore://backend/container",
674 * then all directories in the container should be listed.
675 * If the directory is of form "mwstore://backend/container/dir",
676 * then all directories directly under that directory should be listed.
677 * Results should be storage directories relative to the given directory.
679 * Storage backends with eventual consistency might return stale data.
682 * dir : storage directory
683 * topOnly : only return direct child dirs of the directory
685 * @return Traversable|Array|null Returns null on failure
688 abstract public function getDirectoryList( array $params );
691 * Same as FileBackend::getDirectoryList() except only lists
692 * directories that are immediately under the given directory.
694 * Storage backends with eventual consistency might return stale data.
697 * dir : storage directory
699 * @return Traversable|Array|null Returns null on failure
702 final public function getTopDirectoryList( array $params ) {
703 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
707 * Get an iterator to list *all* stored files under a storage directory.
708 * If the directory is of the form "mwstore://backend/container",
709 * then all files in the container should be listed.
710 * If the directory is of form "mwstore://backend/container/dir",
711 * then all files under that directory should be listed.
712 * Results should be storage paths relative to the given directory.
714 * Storage backends with eventual consistency might return stale data.
717 * dir : storage directory
718 * topOnly : only return direct child files of the directory (@since 1.20)
720 * @return Traversable|Array|null Returns null on failure
722 abstract public function getFileList( array $params );
725 * Same as FileBackend::getFileList() except only lists
726 * files that are immediately under the given directory.
728 * Storage backends with eventual consistency might return stale data.
731 * dir : storage directory
733 * @return Traversable|Array|null Returns null on failure
736 final public function getTopFileList( array $params ) {
737 return $this->getFileList( array( 'topOnly' => true ) +
$params );
741 * Invalidate any in-process file existence and property cache.
742 * If $paths is given, then only the cache for those files will be cleared.
744 * @param $paths Array Storage paths (optional)
747 public function clearCache( array $paths = null ) {}
750 * Lock the files at the given storage paths in the backend.
751 * This will either lock all the files or none (on failure).
753 * Callers should consider using getScopedFileLocks() instead.
755 * @param $paths Array Storage paths
756 * @param $type integer LockManager::LOCK_* constant
759 final public function lockFiles( array $paths, $type ) {
760 return $this->lockManager
->lock( $paths, $type );
764 * Unlock the files at the given storage paths in the backend.
766 * @param $paths Array Storage paths
767 * @param $type integer LockManager::LOCK_* constant
770 final public function unlockFiles( array $paths, $type ) {
771 return $this->lockManager
->unlock( $paths, $type );
775 * Lock the files at the given storage paths in the backend.
776 * This will either lock all the files or none (on failure).
777 * On failure, the status object will be updated with errors.
779 * Once the return value goes out scope, the locks will be released and
780 * the status updated. Unlock fatals will not change the status "OK" value.
782 * @param $paths Array Storage paths
783 * @param $type integer LockManager::LOCK_* constant
784 * @param $status Status Status to update on lock/unlock
785 * @return ScopedLock|null Returns null on failure
787 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
788 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
792 * Get the root storage path of this backend.
793 * All container paths are "subdirectories" of this path.
795 * @return string Storage path
798 final public function getRootStoragePath() {
799 return "mwstore://{$this->name}";
803 * Get the file journal object for this backend
805 * @return FileJournal
807 final public function getJournal() {
808 return $this->fileJournal
;
812 * Check if a given path is a "mwstore://" path.
813 * This does not do any further validation or any existence checks.
815 * @param $path string
818 final public static function isStoragePath( $path ) {
819 return ( strpos( $path, 'mwstore://' ) === 0 );
823 * Split a storage path into a backend name, a container name,
824 * and a relative file path. The relative path may be the empty string.
825 * This does not do any path normalization or traversal checks.
827 * @param $storagePath string
828 * @return Array (backend, container, rel object) or (null, null, null)
830 final public static function splitStoragePath( $storagePath ) {
831 if ( self
::isStoragePath( $storagePath ) ) {
832 // Remove the "mwstore://" prefix and split the path
833 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
834 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
835 if ( count( $parts ) == 3 ) {
836 return $parts; // e.g. "backend/container/path"
838 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
842 return array( null, null, null );
846 * Normalize a storage path by cleaning up directory separators.
847 * Returns null if the path is not of the format of a valid storage path.
849 * @param $storagePath string
850 * @return string|null
852 final public static function normalizeStoragePath( $storagePath ) {
853 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
854 if ( $relPath !== null ) { // must be for this backend
855 $relPath = self
::normalizeContainerPath( $relPath );
856 if ( $relPath !== null ) {
857 return ( $relPath != '' )
858 ?
"mwstore://{$backend}/{$container}/{$relPath}"
859 : "mwstore://{$backend}/{$container}";
866 * Get the parent storage directory of a storage path.
867 * This returns a path like "mwstore://backend/container",
868 * "mwstore://backend/container/...", or null if there is no parent.
870 * @param $storagePath string
871 * @return string|null
873 final public static function parentStoragePath( $storagePath ) {
874 $storagePath = dirname( $storagePath );
875 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
876 return ( $rel === null ) ?
null : $storagePath;
880 * Get the final extension from a storage or FS path
882 * @param $path string
885 final public static function extensionFromPath( $path ) {
886 $i = strrpos( $path, '.' );
887 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
891 * Check if a relative path has no directory traversals
893 * @param $path string
897 final public static function isPathTraversalFree( $path ) {
898 return ( self
::normalizeContainerPath( $path ) !== null );
902 * Validate and normalize a relative storage path.
903 * Null is returned if the path involves directory traversal.
904 * Traversal is insecure for FS backends and broken for others.
906 * This uses the same traversal protection as Title::secureAndSplit().
908 * @param $path string Storage path relative to a container
909 * @return string|null
911 final protected static function normalizeContainerPath( $path ) {
912 // Normalize directory separators
913 $path = strtr( $path, '\\', '/' );
914 // Collapse any consecutive directory separators
915 $path = preg_replace( '![/]{2,}!', '/', $path );
916 // Remove any leading directory separator
917 $path = ltrim( $path, '/' );
918 // Use the same traversal protection as Title::secureAndSplit()
919 if ( strpos( $path, '.' ) !== false ) {
923 strpos( $path, './' ) === 0 ||
924 strpos( $path, '../' ) === 0 ||
925 strpos( $path, '/./' ) !== false ||
926 strpos( $path, '/../' ) !== false