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