"preset": "jsduck5",
"extra": {
"context": "some",
- "source": "some",
"see": "some"
}
},
https://www.mediawiki.org/beacon with basic information about the local
MediaWiki installation. This data includes, for example, the type of system,
PHP version, and chosen database backend. This behavior is off by default.
-* When $EditSubmitButtonLabelPublish is true, MediaWiki will label the button
+* When $wgEditSubmitButtonLabelPublish is true, MediaWiki will label the button
to store-to-database-and-show-to-others as "Publish page"/"Publish changes";
if false, the default, they will be "Save page"/"Save changes".
* The 'editcontentmodel' permission is now granted to all logged-in users ('user').
interact with ApiParse and ApiExpandTemplates.
* (T139565) SECURITY: API: Generate head items in the context of the given title
* (T115333) SECURITY: Check read permission when loading page content in ApiParse
+* ApiBase::makeHelpArrayToString() was removed (deprecated since 1.25)
+* ApiBase::makeHelpMsgParameters() was removed (deprecated since 1.25)
+* ApiBase::makeHelpMsg() was removed (deprecated since 1.25)
+* ApiFormatBase::formatHTML() was removed (deprecated since 1.25)
+* ApiFormatBase::getNeedsRawData() was removed (deprecated since 1.25)
+* ApiFormatBase::getWantsHelp() was removed (deprecated since 1.25)
+* ApiFormatBase::setBufferResult() was removed (deprecated since 1.25)
+* ApiFormatBase::setHelp() was removed (deprecated since 1.25)
+* ApiFormatBase::setUnescapeAmps() was removed (deprecated since 1.25)
+* ApiMain::makeHelpMsgHeader() was removed (deprecated since 1.25)
+* ApiMain::reallyMakeHelpMsg() was removed (deprecated since 1.25)
+* ApiMain::setHelp() was removed (deprecated since 1.25)
+* ApiResult::beginContinuation() was removed (deprecated since 1.25)
+* ApiResult::cleanUpUTF8() was removed (deprecated since 1.25)
+* ApiResult::convertStatusToArray() was removed (deprecated since 1.25)
+* ApiResult::disableSizeCheck() was removed (deprecated since 1.24)
+* ApiResult::enableSizeCheck() was removed (deprecated since 1.24)
+* ApiResult::endContinuation() was removed (deprecated since 1.25)
+* ApiResult::getData() was removed (deprecated since 1.25)
+* ApiResult::getIsRawMode() was removed (deprecated since 1.25)
+* ApiResult::setContent() was removed (deprecated since 1.25)
+* ApiResult::setContinueParam() was removed (deprecated since 1.25)
+* ApiResult::setElement() was removed (deprecated since 1.25)
+* ApiResult::setGeneratorContinueParam() was removed (deprecated since 1.25)
+* ApiResult::setIndexedTagName_internal() was removed (deprecated since 1.25)
+* ApiResult::setIndexedTagName_recursive() was removed (deprecated since 1.25)
+* ApiResult::setMainForContinuation() was removed (deprecated since 1.25)
+* ApiResult::setParsedLimit() was removed (deprecated since 1.25)
+* ApiResult::setRawMode() was removed (deprecated since 1.25)
+* ApiResult::size() was removed (deprecated since 1.25)
=== Languages updated in 1.28 ===
'Field' => __DIR__ . '/includes/libs/rdbms/field/Field.php',
'File' => __DIR__ . '/includes/filerepo/file/File.php',
'FileAwareNodeVisitor' => __DIR__ . '/maintenance/findDeprecated.php',
- 'FileBackend' => __DIR__ . '/includes/filebackend/FileBackend.php',
+ 'FileBackend' => __DIR__ . '/includes/libs/filebackend/FileBackend.php',
'FileBackendDBRepoWrapper' => __DIR__ . '/includes/filerepo/FileBackendDBRepoWrapper.php',
- 'FileBackendError' => __DIR__ . '/includes/filebackend/FileBackend.php',
- 'FileBackendException' => __DIR__ . '/includes/filebackend/FileBackend.php',
+ 'FileBackendError' => __DIR__ . '/includes/libs/filebackend/FileBackendException.php',
+ 'FileBackendException' => __DIR__ . '/includes/libs/filebackend/FileBackendException.php',
'FileBackendGroup' => __DIR__ . '/includes/filebackend/FileBackendGroup.php',
'FileBackendMultiWrite' => __DIR__ . '/includes/filebackend/FileBackendMultiWrite.php',
'FileBackendStore' => __DIR__ . '/includes/filebackend/FileBackendStore.php',
'FileDeleteForm' => __DIR__ . '/includes/FileDeleteForm.php',
'FileDependency' => __DIR__ . '/includes/cache/CacheDependency.php',
'FileDuplicateSearchPage' => __DIR__ . '/includes/specials/SpecialFileDuplicateSearch.php',
- 'FileJournal' => __DIR__ . '/includes/filebackend/filejournal/FileJournal.php',
+ 'FileJournal' => __DIR__ . '/includes/libs/filebackend/filejournal/FileJournal.php',
'FileOp' => __DIR__ . '/includes/filebackend/FileOp.php',
'FileOpBatch' => __DIR__ . '/includes/filebackend/FileOpBatch.php',
'FileRepo' => __DIR__ . '/includes/filerepo/FileRepo.php',
'NotRecursiveIterator' => __DIR__ . '/includes/utils/iterators/NotRecursiveIterator.php',
'NukeNS' => __DIR__ . '/maintenance/nukeNS.php',
'NukePage' => __DIR__ . '/maintenance/nukePage.php',
- 'NullFileJournal' => __DIR__ . '/includes/filebackend/filejournal/FileJournal.php',
+ 'NullFileJournal' => __DIR__ . '/includes/libs/filebackend/filejournal/NullFileJournal.php',
'NullFileOp' => __DIR__ . '/includes/filebackend/FileOp.php',
'NullIndexField' => __DIR__ . '/includes/search/NullIndexField.php',
'NullJob' => __DIR__ . '/includes/jobqueue/jobs/NullJob.php',
'Sanitizer' => __DIR__ . '/includes/Sanitizer.php',
'SavepointPostgres' => __DIR__ . '/includes/libs/rdbms/database/utils/SavepointPostgres.php',
'ScopedCallback' => __DIR__ . '/includes/libs/ScopedCallback.php',
- 'ScopedLock' => __DIR__ . '/includes/filebackend/lockmanager/ScopedLock.php',
+ 'ScopedLock' => __DIR__ . '/includes/libs/lockmanager/ScopedLock.php',
'SearchApi' => __DIR__ . '/includes/api/SearchApi.php',
'SearchDatabase' => __DIR__ . '/includes/search/SearchDatabase.php',
'SearchDump' => __DIR__ . '/maintenance/dumpIterator.php',
$status->getWikiText( 'filedeleteerror-short', 'filedeleteerror-long' )
. '</div>' );
}
- if ( $status->ok ) {
+ if ( $status->isOK() ) {
$wgOut->setPageTitle( wfMessage( 'actioncomplete' ) );
$wgOut->addHTML( $this->prepareMessage( 'filedelete-success' ) );
// Return to the main page if we just deleted all versions of the
return $wgTmpDirectory;
}
- $tmpDir = array_map( "getenv", [ 'TMPDIR', 'TMP', 'TEMP' ] );
- $tmpDir[] = sys_get_temp_dir();
- $tmpDir[] = ini_get( 'upload_tmp_dir' );
-
- foreach ( $tmpDir as $tmp ) {
- if ( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
- return $tmp;
- }
- }
-
- /**
- * PHP on Windows will detect C:\Windows\Temp as not writable even though PHP can write to it
- * so create a directory within that called 'mwtmp' with a suffix of the user running the
- * current process.
- * The user is included as if various scripts are run by different users they will likely
- * not be able to access each others temporary files.
- */
- if ( wfIsWindows() ) {
- $tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'mwtmp' . '-' . get_current_user();
- if ( !file_exists( $tmp ) ) {
- mkdir( $tmp );
- }
- if ( file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
- return $tmp;
- }
- }
-
- throw new MWException( 'No writable temporary directory could be found. ' .
- 'Please set $wgTmpDirectory to a writable directory.' );
+ return TempFSFile::getUsableTempDirectory();
}
/**
*/
public $mBodytext = '';
- /**
- * Holds the debug lines that will be output as comments in page source if
- * $wgDebugComments is enabled. See also $wgShowDebug.
- * @deprecated since 1.20; use MWDebug class instead.
- */
- public $mDebugtext = '';
-
/** @var string Stores contents of "<title>" tag */
private $mHTMLtitle = '';
return false;
}
- /**
- * Generates help message for this module, or false if there is no description
- * @deprecated since 1.25
- * @return string|bool
- */
- public function makeHelpMsg() {
- wfDeprecated( __METHOD__, '1.25' );
- static $lnPrfx = "\n ";
-
- $msg = $this->getFinalDescription();
-
- if ( $msg !== false ) {
-
- if ( !is_array( $msg ) ) {
- $msg = [
- $msg
- ];
- }
- $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
-
- $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
-
- if ( $this->isReadMode() ) {
- $msg .= "\nThis module requires read rights";
- }
- if ( $this->isWriteMode() ) {
- $msg .= "\nThis module requires write rights";
- }
- if ( $this->mustBePosted() ) {
- $msg .= "\nThis module only accepts POST requests";
- }
- if ( $this->isReadMode() || $this->isWriteMode() ||
- $this->mustBePosted()
- ) {
- $msg .= "\n";
- }
-
- // Parameters
- $paramsMsg = $this->makeHelpMsgParameters();
- if ( $paramsMsg !== false ) {
- $msg .= "Parameters:\n$paramsMsg";
- }
-
- $examples = $this->getExamples();
- if ( $examples ) {
- if ( !is_array( $examples ) ) {
- $examples = [
- $examples
- ];
- }
- $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
- foreach ( $examples as $k => $v ) {
- if ( is_numeric( $k ) ) {
- $msg .= " $v\n";
- } else {
- if ( is_array( $v ) ) {
- $msgExample = implode( "\n", array_map( [ $this, 'indentExampleText' ], $v ) );
- } else {
- $msgExample = " $v";
- }
- $msgExample .= ':';
- $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
- }
- }
- }
- }
-
- return $msg;
- }
-
- /**
- * @deprecated since 1.25
- * @param string $item
- * @return string
- */
- private function indentExampleText( $item ) {
- return ' ' . $item;
- }
-
- /**
- * @deprecated since 1.25
- * @param string $prefix Text to split output items
- * @param string $title What is being output
- * @param string|array $input
- * @return string
- */
- protected function makeHelpArrayToString( $prefix, $title, $input ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( $input === false ) {
- return '';
- }
- if ( !is_array( $input ) ) {
- $input = [ $input ];
- }
-
- if ( count( $input ) > 0 ) {
- if ( $title ) {
- $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
- } else {
- $msg = ' ';
- }
- $msg .= implode( $prefix, $input ) . "\n";
-
- return $msg;
- }
-
- return '';
- }
-
- /**
- * Generates the parameter descriptions for this module, to be displayed in the
- * module's help.
- * @deprecated since 1.25
- * @return string|bool
- */
- public function makeHelpMsgParameters() {
- wfDeprecated( __METHOD__, '1.25' );
- $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
- if ( $params ) {
- $paramsDescription = $this->getFinalParamDescription();
- $msg = '';
- $paramPrefix = "\n" . str_repeat( ' ', 24 );
- $descWordwrap = "\n" . str_repeat( ' ', 28 );
- foreach ( $params as $paramName => $paramSettings ) {
- $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
- if ( is_array( $desc ) ) {
- $desc = implode( $paramPrefix, $desc );
- }
-
- // handle shorthand
- if ( !is_array( $paramSettings ) ) {
- $paramSettings = [
- self::PARAM_DFLT => $paramSettings,
- ];
- }
-
- // handle missing type
- if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
- $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
- ? $paramSettings[ApiBase::PARAM_DFLT]
- : null;
- if ( is_bool( $dflt ) ) {
- $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
- } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
- $paramSettings[ApiBase::PARAM_TYPE] = 'string';
- } elseif ( is_int( $dflt ) ) {
- $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
- }
- }
-
- if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
- && $paramSettings[self::PARAM_DEPRECATED]
- ) {
- $desc = "DEPRECATED! $desc";
- }
-
- if ( isset( $paramSettings[self::PARAM_REQUIRED] )
- && $paramSettings[self::PARAM_REQUIRED]
- ) {
- $desc .= $paramPrefix . 'This parameter is required';
- }
-
- $type = isset( $paramSettings[self::PARAM_TYPE] )
- ? $paramSettings[self::PARAM_TYPE]
- : null;
- if ( isset( $type ) ) {
- $hintPipeSeparated = true;
- $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
- ? $paramSettings[self::PARAM_ISMULTI]
- : false;
- if ( $multi ) {
- $prompt = 'Values (separate with \'|\'): ';
- } else {
- $prompt = 'One value: ';
- }
-
- if ( $type === 'submodule' ) {
- if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
- $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
- } else {
- $type = $this->getModuleManager()->getNames( $paramName );
- }
- sort( $type );
- }
- if ( is_array( $type ) ) {
- $choices = [];
- $nothingPrompt = '';
- foreach ( $type as $t ) {
- if ( $t === '' ) {
- $nothingPrompt = 'Can be empty, or ';
- } else {
- $choices[] = $t;
- }
- }
- $desc .= $paramPrefix . $nothingPrompt . $prompt;
- $choicesstring = implode( ', ', $choices );
- $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
- $hintPipeSeparated = false;
- } else {
- switch ( $type ) {
- case 'namespace':
- // Special handling because namespaces are
- // type-limited, yet they are not given
- $desc .= $paramPrefix . $prompt;
- $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
- 100, $descWordwrap );
- $hintPipeSeparated = false;
- break;
- case 'limit':
- $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
- if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
- $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
- }
- $desc .= ' allowed';
- break;
- case 'integer':
- $s = $multi ? 's' : '';
- $hasMin = isset( $paramSettings[self::PARAM_MIN] );
- $hasMax = isset( $paramSettings[self::PARAM_MAX] );
- if ( $hasMin || $hasMax ) {
- if ( !$hasMax ) {
- $intRangeStr = "The value$s must be no less than " .
- "{$paramSettings[self::PARAM_MIN]}";
- } elseif ( !$hasMin ) {
- $intRangeStr = "The value$s must be no more than " .
- "{$paramSettings[self::PARAM_MAX]}";
- } else {
- $intRangeStr = "The value$s must be between " .
- "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
- }
-
- $desc .= $paramPrefix . $intRangeStr;
- }
- break;
- case 'upload':
- $desc .= $paramPrefix . 'Must be posted as a file upload using multipart/form-data';
- break;
- }
- }
-
- if ( $multi ) {
- if ( $hintPipeSeparated ) {
- $desc .= $paramPrefix . "Separate values with '|'";
- }
-
- $isArray = is_array( $type );
- if ( !$isArray
- || $isArray && count( $type ) > self::LIMIT_SML1
- ) {
- $desc .= $paramPrefix . 'Maximum number of values ' .
- self::LIMIT_SML1 . ' (' . self::LIMIT_SML2 . ' for bots)';
- }
- }
- }
-
- $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
- if ( !is_null( $default ) && $default !== false ) {
- $desc .= $paramPrefix . "Default: $default";
- }
-
- $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
- }
-
- return $msg;
- }
-
- return false;
- }
-
/**
* @deprecated since 1.25, always returns empty string
* @param IDatabase|bool $db
return 'https://www.mediawiki.org/wiki/API:Data_formats';
}
- /************************************************************************//**
- * @name Deprecated
- * @{
- */
-
- /**
- * Specify whether or not sequences like &quot; should be unescaped
- * to " . This should only be set to true for the help message
- * when rendered in the default (xmlfm) format. This is a temporary
- * special-case fix that should be removed once the help has been
- * reworked to use a fully HTML interface.
- *
- * @deprecated since 1.25
- * @param bool $b Whether or not ampersands should be escaped.
- */
- public function setUnescapeAmps( $b ) {
- wfDeprecated( __METHOD__, '1.25' );
- $this->mUnescapeAmps = $b;
- }
-
- /**
- * Whether this formatter can format the help message in a nice way.
- * By default, this returns the same as getIsHtml().
- * When action=help is set explicitly, the help will always be shown
- * @deprecated since 1.25
- * @return bool
- */
- public function getWantsHelp() {
- wfDeprecated( __METHOD__, '1.25' );
- return $this->getIsHtml();
- }
-
- /**
- * Sets whether the pretty-printer should format *bold*
- * @deprecated since 1.25
- * @param bool $help
- */
- public function setHelp( $help = true ) {
- wfDeprecated( __METHOD__, '1.25' );
- $this->mHelp = $help;
- }
-
- /**
- * Pretty-print various elements in HTML format, such as xml tags and
- * URLs. This method also escapes characters like <
- * @deprecated since 1.25
- * @param string $text
- * @return string
- */
- protected function formatHTML( $text ) {
- wfDeprecated( __METHOD__, '1.25' );
-
- // Escape everything first for full coverage
- $text = htmlspecialchars( $text );
-
- if ( $this->mFormat === 'XML' ) {
- // encode all comments or tags as safe blue strings
- $text = str_replace( '<', '<span style="color:blue;"><', $text );
- $text = str_replace( '>', '></span>', $text );
- }
-
- // identify requests to api.php
- $text = preg_replace( '#^(\s*)(api\.php\?[^ <\n\t]+)$#m', '\1<a href="\2">\2</a>', $text );
- if ( $this->mHelp ) {
- // make lines inside * bold
- $text = preg_replace( '#^(\s*)(\*[^<>\n]+\*)(\s*)$#m', '$1<b>$2</b>$3', $text );
- }
-
- // Armor links (bug 61362)
- $masked = [];
- $text = preg_replace_callback( '#<a .*?</a>#', function ( $matches ) use ( &$masked ) {
- $sha = sha1( $matches[0] );
- $masked[$sha] = $matches[0];
- return "<$sha>";
- }, $text );
-
- // identify URLs
- $protos = wfUrlProtocolsWithoutProtRel();
- // This regex hacks around bug 13218 (" included in the URL)
- $text = preg_replace(
- "#(((?i)$protos).*?)(")?([ \\'\"<>\n]|<|>|")#",
- '<a href="\\1">\\1</a>\\3\\4',
- $text
- );
-
- // Unarmor links
- $text = preg_replace_callback( '#<([0-9a-f]{40})>#', function ( $matches ) use ( &$masked ) {
- $sha = $matches[1];
- return isset( $masked[$sha] ) ? $masked[$sha] : $matches[0];
- }, $text );
-
- /**
- * Temporary fix for bad links in help messages. As a special case,
- * XML-escaped metachars are de-escaped one level in the help message
- * for legibility. Should be removed once we have completed a fully-HTML
- * version of the help message.
- */
- if ( $this->mUnescapeAmps ) {
- $text = preg_replace( '/&(amp|quot|lt|gt);/', '&\1;', $text );
- }
-
- return $text;
- }
-
- /**
- * @see ApiBase::getDescription
- * @deprecated since 1.25
- */
- public function getDescription() {
- return $this->getIsHtml() ? ' (pretty-print in HTML)' : '';
- }
-
- /**
- * Set the flag to buffer the result instead of printing it.
- * @deprecated since 1.25, output is always buffered
- * @param bool $value
- */
- public function setBufferResult( $value ) {
- }
-
- /**
- * Formerly indicated whether the formatter needed metadata from ApiResult.
- *
- * ApiResult previously (indirectly) used this to decide whether to add
- * metadata or to ignore calls to metadata-setting methods, which
- * unfortunately made several methods that should have been static have to
- * be dynamic instead. Now ApiResult always stores metadata and formatters
- * are required to ignore it or filter it out.
- *
- * @deprecated since 1.25
- * @return bool Always true
- */
- public function getNeedsRawData() {
- wfDeprecated( __METHOD__, '1.25' );
- return true;
- }
-
- /**@}*/
}
/**
return 'application/json';
}
- /**
- * @deprecated since 1.25
- */
- public function getWantsHelp() {
- wfDeprecated( __METHOD__, '1.25' );
- // Help is always ugly in JSON
- return false;
- }
-
public function execute() {
$params = $this->extractRequestParams();
continue;
}
$ext = strtolower( pathinfo( "$srcPath", PATHINFO_EXTENSION ) );
- $tmpFile = TempFSFile::factory( 'rotate_', $ext );
+ $tmpFile = TempFSFile::factory( 'rotate_', $ext, wfTempDir() );
$dstPath = $tmpFile->getPath();
$err = $handler->rotate( $file, [
'srcPath' => $srcPath,
$this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
$this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
$this->mResult->setErrorFormatter( $this->mErrorFormatter );
- $this->mResult->setMainForContinuation( $this );
$this->mContinuationManager = null;
$this->mEnableWrite = $enableWrite;
$this->getRequest()->getHeader( 'User-agent' )
);
}
-
- /************************************************************************//**
- * @name Deprecated
- * @{
- */
-
- /**
- * Sets whether the pretty-printer should format *bold* and $italics$
- *
- * @deprecated since 1.25
- * @param bool $help
- */
- public function setHelp( $help = true ) {
- wfDeprecated( __METHOD__, '1.25' );
- $this->mPrinter->setHelp( $help );
- }
-
- /**
- * Override the parent to generate help messages for all available modules.
- *
- * @deprecated since 1.25
- * @return string
- */
- public function makeHelpMsg() {
- wfDeprecated( __METHOD__, '1.25' );
-
- $this->setHelp();
- $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
-
- return ObjectCache::getMainWANInstance()->getWithSetCallback(
- wfMemcKey(
- 'apihelp',
- $this->getModuleName(),
- str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
- ),
- $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
- [ $this, 'reallyMakeHelpMsg' ]
- );
- }
-
- /**
- * @deprecated since 1.25
- * @return mixed|string
- */
- public function reallyMakeHelpMsg() {
- wfDeprecated( __METHOD__, '1.25' );
- $this->setHelp();
-
- // Use parent to make default message for the main module
- $msg = parent::makeHelpMsg();
-
- $asterisks = str_repeat( '*** ', 14 );
- $msg .= "\n\n$asterisks Modules $asterisks\n\n";
-
- foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
- $module = $this->mModuleMgr->getModule( $name );
- $msg .= self::makeHelpMsgHeader( $module, 'action' );
-
- $msg2 = $module->makeHelpMsg();
- if ( $msg2 !== false ) {
- $msg .= $msg2;
- }
- $msg .= "\n";
- }
-
- $msg .= "\n$asterisks Permissions $asterisks\n\n";
- foreach ( self::$mRights as $right => $rightMsg ) {
- $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
- ->useDatabase( false )
- ->inLanguage( 'en' )
- ->text();
- $groups = User::getGroupsWithPermission( $right );
- $msg .= '* ' . $right . " *\n $rightsMsg" .
- "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
- }
-
- $msg .= "\n$asterisks Formats $asterisks\n\n";
- foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
- $module = $this->mModuleMgr->getModule( $name );
- $msg .= self::makeHelpMsgHeader( $module, 'format' );
- $msg2 = $module->makeHelpMsg();
- if ( $msg2 !== false ) {
- $msg .= $msg2;
- }
- $msg .= "\n";
- }
-
- $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
- $credits = str_replace( "\n", "\n ", $credits );
- $msg .= "\n*** Credits: ***\n $credits\n";
-
- return $msg;
- }
-
- /**
- * @deprecated since 1.25
- * @param ApiBase $module
- * @param string $paramName What type of request is this? e.g. action,
- * query, list, prop, meta, format
- * @return string
- */
- public static function makeHelpMsgHeader( $module, $paramName ) {
- wfDeprecated( __METHOD__, '1.25' );
- $modulePrefix = $module->getModulePrefix();
- if ( strval( $modulePrefix ) !== '' ) {
- $modulePrefix = "($modulePrefix) ";
- }
-
- return "* $paramName={$module->getModuleName()} $modulePrefix*";
- }
-
- /**@}*/
-
}
/**
return $result;
}
- /**
- * Override the parent to generate help messages for all available query modules.
- * @deprecated since 1.25
- * @return string
- */
- public function makeHelpMsg() {
- wfDeprecated( __METHOD__, '1.25' );
-
- // Use parent to make default message for the query module
- $msg = parent::makeHelpMsg();
-
- $querySeparator = str_repeat( '--- ', 12 );
- $moduleSeparator = str_repeat( '*** ', 14 );
- $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
- $msg .= $this->makeHelpMsgHelper( 'prop' );
- $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
- $msg .= $this->makeHelpMsgHelper( 'list' );
- $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
- $msg .= $this->makeHelpMsgHelper( 'meta' );
- $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
-
- return $msg;
- }
-
- /**
- * For all modules of a given group, generate help messages and join them together
- * @deprecated since 1.25
- * @param string $group Module group
- * @return string
- */
- private function makeHelpMsgHelper( $group ) {
- $moduleDescriptions = [];
-
- $moduleNames = $this->mModuleMgr->getNames( $group );
- sort( $moduleNames );
- foreach ( $moduleNames as $name ) {
- /**
- * @var $module ApiQueryBase
- */
- $module = $this->mModuleMgr->getModule( $name );
-
- $msg = ApiMain::makeHelpMsgHeader( $module, $group );
- $msg2 = $module->makeHelpMsg();
- if ( $msg2 !== false ) {
- $msg .= $msg2;
- }
- if ( $module instanceof ApiQueryGeneratorBase ) {
- $msg .= "Generator:\n This module may be used as a generator\n";
- }
- $moduleDescriptions[] = $msg;
- }
-
- return implode( "\n", $moduleDescriptions );
- }
-
public function isReadMode() {
// We need to make an exception for certain meta modules that should be
// accessible even without the 'read' right. Restrict the exception as
$arr = &$this->path( $path, ( $flags & ApiResult::ADD_ON_TOP ) ? 'prepend' : 'append' );
if ( $this->checkingSize && !( $flags & ApiResult::NO_SIZE_CHECK ) ) {
- // self::valueSize needs the validated value. Then flag
+ // self::size needs the validated value. Then flag
// to not re-validate later.
$value = self::validateValue( $value );
$flags |= ApiResult::NO_VALIDATE;
- $newsize = $this->size + self::valueSize( $value );
+ $newsize = $this->size + self::size( $value );
if ( $this->maxSize !== false && $newsize > $this->maxSize ) {
/// @todo Add i18n message when replacing calls to ->setWarning()
$msg = new ApiRawMessage( 'This result was truncated because it would otherwise ' .
}
$ret = self::unsetValue( $this->path( $path, 'dummy' ), $name );
if ( $this->checkingSize && !( $flags & ApiResult::NO_SIZE_CHECK ) ) {
- $newsize = $this->size - self::valueSize( $ret );
+ $newsize = $this->size - self::size( $ret );
$this->size = max( $newsize, 0 );
}
return $ret;
/**
* Get the 'real' size of a result item. This means the strlen() of the item,
* or the sum of the strlen()s of the elements if the item is an array.
- * @note Once the deprecated public self::size is removed, we can rename
- * this back to a less awkward name.
* @param mixed $value Validated value (see self::validateValue())
* @return int
*/
- private static function valueSize( $value ) {
+ private static function size( $value ) {
$s = 0;
if ( is_array( $value ) ) {
foreach ( $value as $k => $v ) {
if ( !self::isMetadataKey( $k ) ) {
- $s += self::valueSize( $v );
+ $s += self::size( $v );
}
}
} elseif ( is_scalar( $value ) ) {
/**@}*/
- /************************************************************************//**
- * @name Deprecated
- * @{
- */
-
- /**
- * Formerly used to enable/disable "raw mode".
- * @deprecated since 1.25, you shouldn't have been using it in the first place
- * @since 1.23 $flag parameter added
- * @param bool $flag Set the raw mode flag to this state
- */
- public function setRawMode( $flag = true ) {
- wfDeprecated( __METHOD__, '1.25' );
- }
-
- /**
- * Returns true, the equivalent of "raw mode" is always enabled now
- * @deprecated since 1.25, you shouldn't have been using it in the first place
- * @return bool
- */
- public function getIsRawMode() {
- wfDeprecated( __METHOD__, '1.25' );
- return true;
- }
-
- /**
- * Get the result's internal data array (read-only)
- * @deprecated since 1.25, use $this->getResultData() instead
- * @return array
- */
- public function getData() {
- wfDeprecated( __METHOD__, '1.25' );
- return $this->getResultData( null, [
- 'BC' => [],
- 'Types' => [],
- 'Strip' => 'all',
- ] );
- }
-
- /**
- * Disable size checking in addValue(). Don't use this unless you
- * REALLY know what you're doing. Values added while size checking
- * was disabled will not be counted (ever)
- * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
- */
- public function disableSizeCheck() {
- wfDeprecated( __METHOD__, '1.24' );
- $this->checkingSize = false;
- }
-
- /**
- * Re-enable size checking in addValue()
- * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
- */
- public function enableSizeCheck() {
- wfDeprecated( __METHOD__, '1.24' );
- $this->checkingSize = true;
- }
-
- /**
- * Alias for self::setValue()
- *
- * @since 1.21 int $flags replaced boolean $override
- * @deprecated since 1.25, use self::setValue() instead
- * @param array $arr To add $value to
- * @param string $name Index of $arr to add $value at
- * @param mixed $value
- * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
- * This parameter used to be boolean, and the value of OVERRIDE=1 was
- * specifically chosen so that it would be backwards compatible with the
- * new method signature.
- */
- public static function setElement( &$arr, $name, $value, $flags = 0 ) {
- wfDeprecated( __METHOD__, '1.25' );
- self::setValue( $arr, $name, $value, $flags );
- }
-
- /**
- * Adds a content element to an array.
- * Use this function instead of hardcoding the '*' element.
- * @deprecated since 1.25, use self::setContentValue() instead
- * @param array $arr To add the content element to
- * @param mixed $value
- * @param string $subElemName When present, content element is created
- * as a sub item of $arr. Use this parameter to create elements in
- * format "<elem>text</elem>" without attributes.
- */
- public static function setContent( &$arr, $value, $subElemName = null ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( is_array( $value ) ) {
- throw new InvalidArgumentException( __METHOD__ . ': Bad parameter' );
- }
- if ( is_null( $subElemName ) ) {
- self::setContentValue( $arr, 'content', $value );
- } else {
- if ( !isset( $arr[$subElemName] ) ) {
- $arr[$subElemName] = [];
- }
- self::setContentValue( $arr[$subElemName], 'content', $value );
- }
- }
-
- /**
- * Set indexed tag name on all subarrays of $arr
- *
- * Does not set the tag name for $arr itself.
- *
- * @deprecated since 1.25, use self::setIndexedTagNameRecursive() instead
- * @param array $arr
- * @param string $tag Tag name
- */
- public function setIndexedTagName_recursive( &$arr, $tag ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( !is_array( $arr ) ) {
- return;
- }
- if ( !is_string( $tag ) ) {
- throw new InvalidArgumentException( 'Bad tag name' );
- }
- foreach ( $arr as $k => &$v ) {
- if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
- $v[self::META_INDEXED_TAG_NAME] = $tag;
- $this->setIndexedTagName_recursive( $v, $tag );
- }
- }
- }
-
- /**
- * Alias for self::addIndexedTagName()
- * @deprecated since 1.25, use $this->addIndexedTagName() instead
- * @param array $path Path to the array, like addValue()'s $path
- * @param string $tag
- */
- public function setIndexedTagName_internal( $path, $tag ) {
- wfDeprecated( __METHOD__, '1.25' );
- $this->addIndexedTagName( $path, $tag );
- }
-
- /**
- * Alias for self::addParsedLimit()
- * @deprecated since 1.25, use $this->addParsedLimit() instead
- * @param string $moduleName
- * @param int $limit
- */
- public function setParsedLimit( $moduleName, $limit ) {
- wfDeprecated( __METHOD__, '1.25' );
- $this->addParsedLimit( $moduleName, $limit );
- }
-
- /**
- * Set the ApiMain for use by $this->beginContinuation()
- * @since 1.25
- * @deprecated for backwards compatibility only, do not use
- * @param ApiMain $main
- */
- public function setMainForContinuation( ApiMain $main ) {
- $this->mainForContinuation = $main;
- }
-
- /**
- * Parse a 'continue' parameter and return status information.
- *
- * This must be balanced by a call to endContinuation().
- *
- * @since 1.24
- * @deprecated since 1.25, use ApiContinuationManager instead
- * @param string|null $continue
- * @param ApiBase[] $allModules
- * @param array $generatedModules
- * @return array
- */
- public function beginContinuation(
- $continue, array $allModules = [], array $generatedModules = []
- ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( $this->mainForContinuation->getContinuationManager() ) {
- throw new UnexpectedValueException(
- __METHOD__ . ': Continuation already in progress from ' .
- $this->mainForContinuation->getContinuationManager()->getSource()
- );
- }
-
- // Ugh. If $continue doesn't match that in the request, temporarily
- // replace the request when creating the ApiContinuationManager.
- if ( $continue === null ) {
- $continue = '';
- }
- if ( $this->mainForContinuation->getVal( 'continue', '' ) !== $continue ) {
- $oldCtx = $this->mainForContinuation->getContext();
- $newCtx = new DerivativeContext( $oldCtx );
- $newCtx->setRequest( new DerivativeRequest(
- $oldCtx->getRequest(),
- [ 'continue' => $continue ] + $oldCtx->getRequest()->getValues(),
- $oldCtx->getRequest()->wasPosted()
- ) );
- $this->mainForContinuation->setContext( $newCtx );
- $reset = new ScopedCallback(
- [ $this->mainForContinuation, 'setContext' ],
- [ $oldCtx ]
- );
- }
- $manager = new ApiContinuationManager(
- $this->mainForContinuation, $allModules, $generatedModules
- );
- $reset = null;
-
- $this->mainForContinuation->setContinuationManager( $manager );
-
- return [
- $manager->isGeneratorDone(),
- $manager->getRunModules(),
- ];
- }
-
- /**
- * @since 1.24
- * @deprecated since 1.25, use ApiContinuationManager instead
- * @param ApiBase $module
- * @param string $paramName
- * @param string|array $paramValue
- */
- public function setContinueParam( ApiBase $module, $paramName, $paramValue ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( $this->mainForContinuation->getContinuationManager() ) {
- $this->mainForContinuation->getContinuationManager()->addContinueParam(
- $module, $paramName, $paramValue
- );
- }
- }
-
- /**
- * @since 1.24
- * @deprecated since 1.25, use ApiContinuationManager instead
- * @param ApiBase $module
- * @param string $paramName
- * @param string|array $paramValue
- */
- public function setGeneratorContinueParam( ApiBase $module, $paramName, $paramValue ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( $this->mainForContinuation->getContinuationManager() ) {
- $this->mainForContinuation->getContinuationManager()->addGeneratorContinueParam(
- $module, $paramName, $paramValue
- );
- }
- }
-
- /**
- * Close continuation, writing the data into the result
- * @since 1.24
- * @deprecated since 1.25, use ApiContinuationManager instead
- * @param string $style 'standard' for the new style since 1.21, 'raw' for
- * the style used in 1.20 and earlier.
- */
- public function endContinuation( $style = 'standard' ) {
- wfDeprecated( __METHOD__, '1.25' );
- if ( !$this->mainForContinuation->getContinuationManager() ) {
- return;
- }
-
- if ( $style === 'raw' ) {
- $data = $this->mainForContinuation->getContinuationManager()->getRawContinuation();
- if ( $data ) {
- $this->addValue( null, 'query-continue', $data, self::ADD_ON_TOP | self::NO_SIZE_CHECK );
- }
- } else {
- $this->mainForContinuation->getContinuationManager()->setContinuationIntoResult( $this );
- }
- }
-
- /**
- * No-op, this is now checked on insert.
- * @deprecated since 1.25
- */
- public function cleanUpUTF8() {
- wfDeprecated( __METHOD__, '1.25' );
- }
-
- /**
- * Get the 'real' size of a result item. This means the strlen() of the item,
- * or the sum of the strlen()s of the elements if the item is an array.
- * @deprecated since 1.25, no external users known and there doesn't seem
- * to be any case for such use over just checking the return value from the
- * add/set methods.
- * @param mixed $value
- * @return int
- */
- public static function size( $value ) {
- wfDeprecated( __METHOD__, '1.25' );
- return self::valueSize( self::validateValue( $value ) );
- }
-
- /**
- * Converts a Status object to an array suitable for addValue
- * @deprecated since 1.25, use ApiErrorFormatter::arrayFromStatus()
- * @param Status $status
- * @param string $errorType
- * @return array
- */
- public function convertStatusToArray( $status, $errorType = 'error' ) {
- wfDeprecated( __METHOD__, '1.25' );
- return $this->errorFormatter->arrayFromStatus( $status, $errorType );
- }
-
- /**@}*/
}
/**
$searchEngine = MediaWikiServices::getInstance()->newSearchEngine();
$params = [];
foreach ( $configs as $paramName => $paramConfig ) {
- $profiles = $searchEngine->getProfiles( $paramConfig['profile-type'] );
+ $profiles = $searchEngine->getProfiles( $paramConfig['profile-type'],
+ $this->getContext()->getUser() );
if ( !$profiles ) {
continue;
}
* containing 'help-message' and 'profile-type' keys.
*/
abstract public function getSearchProfileParams();
+
+ /**
+ * @return IContextSource
+ */
+ abstract public function getContext();
}
* @return null
*/
public function log( $level, $message, array $context = [] ) {
+ if ( $this->channel === 'DBQuery' && isset( $context['method'] )
+ && isset( $context['master'] ) && isset( $context['runtime'] )
+ ) {
+ MWDebug::query( $message, $context['method'], $context['master'], $context['runtime'] );
+ return; // only send profiling data to MWDebug profiling
+ }
+
if ( isset( self::$dbChannels[$this->channel] )
&& isset( self::$levelMapping[$level] )
&& self::$levelMapping[$level] >= LogLevel::ERROR
$destination = self::destination( $effectiveChannel, $message, $context );
self::emit( $text, $destination );
}
- if ( $this->channel === 'DBQuery' && isset( $context['method'] )
- && isset( $context['master'] ) && isset( $context['runtime'] )
- ) {
- MWDebug::query( $message, $context['method'], $context['master'], $context['runtime'] );
- } elseif ( !isset( $context['private'] ) || !$context['private'] ) {
+ if ( !isset( $context['private'] ) || !$context['private'] ) {
// Add to debug toolbar if not marked as "private"
MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
}
return $timestamp;
}
- /**
- * Guess the MIME type from the file contents alone
- *
- * @return string
- */
- public function getMimeType() {
- return MimeMagic::singleton()->guessMimeType( $this->path, false );
- }
-
/**
* Get an associative array containing information about
* a file with the given storage path.
* @return array
*/
public function getProps( $ext = true ) {
- wfDebug( __METHOD__ . ": Getting file info for $this->path\n" );
-
$info = self::placeholderProps();
$info['fileExists'] = $this->exists();
}
# MIME type according to file contents
- $info['file-mime'] = $this->getMimeType();
+ $info['file-mime'] = $magic->guessMimeType( $this->path, false );
# logical MIME type
$info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
$handler = MediaHandler::getHandler( $info['mime'] );
if ( $handler ) {
$tempImage = (object)[]; // XXX (hack for File object)
+ /** @noinspection PhpParamsInspection */
$info['metadata'] = $handler->getMetadata( $tempImage, $this->path );
+ /** @noinspection PhpParamsInspection */
$gis = $handler->getImageSize( $tempImage, $this->path, $info['metadata'] );
if ( is_array( $gis ) ) {
$info = $this->extractImageSizeInfo( $gis ) + $info;
}
}
$info['sha1'] = $this->getSha1Base36();
-
- wfDebug( __METHOD__ . ": $this->path loaded, {$info['size']} bytes, {$info['mime']}.\n" );
- } else {
- wfDebug( __METHOD__ . ": $this->path NOT FOUND!\n" );
}
return $info;
+++ /dev/null
-<?php
-/**
- * @defgroup FileBackend File backend
- *
- * File backend is used to interact with file storage systems,
- * such as the local file system, NFS, or cloud storage systems.
- */
-
-/**
- * Base class for all file backends.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
- * @file
- * @ingroup FileBackend
- * @author Aaron Schulz
- */
-
-/**
- * @brief Base class for all file backend classes (including multi-write backends).
- *
- * This class defines the methods as abstract that subclasses must implement.
- * Outside callers can assume that all backends will have these functions.
- *
- * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
- * The "backend" portion is unique name for MediaWiki to refer to a backend, while
- * the "container" portion is a top-level directory of the backend. The "path" portion
- * is a relative path that uses UNIX file system (FS) notation, though any particular
- * backend may not actually be using a local filesystem. Therefore, the relative paths
- * are only virtual.
- *
- * Backend contents are stored under wiki-specific container names by default.
- * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
- * For legacy reasons, the FSFileBackend class allows manually setting the paths of
- * containers to ones that do not respect the "wiki ID".
- *
- * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
- * FS-based backends are somewhat more restrictive due to the existence of real
- * directory files; a regular file cannot have the same name as a directory. Other
- * backends with virtual directories may not have this limitation. Callers should
- * store files in such a way that no files and directories are under the same path.
- *
- * In general, this class allows for callers to access storage through the same
- * interface, without regard to the underlying storage system. However, calling code
- * must follow certain patterns and be aware of certain things to ensure compatibility:
- * - a) Always call prepare() on the parent directory before trying to put a file there;
- * key/value stores only need the container to exist first, but filesystems need
- * all the parent directories to exist first (prepare() is aware of all this)
- * - b) Always call clean() on a directory when it might become empty to avoid empty
- * directory buildup on filesystems; key/value stores never have empty directories,
- * so doing this helps preserve consistency in both cases
- * - c) Likewise, do not rely on the existence of empty directories for anything;
- * calling directoryExists() on a path that prepare() was previously called on
- * will return false for key/value stores if there are no files under that path
- * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
- * either be a copy of the source file in /tmp or the original source file itself
- * - e) Use a file layout that results in never attempting to store files over directories
- * or directories over files; key/value stores allow this but filesystems do not
- * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
- * - g) Do not assume that move operations are atomic (difficult with key/value stores)
- * - h) Do not assume that file stat or read operations always have immediate consistency;
- * various methods have a "latest" flag that should always be used if up-to-date
- * information is required (this trades performance for correctness as needed)
- * - i) Do not assume that directory listings have immediate consistency
- *
- * Methods of subclasses should avoid throwing exceptions at all costs.
- * As a corollary, external dependencies should be kept to a minimum.
- *
- * @ingroup FileBackend
- * @since 1.19
- */
-abstract class FileBackend {
- /** @var string Unique backend name */
- protected $name;
-
- /** @var string Unique wiki name */
- protected $wikiId;
-
- /** @var string Read-only explanation message */
- protected $readOnly;
-
- /** @var string When to do operations in parallel */
- protected $parallelize;
-
- /** @var int How many operations can be done in parallel */
- protected $concurrency;
-
- /** @var LockManager */
- protected $lockManager;
-
- /** @var FileJournal */
- protected $fileJournal;
-
- /** @var callable */
- protected $statusWrapper;
-
- /** Bitfield flags for supported features */
- const ATTR_HEADERS = 1; // files can be tagged with standard HTTP headers
- const ATTR_METADATA = 2; // files can be stored with metadata key/values
- const ATTR_UNICODE_PATHS = 4; // files can have Unicode paths (not just ASCII)
-
- /**
- * Create a new backend instance from configuration.
- * This should only be called from within FileBackendGroup.
- *
- * @param array $config Parameters include:
- * - name : The unique name of this backend.
- * This should consist of alphanumberic, '-', and '_' characters.
- * This name should not be changed after use (e.g. with journaling).
- * Note that the name is *not* used in actual container names.
- * - wikiId : Prefix to container names that is unique to this backend.
- * It should only consist of alphanumberic, '-', and '_' characters.
- * This ID is what avoids collisions if multiple logical backends
- * use the same storage system, so this should be set carefully.
- * - lockManager : LockManager object to use for any file locking.
- * If not provided, then no file locking will be enforced.
- * - fileJournal : FileJournal object to use for logging changes to files.
- * If not provided, then change journaling will be disabled.
- * - readOnly : Write operations are disallowed if this is a non-empty string.
- * It should be an explanation for the backend being read-only.
- * - parallelize : When to do file operations in parallel (when possible).
- * Allowed values are "implicit", "explicit" and "off".
- * - concurrency : How many file operations can be done in parallel.
- * @throws FileBackendException
- */
- public function __construct( array $config ) {
- $this->name = $config['name'];
- $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
- if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
- throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
- } elseif ( !is_string( $this->wikiId ) ) {
- throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
- }
- $this->lockManager = isset( $config['lockManager'] )
- ? $config['lockManager']
- : new NullLockManager( [] );
- $this->fileJournal = isset( $config['fileJournal'] )
- ? $config['fileJournal']
- : FileJournal::factory( [ 'class' => 'NullFileJournal' ], $this->name );
- $this->readOnly = isset( $config['readOnly'] )
- ? (string)$config['readOnly']
- : '';
- $this->parallelize = isset( $config['parallelize'] )
- ? (string)$config['parallelize']
- : 'off';
- $this->concurrency = isset( $config['concurrency'] )
- ? (int)$config['concurrency']
- : 50;
- // @TODO: dependency inject this
- $this->statusWrapper = [ 'Status', 'wrap' ];
- }
-
- /**
- * Get the unique backend name.
- * We may have multiple different backends of the same type.
- * For example, we can have two Swift backends using different proxies.
- *
- * @return string
- */
- final public function getName() {
- return $this->name;
- }
-
- /**
- * Get the wiki identifier used for this backend (possibly empty).
- * Note that this might *not* be in the same format as wfWikiID().
- *
- * @return string
- * @since 1.20
- */
- final public function getWikiId() {
- return $this->wikiId;
- }
-
- /**
- * Check if this backend is read-only
- *
- * @return bool
- */
- final public function isReadOnly() {
- return ( $this->readOnly != '' );
- }
-
- /**
- * Get an explanatory message if this backend is read-only
- *
- * @return string|bool Returns false if the backend is not read-only
- */
- final public function getReadOnlyReason() {
- return ( $this->readOnly != '' ) ? $this->readOnly : false;
- }
-
- /**
- * Get the a bitfield of extra features supported by the backend medium
- *
- * @return int Bitfield of FileBackend::ATTR_* flags
- * @since 1.23
- */
- public function getFeatures() {
- return self::ATTR_UNICODE_PATHS;
- }
-
- /**
- * Check if the backend medium supports a field of extra features
- *
- * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
- * @return bool
- * @since 1.23
- */
- final public function hasFeatures( $bitfield ) {
- return ( $this->getFeatures() & $bitfield ) === $bitfield;
- }
-
- /**
- * This is the main entry point into the backend for write operations.
- * Callers supply an ordered list of operations to perform as a transaction.
- * Files will be locked, the stat cache cleared, and then the operations attempted.
- * If any serious errors occur, all attempted operations will be rolled back.
- *
- * $ops is an array of arrays. The outer array holds a list of operations.
- * Each inner array is a set of key value pairs that specify an operation.
- *
- * Supported operations and their parameters. The supported actions are:
- * - create
- * - store
- * - copy
- * - move
- * - delete
- * - describe (since 1.21)
- * - null
- *
- * FSFile/TempFSFile object support was added in 1.27.
- *
- * a) Create a new file in storage with the contents of a string
- * @code
- * [
- * 'op' => 'create',
- * 'dst' => <storage path>,
- * 'content' => <string of new file contents>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>,
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * b) Copy a file system file into storage
- * @code
- * [
- * 'op' => 'store',
- * 'src' => <file system path, FSFile, or TempFSFile>,
- * 'dst' => <storage path>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>,
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * c) Copy a file within storage
- * @code
- * [
- * 'op' => 'copy',
- * 'src' => <storage path>,
- * 'dst' => <storage path>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>,
- * 'ignoreMissingSource' => <boolean>, # since 1.21
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * d) Move a file within storage
- * @code
- * [
- * 'op' => 'move',
- * 'src' => <storage path>,
- * 'dst' => <storage path>,
- * 'overwrite' => <boolean>,
- * 'overwriteSame' => <boolean>,
- * 'ignoreMissingSource' => <boolean>, # since 1.21
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * e) Delete a file within storage
- * @code
- * [
- * 'op' => 'delete',
- * 'src' => <storage path>,
- * 'ignoreMissingSource' => <boolean>
- * ]
- * @endcode
- *
- * f) Update metadata for a file within storage
- * @code
- * [
- * 'op' => 'describe',
- * 'src' => <storage path>,
- * 'headers' => <HTTP header name/value map>
- * ]
- * @endcode
- *
- * g) Do nothing (no-op)
- * @code
- * [
- * 'op' => 'null',
- * ]
- * @endcode
- *
- * Boolean flags for operations (operation-specific):
- * - ignoreMissingSource : The operation will simply succeed and do
- * nothing if the source file does not exist.
- * - overwrite : Any destination file will be overwritten.
- * - overwriteSame : If a file already exists at the destination with the
- * same contents, then do nothing to the destination file
- * instead of giving an error. This does not compare headers.
- * This option is ignored if 'overwrite' is already provided.
- * - headers : If supplied, the result of merging these headers with any
- * existing source file headers (replacing conflicting ones)
- * will be set as the destination file headers. Headers are
- * deleted if their value is set to the empty string. When a
- * file has headers they are included in responses to GET and
- * HEAD requests to the backing store for that file.
- * Header values should be no larger than 255 bytes, except for
- * Content-Disposition. The system might ignore or truncate any
- * headers that are too long to store (exact limits will vary).
- * Backends that don't support metadata ignore this. (since 1.21)
- *
- * $opts is an associative of boolean flags, including:
- * - force : Operation precondition errors no longer trigger an abort.
- * Any remaining operations are still attempted. Unexpected
- * failures may still cause remaining operations to be aborted.
- * - nonLocking : No locks are acquired for the operations.
- * This can increase performance for non-critical writes.
- * This has no effect unless the 'force' flag is set.
- * - nonJournaled : Don't log this operation batch in the file journal.
- * This limits the ability of recovery scripts.
- * - parallelize : Try to do operations in parallel when possible.
- * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
- * - preserveCache : Don't clear the process cache before checking files.
- * This should only be used if all entries in the process
- * cache were added after the files were already locked. (since 1.20)
- *
- * @remarks Remarks on locking:
- * File system paths given to operations should refer to files that are
- * already locked or otherwise safe from modification from other processes.
- * Normally these files will be new temp files, which should be adequate.
- *
- * @par Return value:
- *
- * This returns a Status, which contains all warnings and fatals that occurred
- * during the operation. The 'failCount', 'successCount', and 'success' members
- * will reflect each operation attempted.
- *
- * The StatusValue will be "OK" unless:
- * - a) unexpected operation errors occurred (network partitions, disk full...)
- * - b) significant operation errors occurred and 'force' was not set
- *
- * @param array $ops List of operations to execute in order
- * @param array $opts Batch operation options
- * @return StatusValue
- */
- final public function doOperations( array $ops, array $opts = [] ) {
- if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
- return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- if ( !count( $ops ) ) {
- return $this->newStatus(); // nothing to do
- }
-
- $ops = $this->resolveFSFileObjects( $ops );
- if ( empty( $opts['force'] ) ) { // sanity
- unset( $opts['nonLocking'] );
- }
-
- /** @noinspection PhpUnusedLocalVariableInspection */
- $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
-
- return $this->doOperationsInternal( $ops, $opts );
- }
-
- /**
- * @see FileBackend::doOperations()
- * @param array $ops
- * @param array $opts
- */
- abstract protected function doOperationsInternal( array $ops, array $opts );
-
- /**
- * Same as doOperations() except it takes a single operation.
- * If you are doing a batch of operations that should either
- * all succeed or all fail, then use that function instead.
- *
- * @see FileBackend::doOperations()
- *
- * @param array $op Operation
- * @param array $opts Operation options
- * @return StatusValue
- */
- final public function doOperation( array $op, array $opts = [] ) {
- return $this->doOperations( [ $op ], $opts );
- }
-
- /**
- * Performs a single create operation.
- * This sets $params['op'] to 'create' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param array $params Operation parameters
- * @param array $opts Operation options
- * @return StatusValue
- */
- final public function create( array $params, array $opts = [] ) {
- return $this->doOperation( [ 'op' => 'create' ] + $params, $opts );
- }
-
- /**
- * Performs a single store operation.
- * This sets $params['op'] to 'store' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param array $params Operation parameters
- * @param array $opts Operation options
- * @return StatusValue
- */
- final public function store( array $params, array $opts = [] ) {
- return $this->doOperation( [ 'op' => 'store' ] + $params, $opts );
- }
-
- /**
- * Performs a single copy operation.
- * This sets $params['op'] to 'copy' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param array $params Operation parameters
- * @param array $opts Operation options
- * @return StatusValue
- */
- final public function copy( array $params, array $opts = [] ) {
- return $this->doOperation( [ 'op' => 'copy' ] + $params, $opts );
- }
-
- /**
- * Performs a single move operation.
- * This sets $params['op'] to 'move' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param array $params Operation parameters
- * @param array $opts Operation options
- * @return StatusValue
- */
- final public function move( array $params, array $opts = [] ) {
- return $this->doOperation( [ 'op' => 'move' ] + $params, $opts );
- }
-
- /**
- * Performs a single delete operation.
- * This sets $params['op'] to 'delete' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param array $params Operation parameters
- * @param array $opts Operation options
- * @return StatusValue
- */
- final public function delete( array $params, array $opts = [] ) {
- return $this->doOperation( [ 'op' => 'delete' ] + $params, $opts );
- }
-
- /**
- * Performs a single describe operation.
- * This sets $params['op'] to 'describe' and passes it to doOperation().
- *
- * @see FileBackend::doOperation()
- *
- * @param array $params Operation parameters
- * @param array $opts Operation options
- * @return StatusValue
- * @since 1.21
- */
- final public function describe( array $params, array $opts = [] ) {
- return $this->doOperation( [ 'op' => 'describe' ] + $params, $opts );
- }
-
- /**
- * Perform a set of independent file operations on some files.
- *
- * This does no locking, nor journaling, and possibly no stat calls.
- * Any destination files that already exist will be overwritten.
- * This should *only* be used on non-original files, like cache files.
- *
- * Supported operations and their parameters:
- * - create
- * - store
- * - copy
- * - move
- * - delete
- * - describe (since 1.21)
- * - null
- *
- * FSFile/TempFSFile object support was added in 1.27.
- *
- * a) Create a new file in storage with the contents of a string
- * @code
- * [
- * 'op' => 'create',
- * 'dst' => <storage path>,
- * 'content' => <string of new file contents>,
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * b) Copy a file system file into storage
- * @code
- * [
- * 'op' => 'store',
- * 'src' => <file system path, FSFile, or TempFSFile>,
- * 'dst' => <storage path>,
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * c) Copy a file within storage
- * @code
- * [
- * 'op' => 'copy',
- * 'src' => <storage path>,
- * 'dst' => <storage path>,
- * 'ignoreMissingSource' => <boolean>, # since 1.21
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * d) Move a file within storage
- * @code
- * [
- * 'op' => 'move',
- * 'src' => <storage path>,
- * 'dst' => <storage path>,
- * 'ignoreMissingSource' => <boolean>, # since 1.21
- * 'headers' => <HTTP header name/value map> # since 1.21
- * ]
- * @endcode
- *
- * e) Delete a file within storage
- * @code
- * [
- * 'op' => 'delete',
- * 'src' => <storage path>,
- * 'ignoreMissingSource' => <boolean>
- * ]
- * @endcode
- *
- * f) Update metadata for a file within storage
- * @code
- * [
- * 'op' => 'describe',
- * 'src' => <storage path>,
- * 'headers' => <HTTP header name/value map>
- * ]
- * @endcode
- *
- * g) Do nothing (no-op)
- * @code
- * [
- * 'op' => 'null',
- * ]
- * @endcode
- *
- * @par Boolean flags for operations (operation-specific):
- * - ignoreMissingSource : The operation will simply succeed and do
- * nothing if the source file does not exist.
- * - headers : If supplied with a header name/value map, the backend will
- * reply with these headers when GETs/HEADs of the destination
- * file are made. Header values should be smaller than 256 bytes.
- * Content-Disposition headers can be longer, though the system
- * might ignore or truncate ones that are too long to store.
- * Existing headers will remain, but these will replace any
- * conflicting previous headers, and headers will be removed
- * if they are set to an empty string.
- * Backends that don't support metadata ignore this. (since 1.21)
- *
- * $opts is an associative of boolean flags, including:
- * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
- *
- * @par Return value:
- * This returns a Status, which contains all warnings and fatals that occurred
- * during the operation. The 'failCount', 'successCount', and 'success' members
- * will reflect each operation attempted for the given files. The StatusValue will be
- * considered "OK" as long as no fatal errors occurred.
- *
- * @param array $ops Set of operations to execute
- * @param array $opts Batch operation options
- * @return StatusValue
- * @since 1.20
- */
- final public function doQuickOperations( array $ops, array $opts = [] ) {
- if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
- return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- if ( !count( $ops ) ) {
- return $this->newStatus(); // nothing to do
- }
-
- $ops = $this->resolveFSFileObjects( $ops );
- foreach ( $ops as &$op ) {
- $op['overwrite'] = true; // avoids RTTs in key/value stores
- }
-
- /** @noinspection PhpUnusedLocalVariableInspection */
- $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
-
- return $this->doQuickOperationsInternal( $ops );
- }
-
- /**
- * @see FileBackend::doQuickOperations()
- * @param array $ops
- * @since 1.20
- */
- abstract protected function doQuickOperationsInternal( array $ops );
-
- /**
- * Same as doQuickOperations() except it takes a single operation.
- * If you are doing a batch of operations, then use that function instead.
- *
- * @see FileBackend::doQuickOperations()
- *
- * @param array $op Operation
- * @return StatusValue
- * @since 1.20
- */
- final public function doQuickOperation( array $op ) {
- return $this->doQuickOperations( [ $op ] );
- }
-
- /**
- * Performs a single quick create operation.
- * This sets $params['op'] to 'create' and passes it to doQuickOperation().
- *
- * @see FileBackend::doQuickOperation()
- *
- * @param array $params Operation parameters
- * @return StatusValue
- * @since 1.20
- */
- final public function quickCreate( array $params ) {
- return $this->doQuickOperation( [ 'op' => 'create' ] + $params );
- }
-
- /**
- * Performs a single quick store operation.
- * This sets $params['op'] to 'store' and passes it to doQuickOperation().
- *
- * @see FileBackend::doQuickOperation()
- *
- * @param array $params Operation parameters
- * @return StatusValue
- * @since 1.20
- */
- final public function quickStore( array $params ) {
- return $this->doQuickOperation( [ 'op' => 'store' ] + $params );
- }
-
- /**
- * Performs a single quick copy operation.
- * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
- *
- * @see FileBackend::doQuickOperation()
- *
- * @param array $params Operation parameters
- * @return StatusValue
- * @since 1.20
- */
- final public function quickCopy( array $params ) {
- return $this->doQuickOperation( [ 'op' => 'copy' ] + $params );
- }
-
- /**
- * Performs a single quick move operation.
- * This sets $params['op'] to 'move' and passes it to doQuickOperation().
- *
- * @see FileBackend::doQuickOperation()
- *
- * @param array $params Operation parameters
- * @return StatusValue
- * @since 1.20
- */
- final public function quickMove( array $params ) {
- return $this->doQuickOperation( [ 'op' => 'move' ] + $params );
- }
-
- /**
- * Performs a single quick delete operation.
- * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
- *
- * @see FileBackend::doQuickOperation()
- *
- * @param array $params Operation parameters
- * @return StatusValue
- * @since 1.20
- */
- final public function quickDelete( array $params ) {
- return $this->doQuickOperation( [ 'op' => 'delete' ] + $params );
- }
-
- /**
- * Performs a single quick describe operation.
- * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
- *
- * @see FileBackend::doQuickOperation()
- *
- * @param array $params Operation parameters
- * @return StatusValue
- * @since 1.21
- */
- final public function quickDescribe( array $params ) {
- return $this->doQuickOperation( [ 'op' => 'describe' ] + $params );
- }
-
- /**
- * Concatenate a list of storage files into a single file system file.
- * The target path should refer to a file that is already locked or
- * otherwise safe from modification from other processes. Normally,
- * the file will be a new temp file, which should be adequate.
- *
- * @param array $params Operation parameters, include:
- * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
- * - dst : file system path to 0-byte temp file
- * - parallelize : try to do operations in parallel when possible
- * @return StatusValue
- */
- abstract public function concatenate( array $params );
-
- /**
- * Prepare a storage directory for usage.
- * This will create any required containers and parent directories.
- * Backends using key/value stores only need to create the container.
- *
- * The 'noAccess' and 'noListing' parameters works the same as in secure(),
- * except they are only applied *if* the directory/container had to be created.
- * These flags should always be set for directories that have private files.
- * However, setting them is not guaranteed to actually do anything.
- * Additional server configuration may be needed to achieve the desired effect.
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - noAccess : try to deny file access (since 1.20)
- * - noListing : try to deny file listing (since 1.20)
- * - bypassReadOnly : allow writes in read-only mode (since 1.20)
- * @return StatusValue
- */
- final public function prepare( array $params ) {
- if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
- return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- /** @noinspection PhpUnusedLocalVariableInspection */
- $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
- return $this->doPrepare( $params );
- }
-
- /**
- * @see FileBackend::prepare()
- * @param array $params
- */
- abstract protected function doPrepare( array $params );
-
- /**
- * Take measures to block web access to a storage directory and
- * the container it belongs to. FS backends might add .htaccess
- * files whereas key/value store backends might revoke container
- * access to the storage user representing end-users in web requests.
- *
- * This is not guaranteed to actually make files or listings publically hidden.
- * Additional server configuration may be needed to achieve the desired effect.
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - noAccess : try to deny file access
- * - noListing : try to deny file listing
- * - bypassReadOnly : allow writes in read-only mode (since 1.20)
- * @return StatusValue
- */
- final public function secure( array $params ) {
- if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
- return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- /** @noinspection PhpUnusedLocalVariableInspection */
- $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
- return $this->doSecure( $params );
- }
-
- /**
- * @see FileBackend::secure()
- * @param array $params
- */
- abstract protected function doSecure( array $params );
-
- /**
- * Remove measures to block web access to a storage directory and
- * the container it belongs to. FS backends might remove .htaccess
- * files whereas key/value store backends might grant container
- * access to the storage user representing end-users in web requests.
- * This essentially can undo the result of secure() calls.
- *
- * This is not guaranteed to actually make files or listings publically viewable.
- * Additional server configuration may be needed to achieve the desired effect.
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - access : try to allow file access
- * - listing : try to allow file listing
- * - bypassReadOnly : allow writes in read-only mode (since 1.20)
- * @return StatusValue
- * @since 1.20
- */
- final public function publish( array $params ) {
- if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
- return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- /** @noinspection PhpUnusedLocalVariableInspection */
- $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
- return $this->doPublish( $params );
- }
-
- /**
- * @see FileBackend::publish()
- * @param array $params
- */
- abstract protected function doPublish( array $params );
-
- /**
- * Delete a storage directory if it is empty.
- * Backends using key/value stores may do nothing unless the directory
- * is that of an empty container, in which case it will be deleted.
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - recursive : recursively delete empty subdirectories first (since 1.20)
- * - bypassReadOnly : allow writes in read-only mode (since 1.20)
- * @return StatusValue
- */
- final public function clean( array $params ) {
- if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
- return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
- }
- /** @noinspection PhpUnusedLocalVariableInspection */
- $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
- return $this->doClean( $params );
- }
-
- /**
- * @see FileBackend::clean()
- * @param array $params
- */
- abstract protected function doClean( array $params );
-
- /**
- * Enter file operation scope.
- * This just makes PHP ignore user aborts/disconnects until the return
- * value leaves scope. This returns null and does nothing in CLI mode.
- *
- * @return ScopedCallback|null
- */
- final protected function getScopedPHPBehaviorForOps() {
- if ( PHP_SAPI != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
- $old = ignore_user_abort( true ); // avoid half-finished operations
- return new ScopedCallback( function () use ( $old ) {
- ignore_user_abort( $old );
- } );
- }
-
- return null;
- }
-
- /**
- * Check if a file exists at a storage path in the backend.
- * This returns false if only a directory exists at the path.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return bool|null Returns null on failure
- */
- abstract public function fileExists( array $params );
-
- /**
- * Get the last-modified timestamp of the file at a storage path.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return string|bool TS_MW timestamp or false on failure
- */
- abstract public function getFileTimestamp( array $params );
-
- /**
- * Get the contents of a file at a storage path in the backend.
- * This should be avoided for potentially large files.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return string|bool Returns false on failure
- */
- final public function getFileContents( array $params ) {
- $contents = $this->getFileContentsMulti(
- [ 'srcs' => [ $params['src'] ] ] + $params );
-
- return $contents[$params['src']];
- }
-
- /**
- * Like getFileContents() except it takes an array of storage paths
- * and returns a map of storage paths to strings (or null on failure).
- * The map keys (paths) are in the same order as the provided list of paths.
- *
- * @see FileBackend::getFileContents()
- *
- * @param array $params Parameters include:
- * - srcs : list of source storage paths
- * - latest : use the latest available data
- * - parallelize : try to do operations in parallel when possible
- * @return array Map of (path name => string or false on failure)
- * @since 1.20
- */
- abstract public function getFileContentsMulti( array $params );
-
- /**
- * Get metadata about a file at a storage path in the backend.
- * If the file does not exist, then this returns false.
- * Otherwise, the result is an associative array that includes:
- * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
- * - metadata : map of file metadata (name => value)
- * Metadata keys and headers names will be returned in all lower-case.
- * Additional values may be included for internal use only.
- *
- * Use FileBackend::hasFeatures() to check how well this is supported.
- *
- * @param array $params
- * $params include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return array|bool Returns false on failure
- * @since 1.23
- */
- abstract public function getFileXAttributes( array $params );
-
- /**
- * Get the size (bytes) of a file at a storage path in the backend.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return int|bool Returns false on failure
- */
- abstract public function getFileSize( array $params );
-
- /**
- * Get quick information about a file at a storage path in the backend.
- * If the file does not exist, then this returns false.
- * Otherwise, the result is an associative array that includes:
- * - mtime : the last-modified timestamp (TS_MW)
- * - size : the file size (bytes)
- * Additional values may be included for internal use only.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return array|bool|null Returns null on failure
- */
- abstract public function getFileStat( array $params );
-
- /**
- * Get a SHA-1 hash of the file at a storage path in the backend.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return string|bool Hash string or false on failure
- */
- abstract public function getFileSha1Base36( array $params );
-
- /**
- * Get the properties of the file at a storage path in the backend.
- * This gives the result of FSFile::getProps() on a local copy of the file.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return array Returns FSFile::placeholderProps() on failure
- */
- abstract public function getFileProps( array $params );
-
- /**
- * Stream the file at a storage path in the backend.
- *
- * If the file does not exists, an HTTP 404 error will be given.
- * Appropriate HTTP headers (Status, Content-Type, Content-Length)
- * will be sent if streaming began, while none will be sent otherwise.
- * Implementations should flush the output buffer before sending data.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - headers : list of additional HTTP headers to send if the file exists
- * - options : HTTP request header map with lower case keys (since 1.28). Supports:
- * range : format is "bytes=(\d*-\d*)"
- * if-modified-since : format is an HTTP date
- * - headless : only include the body (and headers from "headers") (since 1.28)
- * - latest : use the latest available data
- * - allowOB : preserve any output buffers (since 1.28)
- * @return StatusValue
- */
- abstract public function streamFile( array $params );
-
- /**
- * Returns a file system file, identical to the file at a storage path.
- * The file returned is either:
- * - a) A local copy of the file at a storage path in the backend.
- * The temporary copy will have the same extension as the source.
- * - b) An original of the file at a storage path in the backend.
- * Temporary files may be purged when the file object falls out of scope.
- *
- * Write operations should *never* be done on this file as some backends
- * may do internal tracking or may be instances of FileBackendMultiWrite.
- * In that latter case, there are copies of the file that must stay in sync.
- * Additionally, further calls to this function may return the same file.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return FSFile|null Returns null on failure
- */
- final public function getLocalReference( array $params ) {
- $fsFiles = $this->getLocalReferenceMulti(
- [ 'srcs' => [ $params['src'] ] ] + $params );
-
- return $fsFiles[$params['src']];
- }
-
- /**
- * Like getLocalReference() except it takes an array of storage paths
- * and returns a map of storage paths to FSFile objects (or null on failure).
- * The map keys (paths) are in the same order as the provided list of paths.
- *
- * @see FileBackend::getLocalReference()
- *
- * @param array $params Parameters include:
- * - srcs : list of source storage paths
- * - latest : use the latest available data
- * - parallelize : try to do operations in parallel when possible
- * @return array Map of (path name => FSFile or null on failure)
- * @since 1.20
- */
- abstract public function getLocalReferenceMulti( array $params );
-
- /**
- * Get a local copy on disk of the file at a storage path in the backend.
- * The temporary copy will have the same file extension as the source.
- * Temporary files may be purged when the file object falls out of scope.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - latest : use the latest available data
- * @return TempFSFile|null Returns null on failure
- */
- final public function getLocalCopy( array $params ) {
- $tmpFiles = $this->getLocalCopyMulti(
- [ 'srcs' => [ $params['src'] ] ] + $params );
-
- return $tmpFiles[$params['src']];
- }
-
- /**
- * Like getLocalCopy() except it takes an array of storage paths and
- * returns a map of storage paths to TempFSFile objects (or null on failure).
- * The map keys (paths) are in the same order as the provided list of paths.
- *
- * @see FileBackend::getLocalCopy()
- *
- * @param array $params Parameters include:
- * - srcs : list of source storage paths
- * - latest : use the latest available data
- * - parallelize : try to do operations in parallel when possible
- * @return array Map of (path name => TempFSFile or null on failure)
- * @since 1.20
- */
- abstract public function getLocalCopyMulti( array $params );
-
- /**
- * Return an HTTP URL to a given file that requires no authentication to use.
- * The URL may be pre-authenticated (via some token in the URL) and temporary.
- * This will return null if the backend cannot make an HTTP URL for the file.
- *
- * This is useful for key/value stores when using scripts that seek around
- * large files and those scripts (and the backend) support HTTP Range headers.
- * Otherwise, one would need to use getLocalReference(), which involves loading
- * the entire file on to local disk.
- *
- * @param array $params Parameters include:
- * - src : source storage path
- * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
- * @return string|null
- * @since 1.21
- */
- abstract public function getFileHttpUrl( array $params );
-
- /**
- * Check if a directory exists at a given storage path.
- * Backends using key/value stores will check if the path is a
- * virtual directory, meaning there are files under the given directory.
- *
- * Storage backends with eventual consistency might return stale data.
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * @return bool|null Returns null on failure
- * @since 1.20
- */
- abstract public function directoryExists( array $params );
-
- /**
- * Get an iterator to list *all* directories under a storage directory.
- * If the directory is of the form "mwstore://backend/container",
- * then all directories in the container will be listed.
- * If the directory is of form "mwstore://backend/container/dir",
- * then all directories directly under that directory will be listed.
- * Results will be storage directories relative to the given directory.
- *
- * Storage backends with eventual consistency might return stale data.
- *
- * Failures during iteration can result in FileBackendError exceptions (since 1.22).
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - topOnly : only return direct child dirs of the directory
- * @return Traversable|array|null Returns null on failure
- * @since 1.20
- */
- abstract public function getDirectoryList( array $params );
-
- /**
- * Same as FileBackend::getDirectoryList() except only lists
- * directories that are immediately under the given directory.
- *
- * Storage backends with eventual consistency might return stale data.
- *
- * Failures during iteration can result in FileBackendError exceptions (since 1.22).
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * @return Traversable|array|null Returns null on failure
- * @since 1.20
- */
- final public function getTopDirectoryList( array $params ) {
- return $this->getDirectoryList( [ 'topOnly' => true ] + $params );
- }
-
- /**
- * Get an iterator to list *all* stored files under a storage directory.
- * If the directory is of the form "mwstore://backend/container",
- * then all files in the container will be listed.
- * If the directory is of form "mwstore://backend/container/dir",
- * then all files under that directory will be listed.
- * Results will be storage paths relative to the given directory.
- *
- * Storage backends with eventual consistency might return stale data.
- *
- * Failures during iteration can result in FileBackendError exceptions (since 1.22).
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - topOnly : only return direct child files of the directory (since 1.20)
- * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
- * @return Traversable|array|null Returns null on failure
- */
- abstract public function getFileList( array $params );
-
- /**
- * Same as FileBackend::getFileList() except only lists
- * files that are immediately under the given directory.
- *
- * Storage backends with eventual consistency might return stale data.
- *
- * Failures during iteration can result in FileBackendError exceptions (since 1.22).
- *
- * @param array $params Parameters include:
- * - dir : storage directory
- * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
- * @return Traversable|array|null Returns null on failure
- * @since 1.20
- */
- final public function getTopFileList( array $params ) {
- return $this->getFileList( [ 'topOnly' => true ] + $params );
- }
-
- /**
- * Preload persistent file stat cache and property cache into in-process cache.
- * This should be used when stat calls will be made on a known list of a many files.
- *
- * @see FileBackend::getFileStat()
- *
- * @param array $paths Storage paths
- */
- abstract public function preloadCache( array $paths );
-
- /**
- * Invalidate any in-process file stat and property cache.
- * If $paths is given, then only the cache for those files will be cleared.
- *
- * @see FileBackend::getFileStat()
- *
- * @param array $paths Storage paths (optional)
- */
- abstract public function clearCache( array $paths = null );
-
- /**
- * Preload file stat information (concurrently if possible) into in-process cache.
- *
- * This should be used when stat calls will be made on a known list of a many files.
- * This does not make use of the persistent file stat cache.
- *
- * @see FileBackend::getFileStat()
- *
- * @param array $params Parameters include:
- * - srcs : list of source storage paths
- * - latest : use the latest available data
- * @return bool All requests proceeded without I/O errors (since 1.24)
- * @since 1.23
- */
- abstract public function preloadFileStat( array $params );
-
- /**
- * Lock the files at the given storage paths in the backend.
- * This will either lock all the files or none (on failure).
- *
- * Callers should consider using getScopedFileLocks() instead.
- *
- * @param array $paths Storage paths
- * @param int $type LockManager::LOCK_* constant
- * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
- * @return StatusValue
- */
- final public function lockFiles( array $paths, $type, $timeout = 0 ) {
- $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
-
- return $this->wrapStatus( $this->lockManager->lock( $paths, $type, $timeout ) );
- }
-
- /**
- * Unlock the files at the given storage paths in the backend.
- *
- * @param array $paths Storage paths
- * @param int $type LockManager::LOCK_* constant
- * @return StatusValue
- */
- final public function unlockFiles( array $paths, $type ) {
- $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
-
- return $this->wrapStatus( $this->lockManager->unlock( $paths, $type ) );
- }
-
- /**
- * Lock the files at the given storage paths in the backend.
- * This will either lock all the files or none (on failure).
- * On failure, the StatusValue object will be updated with errors.
- *
- * Once the return value goes out scope, the locks will be released and
- * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
- *
- * @see ScopedLock::factory()
- *
- * @param array $paths List of storage paths or map of lock types to path lists
- * @param int|string $type LockManager::LOCK_* constant or "mixed"
- * @param StatusValue $status StatusValue to update on lock/unlock
- * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
- * @return ScopedLock|null Returns null on failure
- */
- final public function getScopedFileLocks(
- array $paths, $type, StatusValue $status, $timeout = 0
- ) {
- if ( $type === 'mixed' ) {
- foreach ( $paths as &$typePaths ) {
- $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
- }
- } else {
- $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
- }
-
- return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
- }
-
- /**
- * Get an array of scoped locks needed for a batch of file operations.
- *
- * Normally, FileBackend::doOperations() handles locking, unless
- * the 'nonLocking' param is passed in. This function is useful if you
- * want the files to be locked for a broader scope than just when the
- * files are changing. For example, if you need to update DB metadata,
- * you may want to keep the files locked until finished.
- *
- * @see FileBackend::doOperations()
- *
- * @param array $ops List of file operations to FileBackend::doOperations()
- * @param StatusValue $status StatusValue to update on lock/unlock
- * @return ScopedLock|null
- * @since 1.20
- */
- abstract public function getScopedLocksForOps( array $ops, StatusValue $status );
-
- /**
- * Get the root storage path of this backend.
- * All container paths are "subdirectories" of this path.
- *
- * @return string Storage path
- * @since 1.20
- */
- final public function getRootStoragePath() {
- return "mwstore://{$this->name}";
- }
-
- /**
- * Get the storage path for the given container for this backend
- *
- * @param string $container Container name
- * @return string Storage path
- * @since 1.21
- */
- final public function getContainerStoragePath( $container ) {
- return $this->getRootStoragePath() . "/{$container}";
- }
-
- /**
- * Get the file journal object for this backend
- *
- * @return FileJournal
- */
- final public function getJournal() {
- return $this->fileJournal;
- }
-
- /**
- * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
- *
- * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
- * around as long it needs (which may vary greatly depending on configuration)
- *
- * @param array $ops File operation batch for FileBaclend::doOperations()
- * @return array File operation batch
- */
- protected function resolveFSFileObjects( array $ops ) {
- foreach ( $ops as &$op ) {
- $src = isset( $op['src'] ) ? $op['src'] : null;
- if ( $src instanceof FSFile ) {
- $op['srcRef'] = $src;
- $op['src'] = $src->getPath();
- }
- }
- unset( $op );
-
- return $ops;
- }
-
- /**
- * Check if a given path is a "mwstore://" path.
- * This does not do any further validation or any existence checks.
- *
- * @param string $path
- * @return bool
- */
- final public static function isStoragePath( $path ) {
- return ( strpos( $path, 'mwstore://' ) === 0 );
- }
-
- /**
- * Split a storage path into a backend name, a container name,
- * and a relative file path. The relative path may be the empty string.
- * This does not do any path normalization or traversal checks.
- *
- * @param string $storagePath
- * @return array (backend, container, rel object) or (null, null, null)
- */
- final public static function splitStoragePath( $storagePath ) {
- if ( self::isStoragePath( $storagePath ) ) {
- // Remove the "mwstore://" prefix and split the path
- $parts = explode( '/', substr( $storagePath, 10 ), 3 );
- if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
- if ( count( $parts ) == 3 ) {
- return $parts; // e.g. "backend/container/path"
- } else {
- return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
- }
- }
- }
-
- return [ null, null, null ];
- }
-
- /**
- * Normalize a storage path by cleaning up directory separators.
- * Returns null if the path is not of the format of a valid storage path.
- *
- * @param string $storagePath
- * @return string|null
- */
- final public static function normalizeStoragePath( $storagePath ) {
- list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
- if ( $relPath !== null ) { // must be for this backend
- $relPath = self::normalizeContainerPath( $relPath );
- if ( $relPath !== null ) {
- return ( $relPath != '' )
- ? "mwstore://{$backend}/{$container}/{$relPath}"
- : "mwstore://{$backend}/{$container}";
- }
- }
-
- return null;
- }
-
- /**
- * Get the parent storage directory of a storage path.
- * This returns a path like "mwstore://backend/container",
- * "mwstore://backend/container/...", or null if there is no parent.
- *
- * @param string $storagePath
- * @return string|null
- */
- final public static function parentStoragePath( $storagePath ) {
- $storagePath = dirname( $storagePath );
- list( , , $rel ) = self::splitStoragePath( $storagePath );
-
- return ( $rel === null ) ? null : $storagePath;
- }
-
- /**
- * Get the final extension from a storage or FS path
- *
- * @param string $path
- * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
- * @return string
- */
- final public static function extensionFromPath( $path, $case = 'lowercase' ) {
- $i = strrpos( $path, '.' );
- $ext = $i ? substr( $path, $i + 1 ) : '';
-
- if ( $case === 'lowercase' ) {
- $ext = strtolower( $ext );
- } elseif ( $case === 'uppercase' ) {
- $ext = strtoupper( $ext );
- }
-
- return $ext;
- }
-
- /**
- * Check if a relative path has no directory traversals
- *
- * @param string $path
- * @return bool
- * @since 1.20
- */
- final public static function isPathTraversalFree( $path ) {
- return ( self::normalizeContainerPath( $path ) !== null );
- }
-
- /**
- * Build a Content-Disposition header value per RFC 6266.
- *
- * @param string $type One of (attachment, inline)
- * @param string $filename Suggested file name (should not contain slashes)
- * @throws FileBackendError
- * @return string
- * @since 1.20
- */
- final public static function makeContentDisposition( $type, $filename = '' ) {
- $parts = [];
-
- $type = strtolower( $type );
- if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
- throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
- }
- $parts[] = $type;
-
- if ( strlen( $filename ) ) {
- $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
- }
-
- return implode( ';', $parts );
- }
-
- /**
- * Validate and normalize a relative storage path.
- * Null is returned if the path involves directory traversal.
- * Traversal is insecure for FS backends and broken for others.
- *
- * This uses the same traversal protection as Title::secureAndSplit().
- *
- * @param string $path Storage path relative to a container
- * @return string|null
- */
- final protected static function normalizeContainerPath( $path ) {
- // Normalize directory separators
- $path = strtr( $path, '\\', '/' );
- // Collapse any consecutive directory separators
- $path = preg_replace( '![/]{2,}!', '/', $path );
- // Remove any leading directory separator
- $path = ltrim( $path, '/' );
- // Use the same traversal protection as Title::secureAndSplit()
- if ( strpos( $path, '.' ) !== false ) {
- if (
- $path === '.' ||
- $path === '..' ||
- strpos( $path, './' ) === 0 ||
- strpos( $path, '../' ) === 0 ||
- strpos( $path, '/./' ) !== false ||
- strpos( $path, '/../' ) !== false
- ) {
- return null;
- }
- }
-
- return $path;
- }
-
- /**
- * Yields the result of the status wrapper callback on either:
- * - StatusValue::newGood() if this method is called without parameters
- * - StatusValue::newFatal() with all parameters to this method if passed in
- *
- * @param ... string
- * @return StatusValue
- */
- final protected function newStatus() {
- $args = func_get_args();
- if ( count( $args ) ) {
- $sv = call_user_func_array( [ 'StatusValue', 'newFatal' ], $args );
- } else {
- $sv = StatusValue::newGood();
- }
-
- return $this->wrapStatus( $sv );
- }
-
- /**
- * @param StatusValue $sv
- * @return StatusValue Modified status or StatusValue subclass
- */
- final protected function wrapStatus( StatusValue $sv ) {
- return $this->statusWrapper ? call_user_func( $this->statusWrapper, $sv ) : $sv;
- }
-}
-
-/**
- * Generic file backend exception for checked and unexpected (e.g. config) exceptions
- *
- * @ingroup FileBackend
- * @since 1.23
- */
-class FileBackendException extends Exception {
-}
-
-/**
- * File backend exception for checked exceptions (e.g. I/O errors)
- *
- * @ingroup FileBackend
- * @since 1.22
- */
-class FileBackendError extends FileBackendException {
-}
: FileJournal::factory( [ 'class' => 'NullFileJournal' ], $name );
$config['wanCache'] = ObjectCache::getMainWANInstance();
$config['mimeCallback'] = [ $this, 'guessMimeInternal' ];
+ $config['statusWrapper'] = [ 'Status', 'wrap' ];
$this->backends[$name]['instance'] = new $class( $config );
}
* Temporary files may be purged when the file object falls out of scope.
*
* @param string $prefix
- * @param string $extension
+ * @param string $extension Optional file extension
+ * @param string|null $tmpDirectory Optional parent directory
* @return TempFSFile|null
*/
- public static function factory( $prefix, $extension = '' ) {
+ public static function factory( $prefix, $extension = '', $tmpDirectory = null ) {
$ext = ( $extension != '' ) ? ".{$extension}" : '';
$attempts = 5;
while ( $attempts-- ) {
- $path = wfTempDir() . '/' . $prefix . wfRandomString( 12 ) . $ext;
+ $hex = sprintf( '%06x%06x', mt_rand( 0, 0xffffff ), mt_rand( 0, 0xffffff ) );
+ if ( !is_string( $tmpDirectory ) ) {
+ $tmpDirectory = self::getUsableTempDirectory();
+ }
+ $path = wfTempDir() . '/' . $prefix . $hex . $ext;
MediaWiki\suppressWarnings();
$newFileHandle = fopen( $path, 'x' );
MediaWiki\restoreWarnings();
return null;
}
+ /**
+ * @return string Filesystem path to a temporary directory
+ * @throws RuntimeException
+ */
+ public static function getUsableTempDirectory() {
+ $tmpDir = array_map( 'getenv', [ 'TMPDIR', 'TMP', 'TEMP' ] );
+ $tmpDir[] = sys_get_temp_dir();
+ $tmpDir[] = ini_get( 'upload_tmp_dir' );
+ foreach ( $tmpDir as $tmp ) {
+ if ( $tmp != '' && is_dir( $tmp ) && is_writable( $tmp ) ) {
+ return $tmp;
+ }
+ }
+
+ // PHP on Windows will detect C:\Windows\Temp as not writable even though PHP can write to
+ // it so create a directory within that called 'mwtmp' with a suffix of the user running
+ // the current process.
+ // The user is included as if various scripts are run by different users they will likely
+ // not be able to access each others temporary files.
+ if ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' ) {
+ $tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'mwtmp-' . get_current_user();
+ if ( !file_exists( $tmp ) ) {
+ mkdir( $tmp );
+ }
+ if ( is_dir( $tmp ) && is_writable( $tmp ) ) {
+ return $tmp;
+ }
+ }
+
+ throw new RuntimeException(
+ 'No writable temporary directory could be found. ' .
+ 'Please explicitly specify a writable directory in configuration.' );
+ }
+
/**
* Purge this file off the file system
*
+++ /dev/null
-<?php
-/**
- * @defgroup FileJournal File journal
- * @ingroup FileBackend
- */
-
-/**
- * File operation journaling.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
- * @file
- * @ingroup FileJournal
- * @author Aaron Schulz
- */
-
-/**
- * @brief Class for handling file operation journaling.
- *
- * Subclasses should avoid throwing exceptions at all costs.
- *
- * @ingroup FileJournal
- * @since 1.20
- */
-abstract class FileJournal {
- /** @var string */
- protected $backend;
-
- /** @var int */
- protected $ttlDays;
-
- /**
- * Construct a new instance from configuration.
- *
- * @param array $config Includes:
- * 'ttlDays' : days to keep log entries around (false means "forever")
- */
- protected function __construct( array $config ) {
- $this->ttlDays = isset( $config['ttlDays'] ) ? $config['ttlDays'] : false;
- }
-
- /**
- * Create an appropriate FileJournal object from config
- *
- * @param array $config
- * @param string $backend A registered file backend name
- * @throws Exception
- * @return FileJournal
- */
- final public static function factory( array $config, $backend ) {
- $class = $config['class'];
- $jrn = new $class( $config );
- if ( !$jrn instanceof self ) {
- throw new Exception( "Class given is not an instance of FileJournal." );
- }
- $jrn->backend = $backend;
-
- return $jrn;
- }
-
- /**
- * Get a statistically unique ID string
- *
- * @return string <9 char TS_MW timestamp in base 36><22 random base 36 chars>
- */
- final public function getTimestampedUUID() {
- $s = '';
- for ( $i = 0; $i < 5; $i++ ) {
- $s .= mt_rand( 0, 2147483647 );
- }
- $s = Wikimedia\base_convert( sha1( $s ), 16, 36, 31 );
-
- return substr( Wikimedia\base_convert( wfTimestamp( TS_MW ), 10, 36, 9 ) . $s, 0, 31 );
- }
-
- /**
- * Log changes made by a batch file operation.
- *
- * @param array $entries List of file operations (each an array of parameters) which contain:
- * op : Basic operation name (create, update, delete)
- * path : The storage path of the file
- * newSha1 : The final base 36 SHA-1 of the file
- * Note that 'false' should be used as the SHA-1 for non-existing files.
- * @param string $batchId UUID string that identifies the operation batch
- * @return StatusValue
- */
- final public function logChangeBatch( array $entries, $batchId ) {
- if ( !count( $entries ) ) {
- return StatusValue::newGood();
- }
-
- return $this->doLogChangeBatch( $entries, $batchId );
- }
-
- /**
- * @see FileJournal::logChangeBatch()
- *
- * @param array $entries List of file operations (each an array of parameters)
- * @param string $batchId UUID string that identifies the operation batch
- * @return StatusValue
- */
- abstract protected function doLogChangeBatch( array $entries, $batchId );
-
- /**
- * Get the position ID of the latest journal entry
- *
- * @return int|bool
- */
- final public function getCurrentPosition() {
- return $this->doGetCurrentPosition();
- }
-
- /**
- * @see FileJournal::getCurrentPosition()
- * @return int|bool
- */
- abstract protected function doGetCurrentPosition();
-
- /**
- * Get the position ID of the latest journal entry at some point in time
- *
- * @param int|string $time Timestamp
- * @return int|bool
- */
- final public function getPositionAtTime( $time ) {
- return $this->doGetPositionAtTime( $time );
- }
-
- /**
- * @see FileJournal::getPositionAtTime()
- * @param int|string $time Timestamp
- * @return int|bool
- */
- abstract protected function doGetPositionAtTime( $time );
-
- /**
- * Get an array of file change log entries.
- * A starting change ID and/or limit can be specified.
- *
- * @param int $start Starting change ID or null
- * @param int $limit Maximum number of items to return
- * @param string &$next Updated to the ID of the next entry.
- * @return array List of associative arrays, each having:
- * id : unique, monotonic, ID for this change
- * batch_uuid : UUID for an operation batch
- * backend : the backend name
- * op : primitive operation (create,update,delete,null)
- * path : affected storage path
- * new_sha1 : base 36 sha1 of the new file had the operation succeeded
- * timestamp : TS_MW timestamp of the batch change
- * Also, $next is updated to the ID of the next entry.
- */
- final public function getChangeEntries( $start = null, $limit = 0, &$next = null ) {
- $entries = $this->doGetChangeEntries( $start, $limit ? $limit + 1 : 0 );
- if ( $limit && count( $entries ) > $limit ) {
- $last = array_pop( $entries ); // remove the extra entry
- $next = $last['id']; // update for next call
- } else {
- $next = null; // end of list
- }
-
- return $entries;
- }
-
- /**
- * @see FileJournal::getChangeEntries()
- * @param int $start
- * @param int $limit
- * @return array
- */
- abstract protected function doGetChangeEntries( $start, $limit );
-
- /**
- * Purge any old log entries
- *
- * @return StatusValue
- */
- final public function purgeOldLogs() {
- return $this->doPurgeOldLogs();
- }
-
- /**
- * @see FileJournal::purgeOldLogs()
- * @return StatusValue
- */
- abstract protected function doPurgeOldLogs();
-}
-
-/**
- * Simple version of FileJournal that does nothing
- * @since 1.20
- */
-class NullFileJournal extends FileJournal {
- /**
- * @see FileJournal::doLogChangeBatch()
- * @param array $entries
- * @param string $batchId
- * @return StatusValue
- */
- protected function doLogChangeBatch( array $entries, $batchId ) {
- return StatusValue::newGood();
- }
-
- /**
- * @see FileJournal::doGetCurrentPosition()
- * @return int|bool
- */
- protected function doGetCurrentPosition() {
- return false;
- }
-
- /**
- * @see FileJournal::doGetPositionAtTime()
- * @param int|string $time Timestamp
- * @return int|bool
- */
- protected function doGetPositionAtTime( $time ) {
- return false;
- }
-
- /**
- * @see FileJournal::doGetChangeEntries()
- * @param int $start
- * @param int $limit
- * @return array
- */
- protected function doGetChangeEntries( $start, $limit ) {
- return [];
- }
-
- /**
- * @see FileJournal::doPurgeOldLogs()
- * @return StatusValue
- */
- protected function doPurgeOldLogs() {
- return StatusValue::newGood();
- }
-}
+++ /dev/null
-<?php
-/**
- * Resource locking handling.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
- * @file
- * @ingroup LockManager
- * @author Aaron Schulz
- */
-
-/**
- * Self-releasing locks
- *
- * LockManager helper class to handle scoped locks, which
- * release when an object is destroyed or goes out of scope.
- *
- * @ingroup LockManager
- * @since 1.19
- */
-class ScopedLock {
- /** @var LockManager */
- protected $manager;
-
- /** @var StatusValue */
- protected $status;
-
- /** @var array Map of lock types to resource paths */
- protected $pathsByType;
-
- /**
- * @param LockManager $manager
- * @param array $pathsByType Map of lock types to path lists
- * @param StatusValue $status
- */
- protected function __construct( LockManager $manager, array $pathsByType, StatusValue $status ) {
- $this->manager = $manager;
- $this->pathsByType = $pathsByType;
- $this->status = $status;
- }
-
- /**
- * Get a ScopedLock object representing a lock on resource paths.
- * Any locks are released once this object goes out of scope.
- * The StatusValue object is updated with any errors or warnings.
- *
- * @param LockManager $manager
- * @param array $paths List of storage paths or map of lock types to path lists
- * @param int|string $type LockManager::LOCK_* constant or "mixed" and $paths
- * can be a map of types to paths (since 1.22). Otherwise $type should be an
- * integer and $paths should be a list of paths.
- * @param StatusValue $status
- * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.22)
- * @return ScopedLock|null Returns null on failure
- */
- public static function factory(
- LockManager $manager, array $paths, $type, StatusValue $status, $timeout = 0
- ) {
- $pathsByType = is_integer( $type ) ? [ $type => $paths ] : $paths;
- $lockStatus = $manager->lockByType( $pathsByType, $timeout );
- $status->merge( $lockStatus );
- if ( $lockStatus->isOK() ) {
- return new self( $manager, $pathsByType, $status );
- }
-
- return null;
- }
-
- /**
- * Release a scoped lock and set any errors in the attatched StatusValue object.
- * This is useful for early release of locks before function scope is destroyed.
- * This is the same as setting the lock object to null.
- *
- * @param ScopedLock $lock
- * @since 1.21
- */
- public static function release( ScopedLock &$lock = null ) {
- $lock = null;
- }
-
- /**
- * Release the locks when this goes out of scope
- */
- function __destruct() {
- $wasOk = $this->status->isOK();
- $this->status->merge( $this->manager->unlockByType( $this->pathsByType ) );
- if ( $wasOk ) {
- // Make sure StatusValue is OK, despite any unlockFiles() fatals
- $this->status->setResult( true, $this->status->value );
- }
- }
-}
*/
protected function makeTransformTmpFile( $thumbPath ) {
$thumbExt = FileBackend::extensionFromPath( $thumbPath );
- return TempFSFile::factory( 'transform_', $thumbExt );
+ return TempFSFile::factory( 'transform_', $thumbExt, wfTempDir() );
}
/**
--- /dev/null
+<?php
+/**
+ * @defgroup FileBackend File backend
+ *
+ * File backend is used to interact with file storage systems,
+ * such as the local file system, NFS, or cloud storage systems.
+ */
+
+/**
+ * Base class for all file backends.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup FileBackend
+ * @author Aaron Schulz
+ */
+
+/**
+ * @brief Base class for all file backend classes (including multi-write backends).
+ *
+ * This class defines the methods as abstract that subclasses must implement.
+ * Outside callers can assume that all backends will have these functions.
+ *
+ * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
+ * The "backend" portion is unique name for MediaWiki to refer to a backend, while
+ * the "container" portion is a top-level directory of the backend. The "path" portion
+ * is a relative path that uses UNIX file system (FS) notation, though any particular
+ * backend may not actually be using a local filesystem. Therefore, the relative paths
+ * are only virtual.
+ *
+ * Backend contents are stored under wiki-specific container names by default.
+ * Global (qualified) backends are achieved by configuring the "wiki ID" to a constant.
+ * For legacy reasons, the FSFileBackend class allows manually setting the paths of
+ * containers to ones that do not respect the "wiki ID".
+ *
+ * In key/value (object) stores, containers are the only hierarchy (the rest is emulated).
+ * FS-based backends are somewhat more restrictive due to the existence of real
+ * directory files; a regular file cannot have the same name as a directory. Other
+ * backends with virtual directories may not have this limitation. Callers should
+ * store files in such a way that no files and directories are under the same path.
+ *
+ * In general, this class allows for callers to access storage through the same
+ * interface, without regard to the underlying storage system. However, calling code
+ * must follow certain patterns and be aware of certain things to ensure compatibility:
+ * - a) Always call prepare() on the parent directory before trying to put a file there;
+ * key/value stores only need the container to exist first, but filesystems need
+ * all the parent directories to exist first (prepare() is aware of all this)
+ * - b) Always call clean() on a directory when it might become empty to avoid empty
+ * directory buildup on filesystems; key/value stores never have empty directories,
+ * so doing this helps preserve consistency in both cases
+ * - c) Likewise, do not rely on the existence of empty directories for anything;
+ * calling directoryExists() on a path that prepare() was previously called on
+ * will return false for key/value stores if there are no files under that path
+ * - d) Never alter the resulting FSFile returned from getLocalReference(), as it could
+ * either be a copy of the source file in /tmp or the original source file itself
+ * - e) Use a file layout that results in never attempting to store files over directories
+ * or directories over files; key/value stores allow this but filesystems do not
+ * - f) Use ASCII file names (e.g. base32, IDs, hashes) to avoid Unicode issues in Windows
+ * - g) Do not assume that move operations are atomic (difficult with key/value stores)
+ * - h) Do not assume that file stat or read operations always have immediate consistency;
+ * various methods have a "latest" flag that should always be used if up-to-date
+ * information is required (this trades performance for correctness as needed)
+ * - i) Do not assume that directory listings have immediate consistency
+ *
+ * Methods of subclasses should avoid throwing exceptions at all costs.
+ * As a corollary, external dependencies should be kept to a minimum.
+ *
+ * @ingroup FileBackend
+ * @since 1.19
+ */
+abstract class FileBackend {
+ /** @var string Unique backend name */
+ protected $name;
+
+ /** @var string Unique wiki name */
+ protected $wikiId;
+
+ /** @var string Read-only explanation message */
+ protected $readOnly;
+
+ /** @var string When to do operations in parallel */
+ protected $parallelize;
+
+ /** @var int How many operations can be done in parallel */
+ protected $concurrency;
+
+ /** @var LockManager */
+ protected $lockManager;
+
+ /** @var FileJournal */
+ protected $fileJournal;
+
+ /** @var callable */
+ protected $statusWrapper;
+
+ /** Bitfield flags for supported features */
+ const ATTR_HEADERS = 1; // files can be tagged with standard HTTP headers
+ const ATTR_METADATA = 2; // files can be stored with metadata key/values
+ const ATTR_UNICODE_PATHS = 4; // files can have Unicode paths (not just ASCII)
+
+ /**
+ * Create a new backend instance from configuration.
+ * This should only be called from within FileBackendGroup.
+ *
+ * @param array $config Parameters include:
+ * - name : The unique name of this backend.
+ * This should consist of alphanumberic, '-', and '_' characters.
+ * This name should not be changed after use (e.g. with journaling).
+ * Note that the name is *not* used in actual container names.
+ * - wikiId : Prefix to container names that is unique to this backend.
+ * It should only consist of alphanumberic, '-', and '_' characters.
+ * This ID is what avoids collisions if multiple logical backends
+ * use the same storage system, so this should be set carefully.
+ * - lockManager : LockManager object to use for any file locking.
+ * If not provided, then no file locking will be enforced.
+ * - fileJournal : FileJournal object to use for logging changes to files.
+ * If not provided, then change journaling will be disabled.
+ * - readOnly : Write operations are disallowed if this is a non-empty string.
+ * It should be an explanation for the backend being read-only.
+ * - parallelize : When to do file operations in parallel (when possible).
+ * Allowed values are "implicit", "explicit" and "off".
+ * - concurrency : How many file operations can be done in parallel.
+ * @throws FileBackendException
+ */
+ public function __construct( array $config ) {
+ $this->name = $config['name'];
+ $this->wikiId = $config['wikiId']; // e.g. "my_wiki-en_"
+ if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
+ throw new FileBackendException( "Backend name '{$this->name}' is invalid." );
+ } elseif ( !is_string( $this->wikiId ) ) {
+ throw new FileBackendException( "Backend wiki ID not provided for '{$this->name}'." );
+ }
+ $this->lockManager = isset( $config['lockManager'] )
+ ? $config['lockManager']
+ : new NullLockManager( [] );
+ $this->fileJournal = isset( $config['fileJournal'] )
+ ? $config['fileJournal']
+ : FileJournal::factory( [ 'class' => 'NullFileJournal' ], $this->name );
+ $this->readOnly = isset( $config['readOnly'] )
+ ? (string)$config['readOnly']
+ : '';
+ $this->parallelize = isset( $config['parallelize'] )
+ ? (string)$config['parallelize']
+ : 'off';
+ $this->concurrency = isset( $config['concurrency'] )
+ ? (int)$config['concurrency']
+ : 50;
+ $this->statusWrapper = isset( $config['statusWrapper'] ) ? $config['statusWrapper'] : null;
+ }
+
+ /**
+ * Get the unique backend name.
+ * We may have multiple different backends of the same type.
+ * For example, we can have two Swift backends using different proxies.
+ *
+ * @return string
+ */
+ final public function getName() {
+ return $this->name;
+ }
+
+ /**
+ * Get the wiki identifier used for this backend (possibly empty).
+ * Note that this might *not* be in the same format as wfWikiID().
+ *
+ * @return string
+ * @since 1.20
+ */
+ final public function getWikiId() {
+ return $this->wikiId;
+ }
+
+ /**
+ * Check if this backend is read-only
+ *
+ * @return bool
+ */
+ final public function isReadOnly() {
+ return ( $this->readOnly != '' );
+ }
+
+ /**
+ * Get an explanatory message if this backend is read-only
+ *
+ * @return string|bool Returns false if the backend is not read-only
+ */
+ final public function getReadOnlyReason() {
+ return ( $this->readOnly != '' ) ? $this->readOnly : false;
+ }
+
+ /**
+ * Get the a bitfield of extra features supported by the backend medium
+ *
+ * @return int Bitfield of FileBackend::ATTR_* flags
+ * @since 1.23
+ */
+ public function getFeatures() {
+ return self::ATTR_UNICODE_PATHS;
+ }
+
+ /**
+ * Check if the backend medium supports a field of extra features
+ *
+ * @param int $bitfield Bitfield of FileBackend::ATTR_* flags
+ * @return bool
+ * @since 1.23
+ */
+ final public function hasFeatures( $bitfield ) {
+ return ( $this->getFeatures() & $bitfield ) === $bitfield;
+ }
+
+ /**
+ * This is the main entry point into the backend for write operations.
+ * Callers supply an ordered list of operations to perform as a transaction.
+ * Files will be locked, the stat cache cleared, and then the operations attempted.
+ * If any serious errors occur, all attempted operations will be rolled back.
+ *
+ * $ops is an array of arrays. The outer array holds a list of operations.
+ * Each inner array is a set of key value pairs that specify an operation.
+ *
+ * Supported operations and their parameters. The supported actions are:
+ * - create
+ * - store
+ * - copy
+ * - move
+ * - delete
+ * - describe (since 1.21)
+ * - null
+ *
+ * FSFile/TempFSFile object support was added in 1.27.
+ *
+ * a) Create a new file in storage with the contents of a string
+ * @code
+ * [
+ * 'op' => 'create',
+ * 'dst' => <storage path>,
+ * 'content' => <string of new file contents>,
+ * 'overwrite' => <boolean>,
+ * 'overwriteSame' => <boolean>,
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * b) Copy a file system file into storage
+ * @code
+ * [
+ * 'op' => 'store',
+ * 'src' => <file system path, FSFile, or TempFSFile>,
+ * 'dst' => <storage path>,
+ * 'overwrite' => <boolean>,
+ * 'overwriteSame' => <boolean>,
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * c) Copy a file within storage
+ * @code
+ * [
+ * 'op' => 'copy',
+ * 'src' => <storage path>,
+ * 'dst' => <storage path>,
+ * 'overwrite' => <boolean>,
+ * 'overwriteSame' => <boolean>,
+ * 'ignoreMissingSource' => <boolean>, # since 1.21
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * d) Move a file within storage
+ * @code
+ * [
+ * 'op' => 'move',
+ * 'src' => <storage path>,
+ * 'dst' => <storage path>,
+ * 'overwrite' => <boolean>,
+ * 'overwriteSame' => <boolean>,
+ * 'ignoreMissingSource' => <boolean>, # since 1.21
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * e) Delete a file within storage
+ * @code
+ * [
+ * 'op' => 'delete',
+ * 'src' => <storage path>,
+ * 'ignoreMissingSource' => <boolean>
+ * ]
+ * @endcode
+ *
+ * f) Update metadata for a file within storage
+ * @code
+ * [
+ * 'op' => 'describe',
+ * 'src' => <storage path>,
+ * 'headers' => <HTTP header name/value map>
+ * ]
+ * @endcode
+ *
+ * g) Do nothing (no-op)
+ * @code
+ * [
+ * 'op' => 'null',
+ * ]
+ * @endcode
+ *
+ * Boolean flags for operations (operation-specific):
+ * - ignoreMissingSource : The operation will simply succeed and do
+ * nothing if the source file does not exist.
+ * - overwrite : Any destination file will be overwritten.
+ * - overwriteSame : If a file already exists at the destination with the
+ * same contents, then do nothing to the destination file
+ * instead of giving an error. This does not compare headers.
+ * This option is ignored if 'overwrite' is already provided.
+ * - headers : If supplied, the result of merging these headers with any
+ * existing source file headers (replacing conflicting ones)
+ * will be set as the destination file headers. Headers are
+ * deleted if their value is set to the empty string. When a
+ * file has headers they are included in responses to GET and
+ * HEAD requests to the backing store for that file.
+ * Header values should be no larger than 255 bytes, except for
+ * Content-Disposition. The system might ignore or truncate any
+ * headers that are too long to store (exact limits will vary).
+ * Backends that don't support metadata ignore this. (since 1.21)
+ *
+ * $opts is an associative of boolean flags, including:
+ * - force : Operation precondition errors no longer trigger an abort.
+ * Any remaining operations are still attempted. Unexpected
+ * failures may still cause remaining operations to be aborted.
+ * - nonLocking : No locks are acquired for the operations.
+ * This can increase performance for non-critical writes.
+ * This has no effect unless the 'force' flag is set.
+ * - nonJournaled : Don't log this operation batch in the file journal.
+ * This limits the ability of recovery scripts.
+ * - parallelize : Try to do operations in parallel when possible.
+ * - bypassReadOnly : Allow writes in read-only mode. (since 1.20)
+ * - preserveCache : Don't clear the process cache before checking files.
+ * This should only be used if all entries in the process
+ * cache were added after the files were already locked. (since 1.20)
+ *
+ * @remarks Remarks on locking:
+ * File system paths given to operations should refer to files that are
+ * already locked or otherwise safe from modification from other processes.
+ * Normally these files will be new temp files, which should be adequate.
+ *
+ * @par Return value:
+ *
+ * This returns a Status, which contains all warnings and fatals that occurred
+ * during the operation. The 'failCount', 'successCount', and 'success' members
+ * will reflect each operation attempted.
+ *
+ * The StatusValue will be "OK" unless:
+ * - a) unexpected operation errors occurred (network partitions, disk full...)
+ * - b) significant operation errors occurred and 'force' was not set
+ *
+ * @param array $ops List of operations to execute in order
+ * @param array $opts Batch operation options
+ * @return StatusValue
+ */
+ final public function doOperations( array $ops, array $opts = [] ) {
+ if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
+ return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
+ }
+ if ( !count( $ops ) ) {
+ return $this->newStatus(); // nothing to do
+ }
+
+ $ops = $this->resolveFSFileObjects( $ops );
+ if ( empty( $opts['force'] ) ) { // sanity
+ unset( $opts['nonLocking'] );
+ }
+
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
+
+ return $this->doOperationsInternal( $ops, $opts );
+ }
+
+ /**
+ * @see FileBackend::doOperations()
+ * @param array $ops
+ * @param array $opts
+ */
+ abstract protected function doOperationsInternal( array $ops, array $opts );
+
+ /**
+ * Same as doOperations() except it takes a single operation.
+ * If you are doing a batch of operations that should either
+ * all succeed or all fail, then use that function instead.
+ *
+ * @see FileBackend::doOperations()
+ *
+ * @param array $op Operation
+ * @param array $opts Operation options
+ * @return StatusValue
+ */
+ final public function doOperation( array $op, array $opts = [] ) {
+ return $this->doOperations( [ $op ], $opts );
+ }
+
+ /**
+ * Performs a single create operation.
+ * This sets $params['op'] to 'create' and passes it to doOperation().
+ *
+ * @see FileBackend::doOperation()
+ *
+ * @param array $params Operation parameters
+ * @param array $opts Operation options
+ * @return StatusValue
+ */
+ final public function create( array $params, array $opts = [] ) {
+ return $this->doOperation( [ 'op' => 'create' ] + $params, $opts );
+ }
+
+ /**
+ * Performs a single store operation.
+ * This sets $params['op'] to 'store' and passes it to doOperation().
+ *
+ * @see FileBackend::doOperation()
+ *
+ * @param array $params Operation parameters
+ * @param array $opts Operation options
+ * @return StatusValue
+ */
+ final public function store( array $params, array $opts = [] ) {
+ return $this->doOperation( [ 'op' => 'store' ] + $params, $opts );
+ }
+
+ /**
+ * Performs a single copy operation.
+ * This sets $params['op'] to 'copy' and passes it to doOperation().
+ *
+ * @see FileBackend::doOperation()
+ *
+ * @param array $params Operation parameters
+ * @param array $opts Operation options
+ * @return StatusValue
+ */
+ final public function copy( array $params, array $opts = [] ) {
+ return $this->doOperation( [ 'op' => 'copy' ] + $params, $opts );
+ }
+
+ /**
+ * Performs a single move operation.
+ * This sets $params['op'] to 'move' and passes it to doOperation().
+ *
+ * @see FileBackend::doOperation()
+ *
+ * @param array $params Operation parameters
+ * @param array $opts Operation options
+ * @return StatusValue
+ */
+ final public function move( array $params, array $opts = [] ) {
+ return $this->doOperation( [ 'op' => 'move' ] + $params, $opts );
+ }
+
+ /**
+ * Performs a single delete operation.
+ * This sets $params['op'] to 'delete' and passes it to doOperation().
+ *
+ * @see FileBackend::doOperation()
+ *
+ * @param array $params Operation parameters
+ * @param array $opts Operation options
+ * @return StatusValue
+ */
+ final public function delete( array $params, array $opts = [] ) {
+ return $this->doOperation( [ 'op' => 'delete' ] + $params, $opts );
+ }
+
+ /**
+ * Performs a single describe operation.
+ * This sets $params['op'] to 'describe' and passes it to doOperation().
+ *
+ * @see FileBackend::doOperation()
+ *
+ * @param array $params Operation parameters
+ * @param array $opts Operation options
+ * @return StatusValue
+ * @since 1.21
+ */
+ final public function describe( array $params, array $opts = [] ) {
+ return $this->doOperation( [ 'op' => 'describe' ] + $params, $opts );
+ }
+
+ /**
+ * Perform a set of independent file operations on some files.
+ *
+ * This does no locking, nor journaling, and possibly no stat calls.
+ * Any destination files that already exist will be overwritten.
+ * This should *only* be used on non-original files, like cache files.
+ *
+ * Supported operations and their parameters:
+ * - create
+ * - store
+ * - copy
+ * - move
+ * - delete
+ * - describe (since 1.21)
+ * - null
+ *
+ * FSFile/TempFSFile object support was added in 1.27.
+ *
+ * a) Create a new file in storage with the contents of a string
+ * @code
+ * [
+ * 'op' => 'create',
+ * 'dst' => <storage path>,
+ * 'content' => <string of new file contents>,
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * b) Copy a file system file into storage
+ * @code
+ * [
+ * 'op' => 'store',
+ * 'src' => <file system path, FSFile, or TempFSFile>,
+ * 'dst' => <storage path>,
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * c) Copy a file within storage
+ * @code
+ * [
+ * 'op' => 'copy',
+ * 'src' => <storage path>,
+ * 'dst' => <storage path>,
+ * 'ignoreMissingSource' => <boolean>, # since 1.21
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * d) Move a file within storage
+ * @code
+ * [
+ * 'op' => 'move',
+ * 'src' => <storage path>,
+ * 'dst' => <storage path>,
+ * 'ignoreMissingSource' => <boolean>, # since 1.21
+ * 'headers' => <HTTP header name/value map> # since 1.21
+ * ]
+ * @endcode
+ *
+ * e) Delete a file within storage
+ * @code
+ * [
+ * 'op' => 'delete',
+ * 'src' => <storage path>,
+ * 'ignoreMissingSource' => <boolean>
+ * ]
+ * @endcode
+ *
+ * f) Update metadata for a file within storage
+ * @code
+ * [
+ * 'op' => 'describe',
+ * 'src' => <storage path>,
+ * 'headers' => <HTTP header name/value map>
+ * ]
+ * @endcode
+ *
+ * g) Do nothing (no-op)
+ * @code
+ * [
+ * 'op' => 'null',
+ * ]
+ * @endcode
+ *
+ * @par Boolean flags for operations (operation-specific):
+ * - ignoreMissingSource : The operation will simply succeed and do
+ * nothing if the source file does not exist.
+ * - headers : If supplied with a header name/value map, the backend will
+ * reply with these headers when GETs/HEADs of the destination
+ * file are made. Header values should be smaller than 256 bytes.
+ * Content-Disposition headers can be longer, though the system
+ * might ignore or truncate ones that are too long to store.
+ * Existing headers will remain, but these will replace any
+ * conflicting previous headers, and headers will be removed
+ * if they are set to an empty string.
+ * Backends that don't support metadata ignore this. (since 1.21)
+ *
+ * $opts is an associative of boolean flags, including:
+ * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
+ *
+ * @par Return value:
+ * This returns a Status, which contains all warnings and fatals that occurred
+ * during the operation. The 'failCount', 'successCount', and 'success' members
+ * will reflect each operation attempted for the given files. The StatusValue will be
+ * considered "OK" as long as no fatal errors occurred.
+ *
+ * @param array $ops Set of operations to execute
+ * @param array $opts Batch operation options
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function doQuickOperations( array $ops, array $opts = [] ) {
+ if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
+ return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
+ }
+ if ( !count( $ops ) ) {
+ return $this->newStatus(); // nothing to do
+ }
+
+ $ops = $this->resolveFSFileObjects( $ops );
+ foreach ( $ops as &$op ) {
+ $op['overwrite'] = true; // avoids RTTs in key/value stores
+ }
+
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
+
+ return $this->doQuickOperationsInternal( $ops );
+ }
+
+ /**
+ * @see FileBackend::doQuickOperations()
+ * @param array $ops
+ * @since 1.20
+ */
+ abstract protected function doQuickOperationsInternal( array $ops );
+
+ /**
+ * Same as doQuickOperations() except it takes a single operation.
+ * If you are doing a batch of operations, then use that function instead.
+ *
+ * @see FileBackend::doQuickOperations()
+ *
+ * @param array $op Operation
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function doQuickOperation( array $op ) {
+ return $this->doQuickOperations( [ $op ] );
+ }
+
+ /**
+ * Performs a single quick create operation.
+ * This sets $params['op'] to 'create' and passes it to doQuickOperation().
+ *
+ * @see FileBackend::doQuickOperation()
+ *
+ * @param array $params Operation parameters
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function quickCreate( array $params ) {
+ return $this->doQuickOperation( [ 'op' => 'create' ] + $params );
+ }
+
+ /**
+ * Performs a single quick store operation.
+ * This sets $params['op'] to 'store' and passes it to doQuickOperation().
+ *
+ * @see FileBackend::doQuickOperation()
+ *
+ * @param array $params Operation parameters
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function quickStore( array $params ) {
+ return $this->doQuickOperation( [ 'op' => 'store' ] + $params );
+ }
+
+ /**
+ * Performs a single quick copy operation.
+ * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
+ *
+ * @see FileBackend::doQuickOperation()
+ *
+ * @param array $params Operation parameters
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function quickCopy( array $params ) {
+ return $this->doQuickOperation( [ 'op' => 'copy' ] + $params );
+ }
+
+ /**
+ * Performs a single quick move operation.
+ * This sets $params['op'] to 'move' and passes it to doQuickOperation().
+ *
+ * @see FileBackend::doQuickOperation()
+ *
+ * @param array $params Operation parameters
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function quickMove( array $params ) {
+ return $this->doQuickOperation( [ 'op' => 'move' ] + $params );
+ }
+
+ /**
+ * Performs a single quick delete operation.
+ * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
+ *
+ * @see FileBackend::doQuickOperation()
+ *
+ * @param array $params Operation parameters
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function quickDelete( array $params ) {
+ return $this->doQuickOperation( [ 'op' => 'delete' ] + $params );
+ }
+
+ /**
+ * Performs a single quick describe operation.
+ * This sets $params['op'] to 'describe' and passes it to doQuickOperation().
+ *
+ * @see FileBackend::doQuickOperation()
+ *
+ * @param array $params Operation parameters
+ * @return StatusValue
+ * @since 1.21
+ */
+ final public function quickDescribe( array $params ) {
+ return $this->doQuickOperation( [ 'op' => 'describe' ] + $params );
+ }
+
+ /**
+ * Concatenate a list of storage files into a single file system file.
+ * The target path should refer to a file that is already locked or
+ * otherwise safe from modification from other processes. Normally,
+ * the file will be a new temp file, which should be adequate.
+ *
+ * @param array $params Operation parameters, include:
+ * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
+ * - dst : file system path to 0-byte temp file
+ * - parallelize : try to do operations in parallel when possible
+ * @return StatusValue
+ */
+ abstract public function concatenate( array $params );
+
+ /**
+ * Prepare a storage directory for usage.
+ * This will create any required containers and parent directories.
+ * Backends using key/value stores only need to create the container.
+ *
+ * The 'noAccess' and 'noListing' parameters works the same as in secure(),
+ * except they are only applied *if* the directory/container had to be created.
+ * These flags should always be set for directories that have private files.
+ * However, setting them is not guaranteed to actually do anything.
+ * Additional server configuration may be needed to achieve the desired effect.
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - noAccess : try to deny file access (since 1.20)
+ * - noListing : try to deny file listing (since 1.20)
+ * - bypassReadOnly : allow writes in read-only mode (since 1.20)
+ * @return StatusValue
+ */
+ final public function prepare( array $params ) {
+ if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
+ return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
+ }
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
+ return $this->doPrepare( $params );
+ }
+
+ /**
+ * @see FileBackend::prepare()
+ * @param array $params
+ */
+ abstract protected function doPrepare( array $params );
+
+ /**
+ * Take measures to block web access to a storage directory and
+ * the container it belongs to. FS backends might add .htaccess
+ * files whereas key/value store backends might revoke container
+ * access to the storage user representing end-users in web requests.
+ *
+ * This is not guaranteed to actually make files or listings publically hidden.
+ * Additional server configuration may be needed to achieve the desired effect.
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - noAccess : try to deny file access
+ * - noListing : try to deny file listing
+ * - bypassReadOnly : allow writes in read-only mode (since 1.20)
+ * @return StatusValue
+ */
+ final public function secure( array $params ) {
+ if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
+ return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
+ }
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
+ return $this->doSecure( $params );
+ }
+
+ /**
+ * @see FileBackend::secure()
+ * @param array $params
+ */
+ abstract protected function doSecure( array $params );
+
+ /**
+ * Remove measures to block web access to a storage directory and
+ * the container it belongs to. FS backends might remove .htaccess
+ * files whereas key/value store backends might grant container
+ * access to the storage user representing end-users in web requests.
+ * This essentially can undo the result of secure() calls.
+ *
+ * This is not guaranteed to actually make files or listings publically viewable.
+ * Additional server configuration may be needed to achieve the desired effect.
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - access : try to allow file access
+ * - listing : try to allow file listing
+ * - bypassReadOnly : allow writes in read-only mode (since 1.20)
+ * @return StatusValue
+ * @since 1.20
+ */
+ final public function publish( array $params ) {
+ if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
+ return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
+ }
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
+ return $this->doPublish( $params );
+ }
+
+ /**
+ * @see FileBackend::publish()
+ * @param array $params
+ */
+ abstract protected function doPublish( array $params );
+
+ /**
+ * Delete a storage directory if it is empty.
+ * Backends using key/value stores may do nothing unless the directory
+ * is that of an empty container, in which case it will be deleted.
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - recursive : recursively delete empty subdirectories first (since 1.20)
+ * - bypassReadOnly : allow writes in read-only mode (since 1.20)
+ * @return StatusValue
+ */
+ final public function clean( array $params ) {
+ if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
+ return $this->newStatus( 'backend-fail-readonly', $this->name, $this->readOnly );
+ }
+ /** @noinspection PhpUnusedLocalVariableInspection */
+ $scope = $this->getScopedPHPBehaviorForOps(); // try to ignore client aborts
+ return $this->doClean( $params );
+ }
+
+ /**
+ * @see FileBackend::clean()
+ * @param array $params
+ */
+ abstract protected function doClean( array $params );
+
+ /**
+ * Enter file operation scope.
+ * This just makes PHP ignore user aborts/disconnects until the return
+ * value leaves scope. This returns null and does nothing in CLI mode.
+ *
+ * @return ScopedCallback|null
+ */
+ final protected function getScopedPHPBehaviorForOps() {
+ if ( PHP_SAPI != 'cli' ) { // http://bugs.php.net/bug.php?id=47540
+ $old = ignore_user_abort( true ); // avoid half-finished operations
+ return new ScopedCallback( function () use ( $old ) {
+ ignore_user_abort( $old );
+ } );
+ }
+
+ return null;
+ }
+
+ /**
+ * Check if a file exists at a storage path in the backend.
+ * This returns false if only a directory exists at the path.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return bool|null Returns null on failure
+ */
+ abstract public function fileExists( array $params );
+
+ /**
+ * Get the last-modified timestamp of the file at a storage path.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return string|bool TS_MW timestamp or false on failure
+ */
+ abstract public function getFileTimestamp( array $params );
+
+ /**
+ * Get the contents of a file at a storage path in the backend.
+ * This should be avoided for potentially large files.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return string|bool Returns false on failure
+ */
+ final public function getFileContents( array $params ) {
+ $contents = $this->getFileContentsMulti(
+ [ 'srcs' => [ $params['src'] ] ] + $params );
+
+ return $contents[$params['src']];
+ }
+
+ /**
+ * Like getFileContents() except it takes an array of storage paths
+ * and returns a map of storage paths to strings (or null on failure).
+ * The map keys (paths) are in the same order as the provided list of paths.
+ *
+ * @see FileBackend::getFileContents()
+ *
+ * @param array $params Parameters include:
+ * - srcs : list of source storage paths
+ * - latest : use the latest available data
+ * - parallelize : try to do operations in parallel when possible
+ * @return array Map of (path name => string or false on failure)
+ * @since 1.20
+ */
+ abstract public function getFileContentsMulti( array $params );
+
+ /**
+ * Get metadata about a file at a storage path in the backend.
+ * If the file does not exist, then this returns false.
+ * Otherwise, the result is an associative array that includes:
+ * - headers : map of HTTP headers used for GET/HEAD requests (name => value)
+ * - metadata : map of file metadata (name => value)
+ * Metadata keys and headers names will be returned in all lower-case.
+ * Additional values may be included for internal use only.
+ *
+ * Use FileBackend::hasFeatures() to check how well this is supported.
+ *
+ * @param array $params
+ * $params include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return array|bool Returns false on failure
+ * @since 1.23
+ */
+ abstract public function getFileXAttributes( array $params );
+
+ /**
+ * Get the size (bytes) of a file at a storage path in the backend.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return int|bool Returns false on failure
+ */
+ abstract public function getFileSize( array $params );
+
+ /**
+ * Get quick information about a file at a storage path in the backend.
+ * If the file does not exist, then this returns false.
+ * Otherwise, the result is an associative array that includes:
+ * - mtime : the last-modified timestamp (TS_MW)
+ * - size : the file size (bytes)
+ * Additional values may be included for internal use only.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return array|bool|null Returns null on failure
+ */
+ abstract public function getFileStat( array $params );
+
+ /**
+ * Get a SHA-1 hash of the file at a storage path in the backend.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return string|bool Hash string or false on failure
+ */
+ abstract public function getFileSha1Base36( array $params );
+
+ /**
+ * Get the properties of the file at a storage path in the backend.
+ * This gives the result of FSFile::getProps() on a local copy of the file.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return array Returns FSFile::placeholderProps() on failure
+ */
+ abstract public function getFileProps( array $params );
+
+ /**
+ * Stream the file at a storage path in the backend.
+ *
+ * If the file does not exists, an HTTP 404 error will be given.
+ * Appropriate HTTP headers (Status, Content-Type, Content-Length)
+ * will be sent if streaming began, while none will be sent otherwise.
+ * Implementations should flush the output buffer before sending data.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - headers : list of additional HTTP headers to send if the file exists
+ * - options : HTTP request header map with lower case keys (since 1.28). Supports:
+ * range : format is "bytes=(\d*-\d*)"
+ * if-modified-since : format is an HTTP date
+ * - headless : only include the body (and headers from "headers") (since 1.28)
+ * - latest : use the latest available data
+ * - allowOB : preserve any output buffers (since 1.28)
+ * @return StatusValue
+ */
+ abstract public function streamFile( array $params );
+
+ /**
+ * Returns a file system file, identical to the file at a storage path.
+ * The file returned is either:
+ * - a) A local copy of the file at a storage path in the backend.
+ * The temporary copy will have the same extension as the source.
+ * - b) An original of the file at a storage path in the backend.
+ * Temporary files may be purged when the file object falls out of scope.
+ *
+ * Write operations should *never* be done on this file as some backends
+ * may do internal tracking or may be instances of FileBackendMultiWrite.
+ * In that latter case, there are copies of the file that must stay in sync.
+ * Additionally, further calls to this function may return the same file.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return FSFile|null Returns null on failure
+ */
+ final public function getLocalReference( array $params ) {
+ $fsFiles = $this->getLocalReferenceMulti(
+ [ 'srcs' => [ $params['src'] ] ] + $params );
+
+ return $fsFiles[$params['src']];
+ }
+
+ /**
+ * Like getLocalReference() except it takes an array of storage paths
+ * and returns a map of storage paths to FSFile objects (or null on failure).
+ * The map keys (paths) are in the same order as the provided list of paths.
+ *
+ * @see FileBackend::getLocalReference()
+ *
+ * @param array $params Parameters include:
+ * - srcs : list of source storage paths
+ * - latest : use the latest available data
+ * - parallelize : try to do operations in parallel when possible
+ * @return array Map of (path name => FSFile or null on failure)
+ * @since 1.20
+ */
+ abstract public function getLocalReferenceMulti( array $params );
+
+ /**
+ * Get a local copy on disk of the file at a storage path in the backend.
+ * The temporary copy will have the same file extension as the source.
+ * Temporary files may be purged when the file object falls out of scope.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - latest : use the latest available data
+ * @return TempFSFile|null Returns null on failure
+ */
+ final public function getLocalCopy( array $params ) {
+ $tmpFiles = $this->getLocalCopyMulti(
+ [ 'srcs' => [ $params['src'] ] ] + $params );
+
+ return $tmpFiles[$params['src']];
+ }
+
+ /**
+ * Like getLocalCopy() except it takes an array of storage paths and
+ * returns a map of storage paths to TempFSFile objects (or null on failure).
+ * The map keys (paths) are in the same order as the provided list of paths.
+ *
+ * @see FileBackend::getLocalCopy()
+ *
+ * @param array $params Parameters include:
+ * - srcs : list of source storage paths
+ * - latest : use the latest available data
+ * - parallelize : try to do operations in parallel when possible
+ * @return array Map of (path name => TempFSFile or null on failure)
+ * @since 1.20
+ */
+ abstract public function getLocalCopyMulti( array $params );
+
+ /**
+ * Return an HTTP URL to a given file that requires no authentication to use.
+ * The URL may be pre-authenticated (via some token in the URL) and temporary.
+ * This will return null if the backend cannot make an HTTP URL for the file.
+ *
+ * This is useful for key/value stores when using scripts that seek around
+ * large files and those scripts (and the backend) support HTTP Range headers.
+ * Otherwise, one would need to use getLocalReference(), which involves loading
+ * the entire file on to local disk.
+ *
+ * @param array $params Parameters include:
+ * - src : source storage path
+ * - ttl : lifetime (seconds) if pre-authenticated; default is 1 day
+ * @return string|null
+ * @since 1.21
+ */
+ abstract public function getFileHttpUrl( array $params );
+
+ /**
+ * Check if a directory exists at a given storage path.
+ * Backends using key/value stores will check if the path is a
+ * virtual directory, meaning there are files under the given directory.
+ *
+ * Storage backends with eventual consistency might return stale data.
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * @return bool|null Returns null on failure
+ * @since 1.20
+ */
+ abstract public function directoryExists( array $params );
+
+ /**
+ * Get an iterator to list *all* directories under a storage directory.
+ * If the directory is of the form "mwstore://backend/container",
+ * then all directories in the container will be listed.
+ * If the directory is of form "mwstore://backend/container/dir",
+ * then all directories directly under that directory will be listed.
+ * Results will be storage directories relative to the given directory.
+ *
+ * Storage backends with eventual consistency might return stale data.
+ *
+ * Failures during iteration can result in FileBackendError exceptions (since 1.22).
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - topOnly : only return direct child dirs of the directory
+ * @return Traversable|array|null Returns null on failure
+ * @since 1.20
+ */
+ abstract public function getDirectoryList( array $params );
+
+ /**
+ * Same as FileBackend::getDirectoryList() except only lists
+ * directories that are immediately under the given directory.
+ *
+ * Storage backends with eventual consistency might return stale data.
+ *
+ * Failures during iteration can result in FileBackendError exceptions (since 1.22).
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * @return Traversable|array|null Returns null on failure
+ * @since 1.20
+ */
+ final public function getTopDirectoryList( array $params ) {
+ return $this->getDirectoryList( [ 'topOnly' => true ] + $params );
+ }
+
+ /**
+ * Get an iterator to list *all* stored files under a storage directory.
+ * If the directory is of the form "mwstore://backend/container",
+ * then all files in the container will be listed.
+ * If the directory is of form "mwstore://backend/container/dir",
+ * then all files under that directory will be listed.
+ * Results will be storage paths relative to the given directory.
+ *
+ * Storage backends with eventual consistency might return stale data.
+ *
+ * Failures during iteration can result in FileBackendError exceptions (since 1.22).
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - topOnly : only return direct child files of the directory (since 1.20)
+ * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
+ * @return Traversable|array|null Returns null on failure
+ */
+ abstract public function getFileList( array $params );
+
+ /**
+ * Same as FileBackend::getFileList() except only lists
+ * files that are immediately under the given directory.
+ *
+ * Storage backends with eventual consistency might return stale data.
+ *
+ * Failures during iteration can result in FileBackendError exceptions (since 1.22).
+ *
+ * @param array $params Parameters include:
+ * - dir : storage directory
+ * - adviseStat : set to true if stat requests will be made on the files (since 1.22)
+ * @return Traversable|array|null Returns null on failure
+ * @since 1.20
+ */
+ final public function getTopFileList( array $params ) {
+ return $this->getFileList( [ 'topOnly' => true ] + $params );
+ }
+
+ /**
+ * Preload persistent file stat cache and property cache into in-process cache.
+ * This should be used when stat calls will be made on a known list of a many files.
+ *
+ * @see FileBackend::getFileStat()
+ *
+ * @param array $paths Storage paths
+ */
+ abstract public function preloadCache( array $paths );
+
+ /**
+ * Invalidate any in-process file stat and property cache.
+ * If $paths is given, then only the cache for those files will be cleared.
+ *
+ * @see FileBackend::getFileStat()
+ *
+ * @param array $paths Storage paths (optional)
+ */
+ abstract public function clearCache( array $paths = null );
+
+ /**
+ * Preload file stat information (concurrently if possible) into in-process cache.
+ *
+ * This should be used when stat calls will be made on a known list of a many files.
+ * This does not make use of the persistent file stat cache.
+ *
+ * @see FileBackend::getFileStat()
+ *
+ * @param array $params Parameters include:
+ * - srcs : list of source storage paths
+ * - latest : use the latest available data
+ * @return bool All requests proceeded without I/O errors (since 1.24)
+ * @since 1.23
+ */
+ abstract public function preloadFileStat( array $params );
+
+ /**
+ * Lock the files at the given storage paths in the backend.
+ * This will either lock all the files or none (on failure).
+ *
+ * Callers should consider using getScopedFileLocks() instead.
+ *
+ * @param array $paths Storage paths
+ * @param int $type LockManager::LOCK_* constant
+ * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
+ * @return StatusValue
+ */
+ final public function lockFiles( array $paths, $type, $timeout = 0 ) {
+ $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
+
+ return $this->wrapStatus( $this->lockManager->lock( $paths, $type, $timeout ) );
+ }
+
+ /**
+ * Unlock the files at the given storage paths in the backend.
+ *
+ * @param array $paths Storage paths
+ * @param int $type LockManager::LOCK_* constant
+ * @return StatusValue
+ */
+ final public function unlockFiles( array $paths, $type ) {
+ $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
+
+ return $this->wrapStatus( $this->lockManager->unlock( $paths, $type ) );
+ }
+
+ /**
+ * Lock the files at the given storage paths in the backend.
+ * This will either lock all the files or none (on failure).
+ * On failure, the StatusValue object will be updated with errors.
+ *
+ * Once the return value goes out scope, the locks will be released and
+ * the StatusValue updated. Unlock fatals will not change the StatusValue "OK" value.
+ *
+ * @see ScopedLock::factory()
+ *
+ * @param array $paths List of storage paths or map of lock types to path lists
+ * @param int|string $type LockManager::LOCK_* constant or "mixed"
+ * @param StatusValue $status StatusValue to update on lock/unlock
+ * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.24)
+ * @return ScopedLock|null Returns null on failure
+ */
+ final public function getScopedFileLocks(
+ array $paths, $type, StatusValue $status, $timeout = 0
+ ) {
+ if ( $type === 'mixed' ) {
+ foreach ( $paths as &$typePaths ) {
+ $typePaths = array_map( 'FileBackend::normalizeStoragePath', $typePaths );
+ }
+ } else {
+ $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
+ }
+
+ return ScopedLock::factory( $this->lockManager, $paths, $type, $status, $timeout );
+ }
+
+ /**
+ * Get an array of scoped locks needed for a batch of file operations.
+ *
+ * Normally, FileBackend::doOperations() handles locking, unless
+ * the 'nonLocking' param is passed in. This function is useful if you
+ * want the files to be locked for a broader scope than just when the
+ * files are changing. For example, if you need to update DB metadata,
+ * you may want to keep the files locked until finished.
+ *
+ * @see FileBackend::doOperations()
+ *
+ * @param array $ops List of file operations to FileBackend::doOperations()
+ * @param StatusValue $status StatusValue to update on lock/unlock
+ * @return ScopedLock|null
+ * @since 1.20
+ */
+ abstract public function getScopedLocksForOps( array $ops, StatusValue $status );
+
+ /**
+ * Get the root storage path of this backend.
+ * All container paths are "subdirectories" of this path.
+ *
+ * @return string Storage path
+ * @since 1.20
+ */
+ final public function getRootStoragePath() {
+ return "mwstore://{$this->name}";
+ }
+
+ /**
+ * Get the storage path for the given container for this backend
+ *
+ * @param string $container Container name
+ * @return string Storage path
+ * @since 1.21
+ */
+ final public function getContainerStoragePath( $container ) {
+ return $this->getRootStoragePath() . "/{$container}";
+ }
+
+ /**
+ * Get the file journal object for this backend
+ *
+ * @return FileJournal
+ */
+ final public function getJournal() {
+ return $this->fileJournal;
+ }
+
+ /**
+ * Convert FSFile 'src' paths to string paths (with an 'srcRef' field set to the FSFile)
+ *
+ * The 'srcRef' field keeps any TempFSFile objects in scope for the backend to have it
+ * around as long it needs (which may vary greatly depending on configuration)
+ *
+ * @param array $ops File operation batch for FileBaclend::doOperations()
+ * @return array File operation batch
+ */
+ protected function resolveFSFileObjects( array $ops ) {
+ foreach ( $ops as &$op ) {
+ $src = isset( $op['src'] ) ? $op['src'] : null;
+ if ( $src instanceof FSFile ) {
+ $op['srcRef'] = $src;
+ $op['src'] = $src->getPath();
+ }
+ }
+ unset( $op );
+
+ return $ops;
+ }
+
+ /**
+ * Check if a given path is a "mwstore://" path.
+ * This does not do any further validation or any existence checks.
+ *
+ * @param string $path
+ * @return bool
+ */
+ final public static function isStoragePath( $path ) {
+ return ( strpos( $path, 'mwstore://' ) === 0 );
+ }
+
+ /**
+ * Split a storage path into a backend name, a container name,
+ * and a relative file path. The relative path may be the empty string.
+ * This does not do any path normalization or traversal checks.
+ *
+ * @param string $storagePath
+ * @return array (backend, container, rel object) or (null, null, null)
+ */
+ final public static function splitStoragePath( $storagePath ) {
+ if ( self::isStoragePath( $storagePath ) ) {
+ // Remove the "mwstore://" prefix and split the path
+ $parts = explode( '/', substr( $storagePath, 10 ), 3 );
+ if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
+ if ( count( $parts ) == 3 ) {
+ return $parts; // e.g. "backend/container/path"
+ } else {
+ return [ $parts[0], $parts[1], '' ]; // e.g. "backend/container"
+ }
+ }
+ }
+
+ return [ null, null, null ];
+ }
+
+ /**
+ * Normalize a storage path by cleaning up directory separators.
+ * Returns null if the path is not of the format of a valid storage path.
+ *
+ * @param string $storagePath
+ * @return string|null
+ */
+ final public static function normalizeStoragePath( $storagePath ) {
+ list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
+ if ( $relPath !== null ) { // must be for this backend
+ $relPath = self::normalizeContainerPath( $relPath );
+ if ( $relPath !== null ) {
+ return ( $relPath != '' )
+ ? "mwstore://{$backend}/{$container}/{$relPath}"
+ : "mwstore://{$backend}/{$container}";
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Get the parent storage directory of a storage path.
+ * This returns a path like "mwstore://backend/container",
+ * "mwstore://backend/container/...", or null if there is no parent.
+ *
+ * @param string $storagePath
+ * @return string|null
+ */
+ final public static function parentStoragePath( $storagePath ) {
+ $storagePath = dirname( $storagePath );
+ list( , , $rel ) = self::splitStoragePath( $storagePath );
+
+ return ( $rel === null ) ? null : $storagePath;
+ }
+
+ /**
+ * Get the final extension from a storage or FS path
+ *
+ * @param string $path
+ * @param string $case One of (rawcase, uppercase, lowercase) (since 1.24)
+ * @return string
+ */
+ final public static function extensionFromPath( $path, $case = 'lowercase' ) {
+ $i = strrpos( $path, '.' );
+ $ext = $i ? substr( $path, $i + 1 ) : '';
+
+ if ( $case === 'lowercase' ) {
+ $ext = strtolower( $ext );
+ } elseif ( $case === 'uppercase' ) {
+ $ext = strtoupper( $ext );
+ }
+
+ return $ext;
+ }
+
+ /**
+ * Check if a relative path has no directory traversals
+ *
+ * @param string $path
+ * @return bool
+ * @since 1.20
+ */
+ final public static function isPathTraversalFree( $path ) {
+ return ( self::normalizeContainerPath( $path ) !== null );
+ }
+
+ /**
+ * Build a Content-Disposition header value per RFC 6266.
+ *
+ * @param string $type One of (attachment, inline)
+ * @param string $filename Suggested file name (should not contain slashes)
+ * @throws FileBackendError
+ * @return string
+ * @since 1.20
+ */
+ final public static function makeContentDisposition( $type, $filename = '' ) {
+ $parts = [];
+
+ $type = strtolower( $type );
+ if ( !in_array( $type, [ 'inline', 'attachment' ] ) ) {
+ throw new FileBackendError( "Invalid Content-Disposition type '$type'." );
+ }
+ $parts[] = $type;
+
+ if ( strlen( $filename ) ) {
+ $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
+ }
+
+ return implode( ';', $parts );
+ }
+
+ /**
+ * Validate and normalize a relative storage path.
+ * Null is returned if the path involves directory traversal.
+ * Traversal is insecure for FS backends and broken for others.
+ *
+ * This uses the same traversal protection as Title::secureAndSplit().
+ *
+ * @param string $path Storage path relative to a container
+ * @return string|null
+ */
+ final protected static function normalizeContainerPath( $path ) {
+ // Normalize directory separators
+ $path = strtr( $path, '\\', '/' );
+ // Collapse any consecutive directory separators
+ $path = preg_replace( '![/]{2,}!', '/', $path );
+ // Remove any leading directory separator
+ $path = ltrim( $path, '/' );
+ // Use the same traversal protection as Title::secureAndSplit()
+ if ( strpos( $path, '.' ) !== false ) {
+ if (
+ $path === '.' ||
+ $path === '..' ||
+ strpos( $path, './' ) === 0 ||
+ strpos( $path, '../' ) === 0 ||
+ strpos( $path, '/./' ) !== false ||
+ strpos( $path, '/../' ) !== false
+ ) {
+ return null;
+ }
+ }
+
+ return $path;
+ }
+
+ /**
+ * Yields the result of the status wrapper callback on either:
+ * - StatusValue::newGood() if this method is called without parameters
+ * - StatusValue::newFatal() with all parameters to this method if passed in
+ *
+ * @param ... string
+ * @return StatusValue
+ */
+ final protected function newStatus() {
+ $args = func_get_args();
+ if ( count( $args ) ) {
+ $sv = call_user_func_array( [ 'StatusValue', 'newFatal' ], $args );
+ } else {
+ $sv = StatusValue::newGood();
+ }
+
+ return $this->wrapStatus( $sv );
+ }
+
+ /**
+ * @param StatusValue $sv
+ * @return StatusValue Modified status or StatusValue subclass
+ */
+ final protected function wrapStatus( StatusValue $sv ) {
+ return $this->statusWrapper ? call_user_func( $this->statusWrapper, $sv ) : $sv;
+ }
+}
--- /dev/null
+<?php
+/**
+ * Generic file backend exception for checked and unexpected (e.g. config) exceptions
+ *
+ * @ingroup FileBackend
+ * @since 1.23
+ */
+class FileBackendException extends Exception {
+}
+
+/**
+ * File backend exception for checked exceptions (e.g. I/O errors)
+ *
+ * @ingroup FileBackend
+ * @since 1.22
+ */
+class FileBackendError extends FileBackendException {
+}
--- /dev/null
+<?php
+/**
+ * @defgroup FileJournal File journal
+ * @ingroup FileBackend
+ */
+
+/**
+ * File operation journaling.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup FileJournal
+ * @author Aaron Schulz
+ */
+
+/**
+ * @brief Class for handling file operation journaling.
+ *
+ * Subclasses should avoid throwing exceptions at all costs.
+ *
+ * @ingroup FileJournal
+ * @since 1.20
+ */
+abstract class FileJournal {
+ /** @var string */
+ protected $backend;
+
+ /** @var int */
+ protected $ttlDays;
+
+ /**
+ * Construct a new instance from configuration.
+ *
+ * @param array $config Includes:
+ * 'ttlDays' : days to keep log entries around (false means "forever")
+ */
+ protected function __construct( array $config ) {
+ $this->ttlDays = isset( $config['ttlDays'] ) ? $config['ttlDays'] : false;
+ }
+
+ /**
+ * Create an appropriate FileJournal object from config
+ *
+ * @param array $config
+ * @param string $backend A registered file backend name
+ * @throws Exception
+ * @return FileJournal
+ */
+ final public static function factory( array $config, $backend ) {
+ $class = $config['class'];
+ $jrn = new $class( $config );
+ if ( !$jrn instanceof self ) {
+ throw new InvalidArgumentException( "Class given is not an instance of FileJournal." );
+ }
+ $jrn->backend = $backend;
+
+ return $jrn;
+ }
+
+ /**
+ * Get a statistically unique ID string
+ *
+ * @return string <9 char TS_MW timestamp in base 36><22 random base 36 chars>
+ */
+ final public function getTimestampedUUID() {
+ $s = '';
+ for ( $i = 0; $i < 5; $i++ ) {
+ $s .= mt_rand( 0, 2147483647 );
+ }
+ $s = Wikimedia\base_convert( sha1( $s ), 16, 36, 31 );
+
+ return substr( Wikimedia\base_convert( wfTimestamp( TS_MW ), 10, 36, 9 ) . $s, 0, 31 );
+ }
+
+ /**
+ * Log changes made by a batch file operation.
+ *
+ * @param array $entries List of file operations (each an array of parameters) which contain:
+ * op : Basic operation name (create, update, delete)
+ * path : The storage path of the file
+ * newSha1 : The final base 36 SHA-1 of the file
+ * Note that 'false' should be used as the SHA-1 for non-existing files.
+ * @param string $batchId UUID string that identifies the operation batch
+ * @return StatusValue
+ */
+ final public function logChangeBatch( array $entries, $batchId ) {
+ if ( !count( $entries ) ) {
+ return StatusValue::newGood();
+ }
+
+ return $this->doLogChangeBatch( $entries, $batchId );
+ }
+
+ /**
+ * @see FileJournal::logChangeBatch()
+ *
+ * @param array $entries List of file operations (each an array of parameters)
+ * @param string $batchId UUID string that identifies the operation batch
+ * @return StatusValue
+ */
+ abstract protected function doLogChangeBatch( array $entries, $batchId );
+
+ /**
+ * Get the position ID of the latest journal entry
+ *
+ * @return int|bool
+ */
+ final public function getCurrentPosition() {
+ return $this->doGetCurrentPosition();
+ }
+
+ /**
+ * @see FileJournal::getCurrentPosition()
+ * @return int|bool
+ */
+ abstract protected function doGetCurrentPosition();
+
+ /**
+ * Get the position ID of the latest journal entry at some point in time
+ *
+ * @param int|string $time Timestamp
+ * @return int|bool
+ */
+ final public function getPositionAtTime( $time ) {
+ return $this->doGetPositionAtTime( $time );
+ }
+
+ /**
+ * @see FileJournal::getPositionAtTime()
+ * @param int|string $time Timestamp
+ * @return int|bool
+ */
+ abstract protected function doGetPositionAtTime( $time );
+
+ /**
+ * Get an array of file change log entries.
+ * A starting change ID and/or limit can be specified.
+ *
+ * @param int $start Starting change ID or null
+ * @param int $limit Maximum number of items to return
+ * @param string &$next Updated to the ID of the next entry.
+ * @return array List of associative arrays, each having:
+ * id : unique, monotonic, ID for this change
+ * batch_uuid : UUID for an operation batch
+ * backend : the backend name
+ * op : primitive operation (create,update,delete,null)
+ * path : affected storage path
+ * new_sha1 : base 36 sha1 of the new file had the operation succeeded
+ * timestamp : TS_MW timestamp of the batch change
+ * Also, $next is updated to the ID of the next entry.
+ */
+ final public function getChangeEntries( $start = null, $limit = 0, &$next = null ) {
+ $entries = $this->doGetChangeEntries( $start, $limit ? $limit + 1 : 0 );
+ if ( $limit && count( $entries ) > $limit ) {
+ $last = array_pop( $entries ); // remove the extra entry
+ $next = $last['id']; // update for next call
+ } else {
+ $next = null; // end of list
+ }
+
+ return $entries;
+ }
+
+ /**
+ * @see FileJournal::getChangeEntries()
+ * @param int $start
+ * @param int $limit
+ * @return array
+ */
+ abstract protected function doGetChangeEntries( $start, $limit );
+
+ /**
+ * Purge any old log entries
+ *
+ * @return StatusValue
+ */
+ final public function purgeOldLogs() {
+ return $this->doPurgeOldLogs();
+ }
+
+ /**
+ * @see FileJournal::purgeOldLogs()
+ * @return StatusValue
+ */
+ abstract protected function doPurgeOldLogs();
+}
--- /dev/null
+<?php
+/**
+ * Simple version of FileJournal that does nothing
+ * @since 1.20
+ */
+class NullFileJournal extends FileJournal {
+ /**
+ * @see FileJournal::doLogChangeBatch()
+ * @param array $entries
+ * @param string $batchId
+ * @return StatusValue
+ */
+ protected function doLogChangeBatch( array $entries, $batchId ) {
+ return StatusValue::newGood();
+ }
+
+ /**
+ * @see FileJournal::doGetCurrentPosition()
+ * @return int|bool
+ */
+ protected function doGetCurrentPosition() {
+ return false;
+ }
+
+ /**
+ * @see FileJournal::doGetPositionAtTime()
+ * @param int|string $time Timestamp
+ * @return int|bool
+ */
+ protected function doGetPositionAtTime( $time ) {
+ return false;
+ }
+
+ /**
+ * @see FileJournal::doGetChangeEntries()
+ * @param int $start
+ * @param int $limit
+ * @return array
+ */
+ protected function doGetChangeEntries( $start, $limit ) {
+ return [];
+ }
+
+ /**
+ * @see FileJournal::doPurgeOldLogs()
+ * @return StatusValue
+ */
+ protected function doPurgeOldLogs() {
+ return StatusValue::newGood();
+ }
+}
--- /dev/null
+<?php
+/**
+ * Resource locking handling.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup LockManager
+ * @author Aaron Schulz
+ */
+
+/**
+ * Self-releasing locks
+ *
+ * LockManager helper class to handle scoped locks, which
+ * release when an object is destroyed or goes out of scope.
+ *
+ * @ingroup LockManager
+ * @since 1.19
+ */
+class ScopedLock {
+ /** @var LockManager */
+ protected $manager;
+
+ /** @var StatusValue */
+ protected $status;
+
+ /** @var array Map of lock types to resource paths */
+ protected $pathsByType;
+
+ /**
+ * @param LockManager $manager
+ * @param array $pathsByType Map of lock types to path lists
+ * @param StatusValue $status
+ */
+ protected function __construct(
+ LockManager $manager, array $pathsByType, StatusValue $status
+ ) {
+ $this->manager = $manager;
+ $this->pathsByType = $pathsByType;
+ $this->status = $status;
+ }
+
+ /**
+ * Get a ScopedLock object representing a lock on resource paths.
+ * Any locks are released once this object goes out of scope.
+ * The StatusValue object is updated with any errors or warnings.
+ *
+ * @param LockManager $manager
+ * @param array $paths List of storage paths or map of lock types to path lists
+ * @param int|string $type LockManager::LOCK_* constant or "mixed" and $paths
+ * can be a map of types to paths (since 1.22). Otherwise $type should be an
+ * integer and $paths should be a list of paths.
+ * @param StatusValue $status
+ * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.22)
+ * @return ScopedLock|null Returns null on failure
+ */
+ public static function factory(
+ LockManager $manager, array $paths, $type, StatusValue $status, $timeout = 0
+ ) {
+ $pathsByType = is_integer( $type ) ? [ $type => $paths ] : $paths;
+ $lockStatus = $manager->lockByType( $pathsByType, $timeout );
+ $status->merge( $lockStatus );
+ if ( $lockStatus->isOK() ) {
+ return new self( $manager, $pathsByType, $status );
+ }
+
+ return null;
+ }
+
+ /**
+ * Release a scoped lock and set any errors in the attatched StatusValue object.
+ * This is useful for early release of locks before function scope is destroyed.
+ * This is the same as setting the lock object to null.
+ *
+ * @param ScopedLock $lock
+ * @since 1.21
+ */
+ public static function release( ScopedLock &$lock = null ) {
+ $lock = null;
+ }
+
+ /**
+ * Release the locks when this goes out of scope
+ */
+ function __destruct() {
+ $wasOk = $this->status->isOK();
+ $this->status->merge( $this->manager->unlockByType( $this->pathsByType ) );
+ if ( $wasOk ) {
+ // Make sure StatusValue is OK, despite any unlockFiles() fatals
+ $this->status->setResult( true, $this->status->value );
+ }
+ }
+}
/** @var array Map of (name => 1) for locks obtained via lock() */
private $mNamedLocksHeld = [];
+ /** @var array Map of (table name => 1) for TEMPORARY tables */
+ private $mSessionTempTables = [];
/** @var IDatabase|null Lazy handle to the master DB this server replicates from */
private $lazyMasterHandle;
return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
}
+ /**
+ * @param string $sql A SQL query
+ * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
+ */
+ protected function registerTempTableOperation( $sql ) {
+ if ( preg_match(
+ '/^(CREATE|DROP)\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
+ $sql,
+ $matches
+ ) ) {
+ list( , $verb, $table ) = $matches;
+ if ( $verb === 'CREATE' ) {
+ $this->mSessionTempTables[$table] = 1;
+ } else {
+ unset( $this->mSessionTempTables[$table] );
+ }
+
+ return true;
+ } elseif ( preg_match(
+ '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
+ $sql,
+ $matches
+ ) ) {
+ return isset( $this->mSessionTempTables[$matches[1]] );
+ }
+
+ return false;
+ }
+
public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
$priorWritesPending = $this->writesOrCallbacksPending();
$this->mLastQuery = $sql;
- $isWrite = $this->isWriteQuery( $sql );
+ $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
if ( $isWrite ) {
$reason = $this->getReadOnlyReason();
if ( $reason !== false ) {
$lastError = $this->lastError();
$lastErrno = $this->lastErrno();
# Update state tracking to reflect transaction loss due to disconnection
- $this->handleTransactionLoss();
+ $this->handleSessionLoss();
if ( $this->reconnect() ) {
$msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
$this->connLogger->warning( $msg );
$tempIgnore = false; // not recoverable
}
# Update state tracking to reflect transaction loss
- $this->handleTransactionLoss();
+ $this->handleSessionLoss();
}
$this->reportQueryError(
return true;
}
- private function handleTransactionLoss() {
+ private function handleSessionLoss() {
$this->mTrxLevel = 0;
$this->mTrxIdleCallbacks = []; // bug 65263
$this->mTrxPreCommitCallbacks = []; // bug 65263
+ $this->mSessionTempTables = [];
+ $this->mNamedLocksHeld = [];
try {
// Handle callbacks in mTrxEndCallbacks
$this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
return (string)$this->mConn;
}
+ /**
+ * Make sure that copies do not share the same client binding handle
+ * @throws DBConnectionError
+ */
+ public function __clone() {
+ $this->connLogger->warning(
+ "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
+ ( new RuntimeException() )->getTraceAsString()
+ );
+
+ if ( $this->isOpen() ) {
+ // Open a new connection resource without messing with the old one
+ $this->mOpened = false;
+ $this->mConn = false;
+ $this->mTrxLevel = 0; // no trx anymore
+ $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
+ $this->lastPing = microtime( true );
+ }
+ }
+
/**
* Called by serialize. Throw an exception when DB connection is serialized.
* This causes problems on some database engines because the connection is
}
/**
- * Run a few simple sanity checks
+ * Run a few simple sanity checks and close dangling connections
*/
public function __destruct() {
if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
$fnames = implode( ', ', $danglingWriters );
trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
}
+
+ if ( $this->mConn ) {
+ // Avoid connection leaks for sanity
+ $this->closeConnection();
+ $this->mConn = false;
+ $this->mOpened = false;
+ }
}
}
return true;
}
- $this->queryLogger->debug( __METHOD__ . " failed to acquire lock\n" );
+ $this->queryLogger->warning( __METHOD__ . " failed to acquire lock '$lockName'\n" );
return false;
}
return true;
}
- $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
+ $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
return false;
}
*/
/**
- * Interface for database load balancing object that manages IDatabase handles
+ * Database cluster connection, tracking, load balancing, and transaction manager interface
+ *
+ * A "cluster" is considered to be one master database and zero or more replica databases.
+ * Typically, the replica DBs replicate from the master asynchronously. The first node in the
+ * "servers" configuration array is always considered the "master". However, this class can still
+ * be used when all or some of the "replica" DBs are multi-master peers of the master or even
+ * when all the DBs are non-replicating clones of each other holding read-only data. Thus, the
+ * role of "master" is in some cases merely nominal.
+ *
+ * By default, each DB server uses DBO_DEFAULT for its 'flags' setting, unless explicitly set
+ * otherwise in configuration. DBO_DEFAULT behavior depends on whether 'cliMode' is set:
+ * - In CLI mode, the flag has no effect with regards to LoadBalancer.
+ * - In non-CLI mode, the flag causes implicit transactions to be used; the first query on
+ * a database starts a transaction on that database. The transactions are meant to remain
+ * pending until either commitMasterChanges() or rollbackMasterChanges() is called. The
+ * application must have some point where it calls commitMasterChanges() near the end of
+ * the PHP request.
+ * Every iteration of beginMasterChanges()/commitMasterChanges() is called a "transaction round".
+ * Rounds are useful on the master DB connections because they make single-DB (and by and large
+ * multi-DB) updates in web requests all-or-nothing. Also, transactions on replica DBs are useful
+ * when REPEATABLE-READ or SERIALIZABLE isolation is used because all foriegn keys and constraints
+ * hold across separate queries in the DB transaction since the data appears within a consistent
+ * point-in-time snapshot.
+ *
+ * The typical caller will use LoadBalancer::getConnection( DB_* ) to yield a live database
+ * connection handle. The choice of which DB server to use is based on pre-defined loads for
+ * weighted random selection, adjustments thereof by LoadMonitor, and the amount of replication
+ * lag on each DB server. Lag checks might cause problems in certain setups, so they should be
+ * tuned in the server configuration maps as follows:
+ * - Master + N Replica(s): set 'max lag' to an appropriate threshold for avoiding any database
+ * lagged by this much or more. If all DBs are this lagged, then the load balancer considers
+ * the cluster to be read-only.
+ * - Galera Cluster: Seconds_Behind_Master will be 0, so there probably is nothing to tune.
+ * Note that lag is still possible depending on how wsrep-sync-wait is set server-side.
+ * - Read-only archive clones: set 'is static' in the server configuration maps. This will
+ * treat all such DBs as having 0 lag.
+ * - SQL load balancing proxy: any proxy should handle lag checks on its own, so the 'max lag'
+ * parameter should probably be set to INF in the server configuration maps. This will make
+ * the load balancer ignore whatever it detects as the lag of the logical replica is (which
+ * would probably just randomly bounce around).
+ *
+ * If using a SQL proxy service, it would probably be best to have two proxy hosts for the
+ * load balancer to talk to. One would be the 'host' of the master server entry and another for
+ * the (logical) replica server entry. The proxy could map the load balancer's "replica" DB to
+ * any number of physical replica DBs.
*
* @since 1.28
* @ingroup Database
use Psr\Log\LoggerInterface;
/**
- * Database load balancing, tracking, and transaction management object
+ * Database connection, tracking, load balancing, and transaction manager for a cluster
*
* @ingroup Database
*/
}
$server['srvCache'] = $this->srvCache;
- // Set loggers
+ // Set loggers and profilers
$server['connLogger'] = $this->connLogger;
$server['queryLogger'] = $this->queryLogger;
+ $server['errorLogger'] = $this->errorLogger;
$server['profiler'] = $this->profiler;
$server['trxProfiler'] = $this->trxProfiler;
+ // Use the same agent and PHP mode for all DB handles
$server['cliMode'] = $this->cliMode;
- $server['errorLogger'] = $this->errorLogger;
$server['agent'] = $this->agent;
+ // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
+ // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
+ $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : DBO_DEFAULT;
// Create a live connection object
try {
$db->setLBInfo( $server );
$db->setLazyMasterHandle(
- $this->getLazyConnectionRef( DB_MASTER, [], $db->getWikiID() )
+ $this->getLazyConnectionRef( DB_MASTER, [], $db->getDomainID() )
);
$db->setTableAliases( $this->tableAliases );
public function getLagTimes( $domain = false ) {
if ( $this->getServerCount() <= 1 ) {
- return [ 0 => 0 ]; // no replication = no lag
+ return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
}
- # Send the request to the load monitor
- return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $domain );
+ $knownLagTimes = []; // map of (server index => 0 seconds)
+ $indexesWithLag = [];
+ foreach ( $this->mServers as $i => $server ) {
+ if ( empty( $server['is static'] ) ) {
+ $indexesWithLag[] = $i; // DB server might have replication lag
+ } else {
+ $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
+ }
+ }
+
+ return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
}
public function safeGetLag( IDatabase $conn ) {
$db->tablePrefix( $prefix );
} );
}
+
+ function __destruct() {
+ // Avoid connection leaks for sanity
+ $this->closeAll();
+ }
}
function fetchContent() {
// BC cruft!
- ContentHandler::deprecated( __METHOD__, '1.21' );
+ wfDeprecated( __METHOD__, '1.21' );
if ( $this->mContentLoaded && $this->mContent ) {
return $this->mContent;
* - default: set to true if this profile is the default
*
* @since 1.28
- * @param $profileType the type of profiles
+ * @param string $profileType the type of profiles
+ * @param User|null $user the user requesting the list of profiles
* @return array|null the list of profiles or null if none available
*/
- public function getProfiles( $profileType ) {
+ public function getProfiles( $profileType, User $user = null ) {
return null;
}
* @return array
*/
function getToolbox() {
-
$toolbox = [];
if ( isset( $this->data['nav_urls']['whatlinkshere'] )
&& $this->data['nav_urls']['whatlinkshere']
$toolbox['recentchangeslinked'] = $this->data['nav_urls']['recentchangeslinked'];
$toolbox['recentchangeslinked']['msg'] = 'recentchangeslinked-toolbox';
$toolbox['recentchangeslinked']['id'] = 't-recentchangeslinked';
+ $toolbox['recentchangeslinked']['rel'] = 'nofollow';
}
if ( isset( $this->data['feeds'] ) && $this->data['feeds'] ) {
$toolbox['feeds']['id'] = 'feedlinks';
if ( $this->showEmailUser( $user ) ) {
$nav_urls['emailuser'] = [
+ 'text' => $this->msg( 'tool-link-emailuser', $rootUser )->text(),
'href' => self::makeSpecialUrlSubpage( 'Emailuser', $rootUser ),
'tooltip-params' => [ $rootUser ],
];
$sur->setContext( $this->getContext() );
if ( $sur->userCanExecute( $this->getUser() ) ) {
$nav_urls['userrights'] = [
+ 'text' => $this->msg( 'tool-link-userrights', $this->getUser()->getName() )->text(),
'href' => self::makeSpecialUrlSubpage( 'Userrights', $rootUser )
];
}
// Get the file extension from the last chunk
$ext = FileBackend::extensionFromPath( $this->mVirtualTempPath );
// Get a 0-byte temp file to perform the concatenation at
- $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext );
+ $tmpFile = TempFSFile::factory( 'chunkedupload_', $ext, wfTempDir() );
$tmpPath = false; // fail in concatenate()
if ( $tmpFile ) {
// keep alive with $this
* @return string Path to the file
*/
protected function makeTemporaryFile() {
- $tmpFile = TempFSFile::factory( 'URL' );
+ $tmpFile = TempFSFile::factory( 'URL', 'urlupload_', wfTempDir() );
$tmpFile->bind( $this );
return $tmpFile->getPath();
"talk": "Discussion",
"views": "Views",
"toolbox": "Tools",
+ "tool-link-userrights": "Change {{GENDER:$1|user}} groups",
+ "tool-link-emailuser": "Email this {{GENDER:$1|user}}",
"userpage": "View user page",
"projectpage": "View project page",
"imagepage": "View file page",
"talk": "Used as display name for the tab to all {{msg-mw|Talk}} pages. These pages accompany all content pages and can be used for discussing the content page. Example: [[Talk:Example]].\n\nSee also:\n* {{msg-mw|Talk}}\n* {{msg-mw|Accesskey-ca-talk}}\n* {{msg-mw|Tooltip-ca-talk}}\n{{Identical|Discussion}}",
"views": "Subtitle for the list of available views, for the current page. In \"monobook\" skin the list of views are shown as tabs, so this sub-title is not shown. For an example, see [{{canonicalurl:Main_Page|useskin=simple}} Main Page using simple skin].\n\n'''Note:''' This is \"views\" as in \"appearances\"/\"representations\", '''not''' as in \"visits\"/\"accesses\".\n{{Identical|View}}",
"toolbox": "The title of the toolbox below the search menu.\n{{Identical|Tool}}",
+ "tool-link-userrights": "Link to [[Special:UserRights]] (user rights management) in the sidebar toolbox.\n\nParameters:\n* $1 - Name of user who would have their rights changed",
+ "tool-link-emailuser": "Link to [[Special:EmailUser]] (email user tool) in the sidebar toolbox.\n\nParameters:\n* $1 - Name of user who would receive the email\n\nSee also:\n* {{msg-mw|Emailuser-title-target}}",
"userpage": "Used in user talk pages as the text of the link to the user page, with the Cologne Blue skin.",
"projectpage": "Used as link text in Talk page of project page with the Cologne Blue skin.",
"imagepage": "Used as link text in Talk page of file page.",
end
end
-class SourceTag < CommonTag
- def initialize
- @tagname = :source
- @pattern = 'source'
- super
- end
-
- def to_html(context)
- context[@tagname].map do |source|
- <<-EOHTML
- <h3 class='pa'>Source</h3>
- #{source[:doc]}
- EOHTML
- end.join
- end
-end
-
class SeeTag < CommonTag
def initialize
@tagname = :see
/**
+ * Source: <https://api.jquery.com/>
* @class jQuery
- * @source <http://api.jquery.com/>
*/
/**
+ * Source: <https://api.jquery.com/jQuery.ajax/>
* @method ajax
* @static
- * @source <http://api.jquery.com/jQuery.ajax/>
* @return {jqXHR}
*/
/**
+ * Source: <https://api.jquery.com/Types/#Event>
* @class jQuery.Event
- * @source <http://api.jquery.com/Types/#Event>
*/
/**
+ * Source: <https://api.jquery.com/jQuery.Callbacks/>
* @class jQuery.Callbacks
- * @source <http://api.jquery.com/jQuery.Callbacks/>
*/
/**
+ * Source: <https://api.jquery.com/Types/#Promise>
* @class jQuery.Promise
- * @source <http://api.jquery.com/Types/#Promise>
*/
/**
+ * Source: <https://api.jquery.com/jQuery.Deferred/>
* @class jQuery.Deferred
* @mixins jQuery.Promise
- * @source <http://api.jquery.com/jQuery.Deferred/>
*/
/**
+ * Source: <https://api.jquery.com/Types/#jqXHR>
* @class jQuery.jqXHR
- * @source <http://api.jquery.com/Types/#jqXHR>
* @alternateClassName jqXHR
*/
/**
+ * Source: <http://api.qunitjs.com/>
* @class QUnit
- * @source <http://api.qunitjs.com/>
*/
* @member mw
* @param {Function} callback
*/
+ mw.requestIdleCallback = mw.requestIdleCallbackInternal;
+ /*
+ // XXX: Polyfill disabled due to https://bugs.chromium.org/p/chromium/issues/detail?id=647870
mw.requestIdleCallback = window.requestIdleCallback
// Bind because it throws TypeError if context is not window
? window.requestIdleCallback.bind( window )
: mw.requestIdleCallbackInternal;
+ */
}( mediaWiki ) );
->method( 'getSearchTypes' )
->will( $this->returnValue( [ 'the one ring' ] ) );
+ $api = $this->createApi();
$engine = $this->replaceSearchEngine();
$engine->expects( $this->any() )
->method( 'getProfiles' )
->will( $this->returnValueMap( [
- [ SearchEngine::COMPLETION_PROFILE_TYPE, [
+ [ SearchEngine::COMPLETION_PROFILE_TYPE, $api->getUser(), [
[
'name' => 'normal',
'desc-message' => 'normal-message',
] ],
] ) );
- $api = $this->createApi();
$params = $api->getAllowedParams();
$this->assertArrayNotHasKey( 'offset', $params );
], ApiResult::addMetadataToResultVars( $arr ) );
}
- /**
- * @covers ApiResult
- */
- public function testDeprecatedFunctions() {
- // Ignore ApiResult deprecation warnings during this test
- set_error_handler( function ( $errno, $errstr ) use ( &$warnings ) {
- if ( preg_match( '/Use of ApiResult::\S+ was deprecated in MediaWiki \d+.\d+\./', $errstr ) ) {
- return true;
- }
- if ( preg_match( '/Use of ApiMain to ApiResult::__construct ' .
- 'was deprecated in MediaWiki \d+.\d+\./', $errstr ) ) {
- return true;
- }
- return false;
- } );
- $reset = new ScopedCallback( 'restore_error_handler' );
-
- $context = new DerivativeContext( RequestContext::getMain() );
- $context->setConfig( new HashConfig( [
- 'APIModules' => [],
- 'APIFormatModules' => [],
- 'APIMaxResultSize' => 42,
- ] ) );
- $main = new ApiMain( $context );
- $result = TestingAccessWrapper::newFromObject( new ApiResult( $main ) );
- $this->assertSame( 42, $result->maxSize );
- $this->assertSame( $main->getErrorFormatter(), $result->errorFormatter );
- $this->assertSame( $main, $result->mainForContinuation );
-
- $result = new ApiResult( 8388608 );
-
- $result->addContentValue( null, 'test', 'content' );
- $result->addContentValue( [ 'foo', 'bar' ], 'test', 'content' );
- $result->addIndexedTagName( null, 'itn' );
- $result->addSubelementsList( null, [ 'sub' ] );
- $this->assertSame( [
- 'foo' => [
- 'bar' => [
- '*' => 'content',
- ],
- ],
- '*' => 'content',
- ], $result->getData() );
-
- $arr = [];
- ApiResult::setContent( $arr, 'value' );
- ApiResult::setContent( $arr, 'value2', 'foobar' );
- $this->assertSame( [
- ApiResult::META_CONTENT => 'content',
- 'content' => 'value',
- 'foobar' => [
- ApiResult::META_CONTENT => 'content',
- 'content' => 'value2',
- ],
- ], $arr );
-
- $result = new ApiResult( 3 );
- $formatter = new ApiErrorFormatter_BackCompat( $result );
- $result->setErrorFormatter( $formatter );
- $result->disableSizeCheck();
- $this->assertTrue( $result->addValue( null, 'foo', '1234567890' ) );
- $result->enableSizeCheck();
- $this->assertSame( 0, $result->getSize() );
- $this->assertFalse( $result->addValue( null, 'foo', '1234567890' ) );
-
- $arr = [ 'foo' => [ 'bar' => 1 ] ];
- $result->setIndexedTagName_recursive( $arr, 'itn' );
- $this->assertSame( [
- 'foo' => [
- 'bar' => 1,
- ApiResult::META_INDEXED_TAG_NAME => 'itn'
- ],
- ], $arr );
-
- $status = Status::newGood();
- $status->fatal( 'parentheses', '1' );
- $status->fatal( 'parentheses', '2' );
- $status->warning( 'parentheses', '3' );
- $status->warning( 'parentheses', '4' );
- $this->assertSame( [
- [
- 'type' => 'error',
- 'message' => 'parentheses',
- 'params' => [
- 0 => '1',
- ApiResult::META_INDEXED_TAG_NAME => 'param',
- ],
- ],
- [
- 'type' => 'error',
- 'message' => 'parentheses',
- 'params' => [
- 0 => '2',
- ApiResult::META_INDEXED_TAG_NAME => 'param',
- ],
- ],
- ApiResult::META_INDEXED_TAG_NAME => 'error',
- ], $result->convertStatusToArray( $status, 'error' ) );
- $this->assertSame( [
- [
- 'type' => 'warning',
- 'message' => 'parentheses',
- 'params' => [
- 0 => '3',
- ApiResult::META_INDEXED_TAG_NAME => 'param',
- ],
- ],
- [
- 'type' => 'warning',
- 'message' => 'parentheses',
- 'params' => [
- 0 => '4',
- ApiResult::META_INDEXED_TAG_NAME => 'param',
- ],
- ],
- ApiResult::META_INDEXED_TAG_NAME => 'warning',
- ], $result->convertStatusToArray( $status, 'warning' ) );
- }
-
- /**
- * @covers ApiResult
- */
- public function testDeprecatedContinuation() {
- // Ignore ApiResult deprecation warnings during this test
- set_error_handler( function ( $errno, $errstr ) use ( &$warnings ) {
- if ( preg_match( '/Use of ApiResult::\S+ was deprecated in MediaWiki \d+.\d+\./', $errstr ) ) {
- return true;
- }
- return false;
- } );
-
- $reset = new ScopedCallback( 'restore_error_handler' );
- $allModules = [
- new MockApiQueryBase( 'mock1' ),
- new MockApiQueryBase( 'mock2' ),
- new MockApiQueryBase( 'mocklist' ),
- ];
- $generator = new MockApiQueryBase( 'generator' );
-
- $main = new ApiMain( RequestContext::getMain() );
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setContinueParam( $allModules[0], 'm1continue', [ 1, 2 ] );
- $result->setContinueParam( $allModules[2], 'mlcontinue', 2 );
- $result->setGeneratorContinueParam( $generator, 'gcontinue', 3 );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'mlcontinue' => 2,
- 'm1continue' => '1|2',
- 'continue' => '||mock2',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( null, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'mock1' => [ 'm1continue' => '1|2' ],
- 'mocklist' => [ 'mlcontinue' => 2 ],
- 'generator' => [ 'gcontinue' => 3 ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setContinueParam( $allModules[0], 'm1continue', [ 1, 2 ] );
- $result->setGeneratorContinueParam( $generator, 'gcontinue', [ 3, 4 ] );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'm1continue' => '1|2',
- 'continue' => '||mock2|mocklist',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( null, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'mock1' => [ 'm1continue' => '1|2' ],
- 'generator' => [ 'gcontinue' => '3|4' ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setContinueParam( $allModules[2], 'mlcontinue', 2 );
- $result->setGeneratorContinueParam( $generator, 'gcontinue', 3 );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'mlcontinue' => 2,
- 'gcontinue' => 3,
- 'continue' => 'gcontinue||',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( true, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'mocklist' => [ 'mlcontinue' => 2 ],
- 'generator' => [ 'gcontinue' => 3 ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setGeneratorContinueParam( $generator, 'gcontinue', 3 );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'gcontinue' => 3,
- 'continue' => 'gcontinue||mocklist',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( true, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'generator' => [ 'gcontinue' => 3 ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setContinueParam( $allModules[0], 'm1continue', [ 1, 2 ] );
- $result->setContinueParam( $allModules[2], 'mlcontinue', 2 );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'mlcontinue' => 2,
- 'm1continue' => '1|2',
- 'continue' => '||mock2',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( null, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'mock1' => [ 'm1continue' => '1|2' ],
- 'mocklist' => [ 'mlcontinue' => 2 ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setContinueParam( $allModules[0], 'm1continue', [ 1, 2 ] );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'm1continue' => '1|2',
- 'continue' => '||mock2|mocklist',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( null, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'mock1' => [ 'm1continue' => '1|2' ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->setContinueParam( $allModules[2], 'mlcontinue', 2 );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( [
- 'mlcontinue' => 2,
- 'continue' => '-||mock1|mock2',
- ], $result->getResultData( 'continue' ) );
- $this->assertSame( true, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( [
- 'mocklist' => [ 'mlcontinue' => 2 ],
- ], $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( null, $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame( [ false, $allModules ], $ret );
- $result->endContinuation( 'raw' );
- $result->endContinuation( 'standard' );
- $this->assertSame( null, $result->getResultData( 'continue' ) );
- $this->assertSame( true, $result->getResultData( 'batchcomplete' ) );
- $this->assertSame( null, $result->getResultData( 'query-continue' ) );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( '||mock2', $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame(
- [ false, array_values( array_diff_key( $allModules, [ 1 => 1 ] ) ) ],
- $ret
- );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $ret = $result->beginContinuation( '-||', $allModules, [ 'mock1', 'mock2' ] );
- $this->assertSame(
- [ true, array_values( array_diff_key( $allModules, [ 0 => 0, 1 => 1 ] ) ) ],
- $ret
- );
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- try {
- $result->beginContinuation( 'foo', $allModules, [ 'mock1', 'mock2' ] );
- $this->fail( 'Expected exception not thrown' );
- } catch ( UsageException $ex ) {
- $this->assertSame(
- 'Invalid continue param. You should pass the original value returned by the previous query',
- $ex->getMessage(),
- 'Expected exception'
- );
- }
- $main->setContinuationManager( null );
-
- $result = new ApiResult( 8388608 );
- $result->setMainForContinuation( $main );
- $result->beginContinuation( '||mock2', array_slice( $allModules, 0, 2 ),
- [ 'mock1', 'mock2' ] );
- try {
- $result->setContinueParam( $allModules[1], 'm2continue', 1 );
- $this->fail( 'Expected exception not thrown' );
- } catch ( UnexpectedValueException $ex ) {
- $this->assertSame(
- 'Module \'mock2\' was not supposed to have been executed, but it was executed anyway',
- $ex->getMessage(),
- 'Expected exception'
- );
- }
- try {
- $result->setContinueParam( $allModules[2], 'mlcontinue', 1 );
- $this->fail( 'Expected exception not thrown' );
- } catch ( UnexpectedValueException $ex ) {
- $this->assertSame(
- 'Module \'mocklist\' called ApiContinuationManager::addContinueParam ' .
- 'but was not passed to ApiContinuationManager::__construct',
- $ex->getMessage(),
- 'Expected exception'
- );
- }
- $main->setContinuationManager( null );
-
- }
-
public function testObjectSerialization() {
$arr = [];
ApiResult::setValue( $arr, 'foo', (object)[ 'a' => 1, 'b' => 2 ] );
$origTrx = $db->getFlag( DBO_TRX );
$origSsl = $db->getFlag( DBO_SSL );
- if ( $origTrx ) {
- $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR );
- } else {
- $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
- }
+ $origTrx
+ ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
+ : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
$this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
- if ( $origSsl ) {
- $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR );
- } else {
- $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
- }
+ $origSsl
+ ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
+ : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
$this->assertEquals( !$origSsl, $db->getFlag( DBO_SSL ) );
- $db2 = clone $db;
- $db2->restoreFlags( $db::RESTORE_INITIAL );
- $this->assertEquals( $origTrx, $db2->getFlag( DBO_TRX ) );
- $this->assertEquals( $origSsl, $db2->getFlag( DBO_SSL ) );
+ $db->restoreFlags( $db::RESTORE_INITIAL );
+ $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
+ $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
+
+ $origTrx
+ ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
+ : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
+ $origSsl
+ ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
+ : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
$db->restoreFlags();
$this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
public static function provider_testStore() {
$cases = [];
- $tmpName = TempFSFile::factory( "unittests_", 'txt' )->getPath();
+ $tmpName = TempFSFile::factory( "unittests_", 'txt', wfTempDir() )->getPath();
$toPath = self::baseStorePath() . '/unittest-cont1/e/fun/obj1.txt';
$op = [ 'op' => 'store', 'src' => $tmpName, 'dst' => $toPath ];
$cases[] = [ $op ];
$fileBContents = 'g-jmq3gpqgt3qtg q3GT ';
$fileCContents = 'eigna[ogmewt 3qt g3qg flew[ag';
- $tmpNameA = TempFSFile::factory( "unittests_", 'txt' )->getPath();
- $tmpNameB = TempFSFile::factory( "unittests_", 'txt' )->getPath();
- $tmpNameC = TempFSFile::factory( "unittests_", 'txt' )->getPath();
+ $tmpNameA = TempFSFile::factory( "unittests_", 'txt', wfTempDir() )->getPath();
+ $tmpNameB = TempFSFile::factory( "unittests_", 'txt', wfTempDir() )->getPath();
+ $tmpNameC = TempFSFile::factory( "unittests_", 'txt', wfTempDir() )->getPath();
$this->addTmpFiles( [ $tmpNameA, $tmpNameB, $tmpNameC ] );
file_put_contents( $tmpNameA, $fileAContents );
file_put_contents( $tmpNameB, $fileBContents );
// Does nothing
], [ 'force' => 1 ] );
- $this->assertNotEquals( [], $status->errors, "Operation had warnings" );
+ $this->assertNotEquals( [], $status->getErrors(), "Operation had warnings" );
$this->assertEquals( true, $status->isOK(), "Operation batch succeeded" );
$this->assertEquals( 8, count( $status->success ),
"Operation batch has correct success array" );
for ( $i = 0; $i < 25; $i++ ) {
$status = $this->backend->lockFiles( $paths, LockManager::LOCK_EX );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName) ($i)." );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$status = $this->backend->lockFiles( $paths, LockManager::LOCK_SH );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName) ($i)." );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$status = $this->backend->unlockFiles( $paths, LockManager::LOCK_SH );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName) ($i)." );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$status = $this->backend->unlockFiles( $paths, LockManager::LOCK_EX );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName). ($i)" );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
# # Flip the acquire/release ordering around ##
$status = $this->backend->lockFiles( $paths, LockManager::LOCK_SH );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName) ($i)." );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$status = $this->backend->lockFiles( $paths, LockManager::LOCK_EX );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName) ($i)." );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$status = $this->backend->unlockFiles( $paths, LockManager::LOCK_EX );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName). ($i)" );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$status = $this->backend->unlockFiles( $paths, LockManager::LOCK_SH );
- $this->assertEquals( print_r( [], true ), print_r( $status->errors, true ),
+ $this->assertEquals( print_r( [], true ), print_r( $status->getErrors(), true ),
"Locking of files succeeded ($backendName) ($i)." );
$this->assertEquals( true, $status->isOK(),
"Locking of files succeeded with OK status ($backendName) ($i)." );
$sl = $this->backend->getScopedFileLocks( $paths, LockManager::LOCK_EX, $status );
$this->assertInstanceOf( 'ScopedLock', $sl,
"Scoped locking of files succeeded ($backendName)." );
- $this->assertEquals( [], $status->errors,
+ $this->assertEquals( [], $status->getErrors(),
"Scoped locking of files succeeded ($backendName)." );
$this->assertEquals( true, $status->isOK(),
"Scoped locking of files succeeded with OK status ($backendName)." );
ScopedLock::release( $sl );
$this->assertEquals( null, $sl,
"Scoped unlocking of files succeeded ($backendName)." );
- $this->assertEquals( [], $status->errors,
+ $this->assertEquals( [], $status->getErrors(),
"Scoped unlocking of files succeeded ($backendName)." );
$this->assertEquals( true, $status->isOK(),
"Scoped unlocking of files succeeded with OK status ($backendName)." );
}
}
- function assertGoodStatus( $status, $msg ) {
- $this->assertEquals( print_r( [], 1 ), print_r( $status->errors, 1 ), $msg );
+ function assertGoodStatus( StatusValue $status, $msg ) {
+ $this->assertEquals( print_r( [], 1 ), print_r( $status->getErrors(), 1 ), $msg );
}
}
->method( 'getRepo' )
->will( $this->returnValue( $repoMock ) );
- $this->tmpFilepath = TempFSFile::factory( 'migratefilelayout-test-', 'png' )->getPath();
+ $this->tmpFilepath = TempFSFile::factory(
+ 'migratefilelayout-test-', 'png', wfTempDir() )->getPath();
file_put_contents( $this->tmpFilepath, $this->text );
return wfTimestamp( TS_MW );
}
- public function getMimeType() {
- return 'text/mock';
- }
-
public function getProps( $ext = true ) {
return [
'fileExists' => $this->exists(),
'size' => $this->getSize(),
- 'file-mime' => $this->getMimeType(),
+ 'file-mime' => 'text/mock',
'sha1' => $this->getSha1Base36(),
];
}
if ( window.requestIdleCallback ) {
QUnit.test( 'native', function ( assert ) {
var done = assert.async();
- // Remove polyfill
+ // Remove polyfill and clock stub
mw.requestIdleCallback.restore();
+ this.clock.restore();
mw.requestIdleCallback( function () {
assert.expect( 0 );
done();