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