From c13fee87d42bdd6fdf6764edb6f6475c14c27749 Mon Sep 17 00:00:00 2001 From: Reedy Date: Fri, 29 Mar 2019 20:12:24 +0000 Subject: [PATCH] Collapse some nested if statements Change-Id: I9a97325d738d09370d29d35d5254bc0dadc57ff4 --- includes/EditPage.php | 366 +++++++++--------- includes/ForeignResourceManager.php | 14 +- includes/GlobalFunctions.php | 12 +- includes/Html.php | 12 +- includes/MWGrants.php | 6 +- includes/MediaWiki.php | 8 +- includes/Message.php | 9 +- includes/OutputPage.php | 40 +- includes/PageProps.php | 8 +- includes/PathRouter.php | 6 +- includes/Revision/MainSlotRoleHandler.php | 6 +- includes/Revision/RevisionStore.php | 12 +- includes/Title.php | 6 +- includes/Xml.php | 8 +- includes/actions/CreditsAction.php | 8 +- includes/api/ApiComparePages.php | 6 +- includes/api/ApiHelp.php | 8 +- includes/api/ApiMain.php | 24 +- includes/api/ApiPageSet.php | 8 +- includes/api/ApiQueryBase.php | 10 +- includes/api/ApiQueryImageInfo.php | 10 +- includes/api/ApiQueryInfo.php | 6 +- includes/api/ApiQueryUserInfo.php | 12 +- includes/api/ApiQueryWatchlist.php | 14 +- includes/auth/AuthManager.php | 6 +- ...lPasswordPrimaryAuthenticationProvider.php | 20 +- ...yPasswordPrimaryAuthenticationProvider.php | 28 +- includes/cache/CacheHelper.php | 10 +- includes/cache/HTMLFileCache.php | 22 +- includes/cache/dependency/FileDependency.php | 28 +- includes/cache/localisation/LCStoreCDB.php | 8 +- .../cache/localisation/LCStoreStaticArray.php | 8 +- includes/collation/IcuCollation.php | 16 +- includes/exception/MWExceptionRenderer.php | 12 +- includes/filerepo/ForeignAPIRepo.php | 11 +- includes/filerepo/file/File.php | 21 +- includes/filerepo/file/OldLocalFile.php | 8 +- .../fields/HTMLNamespacesMultiselectField.php | 6 +- .../fields/HTMLTitlesMultiselectField.php | 6 +- includes/import/WikiImporter.php | 20 +- includes/installer/PostgresInstaller.php | 10 +- includes/installer/PostgresUpdater.php | 10 +- includes/installer/SqliteInstaller.php | 6 +- includes/installer/WebInstaller.php | 8 +- includes/installer/WebInstallerName.php | 6 +- includes/installer/WebInstallerOptions.php | 6 +- includes/installer/WebInstallerWelcome.php | 6 +- includes/libs/MultiHttpClient.php | 8 +- .../filebackend/FileBackendMultiWrite.php | 22 +- includes/libs/mime/XmlTypeCheck.php | 8 +- includes/libs/objectcache/WANObjectCache.php | 26 +- includes/libs/rdbms/database/Database.php | 71 ++-- .../libs/rdbms/loadbalancer/LoadBalancer.php | 6 +- includes/libs/redis/RedisConnectionPool.php | 26 +- includes/mail/EmailNotification.php | 5 +- includes/media/BitmapHandler.php | 6 +- includes/media/BitmapMetadataHandler.php | 14 +- includes/media/SvgHandler.php | 18 +- includes/page/Article.php | 12 +- includes/parser/BlockLevelPass.php | 26 +- includes/parser/Parser.php | 45 +-- includes/parser/Sanitizer.php | 6 +- includes/resourceloader/ResourceLoader.php | 8 +- .../ResourceLoaderClientHtml.php | 22 +- includes/skins/BaseTemplate.php | 38 +- includes/skins/SkinTemplate.php | 20 +- includes/specials/SpecialContributions.php | 12 +- includes/specials/SpecialImport.php | 6 +- includes/specials/SpecialSearch.php | 12 +- includes/specials/SpecialUpload.php | 8 +- includes/specials/SpecialWhatlinkshere.php | 82 ++-- includes/specials/pagers/BlockListPager.php | 6 +- includes/specials/pagers/ImageListPager.php | 18 +- includes/tidy/RemexCompatFormatter.php | 8 +- includes/title/MediaWikiTitleCodec.php | 6 +- includes/upload/UploadBase.php | 12 +- includes/upload/UploadStash.php | 10 +- includes/user/User.php | 14 +- .../watcheditem/WatchedItemQueryService.php | 8 +- .../shell/FirejailCommandIntegrationTest.php | 8 +- .../includes/Revision/RevisionStoreTest.php | 10 +- tests/phpunit/structure/ApiStructureTest.php | 6 +- .../structure/AutoLoaderStructureTest.php | 12 +- 83 files changed, 666 insertions(+), 860 deletions(-) diff --git a/includes/EditPage.php b/includes/EditPage.php index d8fef17792..add48d99b9 100644 --- a/includes/EditPage.php +++ b/includes/EditPage.php @@ -1214,149 +1214,147 @@ class EditPage { $content = $this->getPreloadedContent( $preload, $params ); } // For existing pages, get text based on "undo" or section parameters. - } else { - if ( $this->section != '' ) { - // Get section edit text (returns $def_text for invalid sections) - $orig = $this->getOriginalContent( $user ); - $content = $orig ? $orig->getSection( $this->section ) : null; + } 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 { - $undoafter = $request->getInt( 'undoafter' ); - $undo = $request->getInt( 'undo' ); - - if ( $undo > 0 && $undoafter > 0 ) { - $undorev = Revision::newFromId( $undo ); - $oldrev = Revision::newFromId( $undoafter ); - $undoMsg = null; - - # Sanity check, make sure it's the right page, - # the revisions exist and they were not deleted. - # Otherwise, $content will be left as-is. - if ( !is_null( $undorev ) && !is_null( $oldrev ) && - !$undorev->isDeleted( Revision::DELETED_TEXT ) && - !$oldrev->isDeleted( Revision::DELETED_TEXT ) + if ( !$content ) { + $content = $def_content; + } + } else { + $undoafter = $request->getInt( 'undoafter' ); + $undo = $request->getInt( 'undo' ); + + if ( $undo > 0 && $undoafter > 0 ) { + $undorev = Revision::newFromId( $undo ); + $oldrev = Revision::newFromId( $undoafter ); + $undoMsg = null; + + # Sanity check, make sure it's the right page, + # the revisions exist and they were not deleted. + # Otherwise, $content will be left as-is. + if ( !is_null( $undorev ) && !is_null( $oldrev ) && + !$undorev->isDeleted( Revision::DELETED_TEXT ) && + !$oldrev->isDeleted( Revision::DELETED_TEXT ) + ) { + if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) + || !$this->isSupportedContentModel( $oldrev->getContentModel() ) ) { - if ( WikiPage::hasDifferencesOutsideMainSlot( $undorev, $oldrev ) - || !$this->isSupportedContentModel( $oldrev->getContentModel() ) - ) { - // Hack for undo while EditPage can't handle multi-slot editing - $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [ - 'action' => 'mcrundo', - 'undo' => $undo, - 'undoafter' => $undoafter, - ] ) ); - return false; - } else { - $content = $this->page->getUndoContent( $undorev, $oldrev ); + // Hack for undo while EditPage can't handle multi-slot editing + $this->context->getOutput()->redirect( $this->mTitle->getFullURL( [ + 'action' => 'mcrundo', + 'undo' => $undo, + 'undoafter' => $undoafter, + ] ) ); + return false; + } else { + $content = $this->page->getUndoContent( $undorev, $oldrev ); - if ( $content === false ) { - # Warn the user that something went wrong - $undoMsg = 'failure'; - } + 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 ( $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; + 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->formtype = 'diff'; + $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() - ) - ); + } 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'; } - if ( $content === false ) { - // Hack for restoring old revisions while EditPage - // can't handle multi-slot editing. + $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() + ) + ); + } - $curRevision = $this->page->getRevision(); - $oldRevision = $this->mArticle->getRevisionFetched(); + if ( $content === false ) { + // Hack for restoring old revisions while EditPage + // can't handle multi-slot editing. - 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(), - ] - ) - ); + $curRevision = $this->page->getRevision(); + $oldRevision = $this->mArticle->getRevisionFetched(); - return false; - } - } + 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(), + ] + ) + ); - if ( $content === false ) { - $content = $this->getOriginalContent( $user ); + return false; } } + + if ( $content === false ) { + $content = $this->getOriginalContent( $user ); + } } return $content; @@ -2804,11 +2802,9 @@ ERROR; $out->addHTML( $this->editFormTextTop ); - if ( $this->wasDeletedSinceLastEdit() ) { - if ( $this->formtype !== 'save' ) { - $out->wrapWikiMsg( "
\n$1\n
", - 'deletedwhileediting' ); - } + if ( $this->wasDeletedSinceLastEdit() && $this->formtype !== 'save' ) { + $out->wrapWikiMsg( "
\n$1\n
", + 'deletedwhileediting' ); } // @todo add EditForm plugin interface and use it here! @@ -3076,12 +3072,12 @@ ERROR; $this->addExplainConflictHeader( $out ); $this->editRevId = $this->page->getLatest(); } else { - if ( $this->section != '' && $this->section != 'new' ) { - if ( !$this->summary && !$this->preview && !$this->diff ) { - $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object - if ( $sectionTitle !== false ) { - $this->summary = "/* $sectionTitle */ "; - } + if ( $this->section != '' && $this->section != 'new' && !$this->summary && + !$this->preview && !$this->diff + ) { + $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object + if ( $sectionTitle !== false ) { + $this->summary = "/* $sectionTitle */ "; } } @@ -3188,44 +3184,42 @@ ERROR; 'anonpreviewwarning' ); } - } else { - if ( $this->mTitle->isUserConfigPage() ) { - # Check the skin exists - if ( $this->isWrongCaseUserConfigPage() ) { - $out->wrapWikiMsg( - "
\n$1\n
", - [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ] - ); - } - if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) { - $isUserCssConfig = $this->mTitle->isUserCssConfigPage(); - $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage(); - $isUserJsConfig = $this->mTitle->isUserJsConfigPage(); - - $warning = $isUserCssConfig - ? 'usercssispublic' - : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' ); - - $out->wrapWikiMsg( '
$1
', $warning ); - - if ( $this->formtype !== 'preview' ) { - $config = $this->context->getConfig(); - if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) { - $out->wrapWikiMsg( - "
\n$1\n
", - [ 'usercssyoucanpreview' ] - ); - } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) { - $out->wrapWikiMsg( - "
\n$1\n
", - [ 'userjsonyoucanpreview' ] - ); - } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) { - $out->wrapWikiMsg( - "
\n$1\n
", - [ 'userjsyoucanpreview' ] - ); - } + } elseif ( $this->mTitle->isUserConfigPage() ) { + # Check the skin exists + if ( $this->isWrongCaseUserConfigPage() ) { + $out->wrapWikiMsg( + "
\n$1\n
", + [ 'userinvalidconfigtitle', $this->mTitle->getSkinFromConfigSubpage() ] + ); + } + if ( $this->getTitle()->isSubpageOf( $user->getUserPage() ) ) { + $isUserCssConfig = $this->mTitle->isUserCssConfigPage(); + $isUserJsonConfig = $this->mTitle->isUserJsonConfigPage(); + $isUserJsConfig = $this->mTitle->isUserJsConfigPage(); + + $warning = $isUserCssConfig + ? 'usercssispublic' + : ( $isUserJsonConfig ? 'userjsonispublic' : 'userjsispublic' ); + + $out->wrapWikiMsg( '
$1
', $warning ); + + if ( $this->formtype !== 'preview' ) { + $config = $this->context->getConfig(); + if ( $isUserCssConfig && $config->get( 'AllowUserCss' ) ) { + $out->wrapWikiMsg( + "
\n$1\n
", + [ 'usercssyoucanpreview' ] + ); + } elseif ( $isUserJsonConfig /* No comparable 'AllowUserJson' */ ) { + $out->wrapWikiMsg( + "
\n$1\n
", + [ 'userjsonyoucanpreview' ] + ); + } elseif ( $isUserJsConfig && $config->get( 'AllowUserJs' ) ) { + $out->wrapWikiMsg( + "
\n$1\n
", + [ 'userjsyoucanpreview' ] + ); } } } @@ -3309,10 +3303,8 @@ ERROR; if ( $this->nosummary ) { return; } - } else { - if ( !$this->mShowSummaryField ) { - return; - } + } elseif ( !$this->mShowSummaryField ) { + return; } $labelText = $this->context->msg( $isSubjectPreview ? 'subject' : 'summary' )->parse(); @@ -4450,16 +4442,14 @@ ERROR; $lang->formatNum( $maxArticleSize ) ] ); - } else { - if ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) { - $out->wrapWikiMsg( "
\n$1\n
", - [ - 'longpage-hint', - $lang->formatSize( strlen( $this->textbox1 ) ), - strlen( $this->textbox1 ) - ] - ); - } + } elseif ( !$this->context->msg( 'longpage-hint' )->isDisabled() ) { + $out->wrapWikiMsg( "
\n$1\n
", + [ + 'longpage-hint', + $lang->formatSize( strlen( $this->textbox1 ) ), + strlen( $this->textbox1 ) + ] + ); } } diff --git a/includes/ForeignResourceManager.php b/includes/ForeignResourceManager.php index 9fd1e4fe45..dddbad5334 100644 --- a/includes/ForeignResourceManager.php +++ b/includes/ForeignResourceManager.php @@ -178,15 +178,13 @@ class ForeignResourceManager { if ( $integrity === $actualIntegrity ) { $this->verbose( "... passed integrity check for {$src}\n" ); $this->cacheSet( $key, $data ); + } elseif ( $this->action === 'make-sri' ) { + $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" ); } else { - if ( $this->action === 'make-sri' ) { - $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" ); - } else { - throw new Exception( "Integrity check failed for {$src}\n" . - "\tExpected: {$integrity}\n" . - "\tActual: {$actualIntegrity}" - ); - } + throw new Exception( "Integrity check failed for {$src}\n" . + "\tExpected: {$integrity}\n" . + "\tActual: {$actualIntegrity}" + ); } return $data; } diff --git a/includes/GlobalFunctions.php b/includes/GlobalFunctions.php index 20f3fd0417..b0a79e8d5c 100644 --- a/includes/GlobalFunctions.php +++ b/includes/GlobalFunctions.php @@ -1750,13 +1750,11 @@ function wfResetOutputBuffers( $resetGzipEncoding = true ) { // to avoid getting in some kind of infinite loop. break; } - if ( $resetGzipEncoding ) { - if ( $status['name'] == 'ob_gzhandler' ) { - // Reset the 'Content-Encoding' field set by this handler - // so we can start fresh. - header_remove( 'Content-Encoding' ); - break; - } + if ( $resetGzipEncoding && $status['name'] == 'ob_gzhandler' ) { + // Reset the 'Content-Encoding' field set by this handler + // so we can start fresh. + header_remove( 'Content-Encoding' ); + break; } } } diff --git a/includes/Html.php b/includes/Html.php index 61785d5e72..aa51243d75 100644 --- a/includes/Html.php +++ b/includes/Html.php @@ -574,10 +574,8 @@ class Html { $attrs = []; if ( $nonce !== null ) { $attrs['nonce'] = $nonce; - } else { - if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) { - wfWarn( "no nonce set on script. CSP will break it" ); - } + } elseif ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) { + wfWarn( "no nonce set on script. CSP will break it" ); } if ( preg_match( '/<\/?script/i', $contents ) ) { @@ -600,10 +598,8 @@ class Html { $attrs = [ 'src' => $url ]; if ( $nonce !== null ) { $attrs['nonce'] = $nonce; - } else { - if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) { - wfWarn( "no nonce set on script. CSP will break it" ); - } + } elseif ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) { + wfWarn( "no nonce set on script. CSP will break it" ); } return self::element( 'script', $attrs ); diff --git a/includes/MWGrants.php b/includes/MWGrants.php index 3079c65512..cbe5a1a141 100644 --- a/includes/MWGrants.php +++ b/includes/MWGrants.php @@ -86,10 +86,8 @@ class MWGrants { * @return string[] Corresponding grant descriptions */ public static function grantNames( array $grants, $lang = null ) { - if ( $lang !== null ) { - if ( is_string( $lang ) ) { - $lang = Language::factory( $lang ); - } + if ( $lang !== null && is_string( $lang ) ) { + $lang = Language::factory( $lang ); } $ret = []; diff --git a/includes/MediaWiki.php b/includes/MediaWiki.php index 8cb9152daa..24aca2ea7b 100644 --- a/includes/MediaWiki.php +++ b/includes/MediaWiki.php @@ -428,11 +428,9 @@ class MediaWiki { if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) { // Is the target already set by an extension? $target = $target ?: $page->followRedirect(); - if ( is_string( $target ) ) { - if ( !$this->config->get( 'DisableHardRedirects' ) ) { - // we'll need to redirect - return $target; - } + if ( is_string( $target ) && !$this->config->get( 'DisableHardRedirects' ) ) { + // we'll need to redirect + return $target; } if ( is_object( $target ) ) { // Rewrite environment to redirected article diff --git a/includes/Message.php b/includes/Message.php index 4049e114f3..0b3113f29c 100644 --- a/includes/Message.php +++ b/includes/Message.php @@ -1163,14 +1163,11 @@ class Message implements MessageSpecifier, Serializable { // escaped, breaking the replacement and avoiding XSS. $replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 ); } - } else { - if ( $paramType === 'after' ) { - $replacementKeys[$marker . ( $n + 1 )] = $value; - } + } elseif ( $paramType === 'after' ) { + $replacementKeys[$marker . ( $n + 1 )] = $value; } } - $message = strtr( $message, $replacementKeys ); - return $message; + return strtr( $message, $replacementKeys ); } /** diff --git a/includes/OutputPage.php b/includes/OutputPage.php index 8a19c51f7a..786ecc4a93 100644 --- a/includes/OutputPage.php +++ b/includes/OutputPage.php @@ -3785,26 +3785,24 @@ class OutputPage extends ContextSource { if ( $config->get( 'EnableCanonicalServerLink' ) ) { if ( $canonicalUrl !== false ) { $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL ); - } else { - if ( $this->isArticleRelated() ) { - // This affects all requests where "setArticleRelated" is true. This is - // typically all requests that show content (query title, curid, oldid, diff), - // and all wikipage actions (edit, delete, purge, info, history etc.). - // It does not apply to File pages and Special pages. - // 'history' and 'info' actions address page metadata rather than the page - // content itself, so they may not be canonicalized to the view page url. - // TODO: this ought to be better encapsulated in the Action class. - $action = Action::getActionName( $this->getContext() ); - if ( in_array( $action, [ 'history', 'info' ] ) ) { - $query = "action={$action}"; - } else { - $query = ''; - } - $canonicalUrl = $this->getTitle()->getCanonicalURL( $query ); + } elseif ( $this->isArticleRelated() ) { + // This affects all requests where "setArticleRelated" is true. This is + // typically all requests that show content (query title, curid, oldid, diff), + // and all wikipage actions (edit, delete, purge, info, history etc.). + // It does not apply to File pages and Special pages. + // 'history' and 'info' actions address page metadata rather than the page + // content itself, so they may not be canonicalized to the view page url. + // TODO: this ought to be better encapsulated in the Action class. + $action = Action::getActionName( $this->getContext() ); + if ( in_array( $action, [ 'history', 'info' ] ) ) { + $query = "action={$action}"; } else { - $reqUrl = $this->getRequest()->getRequestURL(); - $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL ); + $query = ''; } + $canonicalUrl = $this->getTitle()->getCanonicalURL( $query ); + } else { + $reqUrl = $this->getRequest()->getRequestURL(); + $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL ); } } if ( $canonicalUrl !== false ) { @@ -3948,10 +3946,8 @@ class OutputPage extends ContextSource { * @return string HTML fragment */ protected function styleLink( $style, array $options ) { - if ( isset( $options['dir'] ) ) { - if ( $this->getLanguage()->getDir() != $options['dir'] ) { - return ''; - } + if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) { + return ''; } if ( isset( $options['media'] ) ) { diff --git a/includes/PageProps.php b/includes/PageProps.php index df2451c3a5..a84370f877 100644 --- a/includes/PageProps.php +++ b/includes/PageProps.php @@ -129,12 +129,10 @@ class PageProps { if ( $propertyValue === false ) { $queryIDs[] = $pageID; break; + } elseif ( $gotArray ) { + $values[$pageID][$propertyName] = $propertyValue; } else { - if ( $gotArray ) { - $values[$pageID][$propertyName] = $propertyValue; - } else { - $values[$pageID] = $propertyValue; - } + $values[$pageID] = $propertyValue; } } } diff --git a/includes/PathRouter.php b/includes/PathRouter.php index db12e74c42..eb52d7cd23 100644 --- a/includes/PathRouter.php +++ b/includes/PathRouter.php @@ -133,10 +133,8 @@ class PathRouter { // Loop over our options and convert any single value $# restrictions // into an array so we only have to do in_array tests. foreach ( $options as $optionName => $optionData ) { - if ( preg_match( '/^\$\d+$/u', $optionName ) ) { - if ( !is_array( $optionData ) ) { - $options[$optionName] = [ $optionData ]; - } + if ( preg_match( '/^\$\d+$/u', $optionName ) && !is_array( $optionData ) ) { + $options[$optionName] = [ $optionData ]; } } diff --git a/includes/Revision/MainSlotRoleHandler.php b/includes/Revision/MainSlotRoleHandler.php index f3e5a8570d..013910346d 100644 --- a/includes/Revision/MainSlotRoleHandler.php +++ b/includes/Revision/MainSlotRoleHandler.php @@ -86,10 +86,8 @@ class MainSlotRoleHandler extends SlotRoleHandler { // Hook can determine default model $title = Title::newFromLinkTarget( $page ); - if ( !Hooks::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) ) { - if ( !is_null( $model ) ) { - return $model; - } + if ( !Hooks::run( 'ContentHandlerDefaultModelFor', [ $title, &$model ] ) && !is_null( $model ) ) { + return $model; } // Could this page contain code based on the title? diff --git a/includes/Revision/RevisionStore.php b/includes/Revision/RevisionStore.php index 9af2458047..2a54a9b187 100644 --- a/includes/Revision/RevisionStore.php +++ b/includes/Revision/RevisionStore.php @@ -1863,12 +1863,12 @@ class RevisionStore } // if we have a content object, use it to set the model and type - if ( !empty( $fields['content'] ) ) { - if ( !( $fields['content'] instanceof Content ) && !is_array( $fields['content'] ) ) { - throw new MWException( - 'content field must contain a Content object or an array of Content objects.' - ); - } + if ( !empty( $fields['content'] ) && !( $fields['content'] instanceof Content ) + && !is_array( $fields['content'] ) + ) { + throw new MWException( + 'content field must contain a Content object or an array of Content objects.' + ); } if ( !empty( $fields['text_id'] ) ) { diff --git a/includes/Title.php b/includes/Title.php index 0c62c4ff3f..6d86b22573 100644 --- a/includes/Title.php +++ b/includes/Title.php @@ -3556,10 +3556,8 @@ class Title implements LinkTarget, IDBAccessObject { $linkCache->clearLink( $this ); $this->mArticleID = $linkCache->addLinkObj( $this ); $linkCache->forUpdate( $oldUpdate ); - } else { - if ( $this->mArticleID == -1 ) { - $this->mArticleID = $linkCache->addLinkObj( $this ); - } + } elseif ( $this->mArticleID == -1 ) { + $this->mArticleID = $linkCache->addLinkObj( $this ); } return $this->mArticleID; } diff --git a/includes/Xml.php b/includes/Xml.php index d1a56bf78e..febf03e7a2 100644 --- a/includes/Xml.php +++ b/includes/Xml.php @@ -47,12 +47,10 @@ class Xml { } if ( is_null( $contents ) ) { $out .= '>'; + } elseif ( $allowShortTag && $contents === '' ) { + $out .= ' />'; } else { - if ( $allowShortTag && $contents === '' ) { - $out .= ' />'; - } else { - $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . ""; - } + $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . ""; } return $out; } diff --git a/includes/actions/CreditsAction.php b/includes/actions/CreditsAction.php index ed58686ac5..4cb7dda58a 100644 --- a/includes/actions/CreditsAction.php +++ b/includes/actions/CreditsAction.php @@ -222,12 +222,10 @@ class CreditsAction extends FormlessAction { $link = $this->link( $user ); if ( $user->isAnon() ) { return $this->msg( 'anonuser' )->rawParams( $link )->parse(); + } elseif ( $this->canShowRealUserName() && $user->getRealName() ) { + return $link; } else { - if ( $this->canShowRealUserName() && $user->getRealName() ) { - return $link; - } else { - return $this->msg( 'siteuser' )->rawParams( $link )->params( $user->getName() )->escaped(); - } + return $this->msg( 'siteuser' )->rawParams( $link )->params( $user->getName() )->escaped(); } } diff --git a/includes/api/ApiComparePages.php b/includes/api/ApiComparePages.php index 4ba30abfd4..1eb5e8da5e 100644 --- a/includes/api/ApiComparePages.php +++ b/includes/api/ApiComparePages.php @@ -307,10 +307,8 @@ class ApiComparePages extends ApiBase { foreach ( [ 'from', 'to' ] as $prefix ) { if ( $params["{$prefix}rev"] !== null ) { $rev = $this->getRevisionById( $params["{$prefix}rev"] ); - if ( $rev ) { - if ( $rev->hasSlot( $role ) ) { - return $rev->getSlot( $role, RevisionRecord::RAW )->getModel(); - } + if ( $rev && $rev->hasSlot( $role ) ) { + return $rev->getSlot( $role, RevisionRecord::RAW )->getModel(); } } } diff --git a/includes/api/ApiHelp.php b/includes/api/ApiHelp.php index 886dbcc059..1656e7ca29 100644 --- a/includes/api/ApiHelp.php +++ b/includes/api/ApiHelp.php @@ -559,11 +559,9 @@ class ApiHelp extends ApiBase { $arr = &$submodules; try { $submod = $module->getModuleFromPath( $m ); - if ( $submod ) { - if ( $submod->isDeprecated() ) { - $arr = &$deprecatedSubmodules; - $attrs['class'] = 'apihelp-deprecated-value'; - } + if ( $submod && $submod->isDeprecated() ) { + $arr = &$deprecatedSubmodules; + $attrs['class'] = 'apihelp-deprecated-value'; } } catch ( ApiUsageException $ex ) { // Ignore diff --git a/includes/api/ApiMain.php b/includes/api/ApiMain.php index f60443ca6e..588e31ac31 100644 --- a/includes/api/ApiMain.php +++ b/includes/api/ApiMain.php @@ -1117,19 +1117,17 @@ class ApiMain extends ApiBase { . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text() ) ); - } else { - if ( $config->get( 'ShowExceptionDetails' ) ) { - $result->addContentValue( - $path, - 'trace', - $this->msg( 'api-exception-trace', - get_class( $e ), - $e->getFile(), - $e->getLine(), - MWExceptionHandler::getRedactedTraceAsString( $e ) - )->inLanguage( $formatter->getLanguage() )->text() - ); - } + } elseif ( $config->get( 'ShowExceptionDetails' ) ) { + $result->addContentValue( + $path, + 'trace', + $this->msg( 'api-exception-trace', + get_class( $e ), + $e->getFile(), + $e->getLine(), + MWExceptionHandler::getRedactedTraceAsString( $e ) + )->inLanguage( $formatter->getLanguage() )->text() + ); } // Add the id and such diff --git a/includes/api/ApiPageSet.php b/includes/api/ApiPageSet.php index 450ebb6911..b321c7d14c 100644 --- a/includes/api/ApiPageSet.php +++ b/includes/api/ApiPageSet.php @@ -1398,10 +1398,10 @@ class ApiPageSet extends ApiBase { $data[$toPageId], $this->mGeneratorData[$fromNs][$fromDBkey] ); - if ( $result instanceof ApiResult ) { - if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE ) ) { - return false; - } + if ( $result instanceof ApiResult && + !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE ) + ) { + return false; } } } diff --git a/includes/api/ApiQueryBase.php b/includes/api/ApiQueryBase.php index 307066573c..d955b56d03 100644 --- a/includes/api/ApiQueryBase.php +++ b/includes/api/ApiQueryBase.php @@ -157,16 +157,14 @@ abstract class ApiQueryBase extends ApiBase { */ protected function addTables( $tables, $alias = null ) { if ( is_array( $tables ) ) { - if ( !is_null( $alias ) ) { + if ( $alias !== null ) { ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' ); } $this->tables = array_merge( $this->tables, $tables ); + } elseif ( $alias !== null ) { + $this->tables[$alias] = $tables; } else { - if ( !is_null( $alias ) ) { - $this->tables[$alias] = $tables; - } else { - $this->tables[] = $tables; - } + $this->tables[] = $tables; } } diff --git a/includes/api/ApiQueryImageInfo.php b/includes/api/ApiQueryImageInfo.php index 333b7693b4..051e12796f 100644 --- a/includes/api/ApiQueryImageInfo.php +++ b/includes/api/ApiQueryImageInfo.php @@ -249,13 +249,11 @@ class ApiQueryImageInfo extends ApiQueryBase { // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width $scale = []; $scale['height'] = $params['urlheight']; + } elseif ( $params['urlparam'] ) { + // Audio files might not have a width/height. + $scale = []; } else { - if ( $params['urlparam'] ) { - // Audio files might not have a width/height. - $scale = []; - } else { - $scale = null; - } + $scale = null; } return $scale; diff --git a/includes/api/ApiQueryInfo.php b/includes/api/ApiQueryInfo.php index 3d358b96a0..a5437bae78 100644 --- a/includes/api/ApiQueryInfo.php +++ b/includes/api/ApiQueryInfo.php @@ -515,10 +515,8 @@ class ApiQueryInfo extends ApiQueryBase { } } - if ( $this->fld_varianttitles ) { - if ( isset( $this->variantTitles[$pageid] ) ) { - $pageInfo['varianttitles'] = $this->variantTitles[$pageid]; - } + if ( $this->fld_varianttitles && isset( $this->variantTitles[$pageid] ) ) { + $pageInfo['varianttitles'] = $this->variantTitles[$pageid]; } if ( $this->params['testactions'] ) { diff --git a/includes/api/ApiQueryUserInfo.php b/includes/api/ApiQueryUserInfo.php index f594347ab0..d2a7eec7b1 100644 --- a/includes/api/ApiQueryUserInfo.php +++ b/includes/api/ApiQueryUserInfo.php @@ -202,13 +202,11 @@ class ApiQueryUserInfo extends ApiQueryBase { $vals['realname'] = $user->getRealName(); } - if ( $user->isAllowed( 'viewmyprivateinfo' ) ) { - if ( isset( $this->prop['email'] ) ) { - $vals['email'] = $user->getEmail(); - $auth = $user->getEmailAuthenticationTimestamp(); - if ( !is_null( $auth ) ) { - $vals['emailauthenticated'] = wfTimestamp( TS_ISO_8601, $auth ); - } + if ( $user->isAllowed( 'viewmyprivateinfo' ) && isset( $this->prop['email'] ) ) { + $vals['email'] = $user->getEmail(); + $auth = $user->getEmailAuthenticationTimestamp(); + if ( $auth !== null ) { + $vals['emailauthenticated'] = wfTimestamp( TS_ISO_8601, $auth ); } } diff --git a/includes/api/ApiQueryWatchlist.php b/includes/api/ApiQueryWatchlist.php index cb49622588..578a908f78 100644 --- a/includes/api/ApiQueryWatchlist.php +++ b/includes/api/ApiQueryWatchlist.php @@ -81,10 +81,8 @@ class ApiQueryWatchlist extends ApiQueryGeneratorBase { $this->fld_loginfo = isset( $prop['loginfo'] ); $this->fld_tags = isset( $prop['tags'] ); - if ( $this->fld_patrol ) { - if ( !$user->useRCPatrol() && !$user->useNPPatrol() ) { - $this->dieWithError( 'apierror-permissiondenied-patrolflag', 'patrol' ); - } + if ( $this->fld_patrol && !$user->useRCPatrol() && !$user->useNPPatrol() ) { + $this->dieWithError( 'apierror-permissiondenied-patrolflag', 'patrol' ); } if ( $this->fld_comment || $this->fld_parsedcomment ) { @@ -192,12 +190,10 @@ class ApiQueryWatchlist extends ApiQueryGeneratorBase { $startFrom = [ $recentChangeInfo['rc_timestamp'], $recentChangeInfo['rc_id'] ]; break; } + } elseif ( $params['allrev'] ) { + $ids[] = (int)$recentChangeInfo['rc_this_oldid']; } else { - if ( $params['allrev'] ) { - $ids[] = (int)$recentChangeInfo['rc_this_oldid']; - } else { - $ids[] = (int)$recentChangeInfo['rc_cur_id']; - } + $ids[] = (int)$recentChangeInfo['rc_cur_id']; } } diff --git a/includes/auth/AuthManager.php b/includes/auth/AuthManager.php index bfe278b40a..3515a7012c 100644 --- a/includes/auth/AuthManager.php +++ b/includes/auth/AuthManager.php @@ -2101,10 +2101,8 @@ class AuthManager implements LoggerAwareInterface { $id = $req->getUniqueId(); // If a required request if from a Primary, mark it as "primary-required" instead - if ( $isPrimary ) { - if ( $req->required ) { - $req->required = AuthenticationRequest::PRIMARY_REQUIRED; - } + if ( $isPrimary && $req->required ) { + $req->required = AuthenticationRequest::PRIMARY_REQUIRED; } if ( diff --git a/includes/auth/LocalPasswordPrimaryAuthenticationProvider.php b/includes/auth/LocalPasswordPrimaryAuthenticationProvider.php index 047a8117b2..b646380a04 100644 --- a/includes/auth/LocalPasswordPrimaryAuthenticationProvider.php +++ b/includes/auth/LocalPasswordPrimaryAuthenticationProvider.php @@ -303,18 +303,16 @@ class LocalPasswordPrimaryAuthenticationProvider } $req = AuthenticationRequest::getRequestByClass( $reqs, PasswordAuthenticationRequest::class ); - if ( $req ) { - if ( $req->username !== null && $req->password !== null ) { - // Nothing we can do besides claim it, because the user isn't in - // the DB yet - if ( $req->username !== $user->getName() ) { - $req = clone $req; - $req->username = $user->getName(); - } - $ret = AuthenticationResponse::newPass( $req->username ); - $ret->createRequest = $req; - return $ret; + if ( $req && $req->username !== null && $req->password !== null ) { + // Nothing we can do besides claim it, because the user isn't in + // the DB yet + if ( $req->username !== $user->getName() ) { + $req = clone $req; + $req->username = $user->getName(); } + $ret = AuthenticationResponse::newPass( $req->username ); + $ret->createRequest = $req; + return $ret; } return AuthenticationResponse::newAbstain(); } diff --git a/includes/auth/TemporaryPasswordPrimaryAuthenticationProvider.php b/includes/auth/TemporaryPasswordPrimaryAuthenticationProvider.php index 045f7915f3..e129538bbc 100644 --- a/includes/auth/TemporaryPasswordPrimaryAuthenticationProvider.php +++ b/includes/auth/TemporaryPasswordPrimaryAuthenticationProvider.php @@ -356,23 +356,21 @@ class TemporaryPasswordPrimaryAuthenticationProvider $req = AuthenticationRequest::getRequestByClass( $reqs, TemporaryPasswordAuthenticationRequest::class ); - if ( $req ) { - if ( $req->username !== null && $req->password !== null ) { - // Nothing we can do yet, because the user isn't in the DB yet - if ( $req->username !== $user->getName() ) { - $req = clone $req; - $req->username = $user->getName(); - } - - if ( $req->mailpassword ) { - // prevent EmailNotificationSecondaryAuthenticationProvider from sending another mail - $this->manager->setAuthenticationSessionData( 'no-email', true ); - } + if ( $req && $req->username !== null && $req->password !== null ) { + // Nothing we can do yet, because the user isn't in the DB yet + if ( $req->username !== $user->getName() ) { + $req = clone $req; + $req->username = $user->getName(); + } - $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(); } diff --git a/includes/cache/CacheHelper.php b/includes/cache/CacheHelper.php index d7669eb1b9..ec6ce04000 100644 --- a/includes/cache/CacheHelper.php +++ b/includes/cache/CacheHelper.php @@ -221,13 +221,11 @@ class CacheHelper implements ICacheHelper { } else { $value = array_shift( $this->cachedChunks ); } + } elseif ( array_key_exists( $key, $this->cachedChunks ) ) { + $value = $this->cachedChunks[$key]; + unset( $this->cachedChunks[$key] ); } else { - if ( array_key_exists( $key, $this->cachedChunks ) ) { - $value = $this->cachedChunks[$key]; - unset( $this->cachedChunks[$key] ); - } else { - wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__ ); - } + wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__ ); } } else { if ( !is_array( $args ) ) { diff --git a/includes/cache/HTMLFileCache.php b/includes/cache/HTMLFileCache.php index 3a89066f8c..a0d61b259e 100644 --- a/includes/cache/HTMLFileCache.php +++ b/includes/cache/HTMLFileCache.php @@ -128,10 +128,8 @@ class HTMLFileCache extends FileCacheBase { return false; } - if ( $mode === self::MODE_NORMAL ) { - if ( $user->getNewtalk() ) { - return false; - } + if ( ( $mode === self::MODE_NORMAL ) && $user->getNewtalk() ) { + return false; } // Allow extensions to disable caching @@ -211,18 +209,14 @@ class HTMLFileCache extends FileCacheBase { } // gzip output to buffer as needed and set headers... - if ( $this->useGzip() ) { - // @todo Ugly wfClientAcceptsGzip() function - use context! - if ( wfClientAcceptsGzip() ) { - header( 'Content-Encoding: gzip' ); + // @todo Ugly wfClientAcceptsGzip() function - use context! + if ( $this->useGzip() && wfClientAcceptsGzip() ) { + header( 'Content-Encoding: gzip' ); - return $compressed; - } else { - return $text; - } - } else { - return $text; + return $compressed; } + + return $text; } /** diff --git a/includes/cache/dependency/FileDependency.php b/includes/cache/dependency/FileDependency.php index 8d199e2c78..a8f542f740 100644 --- a/includes/cache/dependency/FileDependency.php +++ b/includes/cache/dependency/FileDependency.php @@ -75,22 +75,22 @@ class FileDependency extends CacheDependency { if ( $this->timestamp === false ) { # Still nonexistent 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; - } else { - # Not modified - return false; - } + # Deleted + wfDebug( "Dependency triggered: {$this->filename} deleted.\n" ); + + return true; } + + if ( $lastmod > $this->timestamp ) { + # Modified or created + wfDebug( "Dependency triggered: {$this->filename} changed.\n" ); + + return true; + } + + # Not modified + return false; } } diff --git a/includes/cache/localisation/LCStoreCDB.php b/includes/cache/localisation/LCStoreCDB.php index 246a3dda27..8814cff691 100644 --- a/includes/cache/localisation/LCStoreCDB.php +++ b/includes/cache/localisation/LCStoreCDB.php @@ -86,11 +86,9 @@ class LCStoreCDB implements LCStore { } public function startWrite( $code ) { - if ( !file_exists( $this->directory ) ) { - if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) { - throw new MWException( "Unable to create the localisation store " . - "directory \"{$this->directory}\"" ); - } + if ( !file_exists( $this->directory ) && !wfMkdirParents( $this->directory, null, __METHOD__ ) ) { + throw new MWException( "Unable to create the localisation store " . + "directory \"{$this->directory}\"" ); } // Close reader to stop permission errors on write diff --git a/includes/cache/localisation/LCStoreStaticArray.php b/includes/cache/localisation/LCStoreStaticArray.php index f860146804..d3504a8fad 100644 --- a/includes/cache/localisation/LCStoreStaticArray.php +++ b/includes/cache/localisation/LCStoreStaticArray.php @@ -45,11 +45,9 @@ class LCStoreStaticArray implements LCStore { } public function startWrite( $code ) { - if ( !file_exists( $this->directory ) ) { - if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) { - throw new MWException( "Unable to create the localisation store " . - "directory \"{$this->directory}\"" ); - } + if ( !file_exists( $this->directory ) && !wfMkdirParents( $this->directory, null, __METHOD__ ) ) { + throw new MWException( "Unable to create the localisation store " . + "directory \"{$this->directory}\"" ); } $this->currentLang = $code; diff --git a/includes/collation/IcuCollation.php b/includes/collation/IcuCollation.php index d45b2ceb83..9c1c5f870a 100644 --- a/includes/collation/IcuCollation.php +++ b/includes/collation/IcuCollation.php @@ -365,16 +365,14 @@ class IcuCollation extends Collation { foreach ( $digits as $digit ) { $letters[] = $this->digitTransformLanguage->formatNum( $digit, true ); } + } elseif ( $this->locale === 'root' ) { + $letters = require "$IP/includes/collation/data/first-letters-root.php"; } else { - if ( $this->locale === 'root' ) { - $letters = require "$IP/includes/collation/data/first-letters-root.php"; - } else { - // FIXME: Is this still used? - $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" ); - if ( $letters === false ) { - throw new MWException( "MediaWiki does not support ICU locale " . - "\"{$this->locale}\"" ); - } + // FIXME: Is this still used? + $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" ); + if ( $letters === false ) { + throw new MWException( "MediaWiki does not support ICU locale " . + "\"{$this->locale}\"" ); } } diff --git a/includes/exception/MWExceptionRenderer.php b/includes/exception/MWExceptionRenderer.php index ca590d8ef8..66775bf61f 100644 --- a/includes/exception/MWExceptionRenderer.php +++ b/includes/exception/MWExceptionRenderer.php @@ -71,14 +71,12 @@ class MWExceptionRenderer { self::getShowBacktraceError( $e ); } $message .= "\n"; + } elseif ( $wgShowExceptionDetails ) { + $message = MWExceptionHandler::getLogMessage( $e ) . + "\nBacktrace:\n" . + MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n"; } else { - if ( $wgShowExceptionDetails ) { - $message = MWExceptionHandler::getLogMessage( $e ) . - "\nBacktrace:\n" . - MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n"; - } else { - $message = MWExceptionHandler::getPublicLogMessage( $e ); - } + $message = MWExceptionHandler::getPublicLogMessage( $e ); } echo nl2br( htmlspecialchars( $message ) ) . "\n"; } diff --git a/includes/filerepo/ForeignAPIRepo.php b/includes/filerepo/ForeignAPIRepo.php index 9e4b6dfd71..346ec8ec15 100644 --- a/includes/filerepo/ForeignAPIRepo.php +++ b/includes/filerepo/ForeignAPIRepo.php @@ -348,14 +348,11 @@ class ForeignAPIRepo extends FileRepo { if ( !$knownThumbUrls ) { /* No knownThumbUrls for this file */ $knownThumbUrls = []; - } else { - if ( isset( $knownThumbUrls[$sizekey] ) ) { - wfDebug( __METHOD__ . ': Got thumburl from local cache: ' . - "{$knownThumbUrls[$sizekey]} \n" ); + } elseif ( isset( $knownThumbUrls[$sizekey] ) ) { + wfDebug( __METHOD__ . ': Got thumburl from local cache: ' . + "{$knownThumbUrls[$sizekey]} \n" ); - return $knownThumbUrls[$sizekey]; - } - /* This size is not yet known */ + return $knownThumbUrls[$sizekey]; } $metadata = null; diff --git a/includes/filerepo/file/File.php b/includes/filerepo/file/File.php index c3b519944c..97abe33dae 100644 --- a/includes/filerepo/file/File.php +++ b/includes/filerepo/file/File.php @@ -633,20 +633,15 @@ abstract class File implements IDBAccessObject { // one would not expect it to be animated // so 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 ); } /** diff --git a/includes/filerepo/file/OldLocalFile.php b/includes/filerepo/file/OldLocalFile.php index 23ff304ec5..3cdbfc2ef0 100644 --- a/includes/filerepo/file/OldLocalFile.php +++ b/includes/filerepo/file/OldLocalFile.php @@ -418,10 +418,10 @@ class OldLocalFile extends LocalFile { $dstRel = $this->getArchiveRel( $archiveName ); $status = $this->publishTo( $srcPath, $dstRel ); - if ( $status->isGood() ) { - if ( !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) ) { - $status->fatal( 'filenotfound', $srcPath ); - } + if ( $status->isGood() && + !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) + ) { + $status->fatal( 'filenotfound', $srcPath ); } $this->unlock(); diff --git a/includes/htmlform/fields/HTMLNamespacesMultiselectField.php b/includes/htmlform/fields/HTMLNamespacesMultiselectField.php index bd492d101b..5eab6052a8 100644 --- a/includes/htmlform/fields/HTMLNamespacesMultiselectField.php +++ b/includes/htmlform/fields/HTMLNamespacesMultiselectField.php @@ -38,10 +38,8 @@ class HTMLNamespacesMultiselectField extends HTMLSelectNamespace { // $value is a string, because HTMLForm fields store their values as strings $namespaces = explode( "\n", $value ); - if ( isset( $this->mParams['max'] ) ) { - if ( count( $namespaces ) > $this->mParams['max'] ) { - return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] ); - } + if ( isset( $this->mParams['max'] ) && ( count( $namespaces ) > $this->mParams['max'] ) ) { + return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] ); } foreach ( $namespaces as $namespace ) { diff --git a/includes/htmlform/fields/HTMLTitlesMultiselectField.php b/includes/htmlform/fields/HTMLTitlesMultiselectField.php index 1cfbd5fef7..bd1d2d3f8e 100644 --- a/includes/htmlform/fields/HTMLTitlesMultiselectField.php +++ b/includes/htmlform/fields/HTMLTitlesMultiselectField.php @@ -53,10 +53,8 @@ class HTMLTitlesMultiselectField extends HTMLTitleTextField { // $value is a string, because HTMLForm fields store their values as strings $titlesArray = explode( "\n", $value ); - if ( isset( $this->mParams['max'] ) ) { - if ( count( $titlesArray ) > $this->mParams['max'] ) { - return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] ); - } + if ( isset( $this->mParams['max'] ) && ( count( $titlesArray ) > $this->mParams['max'] ) ) { + return $this->msg( 'htmlform-int-toohigh', $this->mParams['max'] ); } foreach ( $titlesArray as $title ) { diff --git a/includes/import/WikiImporter.php b/includes/import/WikiImporter.php index bd19aa7513..41ec673a18 100644 --- a/includes/import/WikiImporter.php +++ b/includes/import/WikiImporter.php @@ -286,18 +286,16 @@ class WikiImporter { if ( !$title || $title->isExternal() ) { $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 { - if ( !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 { - // set namespace to 'all', so the namespace check in processTitle() can pass - $this->setTargetNamespace( null ); - $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) ); - } + // set namespace to 'all', so the namespace check in processTitle() can pass + $this->setTargetNamespace( null ); + $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) ); } } return $status; diff --git a/includes/installer/PostgresInstaller.php b/includes/installer/PostgresInstaller.php index f3cbbc4e98..f9ee3197c2 100644 --- a/includes/installer/PostgresInstaller.php +++ b/includes/installer/PostgresInstaller.php @@ -443,11 +443,11 @@ class PostgresInstaller extends DatabaseInstaller { } // Recursively search each member of the group to see if the target // is a member of it, up to the given maximum depth. - if ( $maxDepth > 0 ) { - if ( $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) ) { - // Found member of member - return true; - } + if ( $maxDepth > 0 && + $this->isRoleMember( $conn, $targetMember, $row->member, $maxDepth - 1 ) + ) { + // Found member of member + return true; } } diff --git a/includes/installer/PostgresUpdater.php b/includes/installer/PostgresUpdater.php index 75877a1e50..9ba8d027e4 100644 --- a/includes/installer/PostgresUpdater.php +++ b/includes/installer/PostgresUpdater.php @@ -1007,13 +1007,11 @@ END; public function addPgExtIndex( $table, $index, $type ) { if ( $this->db->indexExists( $table, $index ) ) { $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 { - if ( preg_match( '/^\(/', $type ) ) { - $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'" ); - } + $this->applyPatch( $type, true, "Creating index '$index' on table '$table'" ); } } diff --git a/includes/installer/SqliteInstaller.php b/includes/installer/SqliteInstaller.php index 9de1fea23d..cdb11b044f 100644 --- a/includes/installer/SqliteInstaller.php +++ b/includes/installer/SqliteInstaller.php @@ -332,10 +332,8 @@ EOT; if ( !is_writable( $file ) ) { return Status::newFatal( 'config-sqlite-readonly', $file ); } - } else { - if ( file_put_contents( $file, '' ) === false ) { - return Status::newFatal( 'config-sqlite-cant-create-db', $file ); - } + } elseif ( file_put_contents( $file, '' ) === false ) { + return Status::newFatal( 'config-sqlite-cant-create-db', $file ); } return Status::newGood(); diff --git a/includes/installer/WebInstaller.php b/includes/installer/WebInstaller.php index e1070c6e8f..2d12e62de8 100644 --- a/includes/installer/WebInstaller.php +++ b/includes/installer/WebInstaller.php @@ -1072,12 +1072,10 @@ class WebInstaller extends Installer { if ( $value === null ) { // Checkbox? $this->setVar( $name, false ); + } elseif ( stripos( $name, 'password' ) !== false ) { + $this->setPassword( $name, $value ); } else { - if ( stripos( $name, 'password' ) !== false ) { - $this->setPassword( $name, $value ); - } else { - $this->setVar( $name, $value ); - } + $this->setVar( $name, $value ); } } diff --git a/includes/installer/WebInstallerName.php b/includes/installer/WebInstallerName.php index 8314fd2803..1222ac2f3f 100644 --- a/includes/installer/WebInstallerName.php +++ b/includes/installer/WebInstallerName.php @@ -28,10 +28,8 @@ class WebInstallerName extends WebInstallerPage { */ public function execute() { $r = $this->parent->request; - if ( $r->wasPosted() ) { - if ( $this->submit() ) { - return 'continue'; - } + if ( $r->wasPosted() && $this->submit() ) { + return 'continue'; } $this->startForm(); diff --git a/includes/installer/WebInstallerOptions.php b/includes/installer/WebInstallerOptions.php index 47947128c4..bc2517955a 100644 --- a/includes/installer/WebInstallerOptions.php +++ b/includes/installer/WebInstallerOptions.php @@ -31,10 +31,8 @@ class WebInstallerOptions extends WebInstallerPage { $this->submitSkins(); return 'skip'; } - if ( $this->parent->request->wasPosted() ) { - if ( $this->submit() ) { - return 'continue'; - } + if ( $this->parent->request->wasPosted() && $this->submit() ) { + return 'continue'; } $emailwrapperStyle = $this->getVar( 'wgEnableEmail' ) ? '' : 'display: none'; diff --git a/includes/installer/WebInstallerWelcome.php b/includes/installer/WebInstallerWelcome.php index a4f031cd2f..28e8784701 100644 --- a/includes/installer/WebInstallerWelcome.php +++ b/includes/installer/WebInstallerWelcome.php @@ -25,10 +25,8 @@ class WebInstallerWelcome extends WebInstallerPage { * @return string */ public function execute() { - if ( $this->parent->request->wasPosted() ) { - if ( $this->getVar( '_Environment' ) ) { - return 'continue'; - } + if ( $this->parent->request->wasPosted() && $this->getVar( '_Environment' ) ) { + return 'continue'; } $this->parent->output->addWikiTextAsInterface( wfMessage( 'config-welcome' )->plain() ); $status = $this->parent->doEnvironmentChecks(); diff --git a/includes/libs/MultiHttpClient.php b/includes/libs/MultiHttpClient.php index 536177edeb..a6135aeb7a 100644 --- a/includes/libs/MultiHttpClient.php +++ b/includes/libs/MultiHttpClient.php @@ -237,11 +237,9 @@ class MultiHttpClient implements LoggerAwareInterface { } } while ( $mrc == CURLM_CALL_MULTI_PERFORM ); // Wait (if possible) for available work... - if ( $active > 0 && $mrc == CURLM_OK ) { - if ( curl_multi_select( $chm, $selectTimeout ) == -1 ) { - // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html - usleep( 5000 ); // 5ms - } + if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) { + // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html + usleep( 5000 ); // 5ms } } while ( $active > 0 && $mrc == CURLM_OK ); } diff --git a/includes/libs/filebackend/FileBackendMultiWrite.php b/includes/libs/filebackend/FileBackendMultiWrite.php index 9524155d6b..f92d5fa0a9 100644 --- a/includes/libs/filebackend/FileBackendMultiWrite.php +++ b/includes/libs/filebackend/FileBackendMultiWrite.php @@ -257,11 +257,11 @@ class FileBackendMultiWrite extends FileBackend { $status->fatal( 'backend-fail-synced', $path ); continue; } - if ( $this->syncChecks & self::CHECK_SIZE ) { - if ( $cStat['size'] != $mStat['size'] ) { // wrong size - $status->fatal( 'backend-fail-synced', $path ); - continue; - } + if ( ( $this->syncChecks & self::CHECK_SIZE ) + && $cStat['size'] != $mStat['size'] + ) { // wrong size + $status->fatal( 'backend-fail-synced', $path ); + continue; } if ( $this->syncChecks & self::CHECK_TIME ) { $mTs = wfTimestamp( TS_UNIX, $mStat['mtime'] ); @@ -271,16 +271,12 @@ class FileBackendMultiWrite extends FileBackend { continue; } } - if ( $this->syncChecks & self::CHECK_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 + if ( ( $this->syncChecks & self::CHECK_SHA1 ) && $cBackend->getFileSha1Base36( $cParams ) !== $mSha1 ) { // wrong SHA1 $status->fatal( 'backend-fail-synced', $path ); + continue; } + } elseif ( $cStat ) { // file is not in master; file should not exist + $status->fatal( 'backend-fail-synced', $path ); } } } diff --git a/includes/libs/mime/XmlTypeCheck.php b/includes/libs/mime/XmlTypeCheck.php index 993eea97e4..746f3f5382 100644 --- a/includes/libs/mime/XmlTypeCheck.php +++ b/includes/libs/mime/XmlTypeCheck.php @@ -406,10 +406,10 @@ class XmlTypeCheck { $callbackReturn = false; } - if ( $checkIfSafe && isset( $parsedDTD['internal'] ) ) { - if ( !$this->checkDTDIsSafe( $parsedDTD['internal'] ) ) { - $this->wellFormed = false; - } + if ( $checkIfSafe && isset( $parsedDTD['internal'] ) && + !$this->checkDTDIsSafe( $parsedDTD['internal'] ) + ) { + $this->wellFormed = false; } } diff --git a/includes/libs/objectcache/WANObjectCache.php b/includes/libs/objectcache/WANObjectCache.php index 9f9cc3cc53..8f0b5398fa 100644 --- a/includes/libs/objectcache/WANObjectCache.php +++ b/includes/libs/objectcache/WANObjectCache.php @@ -601,22 +601,20 @@ class WANObjectCache implements IExpiringStore, LoggerAwareInterface { [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] ); // 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 { - if ( $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 { - $this->logger->info( - 'Rejected set() for {cachekey} due to high read lag.', - [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] - ); + $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 } } diff --git a/includes/libs/rdbms/database/Database.php b/includes/libs/rdbms/database/Database.php index 18961bd2cb..27392050ce 100644 --- a/includes/libs/rdbms/database/Database.php +++ b/includes/libs/rdbms/database/Database.php @@ -524,20 +524,18 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware $possibleDrivers = $builtinTypes[$dbType]; if ( is_string( $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 { - if ( (string)$driver !== '' ) { - if ( !isset( $possibleDrivers[$driver] ) ) { - throw new InvalidArgumentException( __METHOD__ . - " type '$dbType' does not support driver '{$driver}'" ); - } else { - $class = $possibleDrivers[$driver]; - } - } else { - foreach ( $possibleDrivers as $posDriver => $possibleClass ) { - if ( extension_loaded( $posDriver ) ) { - $class = $possibleClass; - break; - } + 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 ) { if ( is_null( $name ) ) { 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 ) { @@ -3975,17 +3973,15 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware "$fname: Flushing an explicit transaction, getting out of sync." ); } - } else { - if ( !$this->trxLevel ) { - $this->queryLogger->error( - "$fname: No transaction to commit, something got out of sync." ); - return; // nothing to do - } elseif ( $this->trxAutomatic ) { - throw new DBUnexpectedError( - $this, - "$fname: Expected mass commit of all peer transactions (DBO_TRX set)." - ); - } + } elseif ( !$this->trxLevel ) { + $this->queryLogger->error( + "$fname: No transaction to commit, something got out of sync." ); + return; // nothing to do + } elseif ( $this->trxAutomatic ) { + throw new DBUnexpectedError( + $this, + "$fname: Expected mass commit of all peer transactions (DBO_TRX set)." + ); } $this->assertHasConnectionHandle(); @@ -4030,13 +4026,14 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware final public function rollback( $fname = __METHOD__, $flush = '' ) { $trxActive = $this->trxLevel; - if ( $flush !== self::FLUSHING_INTERNAL && $flush !== self::FLUSHING_ALL_PEERS ) { - if ( $this->getFlag( self::DBO_TRX ) ) { - throw new DBUnexpectedError( - $this, - "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)." - ); - } + if ( $flush !== self::FLUSHING_INTERNAL + && $flush !== self::FLUSHING_ALL_PEERS + && $this->getFlag( self::DBO_TRX ) + ) { + throw new DBUnexpectedError( + $this, + "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)." + ); } if ( $trxActive ) { diff --git a/includes/libs/rdbms/loadbalancer/LoadBalancer.php b/includes/libs/rdbms/loadbalancer/LoadBalancer.php index 1fd21d08c6..bd22acaa59 100644 --- a/includes/libs/rdbms/loadbalancer/LoadBalancer.php +++ b/includes/libs/rdbms/loadbalancer/LoadBalancer.php @@ -487,10 +487,8 @@ class LoadBalancer implements ILoadBalancer { $this->waitForPos = $pos; // If a generic reader connection was already established, then wait now $i = $this->readIndex; - if ( $i > 0 ) { - if ( !$this->doWait( $i ) ) { - $this->laggedReplicaMode = true; - } + if ( ( $i > 0 ) && !$this->doWait( $i ) ) { + $this->laggedReplicaMode = true; } } finally { // Restore the older position if it was higher since this is used for lag-protection diff --git a/includes/libs/redis/RedisConnectionPool.php b/includes/libs/redis/RedisConnectionPool.php index aa60242235..9a8086f529 100644 --- a/includes/libs/redis/RedisConnectionPool.php +++ b/includes/libs/redis/RedisConnectionPool.php @@ -245,13 +245,11 @@ class RedisConnectionPool implements LoggerAwareInterface { return false; } - if ( $this->password !== null ) { - if ( !$conn->auth( $this->password ) ) { - $logger->error( - 'Authentication error connecting to "{redis_server}"', - [ 'redis_server' => $server ] - ); - } + if ( ( $this->password !== null ) && !$conn->auth( $this->password ) ) { + $logger->error( + 'Authentication error connecting to "{redis_server}"', + [ 'redis_server' => $server ] + ); } } catch ( RedisException $e ) { $this->downServers[$server] = time() + self::SERVER_DOWN_TTL; @@ -364,15 +362,13 @@ class RedisConnectionPool implements LoggerAwareInterface { * @return bool Success */ public function reauthenticateConnection( $server, Redis $conn ) { - if ( $this->password !== null ) { - if ( !$conn->auth( $this->password ) ) { - $this->logger->error( - 'Authentication error connecting to "{redis_server}"', - [ 'redis_server' => $server ] - ); + if ( $this->password !== null && !$conn->auth( $this->password ) ) { + $this->logger->error( + 'Authentication error connecting to "{redis_server}"', + [ 'redis_server' => $server ] + ); - return false; - } + return false; } return true; diff --git a/includes/mail/EmailNotification.php b/includes/mail/EmailNotification.php index 987239be78..acf2c2e446 100644 --- a/includes/mail/EmailNotification.php +++ b/includes/mail/EmailNotification.php @@ -225,10 +225,9 @@ class EmailNotification { && $watchingUser->getId() != $userTalkId && !in_array( $watchingUser->getName(), $wgUsersNotifiedOnAllChanges ) && !( $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 ); } } } diff --git a/includes/media/BitmapHandler.php b/includes/media/BitmapHandler.php index b8b706d488..f003554727 100644 --- a/includes/media/BitmapHandler.php +++ b/includes/media/BitmapHandler.php @@ -338,10 +338,8 @@ class BitmapHandler extends TransformationalImageHandler { } $im->setImageDepth( 8 ); - if ( $rotation ) { - if ( !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) { - return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" ); - } + if ( $rotation && !$im->rotateImage( new ImagickPixel( 'white' ), 360 - $rotation ) ) { + return $this->getMediaTransformError( $params, "Error rotating $rotation degrees" ); } if ( $this->isAnimatedImage( $image ) ) { diff --git a/includes/media/BitmapMetadataHandler.php b/includes/media/BitmapMetadataHandler.php index 81c63db2e6..9617692ab4 100644 --- a/includes/media/BitmapMetadataHandler.php +++ b/includes/media/BitmapMetadataHandler.php @@ -132,13 +132,13 @@ class BitmapMetadataHandler { // Do some special casing for multilingual values. // Don't discard translations if also as a simple value. foreach ( $this->metadata[$type] as $itemName => $item ) { - if ( is_array( $item ) && isset( $item['_type'] ) && $item['_type'] === 'lang' ) { - if ( isset( $temp[$itemName] ) && !is_array( $temp[$itemName] ) ) { - $default = $temp[$itemName]; - $temp[$itemName] = $item; - $temp[$itemName]['x-default'] = $default; - unset( $this->metadata[$type][$itemName] ); - } + if ( is_array( $item ) && isset( $item['_type'] ) && $item['_type'] === 'lang' && + isset( $temp[$itemName] ) && !is_array( $temp[$itemName] ) + ) { + $default = $temp[$itemName]; + $temp[$itemName] = $item; + $temp[$itemName]['x-default'] = $default; + unset( $this->metadata[$type][$itemName] ); } } diff --git a/includes/media/SvgHandler.php b/includes/media/SvgHandler.php index b7745df9bc..4d75d04449 100644 --- a/includes/media/SvgHandler.php +++ b/includes/media/SvgHandler.php @@ -199,20 +199,16 @@ class SvgHandler extends ImageHandler { $params['physicalWidth'] = $wgSVGMaxSize; $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize ); } - } else { - if ( $params['physicalHeight'] > $wgSVGMaxSize ) { - $srcWidth = $image->getWidth( $params['page'] ); - $srcHeight = $image->getHeight( $params['page'] ); - $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize ); - $params['physicalHeight'] = $wgSVGMaxSize; - } + } elseif ( $params['physicalHeight'] > $wgSVGMaxSize ) { + $srcWidth = $image->getWidth( $params['page'] ); + $srcHeight = $image->getHeight( $params['page'] ); + $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize ); + $params['physicalHeight'] = $wgSVGMaxSize; } // To prevent the proliferation of thumbnails in languages not present in SVGs, unless // explicitly forced by user. - if ( isset( $params['targetlang'] ) ) { - if ( !$image->getMatchedLanguage( $params['targetlang'] ) ) { - unset( $params['targetlang'] ); - } + if ( isset( $params['targetlang'] ) && !$image->getMatchedLanguage( $params['targetlang'] ) ) { + unset( $params['targetlang'] ); } return $params; diff --git a/includes/page/Article.php b/includes/page/Article.php index 22363bf37d..124437ecb6 100644 --- a/includes/page/Article.php +++ b/includes/page/Article.php @@ -1131,13 +1131,11 @@ class Article implements Page { * [[MediaWiki:Talkpagetext]]. For Article::view(). */ public function showNamespaceHeader() { - if ( $this->getTitle()->isTalkPage() ) { - if ( !wfMessage( 'talkpageheader' )->isDisabled() ) { - $this->getContext()->getOutput()->wrapWikiMsg( - "
\n$1\n
", - [ 'talkpageheader' ] - ); - } + if ( $this->getTitle()->isTalkPage() && !wfMessage( 'talkpageheader' )->isDisabled() ) { + $this->getContext()->getOutput()->wrapWikiMsg( + "
\n$1\n
", + [ 'talkpageheader' ] + ); } } diff --git a/includes/parser/BlockLevelPass.php b/includes/parser/BlockLevelPass.php index f925038302..50c7e2376e 100644 --- a/includes/parser/BlockLevelPass.php +++ b/includes/parser/BlockLevelPass.php @@ -380,23 +380,19 @@ class BlockLevelPass { $output .= $pendingPTag . '
'; $pendingPTag = false; $this->lastParagraph = 'p'; - } else { - if ( $this->lastParagraph !== 'p' ) { - $output .= $this->closeParagraph(); - $pendingPTag = '

'; - } else { - $pendingPTag = '

'; - } - } - } else { - if ( $pendingPTag ) { - $output .= $pendingPTag; - $pendingPTag = false; - $this->lastParagraph = 'p'; } elseif ( $this->lastParagraph !== 'p' ) { - $output .= $this->closeParagraph() . '

'; - $this->lastParagraph = 'p'; + $output .= $this->closeParagraph(); + $pendingPTag = '

'; + } else { + $pendingPTag = '

'; } + } elseif ( $pendingPTag ) { + $output .= $pendingPTag; + $pendingPTag = false; + $this->lastParagraph = 'p'; + } elseif ( $this->lastParagraph !== 'p' ) { + $output .= $this->closeParagraph() . '

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

(.*)\n?<\/p>\n?$/sU', $html, $m ) ) { - if ( strpos( $m[1], '

' ) === false ) { - $html = $m[1]; - } + if ( preg_match( '/^

(.*)\n?<\/p>\n?$/sU', $html, $m ) && strpos( $m[1], '

' ) === false ) { + $html = $m[1]; } return $html; diff --git a/includes/parser/Sanitizer.php b/includes/parser/Sanitizer.php index 0aa58c1615..518846ce7e 100644 --- a/includes/parser/Sanitizer.php +++ b/includes/parser/Sanitizer.php @@ -578,10 +578,8 @@ class Sanitizer { $badtag = true; } } - } else { - if ( $t == 'table' ) { - $tagstack = array_pop( $tablestack ); - } + } elseif ( $t == 'table' ) { + $tagstack = array_pop( $tablestack ); } $newparams = ''; } else { diff --git a/includes/resourceloader/ResourceLoader.php b/includes/resourceloader/ResourceLoader.php index 8ab7c0c2de..839948dbc6 100644 --- a/includes/resourceloader/ResourceLoader.php +++ b/includes/resourceloader/ResourceLoader.php @@ -1160,11 +1160,9 @@ MESSAGE; // Use a linebreak between module script and state script (T162719) $out = $this->ensureNewline( $out ) . $stateScript; } - } else { - if ( $states ) { - $this->errors[] = 'Problematic modules: ' - . self::encodeJsonForScript( $states ); - } + } elseif ( $states ) { + $this->errors[] = 'Problematic modules: ' + . self::encodeJsonForScript( $states ); } return $out; diff --git a/includes/resourceloader/ResourceLoaderClientHtml.php b/includes/resourceloader/ResourceLoaderClientHtml.php index 84477ca868..ec408c742b 100644 --- a/includes/resourceloader/ResourceLoaderClientHtml.php +++ b/includes/resourceloader/ResourceLoaderClientHtml.php @@ -450,19 +450,17 @@ class ResourceLoaderClientHtml { // Decide whether to use 'style' or 'script' element if ( $only === ResourceLoaderModule::TYPE_STYLES ) { $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 { - if ( $context->getRaw() || $isRaw ) { - $chunk = Html::element( 'script', [ - // In SpecialJavaScriptTest, QUnit must load synchronous - 'async' => !isset( $extraQuery['sync'] ), - 'src' => $url - ] ); - } else { - $chunk = ResourceLoader::makeInlineScript( - Xml::encodeJsCall( 'mw.loader.load', [ $url ] ), - $nonce - ); - } + $chunk = ResourceLoader::makeInlineScript( + Xml::encodeJsCall( 'mw.loader.load', [ $url ] ), + $nonce + ); } if ( $group == 'noscript' ) { diff --git a/includes/skins/BaseTemplate.php b/includes/skins/BaseTemplate.php index 02247bd0e0..8fe35f08e3 100644 --- a/includes/skins/BaseTemplate.php +++ b/includes/skins/BaseTemplate.php @@ -264,28 +264,26 @@ abstract class BaseTemplate extends QuickTemplate { $boxes[$boxName]['content'] = $content; } } - } else { - if ( $hookContents ) { - $boxes['TOOLBOXEND'] = [ - 'id' => 'p-toolboxend', - 'header' => $boxes['TOOLBOX']['header'], - 'generated' => false, - 'content' => "", - ]; - // HACK: Make sure that TOOLBOXEND is sorted next to TOOLBOX - $boxes2 = []; - foreach ( $boxes as $key => $box ) { - if ( $key === 'TOOLBOXEND' ) { - continue; - } - $boxes2[$key] = $box; - if ( $key === 'TOOLBOX' ) { - $boxes2['TOOLBOXEND'] = $boxes['TOOLBOXEND']; - } + } elseif ( $hookContents ) { + $boxes['TOOLBOXEND'] = [ + 'id' => 'p-toolboxend', + 'header' => $boxes['TOOLBOX']['header'], + 'generated' => false, + 'content' => "", + ]; + // HACK: Make sure that TOOLBOXEND is sorted next to TOOLBOX + $boxes2 = []; + foreach ( $boxes as $key => $box ) { + if ( $key === 'TOOLBOXEND' ) { + continue; + } + $boxes2[$key] = $box; + if ( $key === 'TOOLBOX' ) { + $boxes2['TOOLBOXEND'] = $boxes['TOOLBOXEND']; } - $boxes = $boxes2; - // END hack } + $boxes = $boxes2; + // END hack } return $boxes; diff --git a/includes/skins/SkinTemplate.php b/includes/skins/SkinTemplate.php index a9c0993e29..8f45f281c2 100644 --- a/includes/skins/SkinTemplate.php +++ b/includes/skins/SkinTemplate.php @@ -389,17 +389,15 @@ class SkinTemplate extends Skin { $tpl->set( 'credits', false ); $tpl->set( 'numberofwatchingusers', false ); if ( $title->exists() ) { - if ( $out->isArticle() ) { - if ( $this->isRevisionCurrent() ) { - if ( $wgMaxCredits != 0 ) { - /** @var CreditsAction $action */ - $action = Action::factory( - 'credits', $this->getWikiPage(), $this->getContext() ); - $tpl->set( 'credits', - $action->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) ); - } else { - $tpl->set( 'lastmod', $this->lastModified() ); - } + if ( $out->isArticle() && $this->isRevisionCurrent() ) { + if ( $wgMaxCredits != 0 ) { + /** @var CreditsAction $action */ + $action = Action::factory( + 'credits', $this->getWikiPage(), $this->getContext() ); + $tpl->set( 'credits', + $action->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) ); + } else { + $tpl->set( 'lastmod', $this->lastModified() ); } } if ( $out->showsCopyright() ) { diff --git a/includes/specials/SpecialContributions.php b/includes/specials/SpecialContributions.php index 055a6e2609..08a7fde92b 100644 --- a/includes/specials/SpecialContributions.php +++ b/includes/specials/SpecialContributions.php @@ -267,14 +267,10 @@ class SpecialContributions extends IncludableSpecialPage { $message = 'sp-contributions-footer'; } - if ( $message ) { - if ( !$this->including() ) { - if ( !$this->msg( $message, $target )->isDisabled() ) { - $out->wrapWikiMsg( - "", - [ $message, $target ] ); - } - } + if ( $message && !$this->including() && !$this->msg( $message, $target )->isDisabled() ) { + $out->wrapWikiMsg( + "", + [ $message, $target ] ); } } } diff --git a/includes/specials/SpecialImport.php b/includes/specials/SpecialImport.php index a985bcc638..aaa405a648 100644 --- a/includes/specials/SpecialImport.php +++ b/includes/specials/SpecialImport.php @@ -391,10 +391,8 @@ class SpecialImport extends SpecialPage { Xml::closeElement( 'form' ) . Xml::closeElement( 'fieldset' ) ); - } else { - if ( empty( $this->importSources ) ) { - $out->addWikiMsg( 'importnosources' ); - } + } elseif ( empty( $this->importSources ) ) { + $out->addWikiMsg( 'importnosources' ); } if ( $user->isAllowed( 'import' ) && !empty( $this->importSources ) ) { diff --git a/includes/specials/SpecialSearch.php b/includes/specials/SpecialSearch.php index a5203960c0..f27a73631b 100644 --- a/includes/specials/SpecialSearch.php +++ b/includes/specials/SpecialSearch.php @@ -243,14 +243,12 @@ class SpecialSearch extends SpecialPage { $this->namespaces = $nslist; } elseif ( $profile === 'advanced' ) { $this->namespaces = $nslist; + } elseif ( isset( $profiles[$profile]['namespaces'] ) ) { + $this->namespaces = $profiles[$profile]['namespaces']; } else { - if ( isset( $profiles[$profile]['namespaces'] ) ) { - $this->namespaces = $profiles[$profile]['namespaces']; - } else { - // Unknown profile requested - $profile = 'default'; - $this->namespaces = $profiles['default']['namespaces']; - } + // Unknown profile requested + $profile = 'default'; + $this->namespaces = $profiles['default']['namespaces']; } $this->fulltext = $request->getVal( 'fulltext' ); diff --git a/includes/specials/SpecialUpload.php b/includes/specials/SpecialUpload.php index 5a1b8fbf6d..dcc35fcef7 100644 --- a/includes/specials/SpecialUpload.php +++ b/includes/specials/SpecialUpload.php @@ -191,11 +191,9 @@ class SpecialUpload extends SpecialPage { $this->loadRequest(); # Unsave the temporary file in case this was a cancelled upload - if ( $this->mCancelUpload ) { - if ( !$this->unsaveUploadedFile() ) { - # Something went wrong, so unsaveUploadedFile showed a warning - return; - } + if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) { + # Something went wrong, so unsaveUploadedFile showed a warning + return; } # Process upload or show a form diff --git a/includes/specials/SpecialWhatlinkshere.php b/includes/specials/SpecialWhatlinkshere.php index b48e858719..18c10bf706 100644 --- a/includes/specials/SpecialWhatlinkshere.php +++ b/includes/specials/SpecialWhatlinkshere.php @@ -200,29 +200,27 @@ class SpecialWhatLinksHere extends IncludableSpecialPage { && ( $hidetrans || !$tlRes->numRows() ) && ( $hideimages || !$ilRes->numRows() ) ) { - if ( $level == 0 ) { - if ( !$this->including() ) { - $out->addHTML( $this->whatlinkshereForm() ); - - // Show filters only if there are links - if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) { - $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 ); + if ( $level == 0 && !$this->including() ) { + $out->addHTML( $this->whatlinkshereForm() ); + + // Show filters only if there are links + if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) { + $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 ); } return; @@ -280,27 +278,25 @@ class SpecialWhatLinksHere extends IncludableSpecialPage { } $lb->execute(); - if ( $level == 0 ) { - if ( !$this->including() ) { - $out->addHTML( $this->whatlinkshereForm() ); - $out->addHTML( $this->getFilterPanel() ); + if ( $level == 0 && !$this->including() ) { + $out->addHTML( $this->whatlinkshereForm() ); + $out->addHTML( $this->getFilterPanel() ); - $link = $this->getLinkRenderer()->makeLink( - $this->target, - null, - [], - $this->target->isRedirect() ? [ 'redirect' => 'no' ] : [] - ); + $link = $this->getLinkRenderer()->makeLink( + $this->target, + null, + [], + $this->target->isRedirect() ? [ 'redirect' => 'no' ] : [] + ); - $msg = $this->msg( 'linkshere' ) - ->params( $this->target->getPrefixedText() ) - ->rawParams( $link ) - ->parseAsBlock(); - $out->addHTML( $msg ); + $msg = $this->msg( 'linkshere' ) + ->params( $this->target->getPrefixedText() ) + ->rawParams( $link ) + ->parseAsBlock(); + $out->addHTML( $msg ); - $prevnext = $this->getPrevNext( $prevId, $nextId ); - $out->addHTML( $prevnext ); - } + $prevnext = $this->getPrevNext( $prevId, $nextId ); + $out->addHTML( $prevnext ); } $out->addHTML( $this->listStart( $level ) ); foreach ( $rows as $row ) { @@ -321,10 +317,8 @@ class SpecialWhatLinksHere extends IncludableSpecialPage { $out->addHTML( $this->listEnd() ); - if ( $level == 0 ) { - if ( !$this->including() ) { - $out->addHTML( $prevnext ); - } + if ( $level == 0 && !$this->including() ) { + $out->addHTML( $prevnext ); } } diff --git a/includes/specials/pagers/BlockListPager.php b/includes/specials/pagers/BlockListPager.php index 2b8d1d5fee..71cf787504 100644 --- a/includes/specials/pagers/BlockListPager.php +++ b/includes/specials/pagers/BlockListPager.php @@ -191,10 +191,8 @@ class BlockListPager extends TablePager { case 'ipb_params': $properties = []; - if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) { - if ( $row->ipb_sitewide ) { - $properties[] = htmlspecialchars( $msg['blocklist-editing-sitewide'] ); - } + if ( $this->getConfig()->get( 'EnablePartialBlocks' ) && $row->ipb_sitewide ) { + $properties[] = htmlspecialchars( $msg['blocklist-editing-sitewide'] ); } if ( !$row->ipb_sitewide && $this->restrictions ) { diff --git a/includes/specials/pagers/ImageListPager.php b/includes/specials/pagers/ImageListPager.php index 486b0ec910..ea55568fd2 100644 --- a/includes/specials/pagers/ImageListPager.php +++ b/includes/specials/pagers/ImageListPager.php @@ -269,10 +269,8 @@ class ImageListPager extends TablePager { } } $fields['top'] = $dbr->addQuotes( 'no' ); - } else { - if ( $this->mShowAll ) { - $fields['top'] = $dbr->addQuotes( 'yes' ); - } + } elseif ( $this->mShowAll ) { + $fields['top'] = $dbr->addQuotes( 'yes' ); } $fields['thumb'] = $prefix . '_name'; @@ -382,14 +380,12 @@ class ImageListPager extends TablePager { $resultArray[] = $topRes2; $topRes2 = $res2->next(); } + } elseif ( !$ascending ) { + $resultArray[] = $topRes2; + $topRes2 = $res2->next(); } else { - if ( !$ascending ) { - $resultArray[] = $topRes2; - $topRes2 = $res2->next(); - } else { - $resultArray[] = $topRes1; - $topRes1 = $res1->next(); - } + $resultArray[] = $topRes1; + $topRes1 = $res1->next(); } } diff --git a/includes/tidy/RemexCompatFormatter.php b/includes/tidy/RemexCompatFormatter.php index 4e933827c2..abc98baab4 100644 --- a/includes/tidy/RemexCompatFormatter.php +++ b/includes/tidy/RemexCompatFormatter.php @@ -40,10 +40,10 @@ class RemexCompatFormatter extends HtmlFormatter { $name = $node->name; $attrs = $node->attrs; - if ( isset( self::$markedEmptyElements[$name] ) && $attrs->count() === 0 ) { - if ( strspn( $contents, "\t\n\f\r " ) === strlen( $contents ) ) { - return "<{$name} class=\"mw-empty-elt\">$contents"; - } + if ( isset( self::$markedEmptyElements[$name] ) && $attrs->count() === 0 + && strspn( $contents, "\t\n\f\r " ) === strlen( $contents ) + ) { + return "<{$name} class=\"mw-empty-elt\">$contents"; } $s = "<$name"; diff --git a/includes/title/MediaWikiTitleCodec.php b/includes/title/MediaWikiTitleCodec.php index e06bfb53d8..adbea89db7 100644 --- a/includes/title/MediaWikiTitleCodec.php +++ b/includes/title/MediaWikiTitleCodec.php @@ -421,10 +421,8 @@ class MediaWikiTitleCodec implements TitleFormatter, TitleParser { # Can't make a link to a namespace alone... "empty" local links can only be # self-links with a fragment identifier. - if ( $dbkey == '' && $parts['interwiki'] === '' ) { - if ( $parts['namespace'] != NS_MAIN ) { - throw new MalformedTitleException( 'title-invalid-empty', $text ); - } + if ( $dbkey == '' && $parts['interwiki'] === '' && $parts['namespace'] != NS_MAIN ) { + throw new MalformedTitleException( 'title-invalid-empty', $text ); } // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles. diff --git a/includes/upload/UploadBase.php b/includes/upload/UploadBase.php index d00ad978e7..9e92e78772 100644 --- a/includes/upload/UploadBase.php +++ b/includes/upload/UploadBase.php @@ -1078,10 +1078,8 @@ abstract class UploadBase { $props = $this->mFileProps; $error = null; Hooks::run( 'UploadStashFile', [ $this, $user, $props, &$error ] ); - if ( $error ) { - if ( !is_array( $error ) ) { - $error = [ $error ]; - } + if ( $error && !is_array( $error ) ) { + $error = [ $error ]; } return $error; } @@ -1916,10 +1914,8 @@ abstract class UploadBase { $output = true; # if there's no output, return true } elseif ( $msgPattern ) { $groups = []; - if ( preg_match( $msgPattern, $output, $groups ) ) { - if ( $groups[1] ) { - $output = $groups[1]; - } + if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) { + $output = $groups[1]; } } diff --git a/includes/upload/UploadStash.php b/includes/upload/UploadStash.php index aa31a5b689..7d69fe1e7f 100644 --- a/includes/upload/UploadStash.php +++ b/includes/upload/UploadStash.php @@ -162,12 +162,10 @@ class UploadStash { ); } - if ( !$noAuth ) { - if ( $this->fileMetadata[$key]['us_user'] != $this->userId ) { - throw new UploadStashWrongOwnerException( - wfMessage( 'uploadstash-wrong-owner', $key ) - ); - } + if ( !$noAuth && $this->fileMetadata[$key]['us_user'] != $this->userId ) { + throw new UploadStashWrongOwnerException( + wfMessage( 'uploadstash-wrong-owner', $key ) + ); } return $this->files[$key]; diff --git a/includes/user/User.php b/includes/user/User.php index fa74cb341e..c191c70a15 100644 --- a/includes/user/User.php +++ b/includes/user/User.php @@ -1405,10 +1405,10 @@ class User implements IDBAccessObject, UserIdentity { public function trackBlockWithCookie() { $block = $this->getBlock(); - if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) { - if ( $block->shouldTrackWithCookie( $this->isAnon() ) ) { - $block->setCookie( $this->getRequest()->response() ); - } + if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null + && $block->shouldTrackWithCookie( $this->isAnon() ) + ) { + $block->setCookie( $this->getRequest()->response() ); } } @@ -4424,10 +4424,8 @@ class User implements IDBAccessObject, UserIdentity { [ 'LOCK IN SHARE MODE' ] ); $loaded = false; - if ( $this->mId ) { - if ( $this->loadFromDatabase( self::READ_LOCKING ) ) { - $loaded = true; - } + if ( $this->mId && $this->loadFromDatabase( self::READ_LOCKING ) ) { + $loaded = true; } if ( !$loaded ) { throw new MWException( $fname . ": hit a key conflict attempting " . diff --git a/includes/watcheditem/WatchedItemQueryService.php b/includes/watcheditem/WatchedItemQueryService.php index 3ebc94a564..6094f41721 100644 --- a/includes/watcheditem/WatchedItemQueryService.php +++ b/includes/watcheditem/WatchedItemQueryService.php @@ -445,11 +445,9 @@ class WatchedItemQueryService { $conds = array_merge( $conds, $this->getStartEndConds( $db, $options ) ); - if ( !isset( $options['start'] ) && !isset( $options['end'] ) ) { - if ( $db->getType() === 'mysql' ) { - // This is an index optimization for mysql - $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' ); - } + if ( !isset( $options['start'] ) && !isset( $options['end'] ) && $db->getType() === 'mysql' ) { + // This is an index optimization for mysql + $conds[] = 'rc_timestamp > ' . $db->addQuotes( '' ); } $conds = array_merge( $conds, $this->getUserRelatedConds( $db, $user, $options ) ); diff --git a/tests/integration/includes/shell/FirejailCommandIntegrationTest.php b/tests/integration/includes/shell/FirejailCommandIntegrationTest.php index 47300051a1..3c7cb14382 100644 --- a/tests/integration/includes/shell/FirejailCommandIntegrationTest.php +++ b/tests/integration/includes/shell/FirejailCommandIntegrationTest.php @@ -40,10 +40,10 @@ class FirejailCommandIntegrationTest extends PHPUnit\Framework\TestCase { * @dataProvider provideExecute */ public function testExecute( $testCommand, $flag ) { - if ( preg_match( '/^sudo /', $testCommand ) ) { - if ( Shell::command( 'sudo', '-n', 'ls', '/' )->execute()->getExitCode() ) { - $this->markTestSkipped( 'need passwordless sudo' ); - } + if ( preg_match( '/^sudo /', $testCommand ) + && Shell::command( 'sudo', '-n', 'ls', '/' )->execute()->getExitCode() + ) { + $this->markTestSkipped( 'need passwordless sudo' ); } $command = new FirejailCommand( 'firejail' ); diff --git a/tests/phpunit/includes/Revision/RevisionStoreTest.php b/tests/phpunit/includes/Revision/RevisionStoreTest.php index 1ddc2545cc..5246e36832 100644 --- a/tests/phpunit/includes/Revision/RevisionStoreTest.php +++ b/tests/phpunit/includes/Revision/RevisionStoreTest.php @@ -528,12 +528,10 @@ class RevisionStoreTest extends MediaWikiTestCase { 'old_text' => 'Hello World', 'old_flags' => 'utf-8', ]; - } else { - if ( !isset( $row['content'] ) && isset( $array['old_text'] ) ) { - $row['content'] = [ - 'main' => new WikitextContent( $array['old_text'] ), - ]; - } + } elseif ( !isset( $row['content'] ) && isset( $array['old_text'] ) ) { + $row['content'] = [ + 'main' => new WikitextContent( $array['old_text'] ), + ]; } return (object)$row; diff --git a/tests/phpunit/structure/ApiStructureTest.php b/tests/phpunit/structure/ApiStructureTest.php index 4c64291b85..2453353b85 100644 --- a/tests/phpunit/structure/ApiStructureTest.php +++ b/tests/phpunit/structure/ApiStructureTest.php @@ -500,10 +500,8 @@ class ApiStructureTest extends MediaWikiTestCase { if ( $value instanceof $type ) { return; } - } else { - if ( gettype( $value ) === $type ) { - return; - } + } elseif ( gettype( $value ) === $type ) { + return; } } else { // Array whose values have specified types, recurse diff --git a/tests/phpunit/structure/AutoLoaderStructureTest.php b/tests/phpunit/structure/AutoLoaderStructureTest.php index 75e21ae085..2ae6a78b74 100644 --- a/tests/phpunit/structure/AutoLoaderStructureTest.php +++ b/tests/phpunit/structure/AutoLoaderStructureTest.php @@ -112,14 +112,12 @@ class AutoLoaderStructureTest extends MediaWikiTestCase { // 'class Foo {}' $class = $fileNamespace . $match['class']; $classesInFile[$class] = true; + } elseif ( !empty( $match['original'] ) ) { + // 'class_alias( "Foo", "Bar" );' + $aliasesInFile[$match['alias']] = $match['original']; } else { - if ( !empty( $match['original'] ) ) { - // 'class_alias( "Foo", "Bar" );' - $aliasesInFile[$match['alias']] = $match['original']; - } else { - // 'class_alias( Foo::class, "Bar" );' - $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic']; - } + // 'class_alias( Foo::class, "Bar" );' + $aliasesInFile[$match['aliasString']] = $fileNamespace . $match['originalStatic']; } } -- 2.20.1