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