Merge "Fix TOC display for printing"
[lhc/web/wiklou.git] / includes / filebackend / FileBackend.php
1 <?php
2 /**
3 * @defgroup FileBackend File backend
4 *
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
7 */
8
9 /**
10 * Base class for all file backends.
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
26 *
27 * @file
28 * @ingroup FileBackend
29 * @author Aaron Schulz
30 */
31
32 /**
33 * @brief Base class for all file backend classes (including multi-write backends).
34 *
35 * This class defines the methods as abstract that subclasses must implement.
36 * Outside callers can assume that all backends will have these functions.
37 *
38 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
39 * The "backend" portion is unique name for MediaWiki to refer to a backend, while
40 * the "container" portion is a top-level directory of the backend. The "path" portion
41 * is a relative path that uses UNIX file system (FS) notation, though any particular
42 * backend may not actually be using a local filesystem. Therefore, the relative paths
43 * are only virtual.
44 *
45 * Backend contents are stored under wiki-specific container names by default.
46 * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
47 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
48 * containers to ones that do not respect the "wiki ID".
49 *
50 * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
51 * FS-based backends are somewhat more restrictive due to the existence of real
52 * directory files; a regular file cannot have the same name as a directory. Other
53 * backends with virtual directories may not have this limitation. Callers should
54 * store files in such a way that no files and directories are under the same path.
55 *
56 * In general, this class allows for callers to access storage through the same
57 * interface, without regard to the underlying storage system. However, calling code
58 * must follow certain patterns and be aware of certain things to ensure compatibility:
59 * - a) Always call prepare() on the parent directory before trying to put a file there;
60 * key/value stores only need the container to exist first, but filesystems need
61 * all the parent directories to exist first (prepare() is aware of all this)
62 * - b) Always call clean() on a directory when it might become empty to avoid empty
63 * directory buildup on filesystems; key/value stores never have empty directories,
64 * so doing this helps preserve consistency in both cases
65 * - c) Likewise, do not rely on the existence of empty directories for anything;
66 * calling directoryExists() on a path that prepare() was previously called on
67 * will return false for key/value stores if there are no files under that path
68 * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
69 * either be a copy of the source file in /tmp or the original source file itself
70 * - e) Use a file layout that results in never attempting to store files over directories
71 * or directories over files; key/value stores allow this but filesystems do not
72 * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
73 * - g) Do not assume that move operations are atomic (difficult with key/value stores)
74 * - h) Do not assume that file stat or read operations always have immediate consistency;
75 * various methods have a "latest" flag that should always be used if up-to-date
76 * information is required (this trades performance for correctness as needed)
77 * - i) Do not assume that directory listings have immediate consistency
78 *
79 * Methods of subclasses should avoid throwing exceptions at all costs.
80 * As a corollary, external dependencies should be kept to a minimum.
81 *
82 * @ingroup FileBackend
83 * @since 1.19
84 */
85 abstract class FileBackend {
86 /** @var string Unique backend name */
87 protected $name;
88
89 /** @var string Unique wiki name */
90 protected $wikiId;
91
92 /** @var string Read-only explanation message */
93 protected $readOnly;
94
95 /** @var string When to do operations in parallel */
96 protected $parallelize;
97
98 /** @var int How many operations can be done in parallel */
99 protected $concurrency;
100
101 /** @var LockManager */
102 protected $lockManager;
103
104 /** @var FileJournal */
105 protected $fileJournal;
106
107 /**
108 * Create a new backend instance from configuration.
109 * This should only be called from within FileBackendGroup.
110 *
111 * @param array $config Parameters include:
112 * - name : The unique name of this backend.
113 * This should consist of alphanumberic, '-', and '_' characters.
114 * This name should not be changed after use (e.g. with journaling).
115 * Note that the name is *not* used in actual container names.
116 * - wikiId : Prefix to container names that is unique to this backend.
117 * It should only consist of alphanumberic, '-', and '_' characters.
118 * This ID is what avoids collisions if multiple logical backends
119 * use the same storage system, so this should be set carefully.
120 * - lockManager : LockManager object to use for any file locking.
121 * If not provided, then no file locking will be enforced.
122 * - fileJournal : FileJournal object to use for logging changes to files.
123 * If not provided, then change journaling will be disabled.
124 * - readOnly : Write operations are disallowed if this is a non-empty string.
125 * It should be an explanation for the backend being read-only.
126 * - parallelize : When to do file operations in parallel (when possible).
127 * Allowed values are "implicit", "explicit" and "off".
128 * - concurrency : How many file operations can be done in parallel.
129 * @throws FileBackendException
130 */
131 public function __construct( array $config ) {
132 $this->name = $config['name'];
133 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
134 throw new FileBackendException( "Backend name `{$this->name}` is invalid." );
135 }
136 if ( !isset( $config['wikiId'] ) ) {
137 $config['wikiId'] = wfWikiID();
138 wfDeprecated( __METHOD__ . ' called without "wikiID".', '1.23' );
139 }
140 if ( isset( $config['lockManager'] ) && !is_object( $config['lockManager'] ) ) {
141 $config['lockManager'] =
142 LockManagerGroup::singleton( $config['wikiId'] )->get( $config['lockManager'] );
143 wfDeprecated( __METHOD__ . ' called with non-object "lockManager".', '1.23' );
144 }
145 $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
146 $this->lockManager = isset( $config['lockManager'] )
147 ? $config['lockManager']
148 : new NullLockManager( array() );
149 $this->fileJournal = isset( $config['fileJournal'] )
150 ? $config['fileJournal']
151 : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
152 $this->readOnly = isset( $config['readOnly'] )
153 ? (string)$config['readOnly']
154 : '';
155 $this->parallelize = isset( $config['parallelize'] )
156 ? (string)$config['parallelize']
157 : 'off';
158 $this->concurrency = isset( $config['concurrency'] )
159 ? (int)$config['concurrency']
160 : 50;
161 }
162
163 /**
164 * Get the unique backend name.
165 * We may have multiple different backends of the same type.
166 * For example, we can have two Swift backends using different proxies.
167 *
168 * @return string
169 */
170 final public function getName() {
171 return $this->name;
172 }
173
174 /**
175 * Get the wiki identifier used for this backend (possibly empty).
176 * Note that this might *not* be in the same format as wfWikiID().
177 *
178 * @return string
179 * @since 1.20
180 */
181 final public function getWikiId() {
182 return $this->wikiId;
183 }
184
185 /**
186 * Check if this backend is read-only
187 *
188 * @return bool
189 */
190 final public function isReadOnly() {
191 return ( $this->readOnly != '' );
192 }
193
194 /**
195 * Get an explanatory message if this backend is read-only
196 *
197 * @return string|bool Returns false if the backend is not read-only
198 */
199 final public function getReadOnlyReason() {
200 return ( $this->readOnly != '' ) ? $this->readOnly : false;
201 }
202
203 /**
204 * This is the main entry point into the backend for write operations.
205 * Callers supply an ordered list of operations to perform as a transaction.
206 * Files will be locked, the stat cache cleared, and then the operations attempted.
207 * If any serious errors occur, all attempted operations will be rolled back.
208 *
209 * $ops is an array of arrays. The outer array holds a list of operations.
210 * Each inner array is a set of key value pairs that specify an operation.
211 *
212 * Supported operations and their parameters. The supported actions are:
213 * - create
214 * - store
215 * - copy
216 * - move
217 * - delete
218 * - describe (since 1.21)
219 * - null
220 *
221 * a) Create a new file in storage with the contents of a string
222 * @code
223 * array(
224 * 'op' => 'create',
225 * 'dst' => <storage path>,
226 * 'content' => <string of new file contents>,
227 * 'overwrite' => <boolean>,
228 * 'overwriteSame' => <boolean>,
229 * 'headers' => <HTTP header name/value map> # since 1.21
230 * );
231 * @endcode
232 *
233 * b) Copy a file system file into storage
234 * @code
235 * array(
236 * 'op' => 'store',
237 * 'src' => <file system path>,
238 * 'dst' => <storage path>,
239 * 'overwrite' => <boolean>,
240 * 'overwriteSame' => <boolean>,
241 * 'headers' => <HTTP header name/value map> # since 1.21
242 * )
243 * @endcode
244 *
245 * c) Copy a file within storage
246 * @code
247 * array(
248 * 'op' => 'copy',
249 * 'src' => <storage path>,
250 * 'dst' => <storage path>,
251 * 'overwrite' => <boolean>,
252 * 'overwriteSame' => <boolean>,
253 * 'ignoreMissingSource' => <boolean>, # since 1.21
254 * 'headers' => <HTTP header name/value map> # since 1.21
255 * )
256 * @endcode
257 *
258 * d) Move a file within storage
259 * @code
260 * array(
261 * 'op' => 'move',
262 * 'src' => <storage path>,
263 * 'dst' => <storage path>,
264 * 'overwrite' => <boolean>,
265 * 'overwriteSame' => <boolean>,
266 * 'ignoreMissingSource' => <boolean>, # since 1.21
267 * 'headers' => <HTTP header name/value map> # since 1.21
268 * )
269 * @endcode
270 *
271 * e) Delete a file within storage
272 * @code
273 * array(
274 * 'op' => 'delete',
275 * 'src' => <storage path>,
276 * 'ignoreMissingSource' => <boolean>
277 * )
278 * @endcode
279 *
280 * f) Update metadata for a file within storage
281 * @code
282 * array(
283 * 'op' => 'describe',
284 * 'src' => <storage path>,
285 * 'headers' => <HTTP header name/value map>
286 * )
287 * @endcode
288 *
289 * g) Do nothing (no-op)
290 * @code
291 * array(
292 * 'op' => 'null',
293 * )
294 * @endcode
295 *
296 * Boolean flags for operations (operation-specific):
297 * - ignoreMissingSource : The operation will simply succeed and do
298 * nothing if the source file does not exist.
299 * - overwrite : Any destination file will be overwritten.
300 * - overwriteSame : If a file already exists at the destination with the
301 * same contents, then do nothing to the destination file
302 * instead of giving an error. This does not compare headers.
303 * This option is ignored if 'overwrite' is already provided.
304 * - headers : If supplied, the result of merging these headers with any
305 * existing source file headers (replacing conflicting ones)
306 * will be set as the destination file headers. Headers are
307 * deleted if their value is set to the empty string. When a
308 * file has headers they are included in responses to GET and
309 * HEAD requests to the backing store for that file.
310 * Header values should be no larger than 255 bytes, except for
311 * Content-Disposition. The system might ignore or truncate any
312 * headers that are too long to store (exact limits will vary).
313 * Backends that don't support metadata ignore this. (since 1.21)
314 *
315 * $opts is an associative of boolean flags, including:
316 * - force : Operation precondition errors no longer trigger an abort.
317 * Any remaining operations are still attempted. Unexpected
318 * failures may still cause remaining operations to be aborted.
319 * - nonLocking : No locks are acquired for the operations.
320 * This can increase performance for non-critical writes.
321 * This has no effect unless the 'force' flag is set.
322 * - nonJournaled : Don't log this operation batch in the file journal.
323 * This limits the ability of recovery scripts.
324 * - parallelize : Try to do operations in parallel when possible.
325 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
326 * - preserveCache : Don't clear the process cache before checking files.
327 * This should only be used if all entries in the process
328 * cache were added after the files were already locked. (since 1.20)
329 *
330 * @remarks Remarks on locking:
331 * File system paths given to operations should refer to files that are
332 * already locked or otherwise safe from modification from other processes.
333 * Normally these files will be new temp files, which should be adequate.
334 *
335 * @par Return value:
336 *
337 * This returns a Status, which contains all warnings and fatals that occurred
338 * during the operation. The 'failCount', 'successCount', and 'success' members
339 * will reflect each operation attempted.
340 *
341 * The status will be "OK" unless:
342 * - a) unexpected operation errors occurred (network partitions, disk full...)
343 * - b) significant operation errors occurred and 'force' was not set
344 *
345 * @param array $ops List of operations to execute in order
346 * @param array $opts Batch operation options
347 * @return Status
348 */
349 final public function doOperations( array $ops, array $opts = array() ) {
350 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
351 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
352 }
353 if ( !count( $ops ) ) {
354 return Status::newGood(); // nothing to do
355 }
356 if ( empty( $opts['force'] ) ) { // sanity
357 unset( $opts['nonLocking'] );
358 }
359 foreach ( $ops as &$op ) {
360 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
361 $op['headers']['Content-Disposition'] = $op['disposition'];
362 }
363 }
364 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
365 return $this->doOperationsInternal( $ops, $opts );
366 }
367
368 /**
369 * @see FileBackend::doOperations()
370 */
371 abstract protected function doOperationsInternal( array $ops, array $opts );
372
373 /**
374 * Same as doOperations() except it takes a single operation.
375 * If you are doing a batch of operations that should either
376 * all succeed or all fail, then use that function instead.
377 *
378 * @see FileBackend::doOperations()
379 *
380 * @param array $op Operation
381 * @param array $opts Operation options
382 * @return Status
383 */
384 final public function doOperation( array $op, array $opts = array() ) {
385 return $this->doOperations( array( $op ), $opts );
386 }
387
388 /**
389 * Performs a single create operation.
390 * This sets $params['op'] to 'create' and passes it to doOperation().
391 *
392 * @see FileBackend::doOperation()
393 *
394 * @param array $params Operation parameters
395 * @param array $opts Operation options
396 * @return Status
397 */
398 final public function create( array $params, array $opts = array() ) {
399 return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
400 }
401
402 /**
403 * Performs a single store operation.
404 * This sets $params['op'] to 'store' and passes it to doOperation().
405 *
406 * @see FileBackend::doOperation()
407 *
408 * @param array $params Operation parameters
409 * @param array $opts Operation options
410 * @return Status
411 */
412 final public function store( array $params, array $opts = array() ) {
413 return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
414 }
415
416 /**
417 * Performs a single copy operation.
418 * This sets $params['op'] to 'copy' and passes it to doOperation().
419 *
420 * @see FileBackend::doOperation()
421 *
422 * @param array $params Operation parameters
423 * @param array $opts Operation options
424 * @return Status
425 */
426 final public function copy( array $params, array $opts = array() ) {
427 return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
428 }
429
430 /**
431 * Performs a single move operation.
432 * This sets $params['op'] to 'move' and passes it to doOperation().
433 *
434 * @see FileBackend::doOperation()
435 *
436 * @param array $params Operation parameters
437 * @param array $opts Operation options
438 * @return Status
439 */
440 final public function move( array $params, array $opts = array() ) {
441 return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
442 }
443
444 /**
445 * Performs a single delete operation.
446 * This sets $params['op'] to 'delete' and passes it to doOperation().
447 *
448 * @see FileBackend::doOperation()
449 *
450 * @param array $params Operation parameters
451 * @param array $opts Operation options
452 * @return Status
453 */
454 final public function delete( array $params, array $opts = array() ) {
455 return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
456 }
457
458 /**
459 * Performs a single describe operation.
460 * This sets $params['op'] to 'describe' and passes it to doOperation().
461 *
462 * @see FileBackend::doOperation()
463 *
464 * @param array $params Operation parameters
465 * @param array $opts Operation options
466 * @return Status
467 * @since 1.21
468 */
469 final public function describe( array $params, array $opts = array() ) {
470 return $this->doOperation( array( 'op' => 'describe' ) + $params, $opts );
471 }
472
473 /**
474 * Perform a set of independent file operations on some files.
475 *
476 * This does no locking, nor journaling, and possibly no stat calls.
477 * Any destination files that already exist will be overwritten.
478 * This should *only* be used on non-original files, like cache files.
479 *
480 * Supported operations and their parameters:
481 * - create
482 * - store
483 * - copy
484 * - move
485 * - delete
486 * - describe (since 1.21)
487 * - null
488 *
489 * a) Create a new file in storage with the contents of a string
490 * @code
491 * array(
492 * 'op' => 'create',
493 * 'dst' => <storage path>,
494 * 'content' => <string of new file contents>,
495 * 'headers' => <HTTP header name/value map> # since 1.21
496 * )
497 * @endcode
498 *
499 * b) Copy a file system file into storage
500 * @code
501 * array(
502 * 'op' => 'store',
503 * 'src' => <file system path>,
504 * 'dst' => <storage path>,
505 * 'headers' => <HTTP header name/value map> # since 1.21
506 * )
507 * @endcode
508 *
509 * c) Copy a file within storage
510 * @code
511 * array(
512 * 'op' => 'copy',
513 * 'src' => <storage path>,
514 * 'dst' => <storage path>,
515 * 'ignoreMissingSource' => <boolean>, # since 1.21
516 * 'headers' => <HTTP header name/value map> # since 1.21
517 * )
518 * @endcode
519 *
520 * d) Move a file within storage
521 * @code
522 * array(
523 * 'op' => 'move',
524 * 'src' => <storage path>,
525 * 'dst' => <storage path>,
526 * 'ignoreMissingSource' => <boolean>, # since 1.21
527 * 'headers' => <HTTP header name/value map> # since 1.21
528 * )
529 * @endcode
530 *
531 * e) Delete a file within storage
532 * @code
533 * array(
534 * 'op' => 'delete',
535 * 'src' => <storage path>,
536 * 'ignoreMissingSource' => <boolean>
537 * )
538 * @endcode
539 *
540 * f) Update metadata for a file within storage
541 * @code
542 * array(
543 * 'op' => 'describe',
544 * 'src' => <storage path>,
545 * 'headers' => <HTTP header name/value map>
546 * )
547 * @endcode
548 *
549 * g) Do nothing (no-op)
550 * @code
551 * array(
552 * 'op' => 'null',
553 * )
554 * @endcode
555 *
556 * @par Boolean flags for operations (operation-specific):
557 * - ignoreMissingSource : The operation will simply succeed and do
558 * nothing if the source file does not exist.
559 * - headers : If supplied with a header name/value map, the backend will
560 * reply with these headers when GETs/HEADs of the destination
561 * file are made. Header values should be smaller than 256 bytes.
562 * Content-Disposition headers can be longer, though the system
563 * might ignore or truncate ones that are too long to store.
564 * Existing headers will remain, but these will replace any
565 * conflicting previous headers, and headers will be removed
566 * if they are set to an empty string.
567 * Backends that don't support metadata ignore this. (since 1.21)
568 *
569 * $opts is an associative of boolean flags, including:
570 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
571 *
572 * @par Return value:
573 * This returns a Status, which contains all warnings and fatals that occurred
574 * during the operation. The 'failCount', 'successCount', and 'success' members
575 * will reflect each operation attempted for the given files. The status will be
576 * considered "OK" as long as no fatal errors occurred.
577 *
578 * @param array $ops Set of operations to execute
579 * @param array $opts Batch operation options
580 * @return Status
581 * @since 1.20
582 */
583 final public function doQuickOperations( array $ops, array $opts = array() ) {
584 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
585 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
586 }
587 if ( !count( $ops ) ) {
588 return Status::newGood(); // nothing to do
589 }
590 foreach ( $ops as &$op ) {
591 $op['overwrite'] = true; // avoids RTTs in key/value stores
592 if ( isset( $op['disposition'] ) ) { // b/c (MW 1.20)
593 $op['headers']['Content-Disposition'] = $op['disposition'];
594 }
595 }
596 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
597 return $this->doQuickOperationsInternal( $ops );
598 }
599
600 /**
601 * @see FileBackend::doQuickOperations()
602 * @since 1.20
603 */
604 abstract protected function doQuickOperationsInternal( array $ops );
605
606 /**
607 * Same as doQuickOperations() except it takes a single operation.
608 * If you are doing a batch of operations, then use that function instead.
609 *
610 * @see FileBackend::doQuickOperations()
611 *
612 * @param array $op Operation
613 * @return Status
614 * @since 1.20
615 */
616 final public function doQuickOperation( array $op ) {
617 return $this->doQuickOperations( array( $op ) );
618 }
619
620 /**
621 * Performs a single quick create operation.
622 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
623 *
624 * @see FileBackend::doQuickOperation()
625 *
626 * @param array $params Operation parameters
627 * @return Status
628 * @since 1.20
629 */
630 final public function quickCreate( array $params ) {
631 return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
632 }
633
634 /**
635 * Performs a single quick store operation.
636 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
637 *
638 * @see FileBackend::doQuickOperation()
639 *
640 * @param array $params Operation parameters
641 * @return Status
642 * @since 1.20
643 */
644 final public function quickStore( array $params ) {
645 return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
646 }
647
648 /**
649 * Performs a single quick copy operation.
650 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
651 *
652 * @see FileBackend::doQuickOperation()
653 *
654 * @param array $params Operation parameters
655 * @return Status
656 * @since 1.20
657 */
658 final public function quickCopy( array $params ) {
659 return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
660 }
661
662 /**
663 * Performs a single quick move operation.
664 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
665 *
666 * @see FileBackend::doQuickOperation()
667 *
668 * @param array $params Operation parameters
669 * @return Status
670 * @since 1.20
671 */
672 final public function quickMove( array $params ) {
673 return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
674 }
675
676 /**
677 * Performs a single quick delete operation.
678 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
679 *
680 * @see FileBackend::doQuickOperation()
681 *
682 * @param array $params Operation parameters
683 * @return Status
684 * @since 1.20
685 */
686 final public function quickDelete( array $params ) {
687 return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
688 }
689
690 /**
691 * Performs a single quick describe operation.
692 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
693 *
694 * @see FileBackend::doQuickOperation()
695 *
696 * @param array $params Operation parameters
697 * @return Status
698 * @since 1.21
699 */
700 final public function quickDescribe( array $params ) {
701 return $this->doQuickOperation( array( 'op' => 'describe' ) + $params );
702 }
703
704 /**
705 * Concatenate a list of storage files into a single file system file.
706 * The target path should refer to a file that is already locked or
707 * otherwise safe from modification from other processes. Normally,
708 * the file will be a new temp file, which should be adequate.
709 *
710 * @param array $params Operation parameters, include:
711 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
712 * - dst : file system path to 0-byte temp file
713 * - parallelize : try to do operations in parallel when possible
714 * @return Status
715 */
716 abstract public function concatenate( array $params );
717
718 /**
719 * Prepare a storage directory for usage.
720 * This will create any required containers and parent directories.
721 * Backends using key/value stores only need to create the container.
722 *
723 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
724 * except they are only applied *if* the directory/container had to be created.
725 * These flags should always be set for directories that have private files.
726 * However, setting them is not guaranteed to actually do anything.
727 * Additional server configuration may be needed to achieve the desired effect.
728 *
729 * @param array $params Parameters include:
730 * - dir : storage directory
731 * - noAccess : try to deny file access (since 1.20)
732 * - noListing : try to deny file listing (since 1.20)
733 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
734 * @return Status
735 */
736 final public function prepare( array $params ) {
737 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
738 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
739 }
740 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
741 return $this->doPrepare( $params );
742 }
743
744 /**
745 * @see FileBackend::prepare()
746 */
747 abstract protected function doPrepare( array $params );
748
749 /**
750 * Take measures to block web access to a storage directory and
751 * the container it belongs to. FS backends might add .htaccess
752 * files whereas key/value store backends might revoke container
753 * access to the storage user representing end-users in web requests.
754 *
755 * This is not guaranteed to actually make files or listings publically hidden.
756 * Additional server configuration may be needed to achieve the desired effect.
757 *
758 * @param array $params Parameters include:
759 * - dir : storage directory
760 * - noAccess : try to deny file access
761 * - noListing : try to deny file listing
762 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
763 * @return Status
764 */
765 final public function secure( array $params ) {
766 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
767 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
768 }
769 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
770 return $this->doSecure( $params );
771 }
772
773 /**
774 * @see FileBackend::secure()
775 */
776 abstract protected function doSecure( array $params );
777
778 /**
779 * Remove measures to block web access to a storage directory and
780 * the container it belongs to. FS backends might remove .htaccess
781 * files whereas key/value store backends might grant container
782 * access to the storage user representing end-users in web requests.
783 * This essentially can undo the result of secure() calls.
784 *
785 * This is not guaranteed to actually make files or listings publically viewable.
786 * Additional server configuration may be needed to achieve the desired effect.
787 *
788 * @param array $params Parameters include:
789 * - dir : storage directory
790 * - access : try to allow file access
791 * - listing : try to allow file listing
792 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
793 * @return Status
794 * @since 1.20
795 */
796 final public function publish( array $params ) {
797 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
798 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
799 }
800 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
801 return $this->doPublish( $params );
802 }
803
804 /**
805 * @see FileBackend::publish()
806 */
807 abstract protected function doPublish( array $params );
808
809 /**
810 * Delete a storage directory if it is empty.
811 * Backends using key/value stores may do nothing unless the directory
812 * is that of an empty container, in which case it will be deleted.
813 *
814 * @param array $params Parameters include:
815 * - dir : storage directory
816 * - recursive : recursively delete empty subdirectories first (since 1.20)
817 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
818 * @return Status
819 */
820 final public function clean( array $params ) {
821 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
822 return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
823 }
824 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
825 return $this->doClean( $params );
826 }
827
828 /**
829 * @see FileBackend::clean()
830 */
831 abstract protected function doClean( array $params );
832
833 /**
834 * Enter file operation scope.
835 * This just makes PHP ignore user aborts/disconnects until the return
836 * value leaves scope. This returns null and does nothing in CLI mode.
837 *
838 * @return ScopedCallback|null
839 */
840 final protected function getScopedPHPBehaviorForOps() {
841 if ( PHP_SAPI != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
842 $old = ignore_user_abort( true ); // avoid half-finished operations
843 return new ScopedCallback( function () use ( $old ) {
844 ignore_user_abort( $old );
845 } );
846 }
847
848 return null;
849 }
850
851 /**
852 * Check if a file exists at a storage path in the backend.
853 * This returns false if only a directory exists at the path.
854 *
855 * @param array $params Parameters include:
856 * - src : source storage path
857 * - latest : use the latest available data
858 * @return bool|null Returns null on failure
859 */
860 abstract public function fileExists( array $params );
861
862 /**
863 * Get the last-modified timestamp of the file at a storage path.
864 *
865 * @param array $params Parameters include:
866 * - src : source storage path
867 * - latest : use the latest available data
868 * @return string|bool TS_MW timestamp or false on failure
869 */
870 abstract public function getFileTimestamp( array $params );
871
872 /**
873 * Get the contents of a file at a storage path in the backend.
874 * This should be avoided for potentially large files.
875 *
876 * @param array $params Parameters include:
877 * - src : source storage path
878 * - latest : use the latest available data
879 * @return string|bool Returns false on failure
880 */
881 final public function getFileContents( array $params ) {
882 $contents = $this->getFileContentsMulti(
883 array( 'srcs' => array( $params['src'] ) ) + $params );
884
885 return $contents[$params['src']];
886 }
887
888 /**
889 * Like getFileContents() except it takes an array of storage paths
890 * and returns a map of storage paths to strings (or null on failure).
891 * The map keys (paths) are in the same order as the provided list of paths.
892 *
893 * @see FileBackend::getFileContents()
894 *
895 * @param array $params Parameters include:
896 * - srcs : list of source storage paths
897 * - latest : use the latest available data
898 * - parallelize : try to do operations in parallel when possible
899 * @return array Map of (path name => string or false on failure)
900 * @since 1.20
901 */
902 abstract public function getFileContentsMulti( array $params );
903
904 /**
905 * Get the size (bytes) of a file at a storage path in the backend.
906 *
907 * @param array $params Parameters include:
908 * - src : source storage path
909 * - latest : use the latest available data
910 * @return int|bool Returns false on failure
911 */
912 abstract public function getFileSize( array $params );
913
914 /**
915 * Get quick information about a file at a storage path in the backend.
916 * If the file does not exist, then this returns false.
917 * Otherwise, the result is an associative array that includes:
918 * - mtime : the last-modified timestamp (TS_MW)
919 * - size : the file size (bytes)
920 * Additional values may be included for internal use only.
921 *
922 * @param array $params Parameters include:
923 * - src : source storage path
924 * - latest : use the latest available data
925 * @return array|bool|null Returns null on failure
926 */
927 abstract public function getFileStat( array $params );
928
929 /**
930 * Get a SHA-1 hash of the file at a storage path in the backend.
931 *
932 * @param array $params Parameters include:
933 * - src : source storage path
934 * - latest : use the latest available data
935 * @return string|bool Hash string or false on failure
936 */
937 abstract public function getFileSha1Base36( array $params );
938
939 /**
940 * Get the properties of the file at a storage path in the backend.
941 * This gives the result of FSFile::getProps() on a local copy of the file.
942 *
943 * @param array $params Parameters include:
944 * - src : source storage path
945 * - latest : use the latest available data
946 * @return array Returns FSFile::placeholderProps() on failure
947 */
948 abstract public function getFileProps( array $params );
949
950 /**
951 * Stream the file at a storage path in the backend.
952 * If the file does not exists, an HTTP 404 error will be given.
953 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
954 * will be sent if streaming began, while none will be sent otherwise.
955 * Implementations should flush the output buffer before sending data.
956 *
957 * @param array $params Parameters include:
958 * - src : source storage path
959 * - headers : list of additional HTTP headers to send on success
960 * - latest : use the latest available data
961 * @return Status
962 */
963 abstract public function streamFile( array $params );
964
965 /**
966 * Returns a file system file, identical to the file at a storage path.
967 * The file returned is either:
968 * - a) A local copy of the file at a storage path in the backend.
969 * The temporary copy will have the same extension as the source.
970 * - b) An original of the file at a storage path in the backend.
971 * Temporary files may be purged when the file object falls out of scope.
972 *
973 * Write operations should *never* be done on this file as some backends
974 * may do internal tracking or may be instances of FileBackendMultiWrite.
975 * In that later case, there are copies of the file that must stay in sync.
976 * Additionally, further calls to this function may return the same file.
977 *
978 * @param array $params Parameters include:
979 * - src : source storage path
980 * - latest : use the latest available data
981 * @return FSFile|null Returns null on failure
982 */
983 final public function getLocalReference( array $params ) {
984 $fsFiles = $this->getLocalReferenceMulti(
985 array( 'srcs' => array( $params['src'] ) ) + $params );
986
987 return $fsFiles[$params['src']];
988 }
989
990 /**
991 * Like getLocalReference() except it takes an array of storage paths
992 * and returns a map of storage paths to FSFile objects (or null on failure).
993 * The map keys (paths) are in the same order as the provided list of paths.
994 *
995 * @see FileBackend::getLocalReference()
996 *
997 * @param array $params Parameters include:
998 * - srcs : list of source storage paths
999 * - latest : use the latest available data
1000 * - parallelize : try to do operations in parallel when possible
1001 * @return array Map of (path name => FSFile or null on failure)
1002 * @since 1.20
1003 */
1004 abstract public function getLocalReferenceMulti( array $params );
1005
1006 /**
1007 * Get a local copy on disk of the file at a storage path in the backend.
1008 * The temporary copy will have the same file extension as the source.
1009 * Temporary files may be purged when the file object falls out of scope.
1010 *
1011 * @param array $params Parameters include:
1012 * - src : source storage path
1013 * - latest : use the latest available data
1014 * @return TempFSFile|null Returns null on failure
1015 */
1016 final public function getLocalCopy( array $params ) {
1017 $tmpFiles = $this->getLocalCopyMulti(
1018 array( 'srcs' => array( $params['src'] ) ) + $params );
1019
1020 return $tmpFiles[$params['src']];
1021 }
1022
1023 /**
1024 * Like getLocalCopy() except it takes an array of storage paths and
1025 * returns a map of storage paths to TempFSFile objects (or null on failure).
1026 * The map keys (paths) are in the same order as the provided list of paths.
1027 *
1028 * @see FileBackend::getLocalCopy()
1029 *
1030 * @param array $params Parameters include:
1031 * - srcs : list of source storage paths
1032 * - latest : use the latest available data
1033 * - parallelize : try to do operations in parallel when possible
1034 * @return array Map of (path name => TempFSFile or null on failure)
1035 * @since 1.20
1036 */
1037 abstract public function getLocalCopyMulti( array $params );
1038
1039 /**
1040 * Return an HTTP URL to a given file that requires no authentication to use.
1041 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1042 * This will return null if the backend cannot make an HTTP URL for the file.
1043 *
1044 * This is useful for key/value stores when using scripts that seek around
1045 * large files and those scripts (and the backend) support HTTP Range headers.
1046 * Otherwise, one would need to use getLocalReference(), which involves loading
1047 * the entire file on to local disk.
1048 *
1049 * @param array $params Parameters include:
1050 * - src : source storage path
1051 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1052 * @return string|null
1053 * @since 1.21
1054 */
1055 abstract public function getFileHttpUrl( array $params );
1056
1057 /**
1058 * Check if a directory exists at a given storage path.
1059 * Backends using key/value stores will check if the path is a
1060 * virtual directory, meaning there are files under the given directory.
1061 *
1062 * Storage backends with eventual consistency might return stale data.
1063 *
1064 * @param array $params Parameters include:
1065 * - dir : storage directory
1066 * @return bool|null Returns null on failure
1067 * @since 1.20
1068 */
1069 abstract public function directoryExists( array $params );
1070
1071 /**
1072 * Get an iterator to list *all* directories under a storage directory.
1073 * If the directory is of the form "mwstore://backend/container",
1074 * then all directories in the container will be listed.
1075 * If the directory is of form "mwstore://backend/container/dir",
1076 * then all directories directly under that directory will be listed.
1077 * Results will be storage directories relative to the given directory.
1078 *
1079 * Storage backends with eventual consistency might return stale data.
1080 *
1081 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1082 *
1083 * @param array $params Parameters include:
1084 * - dir : storage directory
1085 * - topOnly : only return direct child dirs of the directory
1086 * @return Traversable|Array|null Returns null on failure
1087 * @since 1.20
1088 */
1089 abstract public function getDirectoryList( array $params );
1090
1091 /**
1092 * Same as FileBackend::getDirectoryList() except only lists
1093 * directories that are immediately under the given directory.
1094 *
1095 * Storage backends with eventual consistency might return stale data.
1096 *
1097 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1098 *
1099 * @param array $params Parameters include:
1100 * - dir : storage directory
1101 * @return Traversable|Array|null Returns null on failure
1102 * @since 1.20
1103 */
1104 final public function getTopDirectoryList( array $params ) {
1105 return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
1106 }
1107
1108 /**
1109 * Get an iterator to list *all* stored files under a storage directory.
1110 * If the directory is of the form "mwstore://backend/container",
1111 * then all files in the container will be listed.
1112 * If the directory is of form "mwstore://backend/container/dir",
1113 * then all files under that directory will be listed.
1114 * Results will be storage paths relative to the given directory.
1115 *
1116 * Storage backends with eventual consistency might return stale data.
1117 *
1118 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1119 *
1120 * @param array $params Parameters include:
1121 * - dir : storage directory
1122 * - topOnly : only return direct child files of the directory (since 1.20)
1123 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1124 * @return Traversable|Array|null Returns null on failure
1125 */
1126 abstract public function getFileList( array $params );
1127
1128 /**
1129 * Same as FileBackend::getFileList() except only lists
1130 * files that are immediately under the given directory.
1131 *
1132 * Storage backends with eventual consistency might return stale data.
1133 *
1134 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1135 *
1136 * @param array $params Parameters include:
1137 * - dir : storage directory
1138 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1139 * @return Traversable|Array|null Returns null on failure
1140 * @since 1.20
1141 */
1142 final public function getTopFileList( array $params ) {
1143 return $this->getFileList( array( 'topOnly' => true ) + $params );
1144 }
1145
1146 /**
1147 * Preload persistent file stat and property cache into in-process cache.
1148 * This should be used when stat calls will be made on a known list of a many files.
1149 *
1150 * @param array $paths Storage paths
1151 */
1152 public function preloadCache( array $paths ) {
1153 }
1154
1155 /**
1156 * Invalidate any in-process file stat and property cache.
1157 * If $paths is given, then only the cache for those files will be cleared.
1158 *
1159 * @param array $paths Storage paths (optional)
1160 */
1161 public function clearCache( array $paths = null ) {
1162 }
1163
1164 /**
1165 * Lock the files at the given storage paths in the backend.
1166 * This will either lock all the files or none (on failure).
1167 *
1168 * Callers should consider using getScopedFileLocks() instead.
1169 *
1170 * @param array $paths Storage paths
1171 * @param int $type LockManager::LOCK_* constant
1172 * @return Status
1173 */
1174 final public function lockFiles( array $paths, $type ) {
1175 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1176
1177 return $this->lockManager->lock( $paths, $type );
1178 }
1179
1180 /**
1181 * Unlock the files at the given storage paths in the backend.
1182 *
1183 * @param array $paths Storage paths
1184 * @param int $type LockManager::LOCK_* constant
1185 * @return Status
1186 */
1187 final public function unlockFiles( array $paths, $type ) {
1188 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1189
1190 return $this->lockManager->unlock( $paths, $type );
1191 }
1192
1193 /**
1194 * Lock the files at the given storage paths in the backend.
1195 * This will either lock all the files or none (on failure).
1196 * On failure, the status object will be updated with errors.
1197 *
1198 * Once the return value goes out scope, the locks will be released and
1199 * the status updated. Unlock fatals will not change the status "OK" value.
1200 *
1201 * @see ScopedLock::factory()
1202 *
1203 * @param array $paths List of storage paths or map of lock types to path lists
1204 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1205 * @param Status $status Status to update on lock/unlock
1206 * @return ScopedLock|null Returns null on failure
1207 */
1208 final public function getScopedFileLocks( array $paths, $type, Status $status ) {
1209 if ( $type === 'mixed' ) {
1210 foreach ( $paths as &$typePaths ) {
1211 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1212 }
1213 } else {
1214 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1215 }
1216
1217 return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
1218 }
1219
1220 /**
1221 * Get an array of scoped locks needed for a batch of file operations.
1222 *
1223 * Normally, FileBackend::doOperations() handles locking, unless
1224 * the 'nonLocking' param is passed in. This function is useful if you
1225 * want the files to be locked for a broader scope than just when the
1226 * files are changing. For example, if you need to update DB metadata,
1227 * you may want to keep the files locked until finished.
1228 *
1229 * @see FileBackend::doOperations()
1230 *
1231 * @param array $ops List of file operations to FileBackend::doOperations()
1232 * @param Status $status Status to update on lock/unlock
1233 * @return array List of ScopedFileLocks or null values
1234 * @since 1.20
1235 */
1236 abstract public function getScopedLocksForOps( array $ops, Status $status );
1237
1238 /**
1239 * Get the root storage path of this backend.
1240 * All container paths are "subdirectories" of this path.
1241 *
1242 * @return string Storage path
1243 * @since 1.20
1244 */
1245 final public function getRootStoragePath() {
1246 return "mwstore://{$this->name}";
1247 }
1248
1249 /**
1250 * Get the storage path for the given container for this backend
1251 *
1252 * @param string $container Container name
1253 * @return string Storage path
1254 * @since 1.21
1255 */
1256 final public function getContainerStoragePath( $container ) {
1257 return $this->getRootStoragePath() . "/{$container}";
1258 }
1259
1260 /**
1261 * Get the file journal object for this backend
1262 *
1263 * @return FileJournal
1264 */
1265 final public function getJournal() {
1266 return $this->fileJournal;
1267 }
1268
1269 /**
1270 * Check if a given path is a "mwstore://" path.
1271 * This does not do any further validation or any existence checks.
1272 *
1273 * @param string $path
1274 * @return bool
1275 */
1276 final public static function isStoragePath( $path ) {
1277 return ( strpos( $path, 'mwstore://' ) === 0 );
1278 }
1279
1280 /**
1281 * Split a storage path into a backend name, a container name,
1282 * and a relative file path. The relative path may be the empty string.
1283 * This does not do any path normalization or traversal checks.
1284 *
1285 * @param string $storagePath
1286 * @return array (backend, container, rel object) or (null, null, null)
1287 */
1288 final public static function splitStoragePath( $storagePath ) {
1289 if ( self::isStoragePath( $storagePath ) ) {
1290 // Remove the "mwstore://" prefix and split the path
1291 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1292 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1293 if ( count( $parts ) == 3 ) {
1294 return $parts; // e.g. "backend/container/path"
1295 } else {
1296 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1297 }
1298 }
1299 }
1300
1301 return array( null, null, null );
1302 }
1303
1304 /**
1305 * Normalize a storage path by cleaning up directory separators.
1306 * Returns null if the path is not of the format of a valid storage path.
1307 *
1308 * @param string $storagePath
1309 * @return string|null
1310 */
1311 final public static function normalizeStoragePath( $storagePath ) {
1312 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1313 if ( $relPath !== null ) { // must be for this backend
1314 $relPath = self::normalizeContainerPath( $relPath );
1315 if ( $relPath !== null ) {
1316 return ( $relPath != '' )
1317 ? "mwstore://{$backend}/{$container}/{$relPath}"
1318 : "mwstore://{$backend}/{$container}";
1319 }
1320 }
1321
1322 return null;
1323 }
1324
1325 /**
1326 * Get the parent storage directory of a storage path.
1327 * This returns a path like "mwstore://backend/container",
1328 * "mwstore://backend/container/...", or null if there is no parent.
1329 *
1330 * @param string $storagePath
1331 * @return string|null
1332 */
1333 final public static function parentStoragePath( $storagePath ) {
1334 $storagePath = dirname( $storagePath );
1335 list( , , $rel ) = self::splitStoragePath( $storagePath );
1336
1337 return ( $rel === null ) ? null : $storagePath;
1338 }
1339
1340 /**
1341 * Get the final extension from a storage or FS path
1342 *
1343 * @param string $path
1344 * @return string
1345 */
1346 final public static function extensionFromPath( $path ) {
1347 $i = strrpos( $path, '.' );
1348
1349 return strtolower( $i ? substr( $path, $i + 1 ) : '' );
1350 }
1351
1352 /**
1353 * Check if a relative path has no directory traversals
1354 *
1355 * @param string $path
1356 * @return bool
1357 * @since 1.20
1358 */
1359 final public static function isPathTraversalFree( $path ) {
1360 return ( self::normalizeContainerPath( $path ) !== null );
1361 }
1362
1363 /**
1364 * Build a Content-Disposition header value per RFC 6266.
1365 *
1366 * @param string $type One of (attachment, inline)
1367 * @param string $filename Suggested file name (should not contain slashes)
1368 * @throws FileBackendError
1369 * @return string
1370 * @since 1.20
1371 */
1372 final public static function makeContentDisposition( $type, $filename = '' ) {
1373 $parts = array();
1374
1375 $type = strtolower( $type );
1376 if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
1377 throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
1378 }
1379 $parts[] = $type;
1380
1381 if ( strlen( $filename ) ) {
1382 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1383 }
1384
1385 return implode( ';', $parts );
1386 }
1387
1388 /**
1389 * Validate and normalize a relative storage path.
1390 * Null is returned if the path involves directory traversal.
1391 * Traversal is insecure for FS backends and broken for others.
1392 *
1393 * This uses the same traversal protection as Title::secureAndSplit().
1394 *
1395 * @param string $path Storage path relative to a container
1396 * @return string|null
1397 */
1398 final protected static function normalizeContainerPath( $path ) {
1399 // Normalize directory separators
1400 $path = strtr( $path, '\\', '/' );
1401 // Collapse any consecutive directory separators
1402 $path = preg_replace( '![/]{2,}!', '/', $path );
1403 // Remove any leading directory separator
1404 $path = ltrim( $path, '/' );
1405 // Use the same traversal protection as Title::secureAndSplit()
1406 if ( strpos( $path, '.' ) !== false ) {
1407 if (
1408 $path === '.' ||
1409 $path === '..' ||
1410 strpos( $path, './' ) === 0 ||
1411 strpos( $path, '../' ) === 0 ||
1412 strpos( $path, '/./' ) !== false ||
1413 strpos( $path, '/../' ) !== false
1414 ) {
1415 return null;
1416 }
1417 }
1418
1419 return $path;
1420 }
1421 }
1422
1423 /**
1424 * Generic file backend exception for checked and unexpected (e.g. config) exceptions
1425 *
1426 * @ingroup FileBackend
1427 * @since 1.23
1428 */
1429 class FileBackendException extends MWException {
1430 }
1431
1432 /**
1433 * File backend exception for checked exceptions (e.g. I/O errors)
1434 *
1435 * @ingroup FileBackend
1436 * @since 1.22
1437 */
1438 class FileBackendError extends FileBackendException {
1439 }