3 * @defgroup FileBackend File backend
5 * File backend is used to interact with file storage systems,
6 * such as the local file system, NFS, or cloud storage systems.
10 * Base class for all file backends.
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.
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.
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
28 * @ingroup FileBackend
30 use Psr\Log\LoggerAwareInterface
;
31 use Psr\Log\LoggerInterface
;
32 use Wikimedia\ScopedCallback
;
35 * @brief Base class for all file backend classes (including multi-write backends).
37 * This class defines the methods as abstract that subclasses must implement.
38 * Outside callers can assume that all backends will have these functions.
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
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.
54 * For legacy reasons, the FSFileBackend class allows manually setting the paths of
55 * containers to ones that do not respect the "domain ID".
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.
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
86 * Methods of subclasses should avoid throwing exceptions at all costs.
87 * As a corollary, external dependencies should be kept to a minimum.
89 * @ingroup FileBackend
92 abstract class FileBackend
implements LoggerAwareInterface
{
93 /** @var string Unique backend name */
96 /** @var string Unique domain name */
99 /** @var string Read-only explanation message */
102 /** @var string When to do operations in parallel */
103 protected $parallelize;
105 /** @var int How many operations can be done in parallel */
106 protected $concurrency;
108 /** @var string Temporary file directory */
109 protected $tmpDirectory;
111 /** @var LockManager */
112 protected $lockManager;
113 /** @var FileJournal */
114 protected $fileJournal;
115 /** @var LoggerInterface */
117 /** @var object|string Class name or object With profileIn/profileOut methods */
121 protected $obResetFunc;
123 protected $streamMimeFunc;
125 protected $statusWrapper;
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)
133 * Create a new backend instance from configuration.
134 * This should only be called from within FileBackendGroup.
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
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}'." );
173 $this->lockManager
= $config['lockManager'] ??
new NullLockManager( [] );
174 $this->fileJournal
= $config['fileJournal']
175 ?? FileJournal
::factory( [ 'class' => NullFileJournal
::class ], $this->name
);
176 $this->readOnly
= isset( $config['readOnly'] )
177 ?
(string)$config['readOnly']
179 $this->parallelize
= isset( $config['parallelize'] )
180 ?
(string)$config['parallelize']
182 $this->concurrency
= isset( $config['concurrency'] )
183 ?
(int)$config['concurrency']
185 $this->obResetFunc
= $config['obResetFunc'] ??
[ $this, 'resetOutputBuffer' ];
186 $this->streamMimeFunc
= $config['streamMimeFunc'] ??
null;
187 $this->statusWrapper
= $config['statusWrapper'] ??
null;
189 $this->profiler
= $config['profiler'] ??
null;
190 $this->logger
= $config['logger'] ??
new \Psr\Log\
NullLogger();
191 $this->statusWrapper
= $config['statusWrapper'] ??
null;
192 $this->tmpDirectory
= $config['tmpDirectory'] ??
null;
195 public function setLogger( LoggerInterface
$logger ) {
196 $this->logger
= $logger;
200 * Get the unique backend name.
201 * We may have multiple different backends of the same type.
202 * For example, we can have two Swift backends using different proxies.
206 final public function getName() {
211 * Get the domain identifier used for this backend (possibly empty).
216 final public function getDomainId() {
217 return $this->domainId
;
221 * Alias to getDomainId()
225 final public function getWikiId() {
226 return $this->getDomainId();
230 * Check if this backend is read-only
234 final public function isReadOnly() {
235 return ( $this->readOnly
!= '' );
239 * Get an explanatory message if this backend is read-only
241 * @return string|bool Returns false if the backend is not read-only
243 final public function getReadOnlyReason() {
244 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
248 * Get the a bitfield of extra features supported by the backend medium
250 * @return int Bitfield of FileBackend::ATTR_* flags
253 public function getFeatures() {
254 return self
::ATTR_UNICODE_PATHS
;
258 * Check if the backend medium supports a field of extra features
260 * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
264 final public function hasFeatures( $bitfield ) {
265 return ( $this->getFeatures() & $bitfield ) === $bitfield;
269 * This is the main entry point into the backend for write operations.
270 * Callers supply an ordered list of operations to perform as a transaction.
271 * Files will be locked, the stat cache cleared, and then the operations attempted.
272 * If any serious errors occur, all attempted operations will be rolled back.
274 * $ops is an array of arrays. The outer array holds a list of operations.
275 * Each inner array is a set of key value pairs that specify an operation.
277 * Supported operations and their parameters. The supported actions are:
283 * - describe (since 1.21)
286 * FSFile/TempFSFile object support was added in 1.27.
288 * a) Create a new file in storage with the contents of a string
292 * 'dst' => <storage path>,
293 * 'content' => <string of new file contents>,
294 * 'overwrite' => <boolean>,
295 * 'overwriteSame' => <boolean>,
296 * 'headers' => <HTTP header name/value map> # since 1.21
300 * b) Copy a file system file into storage
304 * 'src' => <file system path, FSFile, or TempFSFile>,
305 * 'dst' => <storage path>,
306 * 'overwrite' => <boolean>,
307 * 'overwriteSame' => <boolean>,
308 * 'headers' => <HTTP header name/value map> # since 1.21
312 * c) Copy a file within storage
316 * 'src' => <storage path>,
317 * 'dst' => <storage path>,
318 * 'overwrite' => <boolean>,
319 * 'overwriteSame' => <boolean>,
320 * 'ignoreMissingSource' => <boolean>, # since 1.21
321 * 'headers' => <HTTP header name/value map> # since 1.21
325 * d) Move a file within storage
329 * 'src' => <storage path>,
330 * 'dst' => <storage path>,
331 * 'overwrite' => <boolean>,
332 * 'overwriteSame' => <boolean>,
333 * 'ignoreMissingSource' => <boolean>, # since 1.21
334 * 'headers' => <HTTP header name/value map> # since 1.21
338 * e) Delete a file within storage
342 * 'src' => <storage path>,
343 * 'ignoreMissingSource' => <boolean>
347 * f) Update metadata for a file within storage
350 * 'op' => 'describe',
351 * 'src' => <storage path>,
352 * 'headers' => <HTTP header name/value map>
356 * g) Do nothing (no-op)
363 * Boolean flags for operations (operation-specific):
364 * - ignoreMissingSource : The operation will simply succeed and do
365 * nothing if the source file does not exist.
366 * - overwrite : Any destination file will be overwritten.
367 * - overwriteSame : If a file already exists at the destination with the
368 * same contents, then do nothing to the destination file
369 * instead of giving an error. This does not compare headers.
370 * This option is ignored if 'overwrite' is already provided.
371 * - headers : If supplied, the result of merging these headers with any
372 * existing source file headers (replacing conflicting ones)
373 * will be set as the destination file headers. Headers are
374 * deleted if their value is set to the empty string. When a
375 * file has headers they are included in responses to GET and
376 * HEAD requests to the backing store for that file.
377 * Header values should be no larger than 255 bytes, except for
378 * Content-Disposition. The system might ignore or truncate any
379 * headers that are too long to store (exact limits will vary).
380 * Backends that don't support metadata ignore this. (since 1.21)
382 * $opts is an associative of boolean flags, including:
383 * - force : Operation precondition errors no longer trigger an abort.
384 * Any remaining operations are still attempted. Unexpected
385 * failures may still cause remaining operations to be aborted.
386 * - nonLocking : No locks are acquired for the operations.
387 * This can increase performance for non-critical writes.
388 * This has no effect unless the 'force' flag is set.
389 * - nonJournaled : Don't log this operation batch in the file journal.
390 * This limits the ability of recovery scripts.
391 * - parallelize : Try to do operations in parallel when possible.
392 * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
393 * - preserveCache : Don't clear the process cache before checking files.
394 * This should only be used if all entries in the process
395 * cache were added after the files were already locked. (since 1.20)
397 * @remarks Remarks on locking:
398 * File system paths given to operations should refer to files that are
399 * already locked or otherwise safe from modification from other processes.
400 * Normally these files will be new temp files, which should be adequate.
404 * This returns a Status, which contains all warnings and fatals that occurred
405 * during the operation. The 'failCount', 'successCount', and 'success' members
406 * will reflect each operation attempted.
408 * The StatusValue will be "OK" unless:
409 * - a) unexpected operation errors occurred (network partitions, disk full...)
410 * - b) significant operation errors occurred and 'force' was not set
412 * @param array $ops List of operations to execute in order
413 * @param array $opts Batch operation options
414 * @return StatusValue
416 final public function doOperations( array $ops, array $opts = [] ) {
417 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
418 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
420 if ( !count( $ops ) ) {
421 return $this->newStatus(); // nothing to do
424 $ops = $this->resolveFSFileObjects( $ops );
425 if ( empty( $opts['force'] ) ) { // sanity
426 unset( $opts['nonLocking'] );
429 /** @noinspection PhpUnusedLocalVariableInspection */
430 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
432 return $this->doOperationsInternal( $ops, $opts );
436 * @see FileBackend::doOperations()
440 abstract protected function doOperationsInternal( array $ops, array $opts );
443 * Same as doOperations() except it takes a single operation.
444 * If you are doing a batch of operations that should either
445 * all succeed or all fail, then use that function instead.
447 * @see FileBackend::doOperations()
449 * @param array $op Operation
450 * @param array $opts Operation options
451 * @return StatusValue
453 final public function doOperation( array $op, array $opts = [] ) {
454 return $this->doOperations( [ $op ], $opts );
458 * Performs a single create operation.
459 * This sets $params['op'] to 'create' and passes it to doOperation().
461 * @see FileBackend::doOperation()
463 * @param array $params Operation parameters
464 * @param array $opts Operation options
465 * @return StatusValue
467 final public function create( array $params, array $opts = [] ) {
468 return $this->doOperation( [ 'op' => 'create' ] +
$params, $opts );
472 * Performs a single store operation.
473 * This sets $params['op'] to 'store' and passes it to doOperation().
475 * @see FileBackend::doOperation()
477 * @param array $params Operation parameters
478 * @param array $opts Operation options
479 * @return StatusValue
481 final public function store( array $params, array $opts = [] ) {
482 return $this->doOperation( [ 'op' => 'store' ] +
$params, $opts );
486 * Performs a single copy operation.
487 * This sets $params['op'] to 'copy' and passes it to doOperation().
489 * @see FileBackend::doOperation()
491 * @param array $params Operation parameters
492 * @param array $opts Operation options
493 * @return StatusValue
495 final public function copy( array $params, array $opts = [] ) {
496 return $this->doOperation( [ 'op' => 'copy' ] +
$params, $opts );
500 * Performs a single move operation.
501 * This sets $params['op'] to 'move' and passes it to doOperation().
503 * @see FileBackend::doOperation()
505 * @param array $params Operation parameters
506 * @param array $opts Operation options
507 * @return StatusValue
509 final public function move( array $params, array $opts = [] ) {
510 return $this->doOperation( [ 'op' => 'move' ] +
$params, $opts );
514 * Performs a single delete operation.
515 * This sets $params['op'] to 'delete' and passes it to doOperation().
517 * @see FileBackend::doOperation()
519 * @param array $params Operation parameters
520 * @param array $opts Operation options
521 * @return StatusValue
523 final public function delete( array $params, array $opts = [] ) {
524 return $this->doOperation( [ 'op' => 'delete' ] +
$params, $opts );
528 * Performs a single describe operation.
529 * This sets $params['op'] to 'describe' and passes it to doOperation().
531 * @see FileBackend::doOperation()
533 * @param array $params Operation parameters
534 * @param array $opts Operation options
535 * @return StatusValue
538 final public function describe( array $params, array $opts = [] ) {
539 return $this->doOperation( [ 'op' => 'describe' ] +
$params, $opts );
543 * Perform a set of independent file operations on some files.
545 * This does no locking, nor journaling, and possibly no stat calls.
546 * Any destination files that already exist will be overwritten.
547 * This should *only* be used on non-original files, like cache files.
549 * Supported operations and their parameters:
555 * - describe (since 1.21)
558 * FSFile/TempFSFile object support was added in 1.27.
560 * a) Create a new file in storage with the contents of a string
564 * 'dst' => <storage path>,
565 * 'content' => <string of new file contents>,
566 * 'headers' => <HTTP header name/value map> # since 1.21
570 * b) Copy a file system file into storage
574 * 'src' => <file system path, FSFile, or TempFSFile>,
575 * 'dst' => <storage path>,
576 * 'headers' => <HTTP header name/value map> # since 1.21
580 * c) Copy a file within storage
584 * 'src' => <storage path>,
585 * 'dst' => <storage path>,
586 * 'ignoreMissingSource' => <boolean>, # since 1.21
587 * 'headers' => <HTTP header name/value map> # since 1.21
591 * d) Move a file within storage
595 * 'src' => <storage path>,
596 * 'dst' => <storage path>,
597 * 'ignoreMissingSource' => <boolean>, # since 1.21
598 * 'headers' => <HTTP header name/value map> # since 1.21
602 * e) Delete a file within storage
606 * 'src' => <storage path>,
607 * 'ignoreMissingSource' => <boolean>
611 * f) Update metadata for a file within storage
614 * 'op' => 'describe',
615 * 'src' => <storage path>,
616 * 'headers' => <HTTP header name/value map>
620 * g) Do nothing (no-op)
627 * @par Boolean flags for operations (operation-specific):
628 * - ignoreMissingSource : The operation will simply succeed and do
629 * nothing if the source file does not exist.
630 * - headers : If supplied with a header name/value map, the backend will
631 * reply with these headers when GETs/HEADs of the destination
632 * file are made. Header values should be smaller than 256 bytes.
633 * Content-Disposition headers can be longer, though the system
634 * might ignore or truncate ones that are too long to store.
635 * Existing headers will remain, but these will replace any
636 * conflicting previous headers, and headers will be removed
637 * if they are set to an empty string.
638 * Backends that don't support metadata ignore this. (since 1.21)
640 * $opts is an associative of boolean flags, including:
641 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
644 * This returns a Status, which contains all warnings and fatals that occurred
645 * during the operation. The 'failCount', 'successCount', and 'success' members
646 * will reflect each operation attempted for the given files. The StatusValue will be
647 * considered "OK" as long as no fatal errors occurred.
649 * @param array $ops Set of operations to execute
650 * @param array $opts Batch operation options
651 * @return StatusValue
654 final public function doQuickOperations( array $ops, array $opts = [] ) {
655 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
656 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
658 if ( !count( $ops ) ) {
659 return $this->newStatus(); // nothing to do
662 $ops = $this->resolveFSFileObjects( $ops );
663 foreach ( $ops as &$op ) {
664 $op['overwrite'] = true; // avoids RTTs in key/value stores
667 /** @noinspection PhpUnusedLocalVariableInspection */
668 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
670 return $this->doQuickOperationsInternal( $ops );
674 * @see FileBackend::doQuickOperations()
678 abstract protected function doQuickOperationsInternal( array $ops );
681 * Same as doQuickOperations() except it takes a single operation.
682 * If you are doing a batch of operations, then use that function instead.
684 * @see FileBackend::doQuickOperations()
686 * @param array $op Operation
687 * @return StatusValue
690 final public function doQuickOperation( array $op ) {
691 return $this->doQuickOperations( [ $op ] );
695 * Performs a single quick create operation.
696 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
698 * @see FileBackend::doQuickOperation()
700 * @param array $params Operation parameters
701 * @return StatusValue
704 final public function quickCreate( array $params ) {
705 return $this->doQuickOperation( [ 'op' => 'create' ] +
$params );
709 * Performs a single quick store operation.
710 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
712 * @see FileBackend::doQuickOperation()
714 * @param array $params Operation parameters
715 * @return StatusValue
718 final public function quickStore( array $params ) {
719 return $this->doQuickOperation( [ 'op' => 'store' ] +
$params );
723 * Performs a single quick copy operation.
724 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
726 * @see FileBackend::doQuickOperation()
728 * @param array $params Operation parameters
729 * @return StatusValue
732 final public function quickCopy( array $params ) {
733 return $this->doQuickOperation( [ 'op' => 'copy' ] +
$params );
737 * Performs a single quick move operation.
738 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
740 * @see FileBackend::doQuickOperation()
742 * @param array $params Operation parameters
743 * @return StatusValue
746 final public function quickMove( array $params ) {
747 return $this->doQuickOperation( [ 'op' => 'move' ] +
$params );
751 * Performs a single quick delete operation.
752 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
754 * @see FileBackend::doQuickOperation()
756 * @param array $params Operation parameters
757 * @return StatusValue
760 final public function quickDelete( array $params ) {
761 return $this->doQuickOperation( [ 'op' => 'delete' ] +
$params );
765 * Performs a single quick describe operation.
766 * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
768 * @see FileBackend::doQuickOperation()
770 * @param array $params Operation parameters
771 * @return StatusValue
774 final public function quickDescribe( array $params ) {
775 return $this->doQuickOperation( [ 'op' => 'describe' ] +
$params );
779 * Concatenate a list of storage files into a single file system file.
780 * The target path should refer to a file that is already locked or
781 * otherwise safe from modification from other processes. Normally,
782 * the file will be a new temp file, which should be adequate.
784 * @param array $params Operation parameters, include:
785 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
786 * - dst : file system path to 0-byte temp file
787 * - parallelize : try to do operations in parallel when possible
788 * @return StatusValue
790 abstract public function concatenate( array $params );
793 * Prepare a storage directory for usage.
794 * This will create any required containers and parent directories.
795 * Backends using key/value stores only need to create the container.
797 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
798 * except they are only applied *if* the directory/container had to be created.
799 * These flags should always be set for directories that have private files.
800 * However, setting them is not guaranteed to actually do anything.
801 * Additional server configuration may be needed to achieve the desired effect.
803 * @param array $params Parameters include:
804 * - dir : storage directory
805 * - noAccess : try to deny file access (since 1.20)
806 * - noListing : try to deny file listing (since 1.20)
807 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
808 * @return StatusValue
810 final public function prepare( array $params ) {
811 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
812 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
814 /** @noinspection PhpUnusedLocalVariableInspection */
815 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
816 return $this->doPrepare( $params );
820 * @see FileBackend::prepare()
821 * @param array $params
823 abstract protected function doPrepare( array $params );
826 * Take measures to block web access to a storage directory and
827 * the container it belongs to. FS backends might add .htaccess
828 * files whereas key/value store backends might revoke container
829 * access to the storage user representing end-users in web requests.
831 * This is not guaranteed to actually make files or listings publically hidden.
832 * Additional server configuration may be needed to achieve the desired effect.
834 * @param array $params Parameters include:
835 * - dir : storage directory
836 * - noAccess : try to deny file access
837 * - noListing : try to deny file listing
838 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
839 * @return StatusValue
841 final public function secure( array $params ) {
842 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
843 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
845 /** @noinspection PhpUnusedLocalVariableInspection */
846 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
847 return $this->doSecure( $params );
851 * @see FileBackend::secure()
852 * @param array $params
854 abstract protected function doSecure( array $params );
857 * Remove measures to block web access to a storage directory and
858 * the container it belongs to. FS backends might remove .htaccess
859 * files whereas key/value store backends might grant container
860 * access to the storage user representing end-users in web requests.
861 * This essentially can undo the result of secure() calls.
863 * This is not guaranteed to actually make files or listings publically viewable.
864 * Additional server configuration may be needed to achieve the desired effect.
866 * @param array $params Parameters include:
867 * - dir : storage directory
868 * - access : try to allow file access
869 * - listing : try to allow file listing
870 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
871 * @return StatusValue
874 final public function publish( array $params ) {
875 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
876 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
878 /** @noinspection PhpUnusedLocalVariableInspection */
879 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
880 return $this->doPublish( $params );
884 * @see FileBackend::publish()
885 * @param array $params
887 abstract protected function doPublish( array $params );
890 * Delete a storage directory if it is empty.
891 * Backends using key/value stores may do nothing unless the directory
892 * is that of an empty container, in which case it will be deleted.
894 * @param array $params Parameters include:
895 * - dir : storage directory
896 * - recursive : recursively delete empty subdirectories first (since 1.20)
897 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
898 * @return StatusValue
900 final public function clean( array $params ) {
901 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
902 return $this->newStatus( 'backend-fail-readonly', $this->name
, $this->readOnly
);
904 /** @noinspection PhpUnusedLocalVariableInspection */
905 $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
906 return $this->doClean( $params );
910 * @see FileBackend::clean()
911 * @param array $params
913 abstract protected function doClean( array $params );
916 * Enter file operation scope.
917 * This just makes PHP ignore user aborts/disconnects until the return
918 * value leaves scope. This returns null and does nothing in CLI mode.
920 * @return ScopedCallback|null
922 final protected function getScopedPHPBehaviorForOps() {
923 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
924 $old = ignore_user_abort( true ); // avoid half-finished operations
925 return new ScopedCallback( function () use ( $old ) {
926 ignore_user_abort( $old );
934 * Check if a file exists at a storage path in the backend.
935 * This returns false if only a directory exists at the path.
937 * @param array $params Parameters include:
938 * - src : source storage path
939 * - latest : use the latest available data
940 * @return bool|null Returns null on failure
942 abstract public function fileExists( array $params );
945 * Get the last-modified timestamp of the file at a storage path.
947 * @param array $params Parameters include:
948 * - src : source storage path
949 * - latest : use the latest available data
950 * @return string|bool TS_MW timestamp or false on failure
952 abstract public function getFileTimestamp( array $params );
955 * Get the contents of a file at a storage path in the backend.
956 * This should be avoided for potentially large files.
958 * @param array $params Parameters include:
959 * - src : source storage path
960 * - latest : use the latest available data
961 * @return string|bool Returns false on failure
963 final public function getFileContents( array $params ) {
964 $contents = $this->getFileContentsMulti(
965 [ 'srcs' => [ $params['src'] ] ] +
$params );
967 return $contents[$params['src']];
971 * Like getFileContents() except it takes an array of storage paths
972 * and returns a map of storage paths to strings (or null on failure).
973 * The map keys (paths) are in the same order as the provided list of paths.
975 * @see FileBackend::getFileContents()
977 * @param array $params Parameters include:
978 * - srcs : list of source storage paths
979 * - latest : use the latest available data
980 * - parallelize : try to do operations in parallel when possible
981 * @return array Map of (path name => string or false on failure)
984 abstract public function getFileContentsMulti( array $params );
987 * Get metadata about a file at a storage path in the backend.
988 * If the file does not exist, then this returns false.
989 * Otherwise, the result is an associative array that includes:
990 * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
991 * - metadata : map of file metadata (name => value)
992 * Metadata keys and headers names will be returned in all lower-case.
993 * Additional values may be included for internal use only.
995 * Use FileBackend::hasFeatures() to check how well this is supported.
997 * @param array $params
999 * - src : source storage path
1000 * - latest : use the latest available data
1001 * @return array|bool Returns false on failure
1004 abstract public function getFileXAttributes( array $params );
1007 * Get the size (bytes) of a file at a storage path in the backend.
1009 * @param array $params Parameters include:
1010 * - src : source storage path
1011 * - latest : use the latest available data
1012 * @return int|bool Returns false on failure
1014 abstract public function getFileSize( array $params );
1017 * Get quick information about a file at a storage path in the backend.
1018 * If the file does not exist, then this returns false.
1019 * Otherwise, the result is an associative array that includes:
1020 * - mtime : the last-modified timestamp (TS_MW)
1021 * - size : the file size (bytes)
1022 * Additional values may be included for internal use only.
1024 * @param array $params Parameters include:
1025 * - src : source storage path
1026 * - latest : use the latest available data
1027 * @return array|bool|null Returns null on failure
1029 abstract public function getFileStat( array $params );
1032 * Get a SHA-1 hash of the file at a storage path in the backend.
1034 * @param array $params Parameters include:
1035 * - src : source storage path
1036 * - latest : use the latest available data
1037 * @return string|bool Hash string or false on failure
1039 abstract public function getFileSha1Base36( array $params );
1042 * Get the properties of the file at a storage path in the backend.
1043 * This gives the result of FSFile::getProps() on a local copy of the file.
1045 * @param array $params Parameters include:
1046 * - src : source storage path
1047 * - latest : use the latest available data
1048 * @return array Returns FSFile::placeholderProps() on failure
1050 abstract public function getFileProps( array $params );
1053 * Stream the file at a storage path in the backend.
1055 * If the file does not exists, an HTTP 404 error will be given.
1056 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
1057 * will be sent if streaming began, while none will be sent otherwise.
1058 * Implementations should flush the output buffer before sending data.
1060 * @param array $params Parameters include:
1061 * - src : source storage path
1062 * - headers : list of additional HTTP headers to send if the file exists
1063 * - options : HTTP request header map with lower case keys (since 1.28). Supports:
1064 * range : format is "bytes=(\d*-\d*)"
1065 * if-modified-since : format is an HTTP date
1066 * - headless : only include the body (and headers from "headers") (since 1.28)
1067 * - latest : use the latest available data
1068 * - allowOB : preserve any output buffers (since 1.28)
1069 * @return StatusValue
1071 abstract public function streamFile( array $params );
1074 * Returns a file system file, identical to the file at a storage path.
1075 * The file returned is either:
1076 * - a) A local copy of the file at a storage path in the backend.
1077 * The temporary copy will have the same extension as the source.
1078 * - b) An original of the file at a storage path in the backend.
1079 * Temporary files may be purged when the file object falls out of scope.
1081 * Write operations should *never* be done on this file as some backends
1082 * may do internal tracking or may be instances of FileBackendMultiWrite.
1083 * In that latter case, there are copies of the file that must stay in sync.
1084 * Additionally, further calls to this function may return the same file.
1086 * @param array $params Parameters include:
1087 * - src : source storage path
1088 * - latest : use the latest available data
1089 * @return FSFile|null Returns null on failure
1091 final public function getLocalReference( array $params ) {
1092 $fsFiles = $this->getLocalReferenceMulti(
1093 [ 'srcs' => [ $params['src'] ] ] +
$params );
1095 return $fsFiles[$params['src']];
1099 * Like getLocalReference() except it takes an array of storage paths
1100 * and returns a map of storage paths to FSFile objects (or null on failure).
1101 * The map keys (paths) are in the same order as the provided list of paths.
1103 * @see FileBackend::getLocalReference()
1105 * @param array $params Parameters include:
1106 * - srcs : list of source storage paths
1107 * - latest : use the latest available data
1108 * - parallelize : try to do operations in parallel when possible
1109 * @return array Map of (path name => FSFile or null on failure)
1112 abstract public function getLocalReferenceMulti( array $params );
1115 * Get a local copy on disk of the file at a storage path in the backend.
1116 * The temporary copy will have the same file extension as the source.
1117 * Temporary files may be purged when the file object falls out of scope.
1119 * @param array $params Parameters include:
1120 * - src : source storage path
1121 * - latest : use the latest available data
1122 * @return TempFSFile|null Returns null on failure
1124 final public function getLocalCopy( array $params ) {
1125 $tmpFiles = $this->getLocalCopyMulti(
1126 [ 'srcs' => [ $params['src'] ] ] +
$params );
1128 return $tmpFiles[$params['src']];
1132 * Like getLocalCopy() except it takes an array of storage paths and
1133 * returns a map of storage paths to TempFSFile objects (or null on failure).
1134 * The map keys (paths) are in the same order as the provided list of paths.
1136 * @see FileBackend::getLocalCopy()
1138 * @param array $params Parameters include:
1139 * - srcs : list of source storage paths
1140 * - latest : use the latest available data
1141 * - parallelize : try to do operations in parallel when possible
1142 * @return array Map of (path name => TempFSFile or null on failure)
1145 abstract public function getLocalCopyMulti( array $params );
1148 * Return an HTTP URL to a given file that requires no authentication to use.
1149 * The URL may be pre-authenticated (via some token in the URL) and temporary.
1150 * This will return null if the backend cannot make an HTTP URL for the file.
1152 * This is useful for key/value stores when using scripts that seek around
1153 * large files and those scripts (and the backend) support HTTP Range headers.
1154 * Otherwise, one would need to use getLocalReference(), which involves loading
1155 * the entire file on to local disk.
1157 * @param array $params Parameters include:
1158 * - src : source storage path
1159 * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
1160 * @return string|null
1163 abstract public function getFileHttpUrl( array $params );
1166 * Check if a directory exists at a given storage path.
1167 * Backends using key/value stores will check if the path is a
1168 * virtual directory, meaning there are files under the given directory.
1170 * Storage backends with eventual consistency might return stale data.
1172 * @param array $params Parameters include:
1173 * - dir : storage directory
1174 * @return bool|null Returns null on failure
1177 abstract public function directoryExists( array $params );
1180 * Get an iterator to list *all* directories under a storage directory.
1181 * If the directory is of the form "mwstore://backend/container",
1182 * then all directories in the container will be listed.
1183 * If the directory is of form "mwstore://backend/container/dir",
1184 * then all directories directly under that directory will be listed.
1185 * Results will be storage directories relative to the given directory.
1187 * Storage backends with eventual consistency might return stale data.
1189 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1191 * @param array $params Parameters include:
1192 * - dir : storage directory
1193 * - topOnly : only return direct child dirs of the directory
1194 * @return Traversable|array|null Returns null on failure
1197 abstract public function getDirectoryList( array $params );
1200 * Same as FileBackend::getDirectoryList() except only lists
1201 * directories that are immediately under the given directory.
1203 * Storage backends with eventual consistency might return stale data.
1205 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1207 * @param array $params Parameters include:
1208 * - dir : storage directory
1209 * @return Traversable|array|null Returns null on failure
1212 final public function getTopDirectoryList( array $params ) {
1213 return $this->getDirectoryList( [ 'topOnly' => true ] +
$params );
1217 * Get an iterator to list *all* stored files under a storage directory.
1218 * If the directory is of the form "mwstore://backend/container",
1219 * then all files in the container will be listed.
1220 * If the directory is of form "mwstore://backend/container/dir",
1221 * then all files under that directory will be listed.
1222 * Results will be storage paths relative to the given directory.
1224 * Storage backends with eventual consistency might return stale data.
1226 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1228 * @param array $params Parameters include:
1229 * - dir : storage directory
1230 * - topOnly : only return direct child files of the directory (since 1.20)
1231 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1232 * @return Traversable|array|null Returns null on failure
1234 abstract public function getFileList( array $params );
1237 * Same as FileBackend::getFileList() except only lists
1238 * files that are immediately under the given directory.
1240 * Storage backends with eventual consistency might return stale data.
1242 * Failures during iteration can result in FileBackendError exceptions (since 1.22).
1244 * @param array $params Parameters include:
1245 * - dir : storage directory
1246 * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
1247 * @return Traversable|array|null Returns null on failure
1250 final public function getTopFileList( array $params ) {
1251 return $this->getFileList( [ 'topOnly' => true ] +
$params );
1255 * Preload persistent file stat cache and property cache into in-process cache.
1256 * This should be used when stat calls will be made on a known list of a many files.
1258 * @see FileBackend::getFileStat()
1260 * @param array $paths Storage paths
1262 abstract public function preloadCache( array $paths );
1265 * Invalidate any in-process file stat and property cache.
1266 * If $paths is given, then only the cache for those files will be cleared.
1268 * @see FileBackend::getFileStat()
1270 * @param array $paths Storage paths (optional)
1272 abstract public function clearCache( array $paths = null );
1275 * Preload file stat information (concurrently if possible) into in-process cache.
1277 * This should be used when stat calls will be made on a known list of a many files.
1278 * This does not make use of the persistent file stat cache.
1280 * @see FileBackend::getFileStat()
1282 * @param array $params Parameters include:
1283 * - srcs : list of source storage paths
1284 * - latest : use the latest available data
1285 * @return bool All requests proceeded without I/O errors (since 1.24)
1288 abstract public function preloadFileStat( array $params );
1291 * Lock the files at the given storage paths in the backend.
1292 * This will either lock all the files or none (on failure).
1294 * Callers should consider using getScopedFileLocks() instead.
1296 * @param array $paths Storage paths
1297 * @param int $type LockManager::LOCK_* constant
1298 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1299 * @return StatusValue
1301 final public function lockFiles( array $paths, $type, $timeout = 0 ) {
1302 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1304 return $this->wrapStatus( $this->lockManager
->lock( $paths, $type, $timeout ) );
1308 * Unlock the files at the given storage paths in the backend.
1310 * @param array $paths Storage paths
1311 * @param int $type LockManager::LOCK_* constant
1312 * @return StatusValue
1314 final public function unlockFiles( array $paths, $type ) {
1315 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1317 return $this->wrapStatus( $this->lockManager
->unlock( $paths, $type ) );
1321 * Lock the files at the given storage paths in the backend.
1322 * This will either lock all the files or none (on failure).
1323 * On failure, the StatusValue object will be updated with errors.
1325 * Once the return value goes out scope, the locks will be released and
1326 * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
1328 * @see ScopedLock::factory()
1330 * @param array $paths List of storage paths or map of lock types to path lists
1331 * @param int|string $type LockManager::LOCK_* constant or "mixed"
1332 * @param StatusValue $status StatusValue to update on lock/unlock
1333 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
1334 * @return ScopedLock|null Returns null on failure
1336 final public function getScopedFileLocks(
1337 array $paths, $type, StatusValue
$status, $timeout = 0
1339 if ( $type === 'mixed' ) {
1340 foreach ( $paths as &$typePaths ) {
1341 $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
1344 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
1347 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status, $timeout );
1351 * Get an array of scoped locks needed for a batch of file operations.
1353 * Normally, FileBackend::doOperations() handles locking, unless
1354 * the 'nonLocking' param is passed in. This function is useful if you
1355 * want the files to be locked for a broader scope than just when the
1356 * files are changing. For example, if you need to update DB metadata,
1357 * you may want to keep the files locked until finished.
1359 * @see FileBackend::doOperations()
1361 * @param array $ops List of file operations to FileBackend::doOperations()
1362 * @param StatusValue $status StatusValue to update on lock/unlock
1363 * @return ScopedLock|null
1366 abstract public function getScopedLocksForOps( array $ops, StatusValue
$status );
1369 * Get the root storage path of this backend.
1370 * All container paths are "subdirectories" of this path.
1372 * @return string Storage path
1375 final public function getRootStoragePath() {
1376 return "mwstore://{$this->name}";
1380 * Get the storage path for the given container for this backend
1382 * @param string $container Container name
1383 * @return string Storage path
1386 final public function getContainerStoragePath( $container ) {
1387 return $this->getRootStoragePath() . "/{$container}";
1391 * Get the file journal object for this backend
1393 * @return FileJournal
1395 final public function getJournal() {
1396 return $this->fileJournal
;
1400 * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
1402 * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
1403 * around as long it needs (which may vary greatly depending on configuration)
1405 * @param array $ops File operation batch for FileBaclend::doOperations()
1406 * @return array File operation batch
1408 protected function resolveFSFileObjects( array $ops ) {
1409 foreach ( $ops as &$op ) {
1410 $src = $op['src'] ??
null;
1411 if ( $src instanceof FSFile
) {
1412 $op['srcRef'] = $src;
1413 $op['src'] = $src->getPath();
1422 * Check if a given path is a "mwstore://" path.
1423 * This does not do any further validation or any existence checks.
1425 * @param string $path
1428 final public static function isStoragePath( $path ) {
1429 return ( strpos( $path, 'mwstore://' ) === 0 );
1433 * Split a storage path into a backend name, a container name,
1434 * and a relative file path. The relative path may be the empty string.
1435 * This does not do any path normalization or traversal checks.
1437 * @param string $storagePath
1438 * @return array (backend, container, rel object) or (null, null, null)
1440 final public static function splitStoragePath( $storagePath ) {
1441 if ( self
::isStoragePath( $storagePath ) ) {
1442 // Remove the "mwstore://" prefix and split the path
1443 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1444 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1445 if ( count( $parts ) == 3 ) {
1446 return $parts; // e.g. "backend/container/path"
1448 return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
1453 return [ null, null, null ];
1457 * Normalize a storage path by cleaning up directory separators.
1458 * Returns null if the path is not of the format of a valid storage path.
1460 * @param string $storagePath
1461 * @return string|null
1463 final public static function normalizeStoragePath( $storagePath ) {
1464 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1465 if ( $relPath !== null ) { // must be for this backend
1466 $relPath = self
::normalizeContainerPath( $relPath );
1467 if ( $relPath !== null ) {
1468 return ( $relPath != '' )
1469 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1470 : "mwstore://{$backend}/{$container}";
1478 * Get the parent storage directory of a storage path.
1479 * This returns a path like "mwstore://backend/container",
1480 * "mwstore://backend/container/...", or null if there is no parent.
1482 * @param string $storagePath
1483 * @return string|null
1485 final public static function parentStoragePath( $storagePath ) {
1486 $storagePath = dirname( $storagePath );
1487 list( , , $rel ) = self
::splitStoragePath( $storagePath );
1489 return ( $rel === null ) ?
null : $storagePath;
1493 * Get the final extension from a storage or FS path
1495 * @param string $path
1496 * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
1499 final public static function extensionFromPath( $path, $case = 'lowercase' ) {
1500 $i = strrpos( $path, '.' );
1501 $ext = $i ?
substr( $path, $i +
1 ) : '';
1503 if ( $case === 'lowercase' ) {
1504 $ext = strtolower( $ext );
1505 } elseif ( $case === 'uppercase' ) {
1506 $ext = strtoupper( $ext );
1513 * Check if a relative path has no directory traversals
1515 * @param string $path
1519 final public static function isPathTraversalFree( $path ) {
1520 return ( self
::normalizeContainerPath( $path ) !== null );
1524 * Build a Content-Disposition header value per RFC 6266.
1526 * @param string $type One of (attachment, inline)
1527 * @param string $filename Suggested file name (should not contain slashes)
1528 * @throws FileBackendError
1532 final public static function makeContentDisposition( $type, $filename = '' ) {
1535 $type = strtolower( $type );
1536 if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
1537 throw new InvalidArgumentException( "Invalid Content-Disposition type '$type'." );
1541 if ( strlen( $filename ) ) {
1542 $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
1545 return implode( ';', $parts );
1549 * Validate and normalize a relative storage path.
1550 * Null is returned if the path involves directory traversal.
1551 * Traversal is insecure for FS backends and broken for others.
1553 * This uses the same traversal protection as Title::secureAndSplit().
1555 * @param string $path Storage path relative to a container
1556 * @return string|null
1558 final protected static function normalizeContainerPath( $path ) {
1559 // Normalize directory separators
1560 $path = strtr( $path, '\\', '/' );
1561 // Collapse any consecutive directory separators
1562 $path = preg_replace( '![/]{2,}!', '/', $path );
1563 // Remove any leading directory separator
1564 $path = ltrim( $path, '/' );
1565 // Use the same traversal protection as Title::secureAndSplit()
1566 if ( strpos( $path, '.' ) !== false ) {
1570 strpos( $path, './' ) === 0 ||
1571 strpos( $path, '../' ) === 0 ||
1572 strpos( $path, '/./' ) !== false ||
1573 strpos( $path, '/../' ) !== false
1583 * Yields the result of the status wrapper callback on either:
1584 * - StatusValue::newGood() if this method is called without parameters
1585 * - StatusValue::newFatal() with all parameters to this method if passed in
1587 * @param string $args,...
1588 * @return StatusValue
1590 final protected function newStatus() {
1591 $args = func_get_args();
1592 if ( count( $args ) ) {
1593 $sv = call_user_func_array( [ StatusValue
::class, 'newFatal' ], $args );
1595 $sv = StatusValue
::newGood();
1598 return $this->wrapStatus( $sv );
1602 * @param StatusValue $sv
1603 * @return StatusValue Modified status or StatusValue subclass
1605 final protected function wrapStatus( StatusValue
$sv ) {
1606 return $this->statusWrapper ?
call_user_func( $this->statusWrapper
, $sv ) : $sv;
1610 * @param string $section
1611 * @return ScopedCallback|null
1613 protected function scopedProfileSection( $section ) {
1614 if ( $this->profiler
) {
1615 call_user_func( [ $this->profiler
, 'profileIn' ], $section );
1616 return new ScopedCallback( [ $this->profiler
, 'profileOut' ], [ $section ] );
1622 protected function resetOutputBuffer() {
1623 while ( ob_get_status() ) {
1624 if ( !ob_end_clean() ) {
1625 // Could not remove output buffer handler; abort now
1626 // to avoid getting in some kind of infinite loop.