From 2527cca6de0be7c146369288b373008ad69cc3de Mon Sep 17 00:00:00 2001 From: Siebrand Mazeland Date: Sun, 11 May 2014 01:03:45 +0200 Subject: [PATCH] Fix most CodeSniffer issues in includes/parser/ Remaining are the classes containing underscores and possibly a few other issues that will be addressed soonish. Change-Id: Icf56374c71afc134420ebbcfecf12dcb29dc9564 --- includes/parser/CacheTime.php | 14 +- includes/parser/CoreParserFunctions.php | 28 +- includes/parser/DateFormatter.php | 6 +- includes/parser/LinkHolderArray.php | 6 +- includes/parser/Parser.php | 223 ++++++++++++---- includes/parser/ParserCache.php | 11 +- includes/parser/ParserOptions.php | 330 +++++++++++++++++++----- includes/parser/ParserOutput.php | 209 +++++++++++---- includes/parser/Preprocessor.php | 6 +- includes/parser/Preprocessor_DOM.php | 84 ++++-- includes/parser/Preprocessor_Hash.php | 197 ++++++++++---- 11 files changed, 847 insertions(+), 267 deletions(-) diff --git a/includes/parser/CacheTime.php b/includes/parser/CacheTime.php index b44a20fba3..91f404acc2 100644 --- a/includes/parser/CacheTime.php +++ b/includes/parser/CacheTime.php @@ -173,12 +173,14 @@ class CacheTime { */ public function expired( $touched ) { global $wgCacheEpoch; - return !$this->isCacheable() || // parser says it's uncacheable - $this->getCacheTime() < $touched || - $this->getCacheTime() <= $wgCacheEpoch || - $this->getCacheTime() < wfTimestamp( TS_MW, time() - $this->getCacheExpiry() ) || // expiry period has passed - !isset( $this->mVersion ) || - version_compare( $this->mVersion, Parser::VERSION, "lt" ); + + return !$this->isCacheable() // parser says it's uncacheable + || $this->getCacheTime() < $touched + || $this->getCacheTime() <= $wgCacheEpoch + || $this->getCacheTime() < + wfTimestamp( TS_MW, time() - $this->getCacheExpiry() ) // expiry period has passed + || !isset( $this->mVersion ) + || version_compare( $this->mVersion, Parser::VERSION, "lt" ); } /** diff --git a/includes/parser/CoreParserFunctions.php b/includes/parser/CoreParserFunctions.php index 65c3e1dbac..8d52a5bcb2 100644 --- a/includes/parser/CoreParserFunctions.php +++ b/includes/parser/CoreParserFunctions.php @@ -71,7 +71,11 @@ class CoreParserFunctions { $parser->setFunctionHook( 'displaytitle', array( __CLASS__, 'displaytitle' ), SFH_NO_HASH ); } if ( $wgAllowSlowParserFunctions ) { - $parser->setFunctionHook( 'pagesinnamespace', array( __CLASS__, 'pagesinnamespace' ), SFH_NO_HASH ); + $parser->setFunctionHook( + 'pagesinnamespace', + array( __CLASS__, 'pagesinnamespace' ), + SFH_NO_HASH + ); } } @@ -83,7 +87,9 @@ class CoreParserFunctions { static function intFunction( $parser, $part1 = '' /*, ... */ ) { if ( strval( $part1 ) !== '' ) { $args = array_slice( func_get_args(), 2 ); - $message = wfMessage( $part1, $args )->inLanguage( $parser->getOptions()->getUserLangObj() )->plain(); + $message = wfMessage( $part1, $args ) + ->inLanguage( $parser->getOptions()->getUserLangObj() )->plain(); + return array( $message, 'noparse' => false ); } else { return array( 'found' => false ); @@ -393,12 +399,21 @@ class CoreParserFunctions { // only requested titles that normalize to the actual title are allowed through // if $wgRestrictDisplayTitle is true (it is by default) // mimic the escaping process that occurs in OutputPage::setPageTitle - $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $text, $htmlTagsCallback, array(), array(), $bad ) ); + $text = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( + $text, + $htmlTagsCallback, + array(), + array(), + $bad + ) ); $title = Title::newFromText( Sanitizer::stripAllTags( $text ) ); if ( !$wgRestrictDisplayTitle ) { $parser->mOutput->setDisplayTitle( $text ); - } elseif ( $title instanceof Title && !$title->hasFragment() && $title->equals( $parser->mTitle ) ) { + } elseif ( $title instanceof Title + && !$title->hasFragment() + && $title->equals( $parser->mTitle ) + ) { $parser->mOutput->setDisplayTitle( $text ); } @@ -855,8 +870,9 @@ class CoreParserFunctions { } } - // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} or {{filepath|300|nowiki}} - // or {{filepath|300px}}, {{filepath|200x300px}}, {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}} + // Usage {{filepath|300}}, {{filepath|nowiki}}, {{filepath|nowiki|300}} + // or {{filepath|300|nowiki}} or {{filepath|300px}}, {{filepath|200x300px}}, + // {{filepath|nowiki|200x300px}}, {{filepath|200x300px|nowiki}}. public static function filepath( $parser, $name = '', $argA = '', $argB = '' ) { $file = wfFindFile( $name ); diff --git a/includes/parser/DateFormatter.php b/includes/parser/DateFormatter.php index a6092a3fe3..54c6dece68 100644 --- a/includes/parser/DateFormatter.php +++ b/includes/parser/DateFormatter.php @@ -234,7 +234,8 @@ class DateFormatter { $bits = array(); $key = $this->keys[$this->mSource]; - for ( $p = 0; $p < strlen( $key ); $p++ ) { + $keyLength = strlen( $key ); + for ( $p = 0; $p < $keyLength; $p++ ) { if ( $key[$p] != ' ' ) { $bits[$key[$p]] = $matches[$p + 1]; } @@ -283,7 +284,8 @@ class DateFormatter { $bits['d'] = sprintf( '%02d', $bits['j'] ); } - for ( $p = 0; $p < strlen( $format ); $p++ ) { + $formatLength = strlen( $format ); + for ( $p = 0; $p < $formatLength; $p++ ) { $char = $format[$p]; switch ( $char ) { case 'd': # ISO day of month diff --git a/includes/parser/LinkHolderArray.php b/includes/parser/LinkHolderArray.php index 00c5a6c066..dc0f93359a 100644 --- a/includes/parser/LinkHolderArray.php +++ b/includes/parser/LinkHolderArray.php @@ -344,7 +344,8 @@ class LinkHolderArray { $res = $dbr->select( 'page', - array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ), + array( 'page_id', 'page_namespace', 'page_title', + 'page_is_redirect', 'page_len', 'page_latest' ), $dbr->makeList( $where, LIST_OR ), __METHOD__ ); @@ -547,7 +548,8 @@ class LinkHolderArray { // construct query $dbr = wfGetDB( DB_SLAVE ); $varRes = $dbr->select( 'page', - array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ), + array( 'page_id', 'page_namespace', 'page_title', + 'page_is_redirect', 'page_len', 'page_latest' ), $linkBatch->constructSet( 'page', $dbr ), __METHOD__ ); diff --git a/includes/parser/Parser.php b/includes/parser/Parser.php index 9866008c57..5a6dd9e677 100644 --- a/includes/parser/Parser.php +++ b/includes/parser/Parser.php @@ -460,7 +460,9 @@ class Parser { * @param int $revid Number to pass in {{REVISIONID}} * @return ParserOutput A ParserOutput */ - public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) { + public function parse( $text, Title $title, ParserOptions $options, + $linestart = true, $clearState = true, $revid = null + ) { /** * First pass--just handle sections, pass the rest off * to internalParse() which does all the real work. @@ -1191,7 +1193,10 @@ class Parser { array_push( $tr_history, false ); array_push( $td_history, false ); array_push( $last_tag_history, '' ); - } elseif ( $first_character === '|' || $first_character === '!' || substr( $line, 0, 2 ) === '|+' ) { + } elseif ( $first_character === '|' + || $first_character === '!' + || substr( $line, 0, 2 ) === '|+' + ) { # This might be cell elements, td, th or captions if ( substr( $line, 0, 2 ) === '|+' ) { $first_character = '+'; @@ -1336,7 +1341,12 @@ class Parser { } wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState ) ); - $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) ); + $text = Sanitizer::removeHTMLtags( + $text, + array( &$this, 'attributeStripCallback' ), + false, + array_keys( $this->mTransparentTagHooks ) + ); wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) ); # Tables need to come after variable replacement for things to work @@ -1742,7 +1752,8 @@ class Parser { $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE ); if ( $bits === false ) { wfProfileOut( __METHOD__ ); - throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" ); + throw new MWException( "PCRE needs to be compiled with " + . "--enable-unicode-properties in order for MediaWiki to function" ); } $s = array_shift( $bits ); @@ -1912,16 +1923,23 @@ class Parser { } else { $imagematch = false; } + if ( $this->mOptions->getAllowExternalImages() - || ( $imagesexception && $imagematch ) ) { + || ( $imagesexception && $imagematch ) + ) { if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) { # Image found $text = Linker::makeExternalImage( $url ); } } if ( !$text && $this->mOptions->getEnableImageWhitelist() - && preg_match( self::EXT_IMAGE_REGEX, $url ) ) { - $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() ); + && preg_match( self::EXT_IMAGE_REGEX, $url ) + ) { + $whitelist = explode( + "\n", + wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() + ); + foreach ( $whitelist as $entry ) { # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments if ( strpos( $entry, '#' ) === 0 || $entry === '' ) { @@ -2014,8 +2032,11 @@ class Parser { $useSubpages = $this->areSubpagesAllowed(); wfProfileOut( __METHOD__ . '-setup' ); + // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect # Loop for each link for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) { + // @codingStandardsIgnoreStart + # Check for excessive memory usage if ( $holders->isBig() ) { # Too big @@ -2066,7 +2087,8 @@ class Parser { $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) ); } $trail = $m[3]; - } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption + } elseif ( preg_match( $e1_img, $line, $m ) ) { + # Invalid, but might be an image with a link in its caption $might_be_img = true; $text = $m[2]; if ( strpos( $m[1], '%' ) !== false ) { @@ -2176,7 +2198,9 @@ class Parser { if ( $noforce ) { # Interwikis wfProfileIn( __METHOD__ . "-interwiki" ); - if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) { + if ( $iw && $this->mOptions->getInterwikiMagic() + && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) + ) { // XXX: the above check prevents links to sites with identifiers that are not language codes # Bug 24502: filter duplicates @@ -2588,10 +2612,19 @@ class Parser { wfProfileIn( __METHOD__ . "-paragraph" ); # No prefix (not in list)--go to paragraph mode # XXX: use a stack for nestable elements like span, table and div - $openmatch = preg_match( '/(?:mUniqPrefix . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t ); + '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' + . 'mUniqPrefix + . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', + $t + ); + if ( $openmatch or $closematch ) { $paragraphStack = false; # TODO bug 5718: paragraph closed @@ -2606,7 +2639,10 @@ class Parser { } $inBlockElem = !$closematch; } elseif ( !$inBlockElem && !$this->mInPre ) { - if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) and !$inBlockquote ) { + if ( ' ' == substr( $t, 0, 1 ) + && ( $this->mLastSection === 'pre' || trim( $t ) != '' ) + && !$inBlockquote + ) { # pre if ( $this->mLastSection !== 'pre' ) { $paragraphStack = false; @@ -2936,13 +2972,21 @@ class Parser { $value = wfEscapeWikiText( $this->mTitle->getRootText() ); break; case 'rootpagenamee': - $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getRootText() ) ) ); + $value = wfEscapeWikiText( wfUrlEncode( str_replace( + ' ', + '_', + $this->mTitle->getRootText() + ) ) ); break; case 'basepagename': $value = wfEscapeWikiText( $this->mTitle->getBaseText() ); break; case 'basepagenamee': - $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) ); + $value = wfEscapeWikiText( wfUrlEncode( str_replace( + ' ', + '_', + $this->mTitle->getBaseText() + ) ) ); break; case 'talkpagename': if ( $this->mTitle->canTalk() ) { @@ -3053,7 +3097,9 @@ class Parser { $value = $this->mTitle->getNamespace(); break; case 'talkspace': - $value = $this->mTitle->canTalk() ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() ) : ''; + $value = $this->mTitle->canTalk() + ? str_replace( '_', ' ', $this->mTitle->getTalkNsText() ) + : ''; break; case 'talkspacee': $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : ''; @@ -3085,13 +3131,19 @@ class Parser { $value = $pageLang->formatNum( MWTimestamp::getInstance( $ts )->format( 'w' ) ); break; case 'localdayname': - $value = $pageLang->getWeekdayName( (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1 ); + $value = $pageLang->getWeekdayName( + (int)MWTimestamp::getLocalInstance( $ts )->format( 'w' ) + 1 + ); break; case 'localyear': $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'Y' ), true ); break; case 'localtime': - $value = $pageLang->time( MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ), false, false ); + $value = $pageLang->time( + MWTimestamp::getLocalInstance( $ts )->format( 'YmdHis' ), + false, + false + ); break; case 'localhour': $value = $pageLang->formatNum( MWTimestamp::getLocalInstance( $ts )->format( 'H' ), true ); @@ -3160,7 +3212,11 @@ class Parser { break; default: $ret = null; - wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ); + wfRunHooks( + 'ParserGetVariableValueSwitch', + array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) + ); + return $ret; } @@ -3262,7 +3318,8 @@ class Parser { if ( $frame === false ) { $frame = $this->getPreprocessor()->newFrame(); } elseif ( !( $frame instanceof PPFrame ) ) { - wfDebug( __METHOD__ . " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" ); + wfDebug( __METHOD__ . " called using plain parameters instead of " + . "a PPFrame instance. Creating custom frame.\n" ); $frame = $this->getPreprocessor()->newCustomFrame( $frame ); } @@ -3352,13 +3409,20 @@ class Parser { wfProfileIn( __METHOD__ ); wfProfileIn( __METHOD__ . '-setup' ); - # Flags - $found = false; # $text has been filled - $nowiki = false; # wiki markup in $text should be escaped - $isHTML = false; # $text is HTML, armour it against wikitext transformation - $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered - $isChildObj = false; # $text is a DOM node needing expansion in a child frame - $isLocalObj = false; # $text is a DOM node needing expansion in the current frame + // Flags + + // $text has been filled + $found = false; + // wiki markup in $text should be escaped + $nowiki = false; + // $text is HTML, armour it against wikitext transformation + $isHTML = false; + // Force interwiki transclusion to be done in raw mode not rendered + $forceRawInterwiki = false; + // $text is a DOM node needing expansion in a child frame + $isChildObj = false; + // $text is a DOM node needing expansion in the current frame + $isLocalObj = false; # Title object, where $text came from $title = false; @@ -3373,7 +3437,8 @@ class Parser { $originalTitle = $part1; # $args is a list of argument nodes, starting from index 0, not including $part1 - # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object + # @todo FIXME: If piece['parts'] is null then the call to getLength() + # below won't work b/c this $args isn't an object $args = ( null == $piece['parts'] ) ? array() : $piece['parts']; wfProfileOut( __METHOD__ . '-setup' ); @@ -3513,7 +3578,8 @@ class Parser { // "uselang" will have no effect since the Language object // is forced to the one defined in ParserOptions. $pageArgs = array(); - for ( $i = 0; $i < $args->getLength(); $i++ ) { + $argsLength = $args->getLength(); + for ( $i = 0; $i < $argsLength; $i++ ) { $bits = $args->item( $i )->splitArg(); if ( strval( $bits['index'] ) === '' ) { $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) ); @@ -3646,7 +3712,8 @@ class Parser { preg_replace( '/^:/', '', $originalTitle ); $text = "[[:$originalTitle]]"; } - $text .= $this->insertStripItem( '' ); + $text .= $this->insertStripItem( '' ); $this->limitationWarn( 'post-expand-template-inclusion' ); } @@ -3820,7 +3887,8 @@ class Parser { * @return array ( string or false, Title ) */ function fetchTemplateAndTitle( $title ) { - $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate() + // Defaults to Parser::statelessFetchTemplate() + $templateCb = $this->mOptions->getTemplateCallback(); $stuff = call_user_func( $templateCb, $title, $this ); $text = $stuff['text']; $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title; @@ -4029,8 +4097,10 @@ class Parser { $status = $req->execute(); // Status object if ( $status->isOK() ) { $text = $req->getContent(); - } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless. - return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text(); + } elseif ( $req->getStatus() != 200 ) { + // Though we failed to fetch the content, this status is useless. + return wfMessage( 'scarytranscludefailed-httpstatus' ) + ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text(); } else { return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text(); } @@ -4112,7 +4182,8 @@ class Parser { $name = $frame->expand( $params['name'] ); $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] ); $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] ); - $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX; + $marker = "{$this->mUniqPrefix}-$name-" + . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX; $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower( $name )] ) && ( $this->ot['html'] || $this->ot['pre'] ); @@ -4244,7 +4315,9 @@ class Parser { if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) { $this->mShowToc = false; } - if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) { + if ( isset( $this->mDoubleUnderscores['hiddencat'] ) + && $this->mTitle->getNamespace() == NS_CATEGORY + ) { $this->addTrackingCategory( 'hidden-category-category' ); } # (bug 8068) Allow control over whether robots index a page. @@ -4339,7 +4412,11 @@ class Parser { # Get all headlines for numbering them and adding funky stuff like [edit] # links - this is for later, but we need the number of headlines right now $matches = array(); - $numMatches = preg_match_all( '/[1-6])(?P.*?' . '>)\s*(?P
[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches ); + $numMatches = preg_match_all( + '/[1-6])(?P.*?' . '>)\s*(?P
[\s\S]*?)\s*<\/H[1-6] *>/i', + $text, + $matches + ); # if there are fewer than 4 headlines in the article, do not show TOC # unless it's been explicitly enabled. @@ -4488,7 +4565,10 @@ class Parser { # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from , # to allow setting directionality in toc items. $tocline = preg_replace( - array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ), + array( + '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', + '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' + ), array( '', '<$1>' ), $safeHeadline ); @@ -4552,7 +4632,11 @@ class Parser { # Don't number the heading if it is the only one (looks silly) if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) { # the two are different if the line contains a link - $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline; + $headline = Html::element( + 'span', + array( 'class' => 'mw-headline-number' ), + $numbering + ) . ' ' . $headline; } # Create the anchor for linking from the TOC to the section @@ -4602,14 +4686,22 @@ class Parser { # that sections inside should be counted. $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ ); } else { - $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint ); + $editlinkArgs = array( + $this->mTitle->getPrefixedText(), + $sectionIndex, + $headlineHint + ); } - // We use a bit of pesudo-xml for editsection markers. The language converter is run later on - // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff - // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped - // so we don't have to worry about a user trying to input one of these markers directly. - // We use a page and section attribute to stop the language converter from converting these important bits - // of data, but put the headline hint inside a content block because the language converter is supposed to + // We use a bit of pesudo-xml for editsection markers. The + // language converter is run later on. Using a UNIQ style marker + // leads to the converter screwing up the tokens when it + // converts stuff. And trying to insert strip tags fails too. At + // this point all real inputted tags have already been escaped, + // so we don't have to worry about a user trying to input one of + // these markers directly. We use a page and section attribute + // to stop the language converter from converting these + // important bits of data, but put the headline hint inside a + // content block because the language converter is supposed to // be able to convert that piece of data. $editlink = 'lock(); } @@ -4776,10 +4870,14 @@ class Parser { $tc = '[' . Title::legalChars() . ']'; $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii! - $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]] - $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257) - $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma) - $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title) + // [[ns:page (context)|]] + $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; + // [[ns:page(context)|]] (double-width brackets, added in r40257) + $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; + // [[ns:page (context), context|]] (using either single or double-width comma) + $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; + // [[|page]] (reverse pipe trick: add context from page title) + $p2 = "/\[\[\\|($tc+)]]/"; # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]" $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text ); @@ -4856,7 +4954,8 @@ class Parser { $nickText = wfEscapeWikiText( $nickname ); $msgName = $user->isAnon() ? 'signature-anon' : 'signature'; - return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text(); + return wfMessage( $msgName, $userText, $nickText )->inContentLanguage() + ->title( $this->getTitle() )->text(); } /** @@ -4930,7 +5029,9 @@ class Parser { * @param int $outputType * @param bool $clearState */ - public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) { + public function startExternalParse( Title $title = null, ParserOptions $options, + $outputType, $clearState = true + ) { $this->startParse( $title, $options, $outputType, $clearState ); } @@ -4940,7 +5041,9 @@ class Parser { * @param int $outputType * @param bool $clearState */ - private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) { + private function startParse( Title $title = null, ParserOptions $options, + $outputType, $clearState = true + ) { $this->setTitle( $title ); $this->mOptions = $options; $this->setOutputType( $outputType ); @@ -5680,7 +5783,11 @@ class Parser { * @return array */ function getTags() { - return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) ); + return array_merge( + array_keys( $this->mTransparentTagHooks ), + array_keys( $this->mTagHooks ), + array_keys( $this->mFunctionTagHooks ) + ); } /** @@ -5703,7 +5810,10 @@ class Parser { list( $element, $content, $params, $tag ) = $data; $tagName = strtolower( $element ); if ( isset( $this->mTransparentTagHooks[$tagName] ) ) { - $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) ); + $output = call_user_func_array( + $this->mTransparentTagHooks[$tagName], + array( $content, $params, $this ) + ); } else { $output = $tag; } @@ -6280,7 +6390,8 @@ class Parser { */ protected function lock() { if ( $this->mInParse ) { - throw new MWException( "Parser state cleared while parsing. Did you call Parser::parse recursively?" ); + throw new MWException( "Parser state cleared while parsing. " + . "Did you call Parser::parse recursively?" ); } $this->mInParse = true; diff --git a/includes/parser/ParserCache.php b/includes/parser/ParserCache.php index e374361812..f5f9441e37 100644 --- a/includes/parser/ParserCache.php +++ b/includes/parser/ParserCache.php @@ -144,7 +144,8 @@ class ParserCache { if ( !$useOutdated && $optionsKey->expired( $article->getTouched() ) ) { wfIncrStats( "pcache_miss_expired" ); $cacheTime = $optionsKey->getCacheTime(); - wfDebug( "Parser options key expired, touched " . $article->getTouched() . ", epoch $wgCacheEpoch, cached $cacheTime\n" ); + wfDebug( "Parser options key expired, touched " . $article->getTouched() + . ", epoch $wgCacheEpoch, cached $cacheTime\n" ); return false; } elseif ( $optionsKey->isDifferentRevision( $article->getLatest() ) ) { wfIncrStats( "pcache_miss_revid" ); @@ -164,7 +165,10 @@ class ParserCache { $usedOptions = ParserOptions::legacyOptions(); } - return $this->getParserOutputKey( $article, $popts->optionsHash( $usedOptions, $article->getTitle() ) ); + return $this->getParserOutputKey( + $article, + $popts->optionsHash( $usedOptions, $article->getTitle() ) + ); } /** @@ -215,7 +219,8 @@ class ParserCache { if ( !$useOutdated && $value->expired( $touched ) ) { wfIncrStats( "pcache_miss_expired" ); $cacheTime = $value->getCacheTime(); - wfDebug( "ParserOutput key expired, touched $touched, epoch $wgCacheEpoch, cached $cacheTime\n" ); + wfDebug( "ParserOutput key expired, touched $touched, " + . "epoch $wgCacheEpoch, cached $cacheTime\n" ); $value = false; } elseif ( $value->isDifferentRevision( $article->getLatest() ) ) { wfIncrStats( "pcache_miss_revid" ); diff --git a/includes/parser/ParserOptions.php b/includes/parser/ParserOptions.php index ba85a669aa..efd5f7436e 100644 --- a/includes/parser/ParserOptions.php +++ b/includes/parser/ParserOptions.php @@ -24,7 +24,8 @@ /** * \brief Set options of the Parser * - * All member variables are supposed to be private in theory, although in practise this is not the case. + * All member variables are supposed to be private in theory, although in + * practise this is not the case. * * @ingroup Parser */ @@ -143,42 +144,134 @@ class ParserOptions { /** @var int Maximum article size of an article to be marked as "stub" */ private $mStubThreshold; - function getInterwikiMagic() { return $this->mInterwikiMagic; } - function getAllowExternalImages() { return $this->mAllowExternalImages; } - function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; } - function getEnableImageWhitelist() { return $this->mEnableImageWhitelist; } - function getEditSection() { return $this->mEditSection; } - function getNumberHeadings() { $this->optionUsed( 'numberheadings' ); - return $this->mNumberHeadings; } - function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; } - function getTidy() { return $this->mTidy; } - function getInterfaceMessage() { return $this->mInterfaceMessage; } - function getTargetLanguage() { return $this->mTargetLanguage; } - function getMaxIncludeSize() { return $this->mMaxIncludeSize; } - function getMaxPPNodeCount() { return $this->mMaxPPNodeCount; } - function getMaxGeneratedPPNodeCount() { return $this->mMaxGeneratedPPNodeCount; } - function getMaxPPExpandDepth() { return $this->mMaxPPExpandDepth; } - function getMaxTemplateDepth() { return $this->mMaxTemplateDepth; } + function getInterwikiMagic() { + return $this->mInterwikiMagic; + } + + function getAllowExternalImages() { + return $this->mAllowExternalImages; + } + + function getAllowExternalImagesFrom() { + return $this->mAllowExternalImagesFrom; + } + + function getEnableImageWhitelist() { + return $this->mEnableImageWhitelist; + } + + function getEditSection() { + return $this->mEditSection; + } + + function getNumberHeadings() { + $this->optionUsed( 'numberheadings' ); + + return $this->mNumberHeadings; + } + + function getAllowSpecialInclusion() { + return $this->mAllowSpecialInclusion; + } + + function getTidy() { + return $this->mTidy; + } + + function getInterfaceMessage() { + return $this->mInterfaceMessage; + } + + function getTargetLanguage() { + return $this->mTargetLanguage; + } + + function getMaxIncludeSize() { + return $this->mMaxIncludeSize; + } + + function getMaxPPNodeCount() { + return $this->mMaxPPNodeCount; + } + + function getMaxGeneratedPPNodeCount() { + return $this->mMaxGeneratedPPNodeCount; + } + + function getMaxPPExpandDepth() { + return $this->mMaxPPExpandDepth; + } + + function getMaxTemplateDepth() { + return $this->mMaxTemplateDepth; + } + /* @since 1.20 */ - function getExpensiveParserFunctionLimit() { return $this->mExpensiveParserFunctionLimit; } - function getRemoveComments() { return $this->mRemoveComments; } - function getTemplateCallback() { return $this->mTemplateCallback; } - function getEnableLimitReport() { return $this->mEnableLimitReport; } - function getCleanSignatures() { return $this->mCleanSignatures; } - function getExternalLinkTarget() { return $this->mExternalLinkTarget; } - function getDisableContentConversion() { return $this->mDisableContentConversion; } - function getDisableTitleConversion() { return $this->mDisableTitleConversion; } - function getThumbSize() { $this->optionUsed( 'thumbsize' ); - return $this->mThumbSize; } - function getStubThreshold() { $this->optionUsed( 'stubthreshold' ); - return $this->mStubThreshold; } - - function getIsPreview() { return $this->mIsPreview; } - function getIsSectionPreview() { return $this->mIsSectionPreview; } - function getIsPrintable() { $this->optionUsed( 'printable' ); - return $this->mIsPrintable; } - function getUser() { return $this->mUser; } - function getPreSaveTransform() { return $this->mPreSaveTransform; } + function getExpensiveParserFunctionLimit() { + return $this->mExpensiveParserFunctionLimit; + } + + function getRemoveComments() { + return $this->mRemoveComments; + } + + function getTemplateCallback() { + return $this->mTemplateCallback; + } + + function getEnableLimitReport() { + return $this->mEnableLimitReport; + } + + function getCleanSignatures() { + return $this->mCleanSignatures; + } + + function getExternalLinkTarget() { + return $this->mExternalLinkTarget; + } + + function getDisableContentConversion() { + return $this->mDisableContentConversion; + } + + function getDisableTitleConversion() { + return $this->mDisableTitleConversion; + } + + function getThumbSize() { + $this->optionUsed( 'thumbsize' ); + + return $this->mThumbSize; + } + + function getStubThreshold() { + $this->optionUsed( 'stubthreshold' ); + + return $this->mStubThreshold; + } + + function getIsPreview() { + return $this->mIsPreview; + } + + function getIsSectionPreview() { + return $this->mIsSectionPreview; + } + + function getIsPrintable() { + $this->optionUsed( 'printable' ); + + return $this->mIsPrintable; + } + + function getUser() { + return $this->mUser; + } + + function getPreSaveTransform() { + return $this->mPreSaveTransform; + } function getDateFormat() { $this->optionUsed( 'dateformat' ); @@ -226,47 +319,139 @@ class ParserOptions { return $this->getUserLangObj()->getCode(); } - function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); } - function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); } - function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); } - function setEnableImageWhitelist( $x ) { return wfSetVar( $this->mEnableImageWhitelist, $x ); } - function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); } - function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); } - function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); } - function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); } - function setTidy( $x ) { return wfSetVar( $this->mTidy, $x ); } + function setInterwikiMagic( $x ) { + return wfSetVar( $this->mInterwikiMagic, $x ); + } + + function setAllowExternalImages( $x ) { + return wfSetVar( $this->mAllowExternalImages, $x ); + } + + function setAllowExternalImagesFrom( $x ) { + return wfSetVar( $this->mAllowExternalImagesFrom, $x ); + } + + function setEnableImageWhitelist( $x ) { + return wfSetVar( $this->mEnableImageWhitelist, $x ); + } + + function setDateFormat( $x ) { + return wfSetVar( $this->mDateFormat, $x ); + } + + function setEditSection( $x ) { + return wfSetVar( $this->mEditSection, $x ); + } + + function setNumberHeadings( $x ) { + return wfSetVar( $this->mNumberHeadings, $x ); + } + + function setAllowSpecialInclusion( $x ) { + return wfSetVar( $this->mAllowSpecialInclusion, $x ); + } + + function setTidy( $x ) { + return wfSetVar( $this->mTidy, $x ); + } /** @deprecated since 1.19 */ - function setSkin( $x ) { wfDeprecated( __METHOD__, '1.19' ); } - function setInterfaceMessage( $x ) { return wfSetVar( $this->mInterfaceMessage, $x ); } - function setTargetLanguage( $x ) { return wfSetVar( $this->mTargetLanguage, $x, true ); } - function setMaxIncludeSize( $x ) { return wfSetVar( $this->mMaxIncludeSize, $x ); } - function setMaxPPNodeCount( $x ) { return wfSetVar( $this->mMaxPPNodeCount, $x ); } - function setMaxGeneratedPPNodeCount( $x ) { return wfSetVar( $this->mMaxGeneratedPPNodeCount, $x ); } - function setMaxTemplateDepth( $x ) { return wfSetVar( $this->mMaxTemplateDepth, $x ); } + function setSkin( $x ) { + wfDeprecated( __METHOD__, '1.19' ); + } + + function setInterfaceMessage( $x ) { + return wfSetVar( $this->mInterfaceMessage, $x ); + } + + function setTargetLanguage( $x ) { + return wfSetVar( $this->mTargetLanguage, $x, true ); + } + + function setMaxIncludeSize( $x ) { + return wfSetVar( $this->mMaxIncludeSize, $x ); + } + + function setMaxPPNodeCount( $x ) { + return wfSetVar( $this->mMaxPPNodeCount, $x ); + } + + function setMaxGeneratedPPNodeCount( $x ) { + return wfSetVar( $this->mMaxGeneratedPPNodeCount, $x ); + } + + function setMaxTemplateDepth( $x ) { + return wfSetVar( $this->mMaxTemplateDepth, $x ); + } + /* @since 1.20 */ - function setExpensiveParserFunctionLimit( $x ) { return wfSetVar( $this->mExpensiveParserFunctionLimit, $x ); } - function setRemoveComments( $x ) { return wfSetVar( $this->mRemoveComments, $x ); } - function setTemplateCallback( $x ) { return wfSetVar( $this->mTemplateCallback, $x ); } - function enableLimitReport( $x = true ) { return wfSetVar( $this->mEnableLimitReport, $x ); } - function setTimestamp( $x ) { return wfSetVar( $this->mTimestamp, $x ); } - function setCleanSignatures( $x ) { return wfSetVar( $this->mCleanSignatures, $x ); } - function setExternalLinkTarget( $x ) { return wfSetVar( $this->mExternalLinkTarget, $x ); } - function disableContentConversion( $x = true ) { return wfSetVar( $this->mDisableContentConversion, $x ); } - function disableTitleConversion( $x = true ) { return wfSetVar( $this->mDisableTitleConversion, $x ); } - function setUserLang( $x ) { + function setExpensiveParserFunctionLimit( $x ) { + return wfSetVar( $this->mExpensiveParserFunctionLimit, $x ); + } + + function setRemoveComments( $x ) { + return wfSetVar( $this->mRemoveComments, $x ); + } + + function setTemplateCallback( $x ) { + return wfSetVar( $this->mTemplateCallback, $x ); + } + + function enableLimitReport( $x = true ) { + return wfSetVar( $this->mEnableLimitReport, $x ); + } + + function setTimestamp( $x ) { + return wfSetVar( $this->mTimestamp, $x ); + } + + function setCleanSignatures( $x ) { + return wfSetVar( $this->mCleanSignatures, $x ); + } + + function setExternalLinkTarget( $x ) { + return wfSetVar( $this->mExternalLinkTarget, $x ); + } + + function disableContentConversion( $x = true ) { + return wfSetVar( $this->mDisableContentConversion, $x ); + } + + function disableTitleConversion( $x = true ) { + return wfSetVar( $this->mDisableTitleConversion, $x ); + } + + function setUserLang( $x ) { if ( is_string( $x ) ) { $x = Language::factory( $x ); } + return wfSetVar( $this->mUserLang, $x ); } - function setThumbSize( $x ) { return wfSetVar( $this->mThumbSize, $x ); } - function setStubThreshold( $x ) { return wfSetVar( $this->mStubThreshold, $x ); } - function setPreSaveTransform( $x ) { return wfSetVar( $this->mPreSaveTransform, $x ); } - function setIsPreview( $x ) { return wfSetVar( $this->mIsPreview, $x ); } - function setIsSectionPreview( $x ) { return wfSetVar( $this->mIsSectionPreview, $x ); } - function setIsPrintable( $x ) { return wfSetVar( $this->mIsPrintable, $x ); } + function setThumbSize( $x ) { + return wfSetVar( $this->mThumbSize, $x ); + } + + function setStubThreshold( $x ) { + return wfSetVar( $this->mStubThreshold, $x ); + } + + function setPreSaveTransform( $x ) { + return wfSetVar( $this->mPreSaveTransform, $x ); + } + + function setIsPreview( $x ) { + return wfSetVar( $this->mIsPreview, $x ); + } + + function setIsSectionPreview( $x ) { + return wfSetVar( $this->mIsSectionPreview, $x ); + } + + function setIsPrintable( $x ) { + return wfSetVar( $this->mIsPrintable, $x ); + } /** * Extra key that should be present in the parser cache key. @@ -397,7 +582,14 @@ class ParserOptions { * @return array */ public static function legacyOptions() { - return array( 'stubthreshold', 'numberheadings', 'userlang', 'thumbsize', 'editsection', 'printable' ); + return array( + 'stubthreshold', + 'numberheadings', + 'userlang', + 'thumbsize', + 'editsection', + 'printable' + ); } /** diff --git a/includes/parser/ParserOutput.php b/includes/parser/ParserOutput.php index 324a2dddc4..74ce3257f0 100644 --- a/includes/parser/ParserOutput.php +++ b/includes/parser/ParserOutput.php @@ -127,7 +127,8 @@ class ParserOutput extends CacheTime { /** @var array Timestamps for getTimeSinceStart() */ private $mParseStartTime = array(); - const EDITSECTION_REGEX = '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)())#'; + const EDITSECTION_REGEX = + '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)())#'; function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(), $containsOldMagic = false, $titletext = '' @@ -186,50 +187,166 @@ class ParserOutput extends CacheTime { return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args ); } - function &getLanguageLinks() { return $this->mLanguageLinks; } - function getInterwikiLinks() { return $this->mInterwikiLinks; } - function getCategoryLinks() { return array_keys( $this->mCategories ); } - function &getCategories() { return $this->mCategories; } - function getTitleText() { return $this->mTitleText; } - function getSections() { return $this->mSections; } - function getEditSectionTokens() { return $this->mEditSectionTokens; } - function &getLinks() { return $this->mLinks; } - function &getTemplates() { return $this->mTemplates; } - function &getTemplateIds() { return $this->mTemplateIds; } - function &getImages() { return $this->mImages; } - function &getFileSearchOptions() { return $this->mFileSearchOptions; } - function &getExternalLinks() { return $this->mExternalLinks; } - function getNoGallery() { return $this->mNoGallery; } - function getHeadItems() { return $this->mHeadItems; } - function getModules() { return $this->mModules; } - function getModuleScripts() { return $this->mModuleScripts; } - function getModuleStyles() { return $this->mModuleStyles; } - function getModuleMessages() { return $this->mModuleMessages; } + function &getLanguageLinks() { + return $this->mLanguageLinks; + } + + function getInterwikiLinks() { + return $this->mInterwikiLinks; + } + + function getCategoryLinks() { + return array_keys( $this->mCategories ); + } + + function &getCategories() { + return $this->mCategories; + } + + function getTitleText() { + return $this->mTitleText; + } + + function getSections() { + return $this->mSections; + } + + function getEditSectionTokens() { + return $this->mEditSectionTokens; + } + + function &getLinks() { + return $this->mLinks; + } + + function &getTemplates() { + return $this->mTemplates; + } + + function &getTemplateIds() { + return $this->mTemplateIds; + } + + function &getImages() { + return $this->mImages; + } + + function &getFileSearchOptions() { + return $this->mFileSearchOptions; + } + + function &getExternalLinks() { + return $this->mExternalLinks; + } + + function getNoGallery() { + return $this->mNoGallery; + } + + function getHeadItems() { + return $this->mHeadItems; + } + + function getModules() { + return $this->mModules; + } + + function getModuleScripts() { + return $this->mModuleScripts; + } + + function getModuleStyles() { + return $this->mModuleStyles; + } + + function getModuleMessages() { + return $this->mModuleMessages; + } + /** @since 1.23 */ - function getJsConfigVars() { return $this->mJsConfigVars; } - function getOutputHooks() { return (array)$this->mOutputHooks; } - function getWarnings() { return array_keys( $this->mWarnings ); } - function getIndexPolicy() { return $this->mIndexPolicy; } - function getTOCHTML() { return $this->mTOCHTML; } - function getTimestamp() { return $this->mTimestamp; } - function getLimitReportData() { return $this->mLimitReportData; } - function getTOCEnabled() { return $this->mTOCEnabled; } - - function setText( $text ) { return wfSetVar( $this->mText, $text ); } - function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); } - function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); } - - function setTitleText( $t ) { return wfSetVar( $this->mTitleText, $t ); } - function setSections( $toc ) { return wfSetVar( $this->mSections, $toc ); } - function setEditSectionTokens( $t ) { return wfSetVar( $this->mEditSectionTokens, $t ); } - function setIndexPolicy( $policy ) { return wfSetVar( $this->mIndexPolicy, $policy ); } - function setTOCHTML( $tochtml ) { return wfSetVar( $this->mTOCHTML, $tochtml ); } - function setTimestamp( $timestamp ) { return wfSetVar( $this->mTimestamp, $timestamp ); } - function setTOCEnabled( $flag ) { return wfSetVar( $this->mTOCEnabled, $flag ); } - - function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; } - function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; } - function addWarning( $s ) { $this->mWarnings[$s] = 1; } + function getJsConfigVars() { + return $this->mJsConfigVars; + } + + function getOutputHooks() { + return (array)$this->mOutputHooks; + } + + function getWarnings() { + return array_keys( $this->mWarnings ); + } + + function getIndexPolicy() { + return $this->mIndexPolicy; + } + + function getTOCHTML() { + return $this->mTOCHTML; + } + + function getTimestamp() { + return $this->mTimestamp; + } + + function getLimitReportData() { + return $this->mLimitReportData; + } + + function getTOCEnabled() { + return $this->mTOCEnabled; + } + + function setText( $text ) { + return wfSetVar( $this->mText, $text ); + } + + function setLanguageLinks( $ll ) { + return wfSetVar( $this->mLanguageLinks, $ll ); + } + + function setCategoryLinks( $cl ) { + return wfSetVar( $this->mCategories, $cl ); + } + + function setTitleText( $t ) { + return wfSetVar( $this->mTitleText, $t ); + } + + function setSections( $toc ) { + return wfSetVar( $this->mSections, $toc ); + } + + function setEditSectionTokens( $t ) { + return wfSetVar( $this->mEditSectionTokens, $t ); + } + + function setIndexPolicy( $policy ) { + return wfSetVar( $this->mIndexPolicy, $policy ); + } + + function setTOCHTML( $tochtml ) { + return wfSetVar( $this->mTOCHTML, $tochtml ); + } + + function setTimestamp( $timestamp ) { + return wfSetVar( $this->mTimestamp, $timestamp ); + } + + function setTOCEnabled( $flag ) { + return wfSetVar( $this->mTOCEnabled, $flag ); + } + + function addCategory( $c, $sort ) { + $this->mCategories[$c] = $sort; + } + + function addLanguageLink( $t ) { + $this->mLanguageLinks[] = $t; + } + + function addWarning( $s ) { + $this->mWarnings[$s] = 1; + } function addOutputHook( $hook, $data = false ) { $this->mOutputHooks[] = array( $hook, $data ); @@ -582,8 +699,8 @@ class ParserOutput extends CacheTime { * extracted from the page's content, including a LinksUpdate object for all links stored in * this ParserOutput object. * - * @note: Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates() instead! The content - * handler may provide additional update objects. + * @note Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates() + * instead! The content handler may provide additional update objects. * * @since 1.20 * diff --git a/includes/parser/Preprocessor.php b/includes/parser/Preprocessor.php index 4cd5694e08..768dc9a677 100644 --- a/includes/parser/Preprocessor.php +++ b/includes/parser/Preprocessor.php @@ -40,7 +40,8 @@ interface Preprocessor { function newFrame(); /** - * Create a new custom frame for programmatic use of parameter replacement as used in some extensions + * Create a new custom frame for programmatic use of parameter replacement + * as used in some extensions. * * @param array $args * @@ -49,7 +50,8 @@ interface Preprocessor { function newCustomFrame( $args ); /** - * Create a new custom node for programmatic use of parameter replacement as used in some extensions + * Create a new custom node for programmatic use of parameter replacement + * as used in some extensions. * * @param array $values */ diff --git a/includes/parser/Preprocessor_DOM.php b/includes/parser/Preprocessor_DOM.php index c5f482d2fd..ca7fd6006a 100644 --- a/includes/parser/Preprocessor_DOM.php +++ b/includes/parser/Preprocessor_DOM.php @@ -70,9 +70,11 @@ class Preprocessor_DOM implements Preprocessor { foreach ( $values as $k => $val ) { if ( is_int( $k ) ) { - $xml .= "" . htmlspecialchars( $val ) . ""; + $xml .= "" + . htmlspecialchars( $val ) . ""; } else { - $xml .= "" . htmlspecialchars( $k ) . "=" . htmlspecialchars( $val ) . ""; + $xml .= "" . htmlspecialchars( $k ) + . "=" . htmlspecialchars( $val ) . ""; } } @@ -108,8 +110,9 @@ class Preprocessor_DOM implements Preprocessor { * * @param string $text The text to parse * @param int $flags Bitwise combination of: - * Parser::PTD_FOR_INCLUSION Handle "" and "" as if the text is being - * included. Default is to assume a direct page view. + * Parser::PTD_FOR_INCLUSION Handle "" and "" + * as if the text is being included. Default + * is to assume a direct page view. * * The generated DOM tree must depend only on the input text and the flags. * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899. @@ -177,7 +180,8 @@ class Preprocessor_DOM implements Preprocessor { if ( !$result ) { // Try running the XML through UtfNormal to get rid of invalid characters $xml = UtfNormal::cleanUp( $xml ); - // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep + // 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 + // don't barf when the XML is >256 levels deep. $result = $dom->loadXML( $xml, 1 << 19 ); } if ( $result ) { @@ -230,7 +234,9 @@ class Preprocessor_DOM implements Preprocessor { $ignoredTags = array( 'includeonly', '/includeonly' ); $ignoredElements = array( 'noinclude' ); $xmlishElements[] = 'noinclude'; - if ( strpos( $text, '' ) !== false && strpos( $text, '' ) !== false ) { + if ( strpos( $text, '' ) !== false + && strpos( $text, '' ) !== false + ) { $enableOnlyinclude = true; } } else { @@ -246,19 +252,28 @@ class Preprocessor_DOM implements Preprocessor { $stack = new PPDStack; $searchBase = "[{<\n"; #} - $revText = strrev( $text ); // For fast reverse searches + // For fast reverse searches + $revText = strrev( $text ); $lengthText = strlen( $text ); - $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start - $accum =& $stack->getAccum(); # Current accumulator + // Input pointer, starts out pointing to a pseudo-newline before the start + $i = 0; + // Current accumulator + $accum =& $stack->getAccum(); $accum = ''; - $findEquals = false; # True to find equals signs in arguments - $findPipe = false; # True to take notice of pipe characters + // True to find equals signs in arguments + $findEquals = false; + // True to take notice of pipe characters + $findPipe = false; $headingIndex = 1; - $inHeading = false; # True if $i is inside a possible heading - $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i - $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next - $fakeLineStart = true; # Do a line-start run without outputting an LF character + // True if $i is inside a possible heading + $inHeading = false; + // True if there are no more greater-than (>) signs right of $i + $noMoreGT = false; + // True to ignore all input up to the next + $findOnlyinclude = $enableOnlyinclude; + // Do a line-start run without outputting an LF character + $fakeLineStart = true; while ( true ) { //$this->memCheck(); @@ -343,7 +358,9 @@ class Preprocessor_DOM implements Preprocessor { if ( $found == 'angle' ) { $matches = false; // Handle - if ( $enableOnlyinclude && substr( $text, $i, strlen( '' ) ) == '' ) { + if ( $enableOnlyinclude + && substr( $text, $i, strlen( '' ) ) == '' + ) { $findOnlyinclude = true; continue; } @@ -457,7 +474,9 @@ class Preprocessor_DOM implements Preprocessor { // Handle ignored tags if ( in_array( $lowerName, $ignoredTags ) ) { - $accum .= '' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . ''; + $accum .= '' + . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) + . ''; $i = $tagEndPos + 1; continue; } @@ -517,9 +536,11 @@ class Preprocessor_DOM implements Preprocessor { $count = strspn( $text, '=', $i, 6 ); if ( $count == 1 && $findEquals ) { - // DWIM: This looks kind of like a name/value separator - // Let's let the equals handler have it and break the potential heading - // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex. + // DWIM: This looks kind of like a name/value separator. + // Let's let the equals handler have it and break the + // potential heading. This is heuristic, but AFAICT the + // methods for completely correct disambiguation are very + // complex. } elseif ( $count > 0 ) { $piece = array( 'open' => "\n", @@ -538,8 +559,9 @@ class Preprocessor_DOM implements Preprocessor { // A heading must be open, otherwise \n wouldn't have been in the search list assert( '$piece->open == "\n"' ); $part = $piece->getCurrentPart(); - // Search back through the input to see if it has a proper close - // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient + // Search back through the input to see if it has a proper close. + // Do this using the reversed string since the other solutions + // (end anchor, etc.) are inefficient. $wsLength = strspn( $revText, " \t", $lengthText - $i ); $searchStart = $i - $wsLength; if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) { @@ -1160,8 +1182,9 @@ class PPFrame_DOM implements PPFrame { ) { $out .= ''; } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) { - # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result - # Not in RECOVER_COMMENTS mode (extractSections) though + # Add a strip marker in PST mode so that pstPass2() can + # run some old-fashioned regexes on the result. + # Not in RECOVER_COMMENTS mode (extractSections) though. $out .= $this->parser->insertStripItem( $contextNode->textContent ); } else { # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove @@ -1172,7 +1195,9 @@ class PPFrame_DOM implements PPFrame { # OT_WIKI will only respect in substed templates. # The other output types respect it unless NO_IGNORE is set. # extractSections() sets NO_IGNORE and so never respects it. - if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) { + if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) + || ( $flags & PPFrame::NO_IGNORE ) + ) { $out .= $contextNode->textContent; } else { $out .= ''; @@ -1467,7 +1492,9 @@ class PPTemplateFrame_DOM extends PPFrame_DOM { * @param array $namedArgs * @param Title $title */ - function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) { + function __construct( $preprocessor, $parent = false, $numberedArgs = array(), + $namedArgs = array(), $title = false + ) { parent::__construct( $preprocessor ); $this->parent = $parent; @@ -1543,7 +1570,10 @@ class PPTemplateFrame_DOM extends PPFrame_DOM { } if ( !isset( $this->numberedExpansionCache[$index] ) ) { # No trimming for unnamed arguments - $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS ); + $this->numberedExpansionCache[$index] = $this->parent->expand( + $this->numberedArgs[$index], + PPFrame::STRIP_COMMENTS + ); } return $this->numberedExpansionCache[$index]; } diff --git a/includes/parser/Preprocessor_Hash.php b/includes/parser/Preprocessor_Hash.php index 27577669ec..137f885617 100644 --- a/includes/parser/Preprocessor_Hash.php +++ b/includes/parser/Preprocessor_Hash.php @@ -112,7 +112,9 @@ class Preprocessor_Hash implements Preprocessor { // Check cache. global $wgMemc, $wgPreprocessorCacheThreshold; - $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold; + $cacheable = $wgPreprocessorCacheThreshold !== false + && strlen( $text ) > $wgPreprocessorCacheThreshold; + if ( $cacheable ) { wfProfileIn( __METHOD__ . '-cacheable' ); @@ -159,7 +161,9 @@ class Preprocessor_Hash implements Preprocessor { $ignoredTags = array( 'includeonly', '/includeonly' ); $ignoredElements = array( 'noinclude' ); $xmlishElements[] = 'noinclude'; - if ( strpos( $text, '' ) !== false && strpos( $text, '' ) !== false ) { + if ( strpos( $text, '' ) !== false + && strpos( $text, '' ) !== false + ) { $enableOnlyinclude = true; } } else { @@ -175,18 +179,27 @@ class Preprocessor_Hash implements Preprocessor { $stack = new PPDStack_Hash; $searchBase = "[{<\n"; - $revText = strrev( $text ); // For fast reverse searches + // For fast reverse searches + $revText = strrev( $text ); $lengthText = strlen( $text ); - $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start - $accum =& $stack->getAccum(); # Current accumulator - $findEquals = false; # True to find equals signs in arguments - $findPipe = false; # True to take notice of pipe characters + // Input pointer, starts out pointing to a pseudo-newline before the start + $i = 0; + // Current accumulator + $accum =& $stack->getAccum(); + // True to find equals signs in arguments + $findEquals = false; + // True to take notice of pipe characters + $findPipe = false; $headingIndex = 1; - $inHeading = false; # True if $i is inside a possible heading - $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i - $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next - $fakeLineStart = true; # Do a line-start run without outputting an LF character + // True if $i is inside a possible heading + $inHeading = false; + // True if there are no more greater-than (>) signs right of $i + $noMoreGT = false; + // True to ignore all input up to the next + $findOnlyinclude = $enableOnlyinclude; + // Do a line-start run without outputting an LF character + $fakeLineStart = true; while ( true ) { //$this->memCheck(); @@ -271,7 +284,9 @@ class Preprocessor_Hash implements Preprocessor { if ( $found == 'angle' ) { $matches = false; // Handle - if ( $enableOnlyinclude && substr( $text, $i, strlen( '' ) ) == '' ) { + if ( $enableOnlyinclude + && substr( $text, $i, strlen( '' ) ) == '' + ) { $findOnlyinclude = true; continue; } @@ -450,9 +465,10 @@ class Preprocessor_Hash implements Preprocessor { $count = strspn( $text, '=', $i, 6 ); if ( $count == 1 && $findEquals ) { - // DWIM: This looks kind of like a name/value separator - // Let's let the equals handler have it and break the potential heading - // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex. + // DWIM: This looks kind of like a name/value separator. + // Let's let the equals handler have it and break the potential + // heading. This is heuristic, but AFAICT the methods for + // completely correct disambiguation are very complex. } elseif ( $count > 0 ) { $piece = array( 'open' => "\n", @@ -470,8 +486,9 @@ class Preprocessor_Hash implements Preprocessor { // A heading must be open, otherwise \n wouldn't have been in the search list assert( '$piece->open == "\n"' ); $part = $piece->getCurrentPart(); - // Search back through the input to see if it has a proper close - // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient + // Search back through the input to see if it has a proper close. + // Do this using the reversed string since the other solutions + // (end anchor, etc.) are inefficient. $wsLength = strspn( $revText, " \t", $lengthText - $i ); $searchStart = $i - $wsLength; if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) { @@ -1034,7 +1051,11 @@ class PPFrame_Hash implements PPFrame { # Double-brace expansion $bits = $contextNode->splitTemplate(); if ( $flags & PPFrame::NO_TEMPLATES ) { - $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] ); + $newIterator = $this->virtualBracketedImplode( + '{{', '|', '}}', + $bits['title'], + $bits['parts'] + ); } else { $ret = $this->parser->braceSubstitution( $bits, $this ); if ( isset( $ret['object'] ) ) { @@ -1047,7 +1068,11 @@ class PPFrame_Hash implements PPFrame { # Triple-brace expansion $bits = $contextNode->splitTemplate(); if ( $flags & PPFrame::NO_ARGS ) { - $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] ); + $newIterator = $this->virtualBracketedImplode( + '{{{', '|', '}}}', + $bits['title'], + $bits['parts'] + ); } else { $ret = $this->parser->argSubstitution( $bits, $this ); if ( isset( $ret['object'] ) ) { @@ -1065,8 +1090,9 @@ class PPFrame_Hash implements PPFrame { ) { $out .= ''; } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) { - # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result - # Not in RECOVER_COMMENTS mode (extractSections) though + # Add a strip marker in PST mode so that pstPass2() can + # run some old-fashioned regexes on the result. + # Not in RECOVER_COMMENTS mode (extractSections) though. $out .= $this->parser->insertStripItem( $contextNode->firstChild->value ); } else { # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove @@ -1077,7 +1103,9 @@ class PPFrame_Hash implements PPFrame { # OT_WIKI will only respect in substed templates. # The other output types respect it unless NO_IGNORE is set. # extractSections() sets NO_IGNORE and so never respects it. - if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) { + if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) + || ( $flags & PPFrame::NO_IGNORE ) + ) { $out .= $contextNode->firstChild->value; } else { //$out .= ''; @@ -1369,7 +1397,9 @@ class PPTemplateFrame_Hash extends PPFrame_Hash { * @param array $namedArgs * @param Title $title */ - function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) { + function __construct( $preprocessor, $parent = false, $numberedArgs = array(), + $namedArgs = array(), $title = false + ) { parent::__construct( $preprocessor ); $this->parent = $parent; @@ -1458,7 +1488,10 @@ class PPTemplateFrame_Hash extends PPFrame_Hash { } if ( !isset( $this->numberedExpansionCache[$index] ) ) { # No trimming for unnamed arguments - $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS ); + $this->numberedExpansionCache[$index] = $this->parent->expand( + $this->numberedArgs[$index], + PPFrame::STRIP_COMMENTS + ); } return $this->numberedExpansionCache[$index]; } @@ -1804,15 +1837,41 @@ class PPNode_Hash_Text implements PPNode { return $this->nextSibling; } - function getChildren() { return false; } - function getFirstChild() { return false; } - function getChildrenOfType( $name ) { return false; } - function getLength() { return false; } - function item( $i ) { return false; } - function getName() { return '#text'; } - function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); } - function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); } - function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); } + function getChildren() { + return false; + } + + function getFirstChild() { + return false; + } + + function getChildrenOfType( $name ) { + return false; + } + + function getLength() { + return false; + } + + function item( $i ) { + return false; + } + + function getName() { + return '#text'; + } + + function splitArg() { + throw new MWException( __METHOD__ . ': not supported' ); + } + + function splitExt() { + throw new MWException( __METHOD__ . ': not supported' ); + } + + function splitHeading() { + throw new MWException( __METHOD__ . ': not supported' ); + } } /** @@ -1839,18 +1898,37 @@ class PPNode_Hash_Array implements PPNode { return $this->value[$i]; } - function getName() { return '#nodelist'; } + function getName() { + return '#nodelist'; + } function getNextSibling() { return $this->nextSibling; } - function getChildren() { return false; } - function getFirstChild() { return false; } - function getChildrenOfType( $name ) { return false; } - function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); } - function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); } - function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); } + function getChildren() { + return false; + } + + function getFirstChild() { + return false; + } + + function getChildrenOfType( $name ) { + return false; + } + + function splitArg() { + throw new MWException( __METHOD__ . ': not supported' ); + } + + function splitExt() { + throw new MWException( __METHOD__ . ': not supported' ); + } + + function splitHeading() { + throw new MWException( __METHOD__ . ': not supported' ); + } } /** @@ -1882,12 +1960,35 @@ class PPNode_Hash_Attr implements PPNode { return $this->nextSibling; } - function getChildren() { return false; } - function getFirstChild() { return false; } - function getChildrenOfType( $name ) { return false; } - function getLength() { return false; } - function item( $i ) { return false; } - function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); } - function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); } - function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); } + function getChildren() { + return false; + } + + function getFirstChild() { + return false; + } + + function getChildrenOfType( $name ) { + return false; + } + + function getLength() { + return false; + } + + function item( $i ) { + return false; + } + + function splitArg() { + throw new MWException( __METHOD__ . ': not supported' ); + } + + function splitExt() { + throw new MWException( __METHOD__ . ': not supported' ); + } + + function splitHeading() { + throw new MWException( __METHOD__ . ': not supported' ); + } } -- 2.20.1