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