Collapse some nested if statements

Change-Id: I9a97325d738d09370d29d35d5254bc0dadc57ff4
This commit is contained in:
Reedy 2019-03-29 20:12:24 +00:00
parent 9fc202b694
commit c13fee87d4
83 changed files with 669 additions and 863 deletions

View file

@ -1214,148 +1214,146 @@ class EditPage {
$content = $this->getPreloadedContent( $preload, $params ); $content = $this->getPreloadedContent( $preload, $params );
} }
// For existing pages, get text based on "undo" or section parameters. // For existing pages, get text based on "undo" or section parameters.
} elseif ( $this->section != '' ) {
// Get section edit text (returns $def_text for invalid sections)
$orig = $this->getOriginalContent( $user );
$content = $orig ? $orig->getSection( $this->section ) : null;
if ( !$content ) {
$content = $def_content;
}
} else { } else {
if ( $this->section != '' ) { $undoafter = $request->getInt( 'undoafter' );
// Get section edit text (returns $def_text for invalid sections) $undo = $request->getInt( 'undo' );
$orig = $this->getOriginalContent( $user );
$content = $orig ? $orig->getSection( $this->section ) : null;
if ( !$content ) { if ( $undo > 0 && $undoafter > 0 ) {
$content = $def_content; $undorev = Revision::newFromId( $undo );
} $oldrev = Revision::newFromId( $undoafter );
} else { $undoMsg = null;
$undoafter = $request->getInt( 'undoafter' );
$undo = $request->getInt( 'undo' );
if ( $undo > 0 && $undoafter > 0 ) { # Sanity check, make sure it's the right page,
$undorev = Revision::newFromId( $undo ); # the revisions exist and they were not deleted.
$oldrev = Revision::newFromId( $undoafter ); # Otherwise, $content will be left as-is.
$undoMsg = null; if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
!$undorev->isDeleted( Revision::DELETED_TEXT ) &&
# Sanity check, make sure it's the right page, !$oldrev->isDeleted( Revision::DELETED_TEXT )
# the revisions exist and they were not deleted. ) {
# Otherwise, $content will be left as-is. if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev )
if ( !is_null( $undorev ) && !is_null( $oldrev ) && || !$this->isSupportedContentModel( $oldrev->getContentModel() )
!$undorev->isDeleted( Revision::DELETED_TEXT ) &&
!$oldrev->isDeleted( Revision::DELETED_TEXT )
) { ) {
if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) // Hack for undo while EditPage can't handle multi-slot editing
|| !$this->isSupportedContentModel( $oldrev->getContentModel() ) $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [
) { 'action' => 'mcrundo',
// Hack for undo while EditPage can't handle multi-slot editing 'undo' => $undo,
$this->context->getOutput()->redirect( $this->mTitle->getFullURL( [ 'undoafter' => $undoafter,
'action' => 'mcrundo', ] ) );
'undo' => $undo, return false;
'undoafter' => $undoafter,
] ) );
return false;
} else {
$content = $this->page->getUndoContent( $undorev, $oldrev );
if ( $content === false ) {
# Warn the user that something went wrong
$undoMsg = 'failure';
}
}
if ( $undoMsg === null ) {
$oldContent = $this->page->getContent( Revision::RAW );
$popts = ParserOptions::newFromUserAndLang(
$user, MediaWikiServices::getInstance()->getContentLanguage() );
$newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
if ( $newContent->getModel() !== $oldContent->getModel() ) {
// The undo may change content
// model if its reverting the top
// edit. This can result in
// mismatched content model/format.
$this->contentModel = $newContent->getModel();
$this->contentFormat = $oldrev->getContentFormat();
}
if ( $newContent->equals( $oldContent ) ) {
# Tell the user that the undo results in no change,
# i.e. the revisions were already undone.
$undoMsg = 'nochange';
$content = false;
} else {
# Inform the user of our success and set an automatic edit summary
$undoMsg = 'success';
# If we just undid one rev, use an autosummary
$firstrev = $oldrev->getNext();
if ( $firstrev && $firstrev->getId() == $undo ) {
$userText = $undorev->getUserText();
if ( $userText === '' ) {
$undoSummary = $this->context->msg(
'undo-summary-username-hidden',
$undo
)->inContentLanguage()->text();
} else {
$undoSummary = $this->context->msg(
'undo-summary',
$undo,
$userText
)->inContentLanguage()->text();
}
if ( $this->summary === '' ) {
$this->summary = $undoSummary;
} else {
$this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
->inContentLanguage()->text() . $this->summary;
}
$this->undidRev = $undo;
}
$this->formtype = 'diff';
}
}
} else { } else {
// Failed basic sanity checks. $content = $this->page->getUndoContent( $undorev, $oldrev );
// Older revisions may have been removed since the link
// was created, or we may simply have got bogus input. if ( $content === false ) {
$undoMsg = 'norev'; # Warn the user that something went wrong
$undoMsg = 'failure';
}
} }
$out = $this->context->getOutput(); if ( $undoMsg === null ) {
// Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev, $oldContent = $this->page->getContent( Revision::RAW );
// undo-nochange. $popts = ParserOptions::newFromUserAndLang(
$class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}"; $user, MediaWikiServices::getInstance()->getContentLanguage() );
$this->editFormPageTop .= Html::rawElement( $newContent = $content->preSaveTransform( $this->mTitle, $user, $popts );
'div', [ 'class' => $class ], if ( $newContent->getModel() !== $oldContent->getModel() ) {
$out->parseAsInterface( // The undo may change content
$this->context->msg( 'undo-' . $undoMsg )->plain() // model if its reverting the top
// edit. This can result in
// mismatched content model/format.
$this->contentModel = $newContent->getModel();
$this->contentFormat = $oldrev->getContentFormat();
}
if ( $newContent->equals( $oldContent ) ) {
# Tell the user that the undo results in no change,
# i.e. the revisions were already undone.
$undoMsg = 'nochange';
$content = false;
} else {
# Inform the user of our success and set an automatic edit summary
$undoMsg = 'success';
# If we just undid one rev, use an autosummary
$firstrev = $oldrev->getNext();
if ( $firstrev && $firstrev->getId() == $undo ) {
$userText = $undorev->getUserText();
if ( $userText === '' ) {
$undoSummary = $this->context->msg(
'undo-summary-username-hidden',
$undo
)->inContentLanguage()->text();
} else {
$undoSummary = $this->context->msg(
'undo-summary',
$undo,
$userText
)->inContentLanguage()->text();
}
if ( $this->summary === '' ) {
$this->summary = $undoSummary;
} else {
$this->summary = $undoSummary . $this->context->msg( 'colon-separator' )
->inContentLanguage()->text() . $this->summary;
}
$this->undidRev = $undo;
}
$this->formtype = 'diff';
}
}
} else {
// Failed basic sanity checks.
// Older revisions may have been removed since the link
// was created, or we may simply have got bogus input.
$undoMsg = 'norev';
}
$out = $this->context->getOutput();
// Messages: undo-success, undo-failure, undo-main-slot-only, undo-norev,
// undo-nochange.
$class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
$this->editFormPageTop .= Html::rawElement(
'div', [ 'class' => $class ],
$out->parseAsInterface(
$this->context->msg( 'undo-' . $undoMsg )->plain()
)
);
}
if ( $content === false ) {
// Hack for restoring old revisions while EditPage
// can't handle multi-slot editing.
$curRevision = $this->page->getRevision();
$oldRevision = $this->mArticle->getRevisionFetched();
if ( $curRevision
&& $oldRevision
&& $curRevision->getId() !== $oldRevision->getId()
&& ( WikiPage::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
|| !$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
) {
$this->context->getOutput()->redirect(
$this->mTitle->getFullURL(
[
'action' => 'mcrrestore',
'restore' => $oldRevision->getId(),
]
) )
); );
return false;
} }
}
if ( $content === false ) { if ( $content === false ) {
// Hack for restoring old revisions while EditPage $content = $this->getOriginalContent( $user );
// can't handle multi-slot editing.
$curRevision = $this->page->getRevision();
$oldRevision = $this->mArticle->getRevisionFetched();
if ( $curRevision
&& $oldRevision
&& $curRevision->getId() !== $oldRevision->getId()
&& ( WikiPage::hasDifferencesOutsideMainSlot( $oldRevision, $curRevision )
|| !$this->isSupportedContentModel( $oldRevision->getContentModel() ) )
) {
$this->context->getOutput()->redirect(
$this->mTitle->getFullURL(
[
'action' => 'mcrrestore',
'restore' => $oldRevision->getId(),
]
)
);
return false;
}
}
if ( $content === false ) {
$content = $this->getOriginalContent( $user );
}
} }
} }
@ -2804,11 +2802,9 @@ ERROR;
$out->addHTML( $this->editFormTextTop ); $out->addHTML( $this->editFormTextTop );
if ( $this->wasDeletedSinceLastEdit() ) { if ( $this->wasDeletedSinceLastEdit() && $this->formtype !== 'save' ) {
if ( $this->formtype !== 'save' ) { $out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
$out->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>", 'deletedwhileediting' );
'deletedwhileediting' );
}
} }
// @todo add EditForm plugin interface and use it here! // @todo add EditForm plugin interface and use it here!
@ -3076,12 +3072,12 @@ ERROR;
$this->addExplainConflictHeader( $out ); $this->addExplainConflictHeader( $out );
$this->editRevId = $this->page->getLatest(); $this->editRevId = $this->page->getLatest();
} else { } else {
if ( $this->section != '' && $this->section != 'new' ) { if ( $this->section != '' && $this->section != 'new' && !$this->summary &&
if ( !$this->summary && !$this->preview && !$this->diff ) { !$this->preview && !$this->diff
$sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object ) {
if ( $sectionTitle !== false ) { $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
$this->summary = "/* $sectionTitle */ "; if ( $sectionTitle !== false ) {
} $this->summary = "/* $sectionTitle */ ";
} }
} }
@ -3188,44 +3184,42 @@ ERROR;
'anonpreviewwarning' 'anonpreviewwarning'
); );
} }
} else { } elseif ( $this->mTitle->isUserConfigPage() ) {
if ( $this->mTitle->isUserConfigPage() ) { # Check the skin exists
# Check the skin exists if ( $this->isWrongCaseUserConfigPage() ) {
if ( $this->isWrongCaseUserConfigPage() ) { $out->wrapWikiMsg(
$out->wrapWikiMsg( "<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>",
"<div class='error' id='mw-userinvalidconfigtitle'>\n$1\n</div>", [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ]
[ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ] );
); }
} if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) {
if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) { $isUserCssConfig = $this->mTitle->isUserCssConfigPage();
$isUserCssConfig = $this->mTitle->isUserCssConfigPage(); $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage();
$isUserJsonConfig = $this->mTitle->isUserJsonConfigPage(); $isUserJsConfig = $this->mTitle->isUserJsConfigPage();
$isUserJsConfig = $this->mTitle->isUserJsConfigPage();
$warning = $isUserCssConfig $warning = $isUserCssConfig
? 'usercssispublic' ? 'usercssispublic'
: ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' ); : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' );
$out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning ); $out->wrapWikiMsg( '<div class="mw-userconfigpublic">$1</div>', $warning );
if ( $this->formtype !== 'preview' ) { if ( $this->formtype !== 'preview' ) {
$config = $this->context->getConfig(); $config = $this->context->getConfig();
if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) { if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) {
$out->wrapWikiMsg( $out->wrapWikiMsg(
"<div id='mw-usercssyoucanpreview'>\n$1\n</div>", "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
[ 'usercssyoucanpreview' ] [ 'usercssyoucanpreview' ]
); );
} elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) { } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) {
$out->wrapWikiMsg( $out->wrapWikiMsg(
"<div id='mw-userjsonyoucanpreview'>\n$1\n</div>", "<div id='mw-userjsonyoucanpreview'>\n$1\n</div>",
[ 'userjsonyoucanpreview' ] [ 'userjsonyoucanpreview' ]
); );
} elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) { } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) {
$out->wrapWikiMsg( $out->wrapWikiMsg(
"<div id='mw-userjsyoucanpreview'>\n$1\n</div>", "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
[ 'userjsyoucanpreview' ] [ 'userjsyoucanpreview' ]
); );
}
} }
} }
} }
@ -3309,10 +3303,8 @@ ERROR;
if ( $this->nosummary ) { if ( $this->nosummary ) {
return; return;
} }
} else { } elseif ( !$this->mShowSummaryField ) {
if ( !$this->mShowSummaryField ) { return;
return;
}
} }
$labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse(); $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse();
@ -4450,16 +4442,14 @@ ERROR;
$lang->formatNum( $maxArticleSize ) $lang->formatNum( $maxArticleSize )
] ]
); );
} else { } elseif ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) {
if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) { $out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
$out->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>", [
[ 'longpage-hint',
'longpage-hint', $lang->formatSize( strlen( $this->textbox1 ) ),
$lang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 )
strlen( $this->textbox1 ) ]
] );
);
}
} }
} }

View file

@ -178,15 +178,13 @@ class ForeignResourceManager {
if ( $integrity === $actualIntegrity ) { if ( $integrity === $actualIntegrity ) {
$this->verbose( "... passed integrity check for {$src}\n" ); $this->verbose( "... passed integrity check for {$src}\n" );
$this->cacheSet( $key, $data ); $this->cacheSet( $key, $data );
} elseif ( $this->action === 'make-sri' ) {
$this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
} else { } else {
if ( $this->action === 'make-sri' ) { throw new Exception( "Integrity check failed for {$src}\n" .
$this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" ); "\tExpected: {$integrity}\n" .
} else { "\tActual: {$actualIntegrity}"
throw new Exception( "Integrity check failed for {$src}\n" . );
"\tExpected: {$integrity}\n" .
"\tActual: {$actualIntegrity}"
);
}
} }
return $data; return $data;
} }

View file

@ -1750,13 +1750,11 @@ function wfResetOutputBuffers( $resetGzipEncoding = true ) {
// to avoid getting in some kind of infinite loop. // to avoid getting in some kind of infinite loop.
break; break;
} }
if ( $resetGzipEncoding ) { if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) {
if ( $status['name'] == 'ob_gzhandler' ) { // Reset the 'Content-Encoding' field set by this handler
// Reset the 'Content-Encoding' field set by this handler // so we can start fresh.
// so we can start fresh. header_remove( 'Content-Encoding' );
header_remove( 'Content-Encoding' ); break;
break;
}
} }
} }
} }

View file

@ -574,10 +574,8 @@ class Html {
$attrs = []; $attrs = [];
if ( $nonce !== null ) { if ( $nonce !== null ) {
$attrs['nonce'] = $nonce; $attrs['nonce'] = $nonce;
} else { } elseif ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) { wfWarn( "no nonce set on script. CSP will break it" );
wfWarn( "no nonce set on script. CSP will break it" );
}
} }
if ( preg_match( '/<\/?script/i', $contents ) ) { if ( preg_match( '/<\/?script/i', $contents ) ) {
@ -600,10 +598,8 @@ class Html {
$attrs = [ 'src' => $url ]; $attrs = [ 'src' => $url ];
if ( $nonce !== null ) { if ( $nonce !== null ) {
$attrs['nonce'] = $nonce; $attrs['nonce'] = $nonce;
} else { } elseif ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) { wfWarn( "no nonce set on script. CSP will break it" );
wfWarn( "no nonce set on script. CSP will break it" );
}
} }
return self::element( 'script', $attrs ); return self::element( 'script', $attrs );

View file

@ -86,10 +86,8 @@ class MWGrants {
* @return string[] Corresponding grant descriptions * @return string[] Corresponding grant descriptions
*/ */
public static function grantNames( array $grants, $lang = null ) { public static function grantNames( array $grants, $lang = null ) {
if ( $lang !== null ) { if ( $lang !== null && is_string( $lang ) ) {
if ( is_string( $lang ) ) { $lang = Language::factory( $lang );
$lang = Language::factory( $lang );
}
} }
$ret = []; $ret = [];

View file

@ -428,11 +428,9 @@ class MediaWiki {
if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) { if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
// Is the target already set by an extension? // Is the target already set by an extension?
$target = $target ?: $page->followRedirect(); $target = $target ?: $page->followRedirect();
if ( is_string( $target ) ) { if ( is_string( $target ) && !$this->config->get( 'DisableHardRedirects' ) ) {
if ( !$this->config->get( 'DisableHardRedirects' ) ) { // we'll need to redirect
// we'll need to redirect return $target;
return $target;
}
} }
if ( is_object( $target ) ) { if ( is_object( $target ) ) {
// Rewrite environment to redirected article // Rewrite environment to redirected article

View file

@ -1163,14 +1163,11 @@ class Message implements MessageSpecifier, Serializable {
// escaped, breaking the replacement and avoiding XSS. // escaped, breaking the replacement and avoiding XSS.
$replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 ); $replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 );
} }
} else { } elseif ( $paramType === 'after' ) {
if ( $paramType === 'after' ) { $replacementKeys[$marker . ( $n + 1 )] = $value;
$replacementKeys[$marker . ( $n + 1 )] = $value;
}
} }
} }
$message = strtr( $message, $replacementKeys ); return strtr( $message, $replacementKeys );
return $message;
} }
/** /**

View file

@ -3785,26 +3785,24 @@ class OutputPage extends ContextSource {
if ( $config->get( 'EnableCanonicalServerLink' ) ) { if ( $config->get( 'EnableCanonicalServerLink' ) ) {
if ( $canonicalUrl !== false ) { if ( $canonicalUrl !== false ) {
$canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL ); $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
} else { } elseif ( $this->isArticleRelated() ) {
if ( $this->isArticleRelated() ) { // This affects all requests where "setArticleRelated" is true. This is
// This affects all requests where "setArticleRelated" is true. This is // typically all requests that show content (query title, curid, oldid, diff),
// typically all requests that show content (query title, curid, oldid, diff), // and all wikipage actions (edit, delete, purge, info, history etc.).
// and all wikipage actions (edit, delete, purge, info, history etc.). // It does not apply to File pages and Special pages.
// It does not apply to File pages and Special pages. // 'history' and 'info' actions address page metadata rather than the page
// 'history' and 'info' actions address page metadata rather than the page // content itself, so they may not be canonicalized to the view page url.
// content itself, so they may not be canonicalized to the view page url. // TODO: this ought to be better encapsulated in the Action class.
// TODO: this ought to be better encapsulated in the Action class. $action = Action::getActionName( $this->getContext() );
$action = Action::getActionName( $this->getContext() ); if ( in_array( $action, [ 'history', 'info' ] ) ) {
if ( in_array( $action, [ 'history', 'info' ] ) ) { $query = "action={$action}";
$query = "action={$action}";
} else {
$query = '';
}
$canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
} else { } else {
$reqUrl = $this->getRequest()->getRequestURL(); $query = '';
$canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
} }
$canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
} else {
$reqUrl = $this->getRequest()->getRequestURL();
$canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
} }
} }
if ( $canonicalUrl !== false ) { if ( $canonicalUrl !== false ) {
@ -3948,10 +3946,8 @@ class OutputPage extends ContextSource {
* @return string HTML fragment * @return string HTML fragment
*/ */
protected function styleLink( $style, array $options ) { protected function styleLink( $style, array $options ) {
if ( isset( $options['dir'] ) ) { if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
if ( $this->getLanguage()->getDir() != $options['dir'] ) { return '';
return '';
}
} }
if ( isset( $options['media'] ) ) { if ( isset( $options['media'] ) ) {

View file

@ -129,12 +129,10 @@ class PageProps {
if ( $propertyValue === false ) { if ( $propertyValue === false ) {
$queryIDs[] = $pageID; $queryIDs[] = $pageID;
break; break;
} elseif ( $gotArray ) {
$values[$pageID][$propertyName] = $propertyValue;
} else { } else {
if ( $gotArray ) { $values[$pageID] = $propertyValue;
$values[$pageID][$propertyName] = $propertyValue;
} else {
$values[$pageID] = $propertyValue;
}
} }
} }
} }

View file

@ -133,10 +133,8 @@ class PathRouter {
// Loop over our options and convert any single value $# restrictions // Loop over our options and convert any single value $# restrictions
// into an array so we only have to do in_array tests. // into an array so we only have to do in_array tests.
foreach ( $options as $optionName => $optionData ) { foreach ( $options as $optionName => $optionData ) {
if ( preg_match( '/^\$\d+$/u', $optionName ) ) { if ( preg_match( '/^\$\d+$/u', $optionName ) && !is_array( $optionData ) ) {
if ( !is_array( $optionData ) ) { $options[$optionName] = [ $optionData ];
$options[$optionName] = [ $optionData ];
}
} }
} }

View file

@ -86,10 +86,8 @@ class MainSlotRoleHandler extends SlotRoleHandler {
// Hook can determine default model // Hook can determine default model
$title = Title::newFromLinkTarget( $page ); $title = Title::newFromLinkTarget( $page );
if ( !Hooks::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) { if ( !Hooks::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) && !is_null( $model ) ) {
if ( !is_null( $model ) ) { return $model;
return $model;
}
} }
// Could this page contain code based on the title? // Could this page contain code based on the title?

View file

@ -1863,12 +1863,12 @@ class RevisionStore
} }
// if we have a content object, use it to set the model and type // if we have a content object, use it to set the model and type
if ( !empty( $fields['content'] ) ) { if ( !empty( $fields['content'] ) && !( $fields['content'] instanceof Content )
if ( !( $fields['content'] instanceof Content ) && !is_array( $fields['content'] ) ) { && !is_array( $fields['content'] )
throw new MWException( ) {
'content field must contain a Content object or an array of Content objects.' throw new MWException(
); 'content field must contain a Content object or an array of Content objects.'
} );
} }
if ( !empty( $fields['text_id'] ) ) { if ( !empty( $fields['text_id'] ) ) {

View file

@ -3556,10 +3556,8 @@ class Title implements LinkTarget, IDBAccessObject {
$linkCache->clearLink( $this ); $linkCache->clearLink( $this );
$this->mArticleID = $linkCache->addLinkObj( $this ); $this->mArticleID = $linkCache->addLinkObj( $this );
$linkCache->forUpdate( $oldUpdate ); $linkCache->forUpdate( $oldUpdate );
} else { } elseif ( $this->mArticleID == -1 ) {
if ( $this->mArticleID == -1 ) { $this->mArticleID = $linkCache->addLinkObj( $this );
$this->mArticleID = $linkCache->addLinkObj( $this );
}
} }
return $this->mArticleID; return $this->mArticleID;
} }

View file

@ -47,12 +47,10 @@ class Xml {
} }
if ( is_null( $contents ) ) { if ( is_null( $contents ) ) {
$out .= '>'; $out .= '>';
} elseif ( $allowShortTag && $contents === '' ) {
$out .= ' />';
} else { } else {
if ( $allowShortTag && $contents === '' ) { $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
$out .= ' />';
} else {
$out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
}
} }
return $out; return $out;
} }

View file

@ -222,12 +222,10 @@ class CreditsAction extends FormlessAction {
$link = $this->link( $user ); $link = $this->link( $user );
if ( $user->isAnon() ) { if ( $user->isAnon() ) {
return $this->msg( 'anonuser' )->rawParams( $link )->parse(); return $this->msg( 'anonuser' )->rawParams( $link )->parse();
} elseif ( $this->canShowRealUserName() && $user->getRealName() ) {
return $link;
} else { } else {
if ( $this->canShowRealUserName() && $user->getRealName() ) { return $this->msg( 'siteuser' )->rawParams( $link )->params( $user->getName() )->escaped();
return $link;
} else {
return $this->msg( 'siteuser' )->rawParams( $link )->params( $user->getName() )->escaped();
}
} }
} }

View file

@ -307,10 +307,8 @@ class ApiComparePages extends ApiBase {
foreach ( [ 'from', 'to' ] as $prefix ) { foreach ( [ 'from', 'to' ] as $prefix ) {
if ( $params["{$prefix}rev"] !== null ) { if ( $params["{$prefix}rev"] !== null ) {
$rev = $this->getRevisionById( $params["{$prefix}rev"] ); $rev = $this->getRevisionById( $params["{$prefix}rev"] );
if ( $rev ) { if ( $rev && $rev->hasSlot( $role ) ) {
if ( $rev->hasSlot( $role ) ) { return $rev->getSlot( $role, RevisionRecord::RAW )->getModel();
return $rev->getSlot( $role, RevisionRecord::RAW )->getModel();
}
} }
} }
} }

View file

@ -559,11 +559,9 @@ class ApiHelp extends ApiBase {
$arr = &$submodules; $arr = &$submodules;
try { try {
$submod = $module->getModuleFromPath( $m ); $submod = $module->getModuleFromPath( $m );
if ( $submod ) { if ( $submod && $submod->isDeprecated() ) {
if ( $submod->isDeprecated() ) { $arr = &$deprecatedSubmodules;
$arr = &$deprecatedSubmodules; $attrs['class'] = 'apihelp-deprecated-value';
$attrs['class'] = 'apihelp-deprecated-value';
}
} }
} catch ( ApiUsageException $ex ) { } catch ( ApiUsageException $ex ) {
// Ignore // Ignore

View file

@ -1117,19 +1117,17 @@ class ApiMain extends ApiBase {
. $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text() . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
) )
); );
} else { } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
if ( $config->get( 'ShowExceptionDetails' ) ) { $result->addContentValue(
$result->addContentValue( $path,
$path, 'trace',
'trace', $this->msg( 'api-exception-trace',
$this->msg( 'api-exception-trace', get_class( $e ),
get_class( $e ), $e->getFile(),
$e->getFile(), $e->getLine(),
$e->getLine(), MWExceptionHandler::getRedactedTraceAsString( $e )
MWExceptionHandler::getRedactedTraceAsString( $e ) )->inLanguage( $formatter->getLanguage() )->text()
)->inLanguage( $formatter->getLanguage() )->text() );
);
}
} }
// Add the id and such // Add the id and such

View file

@ -1398,10 +1398,10 @@ class ApiPageSet extends ApiBase {
$data[$toPageId], $data[$toPageId],
$this->mGeneratorData[$fromNs][$fromDBkey] $this->mGeneratorData[$fromNs][$fromDBkey]
); );
if ( $result instanceof ApiResult ) { if ( $result instanceof ApiResult &&
if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE ) ) { !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE )
return false; ) {
} return false;
} }
} }
} }

View file

@ -157,16 +157,14 @@ abstract class ApiQueryBase extends ApiBase {
*/ */
protected function addTables( $tables, $alias = null ) { protected function addTables( $tables, $alias = null ) {
if ( is_array( $tables ) ) { if ( is_array( $tables ) ) {
if ( !is_null( $alias ) ) { if ( $alias !== null ) {
ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' ); ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
} }
$this->tables = array_merge( $this->tables, $tables ); $this->tables = array_merge( $this->tables, $tables );
} elseif ( $alias !== null ) {
$this->tables[$alias] = $tables;
} else { } else {
if ( !is_null( $alias ) ) { $this->tables[] = $tables;
$this->tables[$alias] = $tables;
} else {
$this->tables[] = $tables;
}
} }
} }

View file

@ -249,13 +249,11 @@ class ApiQueryImageInfo extends ApiQueryBase {
// Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
$scale = []; $scale = [];
$scale['height'] = $params['urlheight']; $scale['height'] = $params['urlheight'];
} elseif ( $params['urlparam'] ) {
// Audio files might not have a width/height.
$scale = [];
} else { } else {
if ( $params['urlparam'] ) { $scale = null;
// Audio files might not have a width/height.
$scale = [];
} else {
$scale = null;
}
} }
return $scale; return $scale;

View file

@ -515,10 +515,8 @@ class ApiQueryInfo extends ApiQueryBase {
} }
} }
if ( $this->fld_varianttitles ) { if ( $this->fld_varianttitles && isset( $this->variantTitles[$pageid] ) ) {
if ( isset( $this->variantTitles[$pageid] ) ) { $pageInfo['varianttitles'] = $this->variantTitles[$pageid];
$pageInfo['varianttitles'] = $this->variantTitles[$pageid];
}
} }
if ( $this->params['testactions'] ) { if ( $this->params['testactions'] ) {

View file

@ -202,13 +202,11 @@ class ApiQueryUserInfo extends ApiQueryBase {
$vals['realname'] = $user->getRealName(); $vals['realname'] = $user->getRealName();
} }
if ( $user->isAllowed( 'viewmyprivateinfo' ) ) { if ( $user->isAllowed( 'viewmyprivateinfo' ) && isset( $this->prop['email'] ) ) {
if ( isset( $this->prop['email'] ) ) { $vals['email'] = $user->getEmail();
$vals['email'] = $user->getEmail(); $auth = $user->getEmailAuthenticationTimestamp();
$auth = $user->getEmailAuthenticationTimestamp(); if ( $auth !== null ) {
if ( !is_null( $auth ) ) { $vals['emailauthenticated'] = wfTimestamp( TS_ISO_8601, $auth );
$vals['emailauthenticated'] = wfTimestamp( TS_ISO_8601, $auth );
}
} }
} }

View file

@ -81,10 +81,8 @@ class ApiQueryWatchlist extends ApiQueryGeneratorBase {
$this->fld_loginfo = isset( $prop['loginfo'] ); $this->fld_loginfo = isset( $prop['loginfo'] );
$this->fld_tags = isset( $prop['tags'] ); $this->fld_tags = isset( $prop['tags'] );
if ( $this->fld_patrol ) { if ( $this->fld_patrol && !$user->useRCPatrol() && !$user->useNPPatrol() ) {
if ( !$user->useRCPatrol() && !$user->useNPPatrol() ) { $this->dieWithError( 'apierror-permissiondenied-patrolflag', 'patrol' );
$this->dieWithError( 'apierror-permissiondenied-patrolflag', 'patrol' );
}
} }
if ( $this->fld_comment || $this->fld_parsedcomment ) { if ( $this->fld_comment || $this->fld_parsedcomment ) {
@ -192,12 +190,10 @@ class ApiQueryWatchlist extends ApiQueryGeneratorBase {
$startFrom = [ $recentChangeInfo['rc_timestamp'], $recentChangeInfo['rc_id'] ]; $startFrom = [ $recentChangeInfo['rc_timestamp'], $recentChangeInfo['rc_id'] ];
break; break;
} }
} elseif ( $params['allrev'] ) {
$ids[] = (int)$recentChangeInfo['rc_this_oldid'];
} else { } else {
if ( $params['allrev'] ) { $ids[] = (int)$recentChangeInfo['rc_cur_id'];
$ids[] = (int)$recentChangeInfo['rc_this_oldid'];
} else {
$ids[] = (int)$recentChangeInfo['rc_cur_id'];
}
} }
} }

View file

@ -2101,10 +2101,8 @@ class AuthManager implements LoggerAwareInterface {
$id = $req->getUniqueId(); $id = $req->getUniqueId();
// If a required request if from a Primary, mark it as "primary-required" instead // If a required request if from a Primary, mark it as "primary-required" instead
if ( $isPrimary ) { if ( $isPrimary && $req->required ) {
if ( $req->required ) { $req->required = AuthenticationRequest::PRIMARY_REQUIRED;
$req->required = AuthenticationRequest::PRIMARY_REQUIRED;
}
} }
if ( if (

View file

@ -303,18 +303,16 @@ class LocalPasswordPrimaryAuthenticationProvider
} }
$req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class ); $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class );
if ( $req ) { if ( $req && $req->username !== null && $req->password !== null ) {
if ( $req->username !== null && $req->password !== null ) { // Nothing we can do besides claim it, because the user isn't in
// Nothing we can do besides claim it, because the user isn't in // the DB yet
// the DB yet if ( $req->username !== $user->getName() ) {
if ( $req->username !== $user->getName() ) { $req = clone $req;
$req = clone $req; $req->username = $user->getName();
$req->username = $user->getName();
}
$ret = AuthenticationResponse::newPass( $req->username );
$ret->createRequest = $req;
return $ret;
} }
$ret = AuthenticationResponse::newPass( $req->username );
$ret->createRequest = $req;
return $ret;
} }
return AuthenticationResponse::newAbstain(); return AuthenticationResponse::newAbstain();
} }

View file

@ -356,23 +356,21 @@ class TemporaryPasswordPrimaryAuthenticationProvider
$req = AuthenticationRequest::getRequestByClass( $req = AuthenticationRequest::getRequestByClass(
$reqs, TemporaryPasswordAuthenticationRequest::class $reqs, TemporaryPasswordAuthenticationRequest::class
); );
if ( $req ) { if ( $req && $req->username !== null && $req->password !== null ) {
if ( $req->username !== null && $req->password !== null ) { // Nothing we can do yet, because the user isn't in the DB yet
// Nothing we can do yet, because the user isn't in the DB yet if ( $req->username !== $user->getName() ) {
if ( $req->username !== $user->getName() ) { $req = clone $req;
$req = clone $req; $req->username = $user->getName();
$req->username = $user->getName();
}
if ( $req->mailpassword ) {
// prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
$this->manager->setAuthenticationSessionData( 'no-email', true );
}
$ret = AuthenticationResponse::newPass( $req->username );
$ret->createRequest = $req;
return $ret;
} }
if ( $req->mailpassword ) {
// prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail
$this->manager->setAuthenticationSessionData( 'no-email', true );
}
$ret = AuthenticationResponse::newPass( $req->username );
$ret->createRequest = $req;
return $ret;
} }
return AuthenticationResponse::newAbstain(); return AuthenticationResponse::newAbstain();
} }

View file

@ -221,13 +221,11 @@ class CacheHelper implements ICacheHelper {
} else { } else {
$value = array_shift( $this->cachedChunks ); $value = array_shift( $this->cachedChunks );
} }
} elseif ( array_key_exists( $key, $this->cachedChunks ) ) {
$value = $this->cachedChunks[$key];
unset( $this->cachedChunks[$key] );
} else { } else {
if ( array_key_exists( $key, $this->cachedChunks ) ) { wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__ );
$value = $this->cachedChunks[$key];
unset( $this->cachedChunks[$key] );
} else {
wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__ );
}
} }
} else { } else {
if ( !is_array( $args ) ) { if ( !is_array( $args ) ) {

View file

@ -128,10 +128,8 @@ class HTMLFileCache extends FileCacheBase {
return false; return false;
} }
if ( $mode === self::MODE_NORMAL ) { if ( ( $mode === self::MODE_NORMAL ) && $user->getNewtalk() ) {
if ( $user->getNewtalk() ) { return false;
return false;
}
} }
// Allow extensions to disable caching // Allow extensions to disable caching
@ -211,18 +209,14 @@ class HTMLFileCache extends FileCacheBase {
} }
// gzip output to buffer as needed and set headers... // gzip output to buffer as needed and set headers...
if ( $this->useGzip() ) { // @todo Ugly wfClientAcceptsGzip() function - use context!
// @todo Ugly wfClientAcceptsGzip() function - use context! if ( $this->useGzip() && wfClientAcceptsGzip() ) {
if ( wfClientAcceptsGzip() ) { header( 'Content-Encoding: gzip' );
header( 'Content-Encoding: gzip' );
return $compressed; return $compressed;
} else {
return $text;
}
} else {
return $text;
} }
return $text;
} }
/** /**

View file

@ -75,22 +75,22 @@ class FileDependency extends CacheDependency {
if ( $this->timestamp === false ) { if ( $this->timestamp === false ) {
# Still nonexistent # Still nonexistent
return false; return false;
} else {
# Deleted
wfDebug( "Dependency triggered: {$this->filename} deleted.\n" );
return true;
} }
} else {
if ( $lastmod > $this->timestamp ) {
# Modified or created
wfDebug( "Dependency triggered: {$this->filename} changed.\n" );
return true; # Deleted
} else { wfDebug( "Dependency triggered: {$this->filename} deleted.\n" );
# Not modified
return false; return true;
}
} }
if ( $lastmod > $this->timestamp ) {
# Modified or created
wfDebug( "Dependency triggered: {$this->filename} changed.\n" );
return true;
}
# Not modified
return false;
} }
} }

View file

@ -86,11 +86,9 @@ class LCStoreCDB implements LCStore {
} }
public function startWrite( $code ) { public function startWrite( $code ) {
if ( !file_exists( $this->directory ) ) { if ( !file_exists( $this->directory ) && !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) { throw new MWException( "Unable to create the localisation store " .
throw new MWException( "Unable to create the localisation store " . "directory \"{$this->directory}\"" );
"directory \"{$this->directory}\"" );
}
} }
// Close reader to stop permission errors on write // Close reader to stop permission errors on write

View file

@ -45,11 +45,9 @@ class LCStoreStaticArray implements LCStore {
} }
public function startWrite( $code ) { public function startWrite( $code ) {
if ( !file_exists( $this->directory ) ) { if ( !file_exists( $this->directory ) && !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) { throw new MWException( "Unable to create the localisation store " .
throw new MWException( "Unable to create the localisation store " . "directory \"{$this->directory}\"" );
"directory \"{$this->directory}\"" );
}
} }
$this->currentLang = $code; $this->currentLang = $code;

View file

@ -365,16 +365,14 @@ class IcuCollation extends Collation {
foreach ( $digits as $digit ) { foreach ( $digits as $digit ) {
$letters[] = $this->digitTransformLanguage->formatNum( $digit, true ); $letters[] = $this->digitTransformLanguage->formatNum( $digit, true );
} }
} elseif ( $this->locale === 'root' ) {
$letters = require "$IP/includes/collation/data/first-letters-root.php";
} else { } else {
if ( $this->locale === 'root' ) { // FIXME: Is this still used?
$letters = require "$IP/includes/collation/data/first-letters-root.php"; $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
} else { if ( $letters === false ) {
// FIXME: Is this still used? throw new MWException( "MediaWiki does not support ICU locale " .
$letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" ); "\"{$this->locale}\"" );
if ( $letters === false ) {
throw new MWException( "MediaWiki does not support ICU locale " .
"\"{$this->locale}\"" );
}
} }
} }

View file

@ -71,14 +71,12 @@ class MWExceptionRenderer {
self::getShowBacktraceError( $e ); self::getShowBacktraceError( $e );
} }
$message .= "\n"; $message .= "\n";
} elseif ( $wgShowExceptionDetails ) {
$message = MWExceptionHandler::getLogMessage( $e ) .
"\nBacktrace:\n" .
MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
} else { } else {
if ( $wgShowExceptionDetails ) { $message = MWExceptionHandler::getPublicLogMessage( $e );
$message = MWExceptionHandler::getLogMessage( $e ) .
"\nBacktrace:\n" .
MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
} else {
$message = MWExceptionHandler::getPublicLogMessage( $e );
}
} }
echo nl2br( htmlspecialchars( $message ) ) . "\n"; echo nl2br( htmlspecialchars( $message ) ) . "\n";
} }

View file

@ -348,14 +348,11 @@ class ForeignAPIRepo extends FileRepo {
if ( !$knownThumbUrls ) { if ( !$knownThumbUrls ) {
/* No knownThumbUrls for this file */ /* No knownThumbUrls for this file */
$knownThumbUrls = []; $knownThumbUrls = [];
} else { } elseif ( isset( $knownThumbUrls[$sizekey] ) ) {
if ( isset( $knownThumbUrls[$sizekey] ) ) { wfDebug( __METHOD__ . ': Got thumburl from local cache: ' .
wfDebug( __METHOD__ . ': Got thumburl from local cache: ' . "{$knownThumbUrls[$sizekey]} \n" );
"{$knownThumbUrls[$sizekey]} \n" );
return $knownThumbUrls[$sizekey]; return $knownThumbUrls[$sizekey];
}
/* This size is not yet known */
} }
$metadata = null; $metadata = null;

View file

@ -633,20 +633,15 @@ abstract class File implements IDBAccessObject {
// one would not expect it to be animated // one would not expect it to be animated
// so true. // so true.
return true; return true;
} else {
if ( $this->allowInlineDisplay()
&& $handler->isAnimatedImage( $this )
&& !$handler->canAnimateThumbnail( $this )
) {
// Image is animated, but thumbnail isn't.
// This is unexpected to the user.
return false;
} else {
// Image is not animated, so one would
// not expect thumb to be
return true;
}
} }
return !$this->allowInlineDisplay()
// Image is not animated, so one would
// not expect thumb to be
|| !$handler->isAnimatedImage( $this )
// Image is animated, but thumbnail isn't.
// This is unexpected to the user.
|| $handler->canAnimateThumbnail( $this );
} }
/** /**

View file

@ -418,10 +418,10 @@ class OldLocalFile extends LocalFile {
$dstRel = $this->getArchiveRel( $archiveName ); $dstRel = $this->getArchiveRel( $archiveName );
$status = $this->publishTo( $srcPath, $dstRel ); $status = $this->publishTo( $srcPath, $dstRel );
if ( $status->isGood() ) { if ( $status->isGood() &&
if ( !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) ) { !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user )
$status->fatal( 'filenotfound', $srcPath ); ) {
} $status->fatal( 'filenotfound', $srcPath );
} }
$this->unlock(); $this->unlock();

View file

@ -38,10 +38,8 @@ class HTMLNamespacesMultiselectField extends HTMLSelectNamespace {
// $value is a string, because HTMLForm fields store their values as strings // $value is a string, because HTMLForm fields store their values as strings
$namespaces = explode( "\n", $value ); $namespaces = explode( "\n", $value );
if ( isset( $this->mParams['max'] ) ) { if ( isset( $this->mParams['max'] ) && ( count( $namespaces ) > $this->mParams['max'] ) ) {
if ( count( $namespaces ) > $this->mParams['max'] ) { return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] );
return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] );
}
} }
foreach ( $namespaces as $namespace ) { foreach ( $namespaces as $namespace ) {

View file

@ -53,10 +53,8 @@ class HTMLTitlesMultiselectField extends HTMLTitleTextField {
// $value is a string, because HTMLForm fields store their values as strings // $value is a string, because HTMLForm fields store their values as strings
$titlesArray = explode( "\n", $value ); $titlesArray = explode( "\n", $value );
if ( isset( $this->mParams['max'] ) ) { if ( isset( $this->mParams['max'] ) && ( count( $titlesArray ) > $this->mParams['max'] ) ) {
if ( count( $titlesArray ) > $this->mParams['max'] ) { return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] );
return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] );
}
} }
foreach ( $titlesArray as $title ) { foreach ( $titlesArray as $title ) {

View file

@ -286,18 +286,16 @@ class WikiImporter {
if ( !$title || $title->isExternal() ) { if ( !$title || $title->isExternal() ) {
$status->fatal( 'import-rootpage-invalid' ); $status->fatal( 'import-rootpage-invalid' );
} elseif ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
$displayNSText = $title->getNamespace() == NS_MAIN
? wfMessage( 'blanknamespace' )->text()
: MediaWikiServices::getInstance()->getContentLanguage()->
getNsText( $title->getNamespace() );
$status->fatal( 'import-rootpage-nosubpage', $displayNSText );
} else { } else {
if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) { // set namespace to 'all', so the namespace check in processTitle() can pass
$displayNSText = $title->getNamespace() == NS_MAIN $this->setTargetNamespace( null );
? wfMessage( 'blanknamespace' )->text() $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
: MediaWikiServices::getInstance()->getContentLanguage()->
getNsText( $title->getNamespace() );
$status->fatal( 'import-rootpage-nosubpage', $displayNSText );
} else {
// set namespace to 'all', so the namespace check in processTitle() can pass
$this->setTargetNamespace( null );
$this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
}
} }
} }
return $status; return $status;

View file

@ -443,11 +443,11 @@ class PostgresInstaller extends DatabaseInstaller {
} }
// Recursively search each member of the group to see if the target // Recursively search each member of the group to see if the target
// is a member of it, up to the given maximum depth. // is a member of it, up to the given maximum depth.
if ( $maxDepth > 0 ) { if ( $maxDepth > 0 &&
if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) { $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 )
// Found member of member ) {
return true; // Found member of member
} return true;
} }
} }

View file

@ -1007,13 +1007,11 @@ END;
public function addPgExtIndex( $table, $index, $type ) { public function addPgExtIndex( $table, $index, $type ) {
if ( $this->db->indexExists( $table, $index ) ) { if ( $this->db->indexExists( $table, $index ) ) {
$this->output( "...index '$index' on table '$table' already exists\n" ); $this->output( "...index '$index' on table '$table' already exists\n" );
} elseif ( preg_match( '/^\(/', $type ) ) {
$this->output( "Creating index '$index' on table '$table'\n" );
$this->db->query( "CREATE INDEX $index ON $table $type" );
} else { } else {
if ( preg_match( '/^\(/', $type ) ) { $this->applyPatch( $type, true, "Creating index '$index' on table '$table'" );
$this->output( "Creating index '$index' on table '$table'\n" );
$this->db->query( "CREATE INDEX $index ON $table $type" );
} else {
$this->applyPatch( $type, true, "Creating index '$index' on table '$table'" );
}
} }
} }

View file

@ -332,10 +332,8 @@ EOT;
if ( !is_writable( $file ) ) { if ( !is_writable( $file ) ) {
return Status::newFatal( 'config-sqlite-readonly', $file ); return Status::newFatal( 'config-sqlite-readonly', $file );
} }
} else { } elseif ( file_put_contents( $file, '' ) === false ) {
if ( file_put_contents( $file, '' ) === false ) { return Status::newFatal( 'config-sqlite-cant-create-db', $file );
return Status::newFatal( 'config-sqlite-cant-create-db', $file );
}
} }
return Status::newGood(); return Status::newGood();

View file

@ -1072,12 +1072,10 @@ class WebInstaller extends Installer {
if ( $value === null ) { if ( $value === null ) {
// Checkbox? // Checkbox?
$this->setVar( $name, false ); $this->setVar( $name, false );
} elseif ( stripos( $name, 'password' ) !== false ) {
$this->setPassword( $name, $value );
} else { } else {
if ( stripos( $name, 'password' ) !== false ) { $this->setVar( $name, $value );
$this->setPassword( $name, $value );
} else {
$this->setVar( $name, $value );
}
} }
} }

View file

@ -28,10 +28,8 @@ class WebInstallerName extends WebInstallerPage {
*/ */
public function execute() { public function execute() {
$r = $this->parent->request; $r = $this->parent->request;
if ( $r->wasPosted() ) { if ( $r->wasPosted() && $this->submit() ) {
if ( $this->submit() ) { return 'continue';
return 'continue';
}
} }
$this->startForm(); $this->startForm();

View file

@ -31,10 +31,8 @@ class WebInstallerOptions extends WebInstallerPage {
$this->submitSkins(); $this->submitSkins();
return 'skip'; return 'skip';
} }
if ( $this->parent->request->wasPosted() ) { if ( $this->parent->request->wasPosted() && $this->submit() ) {
if ( $this->submit() ) { return 'continue';
return 'continue';
}
} }
$emailwrapperStyle = $this->getVar( 'wgEnableEmail' ) ? '' : 'display: none'; $emailwrapperStyle = $this->getVar( 'wgEnableEmail' ) ? '' : 'display: none';

View file

@ -25,10 +25,8 @@ class WebInstallerWelcome extends WebInstallerPage {
* @return string * @return string
*/ */
public function execute() { public function execute() {
if ( $this->parent->request->wasPosted() ) { if ( $this->parent->request->wasPosted() && $this->getVar( '_Environment' ) ) {
if ( $this->getVar( '_Environment' ) ) { return 'continue';
return 'continue';
}
} }
$this->parent->output->addWikiTextAsInterface( wfMessage( 'config-welcome' )->plain() ); $this->parent->output->addWikiTextAsInterface( wfMessage( 'config-welcome' )->plain() );
$status = $this->parent->doEnvironmentChecks(); $status = $this->parent->doEnvironmentChecks();

View file

@ -237,11 +237,9 @@ class MultiHttpClient implements LoggerAwareInterface {
} }
} while ( $mrc == CURLM_CALL_MULTI_PERFORM ); } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
// Wait (if possible) for available work... // Wait (if possible) for available work...
if ( $active > 0 && $mrc == CURLM_OK ) { if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
if ( curl_multi_select( $chm, $selectTimeout ) == -1 ) { // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
// PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html usleep( 5000 ); // 5ms
usleep( 5000 ); // 5ms
}
} }
} while ( $active > 0 && $mrc == CURLM_OK ); } while ( $active > 0 && $mrc == CURLM_OK );
} }

View file

@ -257,11 +257,11 @@ class FileBackendMultiWrite extends FileBackend {
$status->fatal( 'backend-fail-synced', $path ); $status->fatal( 'backend-fail-synced', $path );
continue; continue;
} }
if ( $this->syncChecks & self::CHECK_SIZE ) { if ( ( $this->syncChecks & self::CHECK_SIZE )
if ( $cStat['size'] != $mStat['size'] ) { // wrong size && $cStat['size'] != $mStat['size']
$status->fatal( 'backend-fail-synced', $path ); ) { // wrong size
continue; $status->fatal( 'backend-fail-synced', $path );
} continue;
} }
if ( $this->syncChecks & self::CHECK_TIME ) { if ( $this->syncChecks & self::CHECK_TIME ) {
$mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] ); $mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] );
@ -271,16 +271,12 @@ class FileBackendMultiWrite extends FileBackend {
continue; continue;
} }
} }
if ( $this->syncChecks & self::CHECK_SHA1 ) { if ( ( $this->syncChecks & self::CHECK_SHA1 ) && $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
if ( $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1
$status->fatal( 'backend-fail-synced', $path );
continue;
}
}
} else { // file is not in master
if ( $cStat ) { // file should not exist
$status->fatal( 'backend-fail-synced', $path ); $status->fatal( 'backend-fail-synced', $path );
continue;
} }
} elseif ( $cStat ) { // file is not in master; file should not exist
$status->fatal( 'backend-fail-synced', $path );
} }
} }
} }

View file

@ -406,10 +406,10 @@ class XmlTypeCheck {
$callbackReturn = false; $callbackReturn = false;
} }
if ( $checkIfSafe && isset( $parsedDTD['internal'] ) ) { if ( $checkIfSafe && isset( $parsedDTD['internal'] ) &&
if ( !$this->checkDTDIsSafe( $parsedDTD['internal'] ) ) { !$this->checkDTDIsSafe( $parsedDTD['internal'] )
$this->wellFormed = false; ) {
} $this->wellFormed = false;
} }
} }

View file

@ -601,22 +601,20 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
[ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
); );
// Case C: medium length request with medium replication lag // Case C: medium length request with medium replication lag
} elseif ( $lockTSE >= 0 ) {
// Store value as *almost* stale to avoid cache and mutex stampedes
$logicalTTL = self::TTL_SECOND;
$this->logger->info(
'Lowered set() TTL for {cachekey} due to high read lag.',
[ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
);
} else { } else {
if ( $lockTSE >= 0 ) { $this->logger->info(
// Store value as *almost* stale to avoid cache and mutex stampedes 'Rejected set() for {cachekey} due to high read lag.',
$logicalTTL = self::TTL_SECOND; [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
$this->logger->info( );
'Lowered set() TTL for {cachekey} due to high read lag.',
[ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
);
} else {
$this->logger->info(
'Rejected set() for {cachekey} due to high read lag.',
[ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
);
return true; // no-op the write for being unsafe return true; // no-op the write for being unsafe
}
} }
} }

View file

@ -524,20 +524,18 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware
$possibleDrivers = $builtinTypes[$dbType]; $possibleDrivers = $builtinTypes[$dbType];
if ( is_string( $possibleDrivers ) ) { if ( is_string( $possibleDrivers ) ) {
$class = $possibleDrivers; $class = $possibleDrivers;
} elseif ( (string)$driver !== '' ) {
if ( !isset( $possibleDrivers[$driver] ) ) {
throw new InvalidArgumentException( __METHOD__ .
" type '$dbType' does not support driver '{$driver}'" );
}
$class = $possibleDrivers[$driver];
} else { } else {
if ( (string)$driver !== '' ) { foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
if ( !isset( $possibleDrivers[$driver] ) ) { if ( extension_loaded( $posDriver ) ) {
throw new InvalidArgumentException( __METHOD__ . $class = $possibleClass;
" type '$dbType' does not support driver '{$driver}'" ); break;
} else {
$class = $possibleDrivers[$driver];
}
} else {
foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
if ( extension_loaded( $posDriver ) ) {
$class = $possibleClass;
break;
}
} }
} }
} }
@ -644,13 +642,13 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware
public function getLBInfo( $name = null ) { public function getLBInfo( $name = null ) {
if ( is_null( $name ) ) { if ( is_null( $name ) ) {
return $this->lbInfo; return $this->lbInfo;
} else {
if ( array_key_exists( $name, $this->lbInfo ) ) {
return $this->lbInfo[$name];
} else {
return null;
}
} }
if ( array_key_exists( $name, $this->lbInfo ) ) {
return $this->lbInfo[$name];
}
return null;
} }
public function setLBInfo( $name, $value = null ) { public function setLBInfo( $name, $value = null ) {
@ -3975,17 +3973,15 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware
"$fname: Flushing an explicit transaction, getting out of sync." "$fname: Flushing an explicit transaction, getting out of sync."
); );
} }
} else { } elseif ( !$this->trxLevel ) {
if ( !$this->trxLevel ) { $this->queryLogger->error(
$this->queryLogger->error( "$fname: No transaction to commit, something got out of sync." );
"$fname: No transaction to commit, something got out of sync." ); return; // nothing to do
return; // nothing to do } elseif ( $this->trxAutomatic ) {
} elseif ( $this->trxAutomatic ) { throw new DBUnexpectedError(
throw new DBUnexpectedError( $this,
$this, "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
"$fname: Expected mass commit of all peer transactions (DBO_TRX set)." );
);
}
} }
$this->assertHasConnectionHandle(); $this->assertHasConnectionHandle();
@ -4030,13 +4026,14 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware
final public function rollback( $fname = __METHOD__, $flush = '' ) { final public function rollback( $fname = __METHOD__, $flush = '' ) {
$trxActive = $this->trxLevel; $trxActive = $this->trxLevel;
if ( $flush !== self::FLUSHING_INTERNAL && $flush !== self::FLUSHING_ALL_PEERS ) { if ( $flush !== self::FLUSHING_INTERNAL
if ( $this->getFlag( self::DBO_TRX ) ) { && $flush !== self::FLUSHING_ALL_PEERS
throw new DBUnexpectedError( && $this->getFlag( self::DBO_TRX )
$this, ) {
"$fname: Expected mass rollback of all peer transactions (DBO_TRX set)." throw new DBUnexpectedError(
); $this,
} "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
);
} }
if ( $trxActive ) { if ( $trxActive ) {

View file

@ -487,10 +487,8 @@ class LoadBalancer implements ILoadBalancer {
$this->waitForPos = $pos; $this->waitForPos = $pos;
// If a generic reader connection was already established, then wait now // If a generic reader connection was already established, then wait now
$i = $this->readIndex; $i = $this->readIndex;
if ( $i > 0 ) { if ( ( $i > 0 ) && !$this->doWait( $i ) ) {
if ( !$this->doWait( $i ) ) { $this->laggedReplicaMode = true;
$this->laggedReplicaMode = true;
}
} }
} finally { } finally {
// Restore the older position if it was higher since this is used for lag-protection // Restore the older position if it was higher since this is used for lag-protection

View file

@ -245,13 +245,11 @@ class RedisConnectionPool implements LoggerAwareInterface {
return false; return false;
} }
if ( $this->password !== null ) { if ( ( $this->password !== null ) && !$conn->auth( $this->password ) ) {
if ( !$conn->auth( $this->password ) ) { $logger->error(
$logger->error( 'Authentication error connecting to "{redis_server}"',
'Authentication error connecting to "{redis_server}"', [ 'redis_server' => $server ]
[ 'redis_server' => $server ] );
);
}
} }
} catch ( RedisException $e ) { } catch ( RedisException $e ) {
$this->downServers[$server] = time() + self::SERVER_DOWN_TTL; $this->downServers[$server] = time() + self::SERVER_DOWN_TTL;
@ -364,15 +362,13 @@ class RedisConnectionPool implements LoggerAwareInterface {
* @return bool Success * @return bool Success
*/ */
public function reauthenticateConnection( $server, Redis $conn ) { public function reauthenticateConnection( $server, Redis $conn ) {
if ( $this->password !== null ) { if ( $this->password !== null && !$conn->auth( $this->password ) ) {
if ( !$conn->auth( $this->password ) ) { $this->logger->error(
$this->logger->error( 'Authentication error connecting to "{redis_server}"',
'Authentication error connecting to "{redis_server}"', [ 'redis_server' => $server ]
[ 'redis_server' => $server ] );
);
return false; return false;
}
} }
return true; return true;

View file

@ -225,10 +225,9 @@ class EmailNotification {
&& $watchingUser->getId() != $userTalkId && $watchingUser->getId() != $userTalkId
&& !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges ) && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges )
&& !( $wgBlockDisablesLogin && $watchingUser->isBlocked() ) && !( $wgBlockDisablesLogin && $watchingUser->isBlocked() )
&& Hooks::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] )
) { ) {
if ( Hooks::run( 'SendWatchlistEmailNotification', [ $watchingUser, $title, $this ] ) ) { $this->compose( $watchingUser, self::WATCHLIST );
$this->compose( $watchingUser, self::WATCHLIST );
}
} }
} }
} }

View file

@ -338,10 +338,8 @@ class BitmapHandler extends TransformationalImageHandler {
} }
$im->setImageDepth( 8 ); $im->setImageDepth( 8 );
if ( $rotation ) { if ( $rotation && !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) {
if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) { return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" );
}
} }
if ( $this->isAnimatedImage( $image ) ) { if ( $this->isAnimatedImage( $image ) ) {

View file

@ -132,13 +132,13 @@ class BitmapMetadataHandler {
// Do some special casing for multilingual values. // Do some special casing for multilingual values.
// Don't discard translations if also as a simple value. // Don't discard translations if also as a simple value.
foreach ( $this->metadata[$type] as $itemName => $item ) { foreach ( $this->metadata[$type] as $itemName => $item ) {
if ( is_array( $item ) && isset( $item['_type'] ) && $item['_type'] === 'lang' ) { if ( is_array( $item ) && isset( $item['_type'] ) && $item['_type'] === 'lang' &&
if ( isset( $temp[$itemName] ) && !is_array( $temp[$itemName] ) ) { isset( $temp[$itemName] ) && !is_array( $temp[$itemName] )
$default = $temp[$itemName]; ) {
$temp[$itemName] = $item; $default = $temp[$itemName];
$temp[$itemName]['x-default'] = $default; $temp[$itemName] = $item;
unset( $this->metadata[$type][$itemName] ); $temp[$itemName]['x-default'] = $default;
} unset( $this->metadata[$type][$itemName] );
} }
} }

View file

@ -199,20 +199,16 @@ class SvgHandler extends ImageHandler {
$params['physicalWidth'] = $wgSVGMaxSize; $params['physicalWidth'] = $wgSVGMaxSize;
$params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize ); $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
} }
} else { } elseif ( $params['physicalHeight'] > $wgSVGMaxSize ) {
if ( $params['physicalHeight'] > $wgSVGMaxSize ) { $srcWidth = $image->getWidth( $params['page'] );
$srcWidth = $image->getWidth( $params['page'] ); $srcHeight = $image->getHeight( $params['page'] );
$srcHeight = $image->getHeight( $params['page'] ); $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
$params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize ); $params['physicalHeight'] = $wgSVGMaxSize;
$params['physicalHeight'] = $wgSVGMaxSize;
}
} }
// To prevent the proliferation of thumbnails in languages not present in SVGs, unless // To prevent the proliferation of thumbnails in languages not present in SVGs, unless
// explicitly forced by user. // explicitly forced by user.
if ( isset( $params['targetlang'] ) ) { if ( isset( $params['targetlang'] ) && !$image->getMatchedLanguage( $params['targetlang'] ) ) {
if ( !$image->getMatchedLanguage( $params['targetlang'] ) ) { unset( $params['targetlang'] );
unset( $params['targetlang'] );
}
} }
return $params; return $params;

View file

@ -1131,13 +1131,11 @@ class Article implements Page {
* [[MediaWiki:Talkpagetext]]. For Article::view(). * [[MediaWiki:Talkpagetext]]. For Article::view().
*/ */
public function showNamespaceHeader() { public function showNamespaceHeader() {
if ( $this->getTitle()->isTalkPage() ) { if ( $this->getTitle()->isTalkPage() && !wfMessage( 'talkpageheader' )->isDisabled() ) {
if ( !wfMessage( 'talkpageheader' )->isDisabled() ) { $this->getContext()->getOutput()->wrapWikiMsg(
$this->getContext()->getOutput()->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1\n</div>",
"<div class=\"mw-talkpageheader\">\n$1\n</div>", [ 'talkpageheader' ]
[ 'talkpageheader' ] );
);
}
} }
} }

View file

@ -380,23 +380,19 @@ class BlockLevelPass {
$output .= $pendingPTag . '<br />'; $output .= $pendingPTag . '<br />';
$pendingPTag = false; $pendingPTag = false;
$this->lastParagraph = 'p'; $this->lastParagraph = 'p';
} else {
if ( $this->lastParagraph !== 'p' ) {
$output .= $this->closeParagraph();
$pendingPTag = '<p>';
} else {
$pendingPTag = '</p><p>';
}
}
} else {
if ( $pendingPTag ) {
$output .= $pendingPTag;
$pendingPTag = false;
$this->lastParagraph = 'p';
} elseif ( $this->lastParagraph !== 'p' ) { } elseif ( $this->lastParagraph !== 'p' ) {
$output .= $this->closeParagraph() . '<p>'; $output .= $this->closeParagraph();
$this->lastParagraph = 'p'; $pendingPTag = '<p>';
} else {
$pendingPTag = '</p><p>';
} }
} elseif ( $pendingPTag ) {
$output .= $pendingPTag;
$pendingPTag = false;
$this->lastParagraph = 'p';
} elseif ( $this->lastParagraph !== 'p' ) {
$output .= $this->closeParagraph() . '<p>';
$this->lastParagraph = 'p';
} }
} }
} }

View file

@ -1421,13 +1421,12 @@ class Parser {
*/ */
if ( !( $this->mOptions->getDisableContentConversion() if ( !( $this->mOptions->getDisableContentConversion()
|| isset( $this->mDoubleUnderscores['nocontentconvert'] ) ) || isset( $this->mDoubleUnderscores['nocontentconvert'] ) )
&& !$this->mOptions->getInterfaceMessage()
) { ) {
if ( !$this->mOptions->getInterfaceMessage() ) { # The position of the convert() call should not be changed. it
# The position of the convert() call should not be changed. it # assumes that the links are all replaced and the only thing left
# assumes that the links are all replaced and the only thing left # is the <nowiki> mark.
# is the <nowiki> mark. $text = $this->getTargetLanguage()->convert( $text );
$text = $this->getTargetLanguage()->convert( $text );
}
} }
$text = $this->mStripState->unstripNoWiki( $text ); $text = $this->mStripState->unstripNoWiki( $text );
@ -1767,10 +1766,8 @@ class Parser {
// if $firstsingleletterword is set, we don't // if $firstsingleletterword is set, we don't
// look at the other options, so we can bail early. // look at the other options, so we can bail early.
break; break;
} else { } elseif ( $firstmultiletterword == -1 ) {
if ( $firstmultiletterword == -1 ) { $firstmultiletterword = $i;
$firstmultiletterword = $i;
}
} }
} }
} }
@ -2578,10 +2575,10 @@ class Parser {
* Some of these require message or data lookups and can be * Some of these require message or data lookups and can be
* expensive to check many times. * expensive to check many times.
*/ */
if ( Hooks::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache ] ) ) { if ( Hooks::run( 'ParserGetVariableValueVarCache', [ &$parser, &$this->mVarCache ] )
if ( isset( $this->mVarCache[$index] ) ) { && isset( $this->mVarCache[$index] )
return $this->mVarCache[$index]; ) {
} return $this->mVarCache[$index];
} }
$ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() ); $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
@ -5367,10 +5364,8 @@ class Parser {
if ( $paramName === 'no-link' ) { if ( $paramName === 'no-link' ) {
$value = true; $value = true;
} }
if ( $paramName === 'link-url' ) { if ( ( $paramName === 'link-url' ) && $this->mOptions->getExternalLinkTarget() ) {
if ( $this->mOptions->getExternalLinkTarget() ) { $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
$params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
}
} }
} }
break; break;
@ -5711,15 +5706,15 @@ class Parser {
if ( $sectionIndex == 0 ) { if ( $sectionIndex == 0 ) {
if ( $mode === 'get' ) { if ( $mode === 'get' ) {
return ''; return '';
} else {
return $newText;
} }
return $newText;
} else { } else {
if ( $mode === 'get' ) { if ( $mode === 'get' ) {
return $newText; return $newText;
} else {
return $text;
} }
return $text;
} }
} }
@ -6334,10 +6329,8 @@ class Parser {
*/ */
public static function stripOuterParagraph( $html ) { public static function stripOuterParagraph( $html ) {
$m = []; $m = [];
if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) { if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '</p>' ) === false ) {
if ( strpos( $m[1], '</p>' ) === false ) { $html = $m[1];
$html = $m[1];
}
} }
return $html; return $html;

View file

@ -578,10 +578,8 @@ class Sanitizer {
$badtag = true; $badtag = true;
} }
} }
} else { } elseif ( $t == 'table' ) {
if ( $t == 'table' ) { $tagstack = array_pop( $tablestack );
$tagstack = array_pop( $tablestack );
}
} }
$newparams = ''; $newparams = '';
} else { } else {

View file

@ -1160,11 +1160,9 @@ MESSAGE;
// Use a linebreak between module script and state script (T162719) // Use a linebreak between module script and state script (T162719)
$out = $this->ensureNewline( $out ) . $stateScript; $out = $this->ensureNewline( $out ) . $stateScript;
} }
} else { } elseif ( $states ) {
if ( $states ) { $this->errors[] = 'Problematic modules: '
$this->errors[] = 'Problematic modules: ' . self::encodeJsonForScript( $states );
. self::encodeJsonForScript( $states );
}
} }
return $out; return $out;

View file

@ -450,19 +450,17 @@ class ResourceLoaderClientHtml {
// Decide whether to use 'style' or 'script' element // Decide whether to use 'style' or 'script' element
if ( $only === ResourceLoaderModule::TYPE_STYLES ) { if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
$chunk = Html::linkedStyle( $url ); $chunk = Html::linkedStyle( $url );
} elseif ( $context->getRaw() || $isRaw ) {
$chunk = Html::element( 'script', [
// In SpecialJavaScriptTest, QUnit must load synchronous
'async' => !isset( $extraQuery['sync'] ),
'src' => $url
] );
} else { } else {
if ( $context->getRaw() || $isRaw ) { $chunk = ResourceLoader::makeInlineScript(
$chunk = Html::element( 'script', [ Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
// In SpecialJavaScriptTest, QUnit must load synchronous $nonce
'async' => !isset( $extraQuery['sync'] ), );
'src' => $url
] );
} else {
$chunk = ResourceLoader::makeInlineScript(
Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
$nonce
);
}
} }
if ( $group == 'noscript' ) { if ( $group == 'noscript' ) {

View file

@ -264,28 +264,26 @@ abstract class BaseTemplate extends QuickTemplate {
$boxes[$boxName]['content'] = $content; $boxes[$boxName]['content'] = $content;
} }
} }
} else { } elseif ( $hookContents ) {
if ( $hookContents ) { $boxes['TOOLBOXEND'] = [
$boxes['TOOLBOXEND'] = [ 'id' => 'p-toolboxend',
'id' => 'p-toolboxend', 'header' => $boxes['TOOLBOX']['header'],
'header' => $boxes['TOOLBOX']['header'], 'generated' => false,
'generated' => false, 'content' => "<ul>{$hookContents}</ul>",
'content' => "<ul>{$hookContents}</ul>", ];
]; // HACK: Make sure that TOOLBOXEND is sorted next to TOOLBOX
// HACK: Make sure that TOOLBOXEND is sorted next to TOOLBOX $boxes2 = [];
$boxes2 = []; foreach ( $boxes as $key => $box ) {
foreach ( $boxes as $key => $box ) { if ( $key === 'TOOLBOXEND' ) {
if ( $key === 'TOOLBOXEND' ) { continue;
continue; }
} $boxes2[$key] = $box;
$boxes2[$key] = $box; if ( $key === 'TOOLBOX' ) {
if ( $key === 'TOOLBOX' ) { $boxes2['TOOLBOXEND'] = $boxes['TOOLBOXEND'];
$boxes2['TOOLBOXEND'] = $boxes['TOOLBOXEND'];
}
} }
$boxes = $boxes2;
// END hack
} }
$boxes = $boxes2;
// END hack
} }
return $boxes; return $boxes;

View file

@ -389,17 +389,15 @@ class SkinTemplate extends Skin {
$tpl->set( 'credits', false ); $tpl->set( 'credits', false );
$tpl->set( 'numberofwatchingusers', false ); $tpl->set( 'numberofwatchingusers', false );
if ( $title->exists() ) { if ( $title->exists() ) {
if ( $out->isArticle() ) { if ( $out->isArticle() && $this->isRevisionCurrent() ) {
if ( $this->isRevisionCurrent() ) { if ( $wgMaxCredits != 0 ) {
if ( $wgMaxCredits != 0 ) { /** @var CreditsAction $action */
/** @var CreditsAction $action */ $action = Action::factory(
$action = Action::factory( 'credits', $this->getWikiPage(), $this->getContext() );
'credits', $this->getWikiPage(), $this->getContext() ); $tpl->set( 'credits',
$tpl->set( 'credits', $action->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) );
$action->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) ); } else {
} else { $tpl->set( 'lastmod', $this->lastModified() );
$tpl->set( 'lastmod', $this->lastModified() );
}
} }
} }
if ( $out->showsCopyright() ) { if ( $out->showsCopyright() ) {

View file

@ -267,14 +267,10 @@ class SpecialContributions extends IncludableSpecialPage {
$message = 'sp-contributions-footer'; $message = 'sp-contributions-footer';
} }
if ( $message ) { if ( $message && !$this->including() && !$this->msg( $message, $target )->isDisabled() ) {
if ( !$this->including() ) { $out->wrapWikiMsg(
if ( !$this->msg( $message, $target )->isDisabled() ) { "<div class='mw-contributions-footer'>\n$1\n</div>",
$out->wrapWikiMsg( [ $message, $target ] );
"<div class='mw-contributions-footer'>\n$1\n</div>",
[ $message, $target ] );
}
}
} }
} }
} }

View file

@ -391,10 +391,8 @@ class SpecialImport extends SpecialPage {
Xml::closeElement( 'form' ) . Xml::closeElement( 'form' ) .
Xml::closeElement( 'fieldset' ) Xml::closeElement( 'fieldset' )
); );
} else { } elseif ( empty( $this->importSources ) ) {
if ( empty( $this->importSources ) ) { $out->addWikiMsg( 'importnosources' );
$out->addWikiMsg( 'importnosources' );
}
} }
if ( $user->isAllowed( 'import' ) && !empty( $this->importSources ) ) { if ( $user->isAllowed( 'import' ) && !empty( $this->importSources ) ) {

View file

@ -243,14 +243,12 @@ class SpecialSearch extends SpecialPage {
$this->namespaces = $nslist; $this->namespaces = $nslist;
} elseif ( $profile === 'advanced' ) { } elseif ( $profile === 'advanced' ) {
$this->namespaces = $nslist; $this->namespaces = $nslist;
} elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
$this->namespaces = $profiles[$profile]['namespaces'];
} else { } else {
if ( isset( $profiles[$profile]['namespaces'] ) ) { // Unknown profile requested
$this->namespaces = $profiles[$profile]['namespaces']; $profile = 'default';
} else { $this->namespaces = $profiles['default']['namespaces'];
// Unknown profile requested
$profile = 'default';
$this->namespaces = $profiles['default']['namespaces'];
}
} }
$this->fulltext = $request->getVal( 'fulltext' ); $this->fulltext = $request->getVal( 'fulltext' );

View file

@ -191,11 +191,9 @@ class SpecialUpload extends SpecialPage {
$this->loadRequest(); $this->loadRequest();
# Unsave the temporary file in case this was a cancelled upload # Unsave the temporary file in case this was a cancelled upload
if ( $this->mCancelUpload ) { if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) {
if ( !$this->unsaveUploadedFile() ) { # Something went wrong, so unsaveUploadedFile showed a warning
# Something went wrong, so unsaveUploadedFile showed a warning return;
return;
}
} }
# Process upload or show a form # Process upload or show a form

View file

@ -200,29 +200,27 @@ class SpecialWhatLinksHere extends IncludableSpecialPage {
&& ( $hidetrans || !$tlRes->numRows() ) && ( $hidetrans || !$tlRes->numRows() )
&& ( $hideimages || !$ilRes->numRows() ) && ( $hideimages || !$ilRes->numRows() )
) { ) {
if ( $level == 0 ) { if ( $level == 0 && !$this->including() ) {
if ( !$this->including() ) { $out->addHTML( $this->whatlinkshereForm() );
$out->addHTML( $this->whatlinkshereForm() );
// Show filters only if there are links // Show filters only if there are links
if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) { if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) {
$out->addHTML( $this->getFilterPanel() ); $out->addHTML( $this->getFilterPanel() );
}
$msgKey = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
$link = $this->getLinkRenderer()->makeLink(
$this->target,
null,
[],
$this->target->isRedirect() ? [ 'redirect' => 'no' ] : []
);
$errMsg = $this->msg( $msgKey )
->params( $this->target->getPrefixedText() )
->rawParams( $link )
->parseAsBlock();
$out->addHTML( $errMsg );
$out->setStatusCode( 404 );
} }
$msgKey = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
$link = $this->getLinkRenderer()->makeLink(
$this->target,
null,
[],
$this->target->isRedirect() ? [ 'redirect' => 'no' ] : []
);
$errMsg = $this->msg( $msgKey )
->params( $this->target->getPrefixedText() )
->rawParams( $link )
->parseAsBlock();
$out->addHTML( $errMsg );
$out->setStatusCode( 404 );
} }
return; return;
@ -280,27 +278,25 @@ class SpecialWhatLinksHere extends IncludableSpecialPage {
} }
$lb->execute(); $lb->execute();
if ( $level == 0 ) { if ( $level == 0 && !$this->including() ) {
if ( !$this->including() ) { $out->addHTML( $this->whatlinkshereForm() );
$out->addHTML( $this->whatlinkshereForm() ); $out->addHTML( $this->getFilterPanel() );
$out->addHTML( $this->getFilterPanel() );
$link = $this->getLinkRenderer()->makeLink( $link = $this->getLinkRenderer()->makeLink(
$this->target, $this->target,
null, null,
[], [],
$this->target->isRedirect() ? [ 'redirect' => 'no' ] : [] $this->target->isRedirect() ? [ 'redirect' => 'no' ] : []
); );
$msg = $this->msg( 'linkshere' ) $msg = $this->msg( 'linkshere' )
->params( $this->target->getPrefixedText() ) ->params( $this->target->getPrefixedText() )
->rawParams( $link ) ->rawParams( $link )
->parseAsBlock(); ->parseAsBlock();
$out->addHTML( $msg ); $out->addHTML( $msg );
$prevnext = $this->getPrevNext( $prevId, $nextId ); $prevnext = $this->getPrevNext( $prevId, $nextId );
$out->addHTML( $prevnext ); $out->addHTML( $prevnext );
}
} }
$out->addHTML( $this->listStart( $level ) ); $out->addHTML( $this->listStart( $level ) );
foreach ( $rows as $row ) { foreach ( $rows as $row ) {
@ -321,10 +317,8 @@ class SpecialWhatLinksHere extends IncludableSpecialPage {
$out->addHTML( $this->listEnd() ); $out->addHTML( $this->listEnd() );
if ( $level == 0 ) { if ( $level == 0 && !$this->including() ) {
if ( !$this->including() ) { $out->addHTML( $prevnext );
$out->addHTML( $prevnext );
}
} }
} }

View file

@ -191,10 +191,8 @@ class BlockListPager extends TablePager {
case 'ipb_params': case 'ipb_params':
$properties = []; $properties = [];
if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) { if ( $this->getConfig()->get( 'EnablePartialBlocks' ) && $row->ipb_sitewide ) {
if ( $row->ipb_sitewide ) { $properties[] = htmlspecialchars( $msg['blocklist-editing-sitewide'] );
$properties[] = htmlspecialchars( $msg['blocklist-editing-sitewide'] );
}
} }
if ( !$row->ipb_sitewide && $this->restrictions ) { if ( !$row->ipb_sitewide && $this->restrictions ) {

View file

@ -269,10 +269,8 @@ class ImageListPager extends TablePager {
} }
} }
$fields['top'] = $dbr->addQuotes( 'no' ); $fields['top'] = $dbr->addQuotes( 'no' );
} else { } elseif ( $this->mShowAll ) {
if ( $this->mShowAll ) { $fields['top'] = $dbr->addQuotes( 'yes' );
$fields['top'] = $dbr->addQuotes( 'yes' );
}
} }
$fields['thumb'] = $prefix . '_name'; $fields['thumb'] = $prefix . '_name';
@ -382,14 +380,12 @@ class ImageListPager extends TablePager {
$resultArray[] = $topRes2; $resultArray[] = $topRes2;
$topRes2 = $res2->next(); $topRes2 = $res2->next();
} }
} elseif ( !$ascending ) {
$resultArray[] = $topRes2;
$topRes2 = $res2->next();
} else { } else {
if ( !$ascending ) { $resultArray[] = $topRes1;
$resultArray[] = $topRes2; $topRes1 = $res1->next();
$topRes2 = $res2->next();
} else {
$resultArray[] = $topRes1;
$topRes1 = $res1->next();
}
} }
} }

View file

@ -40,10 +40,10 @@ class RemexCompatFormatter extends HtmlFormatter {
$name = $node->name; $name = $node->name;
$attrs = $node->attrs; $attrs = $node->attrs;
if ( isset( self::$markedEmptyElements[$name] ) && $attrs->count() === 0 ) { if ( isset( self::$markedEmptyElements[$name] ) && $attrs->count() === 0
if ( strspn( $contents, "\t\n\f\r " ) === strlen( $contents ) ) { && strspn( $contents, "\t\n\f\r " ) === strlen( $contents )
return "<{$name} class=\"mw-empty-elt\">$contents</{$name}>"; ) {
} return "<{$name} class=\"mw-empty-elt\">$contents</{$name}>";
} }
$s = "<$name"; $s = "<$name";

View file

@ -421,10 +421,8 @@ class MediaWikiTitleCodec implements TitleFormatter, TitleParser {
# Can't make a link to a namespace alone... "empty" local links can only be # Can't make a link to a namespace alone... "empty" local links can only be
# self-links with a fragment identifier. # self-links with a fragment identifier.
if ( $dbkey == '' && $parts['interwiki'] === '' ) { if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] != NS_MAIN ) {
if ( $parts['namespace'] != NS_MAIN ) { throw new MalformedTitleException( 'title-invalid-empty', $text );
throw new MalformedTitleException( 'title-invalid-empty', $text );
}
} }
// Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles. // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.

View file

@ -1078,10 +1078,8 @@ abstract class UploadBase {
$props = $this->mFileProps; $props = $this->mFileProps;
$error = null; $error = null;
Hooks::run( 'UploadStashFile', [ $this, $user, $props, &$error ] ); Hooks::run( 'UploadStashFile', [ $this, $user, $props, &$error ] );
if ( $error ) { if ( $error && !is_array( $error ) ) {
if ( !is_array( $error ) ) { $error = [ $error ];
$error = [ $error ];
}
} }
return $error; return $error;
} }
@ -1916,10 +1914,8 @@ abstract class UploadBase {
$output = true; # if there's no output, return true $output = true; # if there's no output, return true
} elseif ( $msgPattern ) { } elseif ( $msgPattern ) {
$groups = []; $groups = [];
if ( preg_match( $msgPattern, $output, $groups ) ) { if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
if ( $groups[1] ) { $output = $groups[1];
$output = $groups[1];
}
} }
} }

View file

@ -162,12 +162,10 @@ class UploadStash {
); );
} }
if ( !$noAuth ) { if ( !$noAuth && $this->fileMetadata[$key]['us_user'] != $this->userId ) {
if ( $this->fileMetadata[$key]['us_user'] != $this->userId ) { throw new UploadStashWrongOwnerException(
throw new UploadStashWrongOwnerException( wfMessage( 'uploadstash-wrong-owner', $key )
wfMessage( 'uploadstash-wrong-owner', $key ) );
);
}
} }
return $this->files[$key]; return $this->files[$key];

View file

@ -1405,10 +1405,10 @@ class User implements IDBAccessObject, UserIdentity {
public function trackBlockWithCookie() { public function trackBlockWithCookie() {
$block = $this->getBlock(); $block = $this->getBlock();
if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) { if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null
if ( $block->shouldTrackWithCookie( $this->isAnon() ) ) { && $block->shouldTrackWithCookie( $this->isAnon() )
$block->setCookie( $this->getRequest()->response() ); ) {
} $block->setCookie( $this->getRequest()->response() );
} }
} }
@ -4424,10 +4424,8 @@ class User implements IDBAccessObject, UserIdentity {
[ 'LOCK IN SHARE MODE' ] [ 'LOCK IN SHARE MODE' ]
); );
$loaded = false; $loaded = false;
if ( $this->mId ) { if ( $this->mId && $this->loadFromDatabase( self::READ_LOCKING ) ) {
if ( $this->loadFromDatabase( self::READ_LOCKING ) ) { $loaded = true;
$loaded = true;
}
} }
if ( !$loaded ) { if ( !$loaded ) {
throw new MWException( $fname . ": hit a key conflict attempting " . throw new MWException( $fname . ": hit a key conflict attempting " .

View file

@ -445,11 +445,9 @@ class WatchedItemQueryService {
$conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) ); $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) );
if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) { if ( !isset( $options['start'] ) && !isset( $options['end'] ) && $db->getType() === 'mysql' ) {
if ( $db->getType() === 'mysql' ) { // This is an index optimization for mysql
// This is an index optimization for mysql $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' );
$conds[] = 'rc_timestamp > ' . $db->addQuotes( '' );
}
} }
$conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) ); $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) );

View file

@ -40,10 +40,10 @@ class FirejailCommandIntegrationTest extends PHPUnit\Framework\TestCase {
* @dataProvider provideExecute * @dataProvider provideExecute
*/ */
public function testExecute( $testCommand, $flag ) { public function testExecute( $testCommand, $flag ) {
if ( preg_match( '/^sudo /', $testCommand ) ) { if ( preg_match( '/^sudo /', $testCommand )
if ( Shell::command( 'sudo', '-n', 'ls', '/' )->execute()->getExitCode() ) { && Shell::command( 'sudo', '-n', 'ls', '/' )->execute()->getExitCode()
$this->markTestSkipped( 'need passwordless sudo' ); ) {
} $this->markTestSkipped( 'need passwordless sudo' );
} }
$command = new FirejailCommand( 'firejail' ); $command = new FirejailCommand( 'firejail' );

View file

@ -528,12 +528,10 @@ class RevisionStoreTest extends MediaWikiTestCase {
'old_text' => 'Hello World', 'old_text' => 'Hello World',
'old_flags' => 'utf-8', 'old_flags' => 'utf-8',
]; ];
} else { } elseif ( !isset( $row['content'] ) && isset( $array['old_text'] ) ) {
if ( !isset( $row['content'] ) && isset( $array['old_text'] ) ) { $row['content'] = [
$row['content'] = [ 'main' => new WikitextContent( $array['old_text'] ),
'main' => new WikitextContent( $array['old_text'] ), ];
];
}
} }
return (object)$row; return (object)$row;

View file

@ -500,10 +500,8 @@ class ApiStructureTest extends MediaWikiTestCase {
if ( $value instanceof $type ) { if ( $value instanceof $type ) {
return; return;
} }
} else { } elseif ( gettype( $value ) === $type ) {
if ( gettype( $value ) === $type ) { return;
return;
}
} }
} else { } else {
// Array whose values have specified types, recurse // Array whose values have specified types, recurse

View file

@ -112,14 +112,12 @@ class AutoLoaderStructureTest extends MediaWikiTestCase {
// 'class Foo {}' // 'class Foo {}'
$class = $fileNamespace . $match['class']; $class = $fileNamespace . $match['class'];
$classesInFile[$class] = true; $classesInFile[$class] = true;
} elseif ( !empty( $match['original'] ) ) {
// 'class_alias( "Foo", "Bar" );'
$aliasesInFile[$match['alias']] = $match['original'];
} else { } else {
if ( !empty( $match['original'] ) ) { // 'class_alias( Foo::class, "Bar" );'
// 'class_alias( "Foo", "Bar" );' $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
$aliasesInFile[$match['alias']] = $match['original'];
} else {
// 'class_alias( Foo::class, "Bar" );'
$aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic'];
}
} }
} }