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