3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
118 # Markers used for wrapping the table of contents
119 const TOC_START
= '<mw:toc>';
120 const TOC_END
= '</mw:toc>';
123 public $mTagHooks = array();
124 public $mTransparentTagHooks = array();
125 public $mFunctionHooks = array();
126 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
127 public $mFunctionTagHooks = array();
128 public $mStripList = array();
129 public $mDefaultStripList = array();
130 public $mVarCache = array();
131 public $mImageParams = array();
132 public $mImageParamsMagicArray = array();
133 public $mMarkerIndex = 0;
134 public $mFirstCall = true;
136 # Initialised by initialiseVariables()
139 * @var MagicWordArray
144 * @var MagicWordArray
147 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
149 # Cleared with clearState():
154 public $mAutonumber, $mDTopen;
161 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
163 * @var LinkHolderArray
165 public $mLinkHolders;
168 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
169 public $mDefaultSort;
170 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
171 public $mExpensiveFunctionCount; # number of expensive parser function calls
172 public $mShowToc, $mForceTocPosition;
177 public $mUser; # User object; only used when doing pre-save transform
180 # These are variables reset at least once per parse regardless of $clearState
190 public $mTitle; # Title context, used for self-link rendering and similar things
191 public $mOutputType; # Output type, one of the OT_xxx constants
192 public $ot; # Shortcut alias, see setOutputType()
193 public $mRevisionObject; # The revision object of the specified revision ID
194 public $mRevisionId; # ID to display in {{REVISIONID}} tags
195 public $mRevisionTimestamp; # The timestamp of the specified revision ID
196 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
197 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
198 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
199 public $mInputSize = false; # For {{PAGESIZE}} on current page.
207 * @var array Array with the language name of each language link (i.e. the
208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
209 * duplicate language links to the ParserOutput.
211 public $mLangLinkLanguages;
214 * @var bool Recursive call protection.
215 * This variable should be treated as if it were private.
217 public $mInParse = false;
222 public function __construct( $conf = array() ) {
223 $this->mConf
= $conf;
224 $this->mUrlProtocols
= wfUrlProtocols();
225 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
226 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
227 if ( isset( $conf['preprocessorClass'] ) ) {
228 $this->mPreprocessorClass
= $conf['preprocessorClass'];
229 } elseif ( defined( 'HPHP_VERSION' ) ) {
230 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
231 $this->mPreprocessorClass
= 'Preprocessor_Hash';
232 } elseif ( extension_loaded( 'domxml' ) ) {
233 # PECL extension that conflicts with the core DOM extension (bug 13770)
234 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
235 $this->mPreprocessorClass
= 'Preprocessor_Hash';
236 } elseif ( extension_loaded( 'dom' ) ) {
237 $this->mPreprocessorClass
= 'Preprocessor_DOM';
239 $this->mPreprocessorClass
= 'Preprocessor_Hash';
241 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
245 * Reduce memory usage to reduce the impact of circular references
247 public function __destruct() {
248 if ( isset( $this->mLinkHolders
) ) {
249 unset( $this->mLinkHolders
);
251 foreach ( $this as $name => $value ) {
252 unset( $this->$name );
257 * Allow extensions to clean up when the parser is cloned
259 public function __clone() {
260 $this->mInParse
= false;
262 // Bug 56226: When you create a reference "to" an object field, that
263 // makes the object field itself be a reference too (until the other
264 // reference goes out of scope). When cloning, any field that's a
265 // reference is copied as a reference in the new object. Both of these
266 // are defined PHP5 behaviors, as inconvenient as it is for us when old
267 // hooks from PHP4 days are passing fields by reference.
268 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
269 // Make a non-reference copy of the field, then rebind the field to
270 // reference the new copy.
276 wfRunHooks( 'ParserCloned', array( $this ) );
280 * Do various kinds of initialisation on the first call of the parser
282 public function firstCallInit() {
283 if ( !$this->mFirstCall
) {
286 $this->mFirstCall
= false;
288 wfProfileIn( __METHOD__
);
290 CoreParserFunctions
::register( $this );
291 CoreTagHooks
::register( $this );
292 $this->initialiseVariables();
294 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
295 wfProfileOut( __METHOD__
);
303 public function clearState() {
304 wfProfileIn( __METHOD__
);
305 if ( $this->mFirstCall
) {
306 $this->firstCallInit();
308 $this->mOutput
= new ParserOutput
;
309 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
310 $this->mAutonumber
= 0;
311 $this->mLastSection
= '';
312 $this->mDTopen
= false;
313 $this->mIncludeCount
= array();
314 $this->mArgStack
= false;
315 $this->mInPre
= false;
316 $this->mLinkHolders
= new LinkHolderArray( $this );
318 $this->mRevisionObject
= $this->mRevisionTimestamp
=
319 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
320 $this->mVarCache
= array();
322 $this->mLangLinkLanguages
= array();
325 * Prefix for temporary replacement strings for the multipass parser.
326 * \x07 should never appear in input as it's disallowed in XML.
327 * Using it at the front also gives us a little extra robustness
328 * since it shouldn't match when butted up against identifier-like
331 * Must not consist of all title characters, or else it will change
332 * the behavior of <nowiki> in a link.
334 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
335 $this->mStripState
= new StripState( $this->mUniqPrefix
);
337 # Clear these on every parse, bug 4549
338 $this->mTplRedirCache
= $this->mTplDomCache
= array();
340 $this->mShowToc
= true;
341 $this->mForceTocPosition
= false;
342 $this->mIncludeSizes
= array(
346 $this->mPPNodeCount
= 0;
347 $this->mGeneratedPPNodeCount
= 0;
348 $this->mHighestExpansionDepth
= 0;
349 $this->mDefaultSort
= false;
350 $this->mHeadings
= array();
351 $this->mDoubleUnderscores
= array();
352 $this->mExpensiveFunctionCount
= 0;
355 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
356 $this->mPreprocessor
= null;
359 wfRunHooks( 'ParserClearState', array( &$this ) );
360 wfProfileOut( __METHOD__
);
364 * Convert wikitext to HTML
365 * Do not call this function recursively.
367 * @param string $text Text we want to parse
368 * @param Title $title
369 * @param ParserOptions $options
370 * @param bool $linestart
371 * @param bool $clearState
372 * @param int $revid Number to pass in {{REVISIONID}}
373 * @return ParserOutput A ParserOutput
375 public function parse( $text, Title
$title, ParserOptions
$options,
376 $linestart = true, $clearState = true, $revid = null
379 * First pass--just handle <nowiki> sections, pass the rest off
380 * to internalParse() which does all the real work.
383 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
384 $fname = __METHOD__
. '-' . wfGetCaller();
385 wfProfileIn( __METHOD__
);
386 wfProfileIn( $fname );
389 $magicScopeVariable = $this->lock();
392 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
394 $this->mInputSize
= strlen( $text );
395 if ( $this->mOptions
->getEnableLimitReport() ) {
396 $this->mOutput
->resetParseStartTime();
399 # Remove the strip marker tag prefix from the input, if present.
401 $text = str_replace( $this->mUniqPrefix
, '', $text );
404 $oldRevisionId = $this->mRevisionId
;
405 $oldRevisionObject = $this->mRevisionObject
;
406 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
407 $oldRevisionUser = $this->mRevisionUser
;
408 $oldRevisionSize = $this->mRevisionSize
;
409 if ( $revid !== null ) {
410 $this->mRevisionId
= $revid;
411 $this->mRevisionObject
= null;
412 $this->mRevisionTimestamp
= null;
413 $this->mRevisionUser
= null;
414 $this->mRevisionSize
= null;
417 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
419 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
420 $text = $this->internalParse( $text );
421 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
423 $text = $this->mStripState
->unstripGeneral( $text );
425 # Clean up special characters, only run once, next-to-last before doBlockLevels
427 # french spaces, last one Guillemet-left
428 # only if there is something before the space
429 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
430 # french spaces, Guillemet-right
431 '/(\\302\\253) /' => '\\1 ',
432 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
434 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
436 $text = $this->doBlockLevels( $text, $linestart );
438 $this->replaceLinkHolders( $text );
441 * The input doesn't get language converted if
443 * b) Content isn't converted
444 * c) It's a conversion table
445 * d) it is an interface message (which is in the user language)
447 if ( !( $options->getDisableContentConversion()
448 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
450 if ( !$this->mOptions
->getInterfaceMessage() ) {
451 # The position of the convert() call should not be changed. it
452 # assumes that the links are all replaced and the only thing left
453 # is the <nowiki> mark.
454 $text = $this->getConverterLanguage()->convert( $text );
459 * A converted title will be provided in the output object if title and
460 * content conversion are enabled, the article text does not contain
461 * a conversion-suppressing double-underscore tag, and no
462 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
463 * automatic link conversion.
465 if ( !( $options->getDisableTitleConversion()
466 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
467 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
468 ||
$this->mOutput
->getDisplayTitle() !== false )
470 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
471 if ( $convruletitle ) {
472 $this->mOutput
->setTitleText( $convruletitle );
474 $titleText = $this->getConverterLanguage()->convertTitle( $title );
475 $this->mOutput
->setTitleText( $titleText );
479 $text = $this->mStripState
->unstripNoWiki( $text );
481 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
483 $text = $this->replaceTransparentTags( $text );
484 $text = $this->mStripState
->unstripGeneral( $text );
486 $text = Sanitizer
::normalizeCharReferences( $text );
488 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
489 $text = MWTidy
::tidy( $text );
491 # attempt to sanitize at least some nesting problems
492 # (bug #2702 and quite a few others)
494 # ''Something [http://www.cool.com cool''] -->
495 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
496 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
497 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
498 # fix up an anchor inside another anchor, only
499 # at least for a single single nested link (bug 3695)
500 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
501 '\\1\\2</a>\\3</a>\\1\\4</a>',
502 # fix div inside inline elements- doBlockLevels won't wrap a line which
503 # contains a div, so fix it up here; replace
504 # div with escaped text
505 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
506 '\\1\\3<div\\5>\\6</div>\\8\\9',
507 # remove empty italic or bold tag pairs, some
508 # introduced by rules above
509 '/<([bi])><\/\\1>/' => '',
512 $text = preg_replace(
513 array_keys( $tidyregs ),
514 array_values( $tidyregs ),
518 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
519 $this->limitationWarn( 'expensive-parserfunction',
520 $this->mExpensiveFunctionCount
,
521 $this->mOptions
->getExpensiveParserFunctionLimit()
525 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
527 # Information on include size limits, for the benefit of users who try to skirt them
528 if ( $this->mOptions
->getEnableLimitReport() ) {
529 $max = $this->mOptions
->getMaxIncludeSize();
531 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
532 if ( $cpuTime !== null ) {
533 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
534 sprintf( "%.3f", $cpuTime )
538 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
539 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
540 sprintf( "%.3f", $wallTime )
543 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
544 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
546 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
547 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
549 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
550 array( $this->mIncludeSizes
['post-expand'], $max )
552 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
553 array( $this->mIncludeSizes
['arg'], $max )
555 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
556 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
558 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
559 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
561 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
563 $limitReport = "NewPP limit report\n";
564 if ( $wgShowHostnames ) {
565 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
567 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
568 if ( wfRunHooks( 'ParserLimitReportFormat',
569 array( $key, &$value, &$limitReport, false, false )
571 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
572 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
573 ->inLanguage( 'en' )->useDatabase( false );
574 if ( !$valueMsg->exists() ) {
575 $valueMsg = new RawMessage( '$1' );
577 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
578 $valueMsg->params( $value );
579 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
583 // Since we're not really outputting HTML, decode the entities and
584 // then re-encode the things that need hiding inside HTML comments.
585 $limitReport = htmlspecialchars_decode( $limitReport );
586 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
588 // Sanitize for comment. Note '‐' in the replacement is U+2010,
589 // which looks much like the problematic '-'.
590 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
591 $text .= "\n<!-- \n$limitReport-->\n";
593 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
594 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
595 $this->mTitle
->getPrefixedDBkey() );
598 $this->mOutput
->setText( $text );
600 $this->mRevisionId
= $oldRevisionId;
601 $this->mRevisionObject
= $oldRevisionObject;
602 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
603 $this->mRevisionUser
= $oldRevisionUser;
604 $this->mRevisionSize
= $oldRevisionSize;
605 $this->mInputSize
= false;
606 wfProfileOut( $fname );
607 wfProfileOut( __METHOD__
);
609 return $this->mOutput
;
613 * Recursive parser entry point that can be called from an extension tag
616 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
618 * @param string $text Text extension wants to have parsed
619 * @param bool|PPFrame $frame The frame to use for expanding any template variables
623 public function recursiveTagParse( $text, $frame = false ) {
624 wfProfileIn( __METHOD__
);
625 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
626 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
627 $text = $this->internalParse( $text, false, $frame );
628 wfProfileOut( __METHOD__
);
633 * Expand templates and variables in the text, producing valid, static wikitext.
634 * Also removes comments.
635 * Do not call this function recursively.
636 * @param string $text
637 * @param Title $title
638 * @param ParserOptions $options
639 * @param int|null $revid
640 * @param bool|PPFrame $frame
641 * @return mixed|string
643 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
644 wfProfileIn( __METHOD__
);
645 $magicScopeVariable = $this->lock();
646 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
647 if ( $revid !== null ) {
648 $this->mRevisionId
= $revid;
650 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
651 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
652 $text = $this->replaceVariables( $text, $frame );
653 $text = $this->mStripState
->unstripBoth( $text );
654 wfProfileOut( __METHOD__
);
659 * Recursive parser entry point that can be called from an extension tag
662 * @param string $text Text to be expanded
663 * @param bool|PPFrame $frame The frame to use for expanding any template variables
667 public function recursivePreprocess( $text, $frame = false ) {
668 wfProfileIn( __METHOD__
);
669 $text = $this->replaceVariables( $text, $frame );
670 $text = $this->mStripState
->unstripBoth( $text );
671 wfProfileOut( __METHOD__
);
676 * Process the wikitext for the "?preload=" feature. (bug 5210)
678 * "<noinclude>", "<includeonly>" etc. are parsed as for template
679 * transclusion, comments, templates, arguments, tags hooks and parser
680 * functions are untouched.
682 * @param string $text
683 * @param Title $title
684 * @param ParserOptions $options
685 * @param array $params
688 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
689 $msg = new RawMessage( $text );
690 $text = $msg->params( $params )->plain();
692 # Parser (re)initialisation
693 $magicScopeVariable = $this->lock();
694 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
696 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
697 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
698 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
699 $text = $this->mStripState
->unstripBoth( $text );
704 * Get a random string
708 public static function getRandomString() {
709 return wfRandomString( 16 );
713 * Set the current user.
714 * Should only be used when doing pre-save transform.
716 * @param User|null $user User object or null (to reset)
718 public function setUser( $user ) {
719 $this->mUser
= $user;
723 * Accessor for mUniqPrefix.
727 public function uniqPrefix() {
728 if ( !isset( $this->mUniqPrefix
) ) {
729 # @todo FIXME: This is probably *horribly wrong*
730 # LanguageConverter seems to want $wgParser's uniqPrefix, however
731 # if this is called for a parser cache hit, the parser may not
732 # have ever been initialized in the first place.
733 # Not really sure what the heck is supposed to be going on here.
735 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
737 return $this->mUniqPrefix
;
741 * Set the context title
745 public function setTitle( $t ) {
747 $t = Title
::newFromText( 'NO TITLE' );
750 if ( $t->hasFragment() ) {
751 # Strip the fragment to avoid various odd effects
752 $this->mTitle
= clone $t;
753 $this->mTitle
->setFragment( '' );
760 * Accessor for the Title object
764 public function getTitle() {
765 return $this->mTitle
;
769 * Accessor/mutator for the Title object
771 * @param Title $x Title object or null to just get the current one
774 public function Title( $x = null ) {
775 return wfSetVar( $this->mTitle
, $x );
779 * Set the output type
781 * @param int $ot New value
783 public function setOutputType( $ot ) {
784 $this->mOutputType
= $ot;
787 'html' => $ot == self
::OT_HTML
,
788 'wiki' => $ot == self
::OT_WIKI
,
789 'pre' => $ot == self
::OT_PREPROCESS
,
790 'plain' => $ot == self
::OT_PLAIN
,
795 * Accessor/mutator for the output type
797 * @param int|null $x New value or null to just get the current one
800 public function OutputType( $x = null ) {
801 return wfSetVar( $this->mOutputType
, $x );
805 * Get the ParserOutput object
807 * @return ParserOutput
809 public function getOutput() {
810 return $this->mOutput
;
814 * Get the ParserOptions object
816 * @return ParserOptions
818 public function getOptions() {
819 return $this->mOptions
;
823 * Accessor/mutator for the ParserOptions object
825 * @param ParserOptions $x New value or null to just get the current one
826 * @return ParserOptions Current ParserOptions object
828 public function Options( $x = null ) {
829 return wfSetVar( $this->mOptions
, $x );
835 public function nextLinkID() {
836 return $this->mLinkID++
;
842 public function setLinkID( $id ) {
843 $this->mLinkID
= $id;
847 * Get a language object for use in parser functions such as {{FORMATNUM:}}
850 public function getFunctionLang() {
851 return $this->getTargetLanguage();
855 * Get the target language for the content being parsed. This is usually the
856 * language that the content is in.
860 * @throws MWException
863 public function getTargetLanguage() {
864 $target = $this->mOptions
->getTargetLanguage();
866 if ( $target !== null ) {
868 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
869 return $this->mOptions
->getUserLangObj();
870 } elseif ( is_null( $this->mTitle
) ) {
871 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
874 return $this->mTitle
->getPageLanguage();
878 * Get the language object for language conversion
879 * @return Language|null
881 public function getConverterLanguage() {
882 return $this->getTargetLanguage();
886 * Get a User object either from $this->mUser, if set, or from the
887 * ParserOptions object otherwise
891 public function getUser() {
892 if ( !is_null( $this->mUser
) ) {
895 return $this->mOptions
->getUser();
899 * Get a preprocessor object
901 * @return Preprocessor
903 public function getPreprocessor() {
904 if ( !isset( $this->mPreprocessor
) ) {
905 $class = $this->mPreprocessorClass
;
906 $this->mPreprocessor
= new $class( $this );
908 return $this->mPreprocessor
;
912 * Replaces all occurrences of HTML-style comments and the given tags
913 * in the text with a random marker and returns the next text. The output
914 * parameter $matches will be an associative array filled with data in
918 * 'UNIQ-xxxxx' => array(
921 * array( 'param' => 'x' ),
922 * '<element param="x">tag content</element>' ) )
925 * @param array $elements List of element names. Comments are always extracted.
926 * @param string $text Source text string.
927 * @param array $matches Out parameter, Array: extracted tags
928 * @param string $uniq_prefix
929 * @return string Stripped text
931 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
936 $taglist = implode( '|', $elements );
937 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
939 while ( $text != '' ) {
940 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
942 if ( count( $p ) < 5 ) {
945 if ( count( $p ) > 5 ) {
959 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
960 $stripped .= $marker;
962 if ( $close === '/>' ) {
963 # Empty element tag, <tag />
968 if ( $element === '!--' ) {
971 $end = "/(<\\/$element\\s*>)/i";
973 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
975 if ( count( $q ) < 3 ) {
976 # No end tag -- let it run out to the end of the text.
985 $matches[$marker] = array( $element,
987 Sanitizer
::decodeTagAttributes( $attributes ),
988 "<$element$attributes$close$content$tail" );
994 * Get a list of strippable XML-like elements
998 public function getStripList() {
999 return $this->mStripList
;
1003 * Add an item to the strip state
1004 * Returns the unique tag which must be inserted into the stripped text
1005 * The tag will be replaced with the original text in unstrip()
1007 * @param string $text
1011 public function insertStripItem( $text ) {
1012 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1013 $this->mMarkerIndex++
;
1014 $this->mStripState
->addGeneral( $rnd, $text );
1019 * parse the wiki syntax used to render tables
1022 * @param string $text
1025 public function doTableStuff( $text ) {
1026 wfProfileIn( __METHOD__
);
1028 $lines = StringUtils
::explode( "\n", $text );
1030 $td_history = array(); # Is currently a td tag open?
1031 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1032 $tr_history = array(); # Is currently a tr tag open?
1033 $tr_attributes = array(); # history of tr attributes
1034 $has_opened_tr = array(); # Did this table open a <tr> element?
1035 $indent_level = 0; # indent level of the table
1037 foreach ( $lines as $outLine ) {
1038 $line = trim( $outLine );
1040 if ( $line === '' ) { # empty line, go to next line
1041 $out .= $outLine . "\n";
1045 $first_character = $line[0];
1048 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1049 # First check if we are starting a new table
1050 $indent_level = strlen( $matches[1] );
1052 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1053 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1055 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1056 array_push( $td_history, false );
1057 array_push( $last_tag_history, '' );
1058 array_push( $tr_history, false );
1059 array_push( $tr_attributes, '' );
1060 array_push( $has_opened_tr, false );
1061 } elseif ( count( $td_history ) == 0 ) {
1062 # Don't do any of the following
1063 $out .= $outLine . "\n";
1065 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1066 # We are ending a table
1067 $line = '</table>' . substr( $line, 2 );
1068 $last_tag = array_pop( $last_tag_history );
1070 if ( !array_pop( $has_opened_tr ) ) {
1071 $line = "<tr><td></td></tr>{$line}";
1074 if ( array_pop( $tr_history ) ) {
1075 $line = "</tr>{$line}";
1078 if ( array_pop( $td_history ) ) {
1079 $line = "</{$last_tag}>{$line}";
1081 array_pop( $tr_attributes );
1082 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1083 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1084 # Now we have a table row
1085 $line = preg_replace( '#^\|-+#', '', $line );
1087 # Whats after the tag is now only attributes
1088 $attributes = $this->mStripState
->unstripBoth( $line );
1089 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1090 array_pop( $tr_attributes );
1091 array_push( $tr_attributes, $attributes );
1094 $last_tag = array_pop( $last_tag_history );
1095 array_pop( $has_opened_tr );
1096 array_push( $has_opened_tr, true );
1098 if ( array_pop( $tr_history ) ) {
1102 if ( array_pop( $td_history ) ) {
1103 $line = "</{$last_tag}>{$line}";
1107 array_push( $tr_history, false );
1108 array_push( $td_history, false );
1109 array_push( $last_tag_history, '' );
1110 } elseif ( $first_character === '|'
1111 ||
$first_character === '!'
1112 ||
substr( $line, 0, 2 ) === '|+'
1114 # This might be cell elements, td, th or captions
1115 if ( substr( $line, 0, 2 ) === '|+' ) {
1116 $first_character = '+';
1117 $line = substr( $line, 1 );
1120 $line = substr( $line, 1 );
1122 if ( $first_character === '!' ) {
1123 $line = str_replace( '!!', '||', $line );
1126 # Split up multiple cells on the same line.
1127 # FIXME : This can result in improper nesting of tags processed
1128 # by earlier parser steps, but should avoid splitting up eg
1129 # attribute values containing literal "||".
1130 $cells = StringUtils
::explodeMarkup( '||', $line );
1134 # Loop through each table cell
1135 foreach ( $cells as $cell ) {
1137 if ( $first_character !== '+' ) {
1138 $tr_after = array_pop( $tr_attributes );
1139 if ( !array_pop( $tr_history ) ) {
1140 $previous = "<tr{$tr_after}>\n";
1142 array_push( $tr_history, true );
1143 array_push( $tr_attributes, '' );
1144 array_pop( $has_opened_tr );
1145 array_push( $has_opened_tr, true );
1148 $last_tag = array_pop( $last_tag_history );
1150 if ( array_pop( $td_history ) ) {
1151 $previous = "</{$last_tag}>\n{$previous}";
1154 if ( $first_character === '|' ) {
1156 } elseif ( $first_character === '!' ) {
1158 } elseif ( $first_character === '+' ) {
1159 $last_tag = 'caption';
1164 array_push( $last_tag_history, $last_tag );
1166 # A cell could contain both parameters and data
1167 $cell_data = explode( '|', $cell, 2 );
1169 # Bug 553: Note that a '|' inside an invalid link should not
1170 # be mistaken as delimiting cell parameters
1171 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1172 $cell = "{$previous}<{$last_tag}>{$cell}";
1173 } elseif ( count( $cell_data ) == 1 ) {
1174 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1176 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1177 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1178 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1182 array_push( $td_history, true );
1185 $out .= $outLine . "\n";
1188 # Closing open td, tr && table
1189 while ( count( $td_history ) > 0 ) {
1190 if ( array_pop( $td_history ) ) {
1193 if ( array_pop( $tr_history ) ) {
1196 if ( !array_pop( $has_opened_tr ) ) {
1197 $out .= "<tr><td></td></tr>\n";
1200 $out .= "</table>\n";
1203 # Remove trailing line-ending (b/c)
1204 if ( substr( $out, -1 ) === "\n" ) {
1205 $out = substr( $out, 0, -1 );
1208 # special case: don't return empty table
1209 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1213 wfProfileOut( __METHOD__
);
1219 * Helper function for parse() that transforms wiki markup into
1220 * HTML. Only called for $mOutputType == self::OT_HTML.
1224 * @param string $text
1225 * @param bool $isMain
1226 * @param bool $frame
1230 public function internalParse( $text, $isMain = true, $frame = false ) {
1231 wfProfileIn( __METHOD__
);
1235 # Hook to suspend the parser in this state
1236 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1237 wfProfileOut( __METHOD__
);
1241 # if $frame is provided, then use $frame for replacing any variables
1243 # use frame depth to infer how include/noinclude tags should be handled
1244 # depth=0 means this is the top-level document; otherwise it's an included document
1245 if ( !$frame->depth
) {
1248 $flag = Parser
::PTD_FOR_INCLUSION
;
1250 $dom = $this->preprocessToDom( $text, $flag );
1251 $text = $frame->expand( $dom );
1253 # if $frame is not provided, then use old-style replaceVariables
1254 $text = $this->replaceVariables( $text );
1257 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1258 $text = Sanitizer
::removeHTMLtags(
1260 array( &$this, 'attributeStripCallback' ),
1262 array_keys( $this->mTransparentTagHooks
)
1264 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1266 # Tables need to come after variable replacement for things to work
1267 # properly; putting them before other transformations should keep
1268 # exciting things like link expansions from showing up in surprising
1270 $text = $this->doTableStuff( $text );
1272 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1274 $text = $this->doDoubleUnderscore( $text );
1276 $text = $this->doHeadings( $text );
1277 $text = $this->replaceInternalLinks( $text );
1278 $text = $this->doAllQuotes( $text );
1279 $text = $this->replaceExternalLinks( $text );
1281 # replaceInternalLinks may sometimes leave behind
1282 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1283 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1285 $text = $this->doMagicLinks( $text );
1286 $text = $this->formatHeadings( $text, $origText, $isMain );
1288 wfProfileOut( __METHOD__
);
1293 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1294 * magic external links.
1299 * @param string $text
1303 public function doMagicLinks( $text ) {
1304 wfProfileIn( __METHOD__
);
1305 $prots = wfUrlProtocolsWithoutProtRel();
1306 $urlChar = self
::EXT_LINK_URL_CLASS
;
1307 $text = preg_replace_callback(
1309 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1310 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1311 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1312 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1313 ISBN\s+(\b # m[5]: ISBN, capture number
1314 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1315 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1316 [0-9Xx] # check digit
1318 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1319 wfProfileOut( __METHOD__
);
1324 * @throws MWException
1326 * @return HTML|string
1328 public function magicLinkCallback( $m ) {
1329 if ( isset( $m[1] ) && $m[1] !== '' ) {
1332 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1335 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1336 # Free external link
1337 return $this->makeFreeExternalLink( $m[0] );
1338 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1340 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1343 $cssClass = 'mw-magiclink-rfc';
1345 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1347 $urlmsg = 'pubmedurl';
1348 $cssClass = 'mw-magiclink-pmid';
1351 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1352 substr( $m[0], 0, 20 ) . '"' );
1354 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1355 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1356 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1359 $num = strtr( $isbn, array(
1364 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1365 return '<a href="' .
1366 htmlspecialchars( $titleObj->getLocalURL() ) .
1367 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1374 * Make a free external link, given a user-supplied URL
1376 * @param string $url
1378 * @return string HTML
1381 public function makeFreeExternalLink( $url ) {
1382 wfProfileIn( __METHOD__
);
1386 # The characters '<' and '>' (which were escaped by
1387 # removeHTMLtags()) should not be included in
1388 # URLs, per RFC 2396.
1390 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1391 $trail = substr( $url, $m2[0][1] ) . $trail;
1392 $url = substr( $url, 0, $m2[0][1] );
1395 # Move trailing punctuation to $trail
1397 # If there is no left bracket, then consider right brackets fair game too
1398 if ( strpos( $url, '(' ) === false ) {
1402 $numSepChars = strspn( strrev( $url ), $sep );
1403 if ( $numSepChars ) {
1404 $trail = substr( $url, -$numSepChars ) . $trail;
1405 $url = substr( $url, 0, -$numSepChars );
1408 $url = Sanitizer
::cleanUrl( $url );
1410 # Is this an external image?
1411 $text = $this->maybeMakeExternalImage( $url );
1412 if ( $text === false ) {
1413 # Not an image, make a link
1414 $text = Linker
::makeExternalLink( $url,
1415 $this->getConverterLanguage()->markNoConversion( $url, true ),
1417 $this->getExternalLinkAttribs( $url ) );
1418 # Register it in the output object...
1419 # Replace unnecessary URL escape codes with their equivalent characters
1420 $pasteurized = self
::normalizeLinkUrl( $url );
1421 $this->mOutput
->addExternalLink( $pasteurized );
1423 wfProfileOut( __METHOD__
);
1424 return $text . $trail;
1428 * Parse headers and return html
1432 * @param string $text
1436 public function doHeadings( $text ) {
1437 wfProfileIn( __METHOD__
);
1438 for ( $i = 6; $i >= 1; --$i ) {
1439 $h = str_repeat( '=', $i );
1440 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1442 wfProfileOut( __METHOD__
);
1447 * Replace single quotes with HTML markup
1450 * @param string $text
1452 * @return string The altered text
1454 public function doAllQuotes( $text ) {
1455 wfProfileIn( __METHOD__
);
1457 $lines = StringUtils
::explode( "\n", $text );
1458 foreach ( $lines as $line ) {
1459 $outtext .= $this->doQuotes( $line ) . "\n";
1461 $outtext = substr( $outtext, 0, -1 );
1462 wfProfileOut( __METHOD__
);
1467 * Helper function for doAllQuotes()
1469 * @param string $text
1473 public function doQuotes( $text ) {
1474 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1475 $countarr = count( $arr );
1476 if ( $countarr == 1 ) {
1480 // First, do some preliminary work. This may shift some apostrophes from
1481 // being mark-up to being text. It also counts the number of occurrences
1482 // of bold and italics mark-ups.
1485 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1486 $thislen = strlen( $arr[$i] );
1487 // If there are ever four apostrophes, assume the first is supposed to
1488 // be text, and the remaining three constitute mark-up for bold text.
1489 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1490 if ( $thislen == 4 ) {
1491 $arr[$i - 1] .= "'";
1494 } elseif ( $thislen > 5 ) {
1495 // If there are more than 5 apostrophes in a row, assume they're all
1496 // text except for the last 5.
1497 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1498 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1502 // Count the number of occurrences of bold and italics mark-ups.
1503 if ( $thislen == 2 ) {
1505 } elseif ( $thislen == 3 ) {
1507 } elseif ( $thislen == 5 ) {
1513 // If there is an odd number of both bold and italics, it is likely
1514 // that one of the bold ones was meant to be an apostrophe followed
1515 // by italics. Which one we cannot know for certain, but it is more
1516 // likely to be one that has a single-letter word before it.
1517 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1518 $firstsingleletterword = -1;
1519 $firstmultiletterword = -1;
1521 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1522 if ( strlen( $arr[$i] ) == 3 ) {
1523 $x1 = substr( $arr[$i - 1], -1 );
1524 $x2 = substr( $arr[$i - 1], -2, 1 );
1525 if ( $x1 === ' ' ) {
1526 if ( $firstspace == -1 ) {
1529 } elseif ( $x2 === ' ' ) {
1530 if ( $firstsingleletterword == -1 ) {
1531 $firstsingleletterword = $i;
1532 // if $firstsingleletterword is set, we don't
1533 // look at the other options, so we can bail early.
1537 if ( $firstmultiletterword == -1 ) {
1538 $firstmultiletterword = $i;
1544 // If there is a single-letter word, use it!
1545 if ( $firstsingleletterword > -1 ) {
1546 $arr[$firstsingleletterword] = "''";
1547 $arr[$firstsingleletterword - 1] .= "'";
1548 } elseif ( $firstmultiletterword > -1 ) {
1549 // If not, but there's a multi-letter word, use that one.
1550 $arr[$firstmultiletterword] = "''";
1551 $arr[$firstmultiletterword - 1] .= "'";
1552 } elseif ( $firstspace > -1 ) {
1553 // ... otherwise use the first one that has neither.
1554 // (notice that it is possible for all three to be -1 if, for example,
1555 // there is only one pentuple-apostrophe in the line)
1556 $arr[$firstspace] = "''";
1557 $arr[$firstspace - 1] .= "'";
1561 // Now let's actually convert our apostrophic mush to HTML!
1566 foreach ( $arr as $r ) {
1567 if ( ( $i %
2 ) == 0 ) {
1568 if ( $state === 'both' ) {
1574 $thislen = strlen( $r );
1575 if ( $thislen == 2 ) {
1576 if ( $state === 'i' ) {
1579 } elseif ( $state === 'bi' ) {
1582 } elseif ( $state === 'ib' ) {
1583 $output .= '</b></i><b>';
1585 } elseif ( $state === 'both' ) {
1586 $output .= '<b><i>' . $buffer . '</i>';
1588 } else { // $state can be 'b' or ''
1592 } elseif ( $thislen == 3 ) {
1593 if ( $state === 'b' ) {
1596 } elseif ( $state === 'bi' ) {
1597 $output .= '</i></b><i>';
1599 } elseif ( $state === 'ib' ) {
1602 } elseif ( $state === 'both' ) {
1603 $output .= '<i><b>' . $buffer . '</b>';
1605 } else { // $state can be 'i' or ''
1609 } elseif ( $thislen == 5 ) {
1610 if ( $state === 'b' ) {
1611 $output .= '</b><i>';
1613 } elseif ( $state === 'i' ) {
1614 $output .= '</i><b>';
1616 } elseif ( $state === 'bi' ) {
1617 $output .= '</i></b>';
1619 } elseif ( $state === 'ib' ) {
1620 $output .= '</b></i>';
1622 } elseif ( $state === 'both' ) {
1623 $output .= '<i><b>' . $buffer . '</b></i>';
1625 } else { // ($state == '')
1633 // Now close all remaining tags. Notice that the order is important.
1634 if ( $state === 'b' ||
$state === 'ib' ) {
1637 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1640 if ( $state === 'bi' ) {
1643 // There might be lonely ''''', so make sure we have a buffer
1644 if ( $state === 'both' && $buffer ) {
1645 $output .= '<b><i>' . $buffer . '</i></b>';
1651 * Replace external links (REL)
1653 * Note: this is all very hackish and the order of execution matters a lot.
1654 * Make sure to run tests/parserTests.php if you change this code.
1658 * @param string $text
1660 * @throws MWException
1663 public function replaceExternalLinks( $text ) {
1664 wfProfileIn( __METHOD__
);
1666 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1667 if ( $bits === false ) {
1668 wfProfileOut( __METHOD__
);
1669 throw new MWException( "PCRE needs to be compiled with "
1670 . "--enable-unicode-properties in order for MediaWiki to function" );
1672 $s = array_shift( $bits );
1675 while ( $i < count( $bits ) ) {
1678 $text = $bits[$i++
];
1679 $trail = $bits[$i++
];
1681 # The characters '<' and '>' (which were escaped by
1682 # removeHTMLtags()) should not be included in
1683 # URLs, per RFC 2396.
1685 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1686 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1687 $url = substr( $url, 0, $m2[0][1] );
1690 # If the link text is an image URL, replace it with an <img> tag
1691 # This happened by accident in the original parser, but some people used it extensively
1692 $img = $this->maybeMakeExternalImage( $text );
1693 if ( $img !== false ) {
1699 # Set linktype for CSS - if URL==text, link is essentially free
1700 $linktype = ( $text === $url ) ?
'free' : 'text';
1702 # No link text, e.g. [http://domain.tld/some.link]
1703 if ( $text == '' ) {
1705 $langObj = $this->getTargetLanguage();
1706 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1707 $linktype = 'autonumber';
1709 # Have link text, e.g. [http://domain.tld/some.link text]s
1711 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1714 $text = $this->getConverterLanguage()->markNoConversion( $text );
1716 $url = Sanitizer
::cleanUrl( $url );
1718 # Use the encoded URL
1719 # This means that users can paste URLs directly into the text
1720 # Funny characters like ö aren't valid in URLs anyway
1721 # This was changed in August 2004
1722 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1723 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1725 # Register link in the output object.
1726 # Replace unnecessary URL escape codes with the referenced character
1727 # This prevents spammers from hiding links from the filters
1728 $pasteurized = self
::normalizeLinkUrl( $url );
1729 $this->mOutput
->addExternalLink( $pasteurized );
1732 wfProfileOut( __METHOD__
);
1737 * Get the rel attribute for a particular external link.
1740 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1741 * nofollow if appropriate
1742 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1743 * @return string|null Rel attribute for $url
1745 public static function getExternalLinkRel( $url = false, $title = null ) {
1746 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1747 $ns = $title ?
$title->getNamespace() : false;
1748 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1749 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1757 * Get an associative array of additional HTML attributes appropriate for a
1758 * particular external link. This currently may include rel => nofollow
1759 * (depending on configuration, namespace, and the URL's domain) and/or a
1760 * target attribute (depending on configuration).
1762 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1763 * nofollow if appropriate
1764 * @return array Associative array of HTML attributes
1766 public function getExternalLinkAttribs( $url = false ) {
1768 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1770 if ( $this->mOptions
->getExternalLinkTarget() ) {
1771 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1777 * Replace unusual escape codes in a URL with their equivalent characters
1779 * @deprecated since 1.24, use normalizeLinkUrl
1780 * @param string $url
1783 public static function replaceUnusualEscapes( $url ) {
1784 wfDeprecated( __METHOD__
, '1.24' );
1785 return self
::normalizeLinkUrl( $url );
1789 * Replace unusual escape codes in a URL with their equivalent characters
1791 * This generally follows the syntax defined in RFC 3986, with special
1792 * consideration for HTTP query strings.
1794 * @param string $url
1797 public static function normalizeLinkUrl( $url ) {
1798 # First, make sure unsafe characters are encoded
1799 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1801 return rawurlencode( $m[0] );
1807 $end = strlen( $url );
1809 # Fragment part - 'fragment'
1810 $start = strpos( $url, '#' );
1811 if ( $start !== false && $start < $end ) {
1812 $ret = self
::normalizeUrlComponent(
1813 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1817 # Query part - 'query' minus &=+;
1818 $start = strpos( $url, '?' );
1819 if ( $start !== false && $start < $end ) {
1820 $ret = self
::normalizeUrlComponent(
1821 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1825 # Scheme and path part - 'pchar'
1826 # (we assume no userinfo or encoded colons in the host)
1827 $ret = self
::normalizeUrlComponent(
1828 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1833 private static function normalizeUrlComponent( $component, $unsafe ) {
1834 $callback = function ( $matches ) use ( $unsafe ) {
1835 $char = urldecode( $matches[0] );
1836 $ord = ord( $char );
1837 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1841 # Leave it escaped, but use uppercase for a-f
1842 return strtoupper( $matches[0] );
1845 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1849 * make an image if it's allowed, either through the global
1850 * option, through the exception, or through the on-wiki whitelist
1852 * @param string $url
1856 private function maybeMakeExternalImage( $url ) {
1857 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1858 $imagesexception = !empty( $imagesfrom );
1860 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1861 if ( $imagesexception && is_array( $imagesfrom ) ) {
1862 $imagematch = false;
1863 foreach ( $imagesfrom as $match ) {
1864 if ( strpos( $url, $match ) === 0 ) {
1869 } elseif ( $imagesexception ) {
1870 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1872 $imagematch = false;
1875 if ( $this->mOptions
->getAllowExternalImages()
1876 ||
( $imagesexception && $imagematch )
1878 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1880 $text = Linker
::makeExternalImage( $url );
1883 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1884 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1886 $whitelist = explode(
1888 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1891 foreach ( $whitelist as $entry ) {
1892 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1893 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1896 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1897 # Image matches a whitelist entry
1898 $text = Linker
::makeExternalImage( $url );
1907 * Process [[ ]] wikilinks
1911 * @return string Processed text
1915 public function replaceInternalLinks( $s ) {
1916 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1921 * Process [[ ]] wikilinks (RIL)
1923 * @throws MWException
1924 * @return LinkHolderArray
1928 public function replaceInternalLinks2( &$s ) {
1929 global $wgExtraInterlanguageLinkPrefixes;
1930 wfProfileIn( __METHOD__
);
1932 wfProfileIn( __METHOD__
. '-setup' );
1933 static $tc = false, $e1, $e1_img;
1934 # the % is needed to support urlencoded titles as well
1936 $tc = Title
::legalChars() . '#%';
1937 # Match a link having the form [[namespace:link|alternate]]trail
1938 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1939 # Match cases where there is no "]]", which might still be images
1940 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1943 $holders = new LinkHolderArray( $this );
1945 # split the entire text string on occurrences of [[
1946 $a = StringUtils
::explode( '[[', ' ' . $s );
1947 # get the first element (all text up to first [[), and remove the space we added
1950 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1951 $s = substr( $s, 1 );
1953 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1955 if ( $useLinkPrefixExtension ) {
1956 # Match the end of a line for a word that's not followed by whitespace,
1957 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1959 $charset = $wgContLang->linkPrefixCharset();
1960 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1963 if ( is_null( $this->mTitle
) ) {
1964 wfProfileOut( __METHOD__
. '-setup' );
1965 wfProfileOut( __METHOD__
);
1966 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1968 $nottalk = !$this->mTitle
->isTalkPage();
1970 if ( $useLinkPrefixExtension ) {
1972 if ( preg_match( $e2, $s, $m ) ) {
1973 $first_prefix = $m[2];
1975 $first_prefix = false;
1981 $useSubpages = $this->areSubpagesAllowed();
1982 wfProfileOut( __METHOD__
. '-setup' );
1984 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1985 # Loop for each link
1986 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1987 // @codingStandardsIgnoreStart
1989 # Check for excessive memory usage
1990 if ( $holders->isBig() ) {
1992 # Do the existence check, replace the link holders and clear the array
1993 $holders->replace( $s );
1997 if ( $useLinkPrefixExtension ) {
1998 wfProfileIn( __METHOD__
. '-prefixhandling' );
1999 if ( preg_match( $e2, $s, $m ) ) {
2006 if ( $first_prefix ) {
2007 $prefix = $first_prefix;
2008 $first_prefix = false;
2010 wfProfileOut( __METHOD__
. '-prefixhandling' );
2013 $might_be_img = false;
2015 wfProfileIn( __METHOD__
. "-e1" );
2016 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2018 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2019 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2020 # the real problem is with the $e1 regex
2023 # Still some problems for cases where the ] is meant to be outside punctuation,
2024 # and no image is in sight. See bug 2095.
2027 && substr( $m[3], 0, 1 ) === ']'
2028 && strpos( $text, '[' ) !== false
2030 $text .= ']'; # so that replaceExternalLinks($text) works later
2031 $m[3] = substr( $m[3], 1 );
2033 # fix up urlencoded title texts
2034 if ( strpos( $m[1], '%' ) !== false ) {
2035 # Should anchors '#' also be rejected?
2036 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2039 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2040 # Invalid, but might be an image with a link in its caption
2041 $might_be_img = true;
2043 if ( strpos( $m[1], '%' ) !== false ) {
2044 $m[1] = rawurldecode( $m[1] );
2047 } else { # Invalid form; output directly
2048 $s .= $prefix . '[[' . $line;
2049 wfProfileOut( __METHOD__
. "-e1" );
2052 wfProfileOut( __METHOD__
. "-e1" );
2053 wfProfileIn( __METHOD__
. "-misc" );
2057 # Don't allow internal links to pages containing
2058 # PROTO: where PROTO is a valid URL protocol; these
2059 # should be external links.
2060 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2061 $s .= $prefix . '[[' . $line;
2062 wfProfileOut( __METHOD__
. "-misc" );
2066 # Make subpage if necessary
2067 if ( $useSubpages ) {
2068 $link = $this->maybeDoSubpageLink( $origLink, $text );
2073 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2075 # Strip off leading ':'
2076 $link = substr( $link, 1 );
2079 wfProfileOut( __METHOD__
. "-misc" );
2080 wfProfileIn( __METHOD__
. "-title" );
2081 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2082 if ( $nt === null ) {
2083 $s .= $prefix . '[[' . $line;
2084 wfProfileOut( __METHOD__
. "-title" );
2088 $ns = $nt->getNamespace();
2089 $iw = $nt->getInterwiki();
2090 wfProfileOut( __METHOD__
. "-title" );
2092 if ( $might_be_img ) { # if this is actually an invalid link
2093 wfProfileIn( __METHOD__
. "-might_be_img" );
2094 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2097 # look at the next 'line' to see if we can close it there
2099 $next_line = $a->current();
2100 if ( $next_line === false ||
$next_line === null ) {
2103 $m = explode( ']]', $next_line, 3 );
2104 if ( count( $m ) == 3 ) {
2105 # the first ]] closes the inner link, the second the image
2107 $text .= "[[{$m[0]}]]{$m[1]}";
2110 } elseif ( count( $m ) == 2 ) {
2111 # if there's exactly one ]] that's fine, we'll keep looking
2112 $text .= "[[{$m[0]}]]{$m[1]}";
2114 # if $next_line is invalid too, we need look no further
2115 $text .= '[[' . $next_line;
2120 # we couldn't find the end of this imageLink, so output it raw
2121 # but don't ignore what might be perfectly normal links in the text we've examined
2122 $holders->merge( $this->replaceInternalLinks2( $text ) );
2123 $s .= "{$prefix}[[$link|$text";
2124 # note: no $trail, because without an end, there *is* no trail
2125 wfProfileOut( __METHOD__
. "-might_be_img" );
2128 } else { # it's not an image, so output it raw
2129 $s .= "{$prefix}[[$link|$text";
2130 # note: no $trail, because without an end, there *is* no trail
2131 wfProfileOut( __METHOD__
. "-might_be_img" );
2134 wfProfileOut( __METHOD__
. "-might_be_img" );
2137 $wasblank = ( $text == '' );
2141 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2142 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2143 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2144 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2145 $text = $this->doQuotes( $text );
2148 # Link not escaped by : , create the various objects
2149 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2151 wfProfileIn( __METHOD__
. "-interwiki" );
2153 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2154 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2155 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2158 # Bug 24502: filter duplicates
2159 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2160 $this->mLangLinkLanguages
[$iw] = true;
2161 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2164 $s = rtrim( $s . $prefix );
2165 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2166 wfProfileOut( __METHOD__
. "-interwiki" );
2169 wfProfileOut( __METHOD__
. "-interwiki" );
2171 if ( $ns == NS_FILE
) {
2172 wfProfileIn( __METHOD__
. "-image" );
2173 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2175 # if no parameters were passed, $text
2176 # becomes something like "File:Foo.png",
2177 # which we don't want to pass on to the
2181 # recursively parse links inside the image caption
2182 # actually, this will parse them in any other parameters, too,
2183 # but it might be hard to fix that, and it doesn't matter ATM
2184 $text = $this->replaceExternalLinks( $text );
2185 $holders->merge( $this->replaceInternalLinks2( $text ) );
2187 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2188 $s .= $prefix . $this->armorLinks(
2189 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2191 $s .= $prefix . $trail;
2193 wfProfileOut( __METHOD__
. "-image" );
2197 if ( $ns == NS_CATEGORY
) {
2198 wfProfileIn( __METHOD__
. "-category" );
2199 $s = rtrim( $s . "\n" ); # bug 87
2202 $sortkey = $this->getDefaultSort();
2206 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2207 $sortkey = str_replace( "\n", '', $sortkey );
2208 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2209 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2212 * Strip the whitespace Category links produce, see bug 87
2214 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2216 wfProfileOut( __METHOD__
. "-category" );
2221 # Self-link checking. For some languages, variants of the title are checked in
2222 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2223 # for linking to a different variant.
2224 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2225 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2229 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2230 # @todo FIXME: Should do batch file existence checks, see comment below
2231 if ( $ns == NS_MEDIA
) {
2232 wfProfileIn( __METHOD__
. "-media" );
2233 # Give extensions a chance to select the file revision for us
2236 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2237 array( $this, $nt, &$options, &$descQuery ) );
2238 # Fetch and register the file (file title may be different via hooks)
2239 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2240 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2241 $s .= $prefix . $this->armorLinks(
2242 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2243 wfProfileOut( __METHOD__
. "-media" );
2247 wfProfileIn( __METHOD__
. "-always_known" );
2248 # Some titles, such as valid special pages or files in foreign repos, should
2249 # be shown as bluelinks even though they're not included in the page table
2251 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2252 # batch file existence checks for NS_FILE and NS_MEDIA
2253 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2254 $this->mOutput
->addLink( $nt );
2255 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2257 # Links will be added to the output link list after checking
2258 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2260 wfProfileOut( __METHOD__
. "-always_known" );
2262 wfProfileOut( __METHOD__
);
2267 * Render a forced-blue link inline; protect against double expansion of
2268 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2269 * Since this little disaster has to split off the trail text to avoid
2270 * breaking URLs in the following text without breaking trails on the
2271 * wiki links, it's been made into a horrible function.
2274 * @param string $text
2275 * @param array|string $query
2276 * @param string $trail
2277 * @param string $prefix
2278 * @return string HTML-wikitext mix oh yuck
2280 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2281 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2283 if ( is_string( $query ) ) {
2284 $query = wfCgiToArray( $query );
2286 if ( $text == '' ) {
2287 $text = htmlspecialchars( $nt->getPrefixedText() );
2290 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2292 return $this->armorLinks( $link ) . $trail;
2296 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2297 * going to go through further parsing steps before inline URL expansion.
2299 * Not needed quite as much as it used to be since free links are a bit
2300 * more sensible these days. But bracketed links are still an issue.
2302 * @param string $text More-or-less HTML
2303 * @return string Less-or-more HTML with NOPARSE bits
2305 public function armorLinks( $text ) {
2306 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2307 "{$this->mUniqPrefix}NOPARSE$1", $text );
2311 * Return true if subpage links should be expanded on this page.
2314 public function areSubpagesAllowed() {
2315 # Some namespaces don't allow subpages
2316 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2320 * Handle link to subpage if necessary
2322 * @param string $target The source of the link
2323 * @param string &$text The link text, modified as necessary
2324 * @return string The full name of the link
2327 public function maybeDoSubpageLink( $target, &$text ) {
2328 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2332 * Used by doBlockLevels()
2337 public function closeParagraph() {
2339 if ( $this->mLastSection
!= '' ) {
2340 $result = '</' . $this->mLastSection
. ">\n";
2342 $this->mInPre
= false;
2343 $this->mLastSection
= '';
2348 * getCommon() returns the length of the longest common substring
2349 * of both arguments, starting at the beginning of both.
2352 * @param string $st1
2353 * @param string $st2
2357 public function getCommon( $st1, $st2 ) {
2358 $fl = strlen( $st1 );
2359 $shorter = strlen( $st2 );
2360 if ( $fl < $shorter ) {
2364 for ( $i = 0; $i < $shorter; ++
$i ) {
2365 if ( $st1[$i] != $st2[$i] ) {
2373 * These next three functions open, continue, and close the list
2374 * element appropriate to the prefix character passed into them.
2377 * @param string $char
2381 public function openList( $char ) {
2382 $result = $this->closeParagraph();
2384 if ( '*' === $char ) {
2385 $result .= "<ul><li>";
2386 } elseif ( '#' === $char ) {
2387 $result .= "<ol><li>";
2388 } elseif ( ':' === $char ) {
2389 $result .= "<dl><dd>";
2390 } elseif ( ';' === $char ) {
2391 $result .= "<dl><dt>";
2392 $this->mDTopen
= true;
2394 $result = '<!-- ERR 1 -->';
2402 * @param string $char
2407 public function nextItem( $char ) {
2408 if ( '*' === $char ||
'#' === $char ) {
2409 return "</li>\n<li>";
2410 } elseif ( ':' === $char ||
';' === $char ) {
2412 if ( $this->mDTopen
) {
2415 if ( ';' === $char ) {
2416 $this->mDTopen
= true;
2417 return $close . '<dt>';
2419 $this->mDTopen
= false;
2420 return $close . '<dd>';
2423 return '<!-- ERR 2 -->';
2428 * @param string $char
2433 public function closeList( $char ) {
2434 if ( '*' === $char ) {
2435 $text = "</li></ul>";
2436 } elseif ( '#' === $char ) {
2437 $text = "</li></ol>";
2438 } elseif ( ':' === $char ) {
2439 if ( $this->mDTopen
) {
2440 $this->mDTopen
= false;
2441 $text = "</dt></dl>";
2443 $text = "</dd></dl>";
2446 return '<!-- ERR 3 -->';
2453 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2455 * @param string $text
2456 * @param bool $linestart Whether or not this is at the start of a line.
2458 * @return string The lists rendered as HTML
2460 public function doBlockLevels( $text, $linestart ) {
2461 wfProfileIn( __METHOD__
);
2463 # Parsing through the text line by line. The main thing
2464 # happening here is handling of block-level elements p, pre,
2465 # and making lists from lines starting with * # : etc.
2467 $textLines = StringUtils
::explode( "\n", $text );
2469 $lastPrefix = $output = '';
2470 $this->mDTopen
= $inBlockElem = false;
2472 $paragraphStack = false;
2473 $inBlockquote = false;
2475 foreach ( $textLines as $oLine ) {
2477 if ( !$linestart ) {
2487 $lastPrefixLength = strlen( $lastPrefix );
2488 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2489 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2490 # If not in a <pre> element, scan for and figure out what prefixes are there.
2491 if ( !$this->mInPre
) {
2492 # Multiple prefixes may abut each other for nested lists.
2493 $prefixLength = strspn( $oLine, '*#:;' );
2494 $prefix = substr( $oLine, 0, $prefixLength );
2497 # ; and : are both from definition-lists, so they're equivalent
2498 # for the purposes of determining whether or not we need to open/close
2500 $prefix2 = str_replace( ';', ':', $prefix );
2501 $t = substr( $oLine, $prefixLength );
2502 $this->mInPre
= (bool)$preOpenMatch;
2504 # Don't interpret any other prefixes in preformatted text
2506 $prefix = $prefix2 = '';
2511 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2512 # Same as the last item, so no need to deal with nesting or opening stuff
2513 $output .= $this->nextItem( substr( $prefix, -1 ) );
2514 $paragraphStack = false;
2516 if ( substr( $prefix, -1 ) === ';' ) {
2517 # The one nasty exception: definition lists work like this:
2518 # ; title : definition text
2519 # So we check for : in the remainder text to split up the
2520 # title and definition, without b0rking links.
2522 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2524 $output .= $term . $this->nextItem( ':' );
2527 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2528 # We need to open or close prefixes, or both.
2530 # Either open or close a level...
2531 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2532 $paragraphStack = false;
2534 # Close all the prefixes which aren't shared.
2535 while ( $commonPrefixLength < $lastPrefixLength ) {
2536 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2537 --$lastPrefixLength;
2540 # Continue the current prefix if appropriate.
2541 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2542 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2545 # Open prefixes where appropriate.
2546 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2549 while ( $prefixLength > $commonPrefixLength ) {
2550 $char = substr( $prefix, $commonPrefixLength, 1 );
2551 $output .= $this->openList( $char );
2553 if ( ';' === $char ) {
2554 # @todo FIXME: This is dupe of code above
2555 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2557 $output .= $term . $this->nextItem( ':' );
2560 ++
$commonPrefixLength;
2562 if ( !$prefixLength && $lastPrefix ) {
2565 $lastPrefix = $prefix2;
2568 # If we have no prefixes, go to paragraph mode.
2569 if ( 0 == $prefixLength ) {
2570 wfProfileIn( __METHOD__
. "-paragraph" );
2571 # No prefix (not in list)--go to paragraph mode
2572 # XXX: use a stack for nestable elements like span, table and div
2573 $openmatch = preg_match(
2574 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2575 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2578 $closematch = preg_match(
2579 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2580 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2581 . $this->mUniqPrefix
2582 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2586 if ( $openmatch or $closematch ) {
2587 $paragraphStack = false;
2588 # @todo bug 5718: paragraph closed
2589 $output .= $this->closeParagraph();
2590 if ( $preOpenMatch and !$preCloseMatch ) {
2591 $this->mInPre
= true;
2594 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2595 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2596 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2598 $inBlockElem = !$closematch;
2599 } elseif ( !$inBlockElem && !$this->mInPre
) {
2600 if ( ' ' == substr( $t, 0, 1 )
2601 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2605 if ( $this->mLastSection
!== 'pre' ) {
2606 $paragraphStack = false;
2607 $output .= $this->closeParagraph() . '<pre>';
2608 $this->mLastSection
= 'pre';
2610 $t = substr( $t, 1 );
2613 if ( trim( $t ) === '' ) {
2614 if ( $paragraphStack ) {
2615 $output .= $paragraphStack . '<br />';
2616 $paragraphStack = false;
2617 $this->mLastSection
= 'p';
2619 if ( $this->mLastSection
!== 'p' ) {
2620 $output .= $this->closeParagraph();
2621 $this->mLastSection
= '';
2622 $paragraphStack = '<p>';
2624 $paragraphStack = '</p><p>';
2628 if ( $paragraphStack ) {
2629 $output .= $paragraphStack;
2630 $paragraphStack = false;
2631 $this->mLastSection
= 'p';
2632 } elseif ( $this->mLastSection
!== 'p' ) {
2633 $output .= $this->closeParagraph() . '<p>';
2634 $this->mLastSection
= 'p';
2639 wfProfileOut( __METHOD__
. "-paragraph" );
2641 # somewhere above we forget to get out of pre block (bug 785)
2642 if ( $preCloseMatch && $this->mInPre
) {
2643 $this->mInPre
= false;
2645 if ( $paragraphStack === false ) {
2647 if ( $prefixLength === 0 ) {
2652 while ( $prefixLength ) {
2653 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2655 if ( !$prefixLength ) {
2659 if ( $this->mLastSection
!= '' ) {
2660 $output .= '</' . $this->mLastSection
. '>';
2661 $this->mLastSection
= '';
2664 wfProfileOut( __METHOD__
);
2669 * Split up a string on ':', ignoring any occurrences inside tags
2670 * to prevent illegal overlapping.
2672 * @param string $str The string to split
2673 * @param string &$before Set to everything before the ':'
2674 * @param string &$after Set to everything after the ':'
2675 * @throws MWException
2676 * @return string The position of the ':', or false if none found
2678 public function findColonNoLinks( $str, &$before, &$after ) {
2679 wfProfileIn( __METHOD__
);
2681 $pos = strpos( $str, ':' );
2682 if ( $pos === false ) {
2684 wfProfileOut( __METHOD__
);
2688 $lt = strpos( $str, '<' );
2689 if ( $lt === false ||
$lt > $pos ) {
2690 # Easy; no tag nesting to worry about
2691 $before = substr( $str, 0, $pos );
2692 $after = substr( $str, $pos +
1 );
2693 wfProfileOut( __METHOD__
);
2697 # Ugly state machine to walk through avoiding tags.
2698 $state = self
::COLON_STATE_TEXT
;
2700 $len = strlen( $str );
2701 for ( $i = 0; $i < $len; $i++
) {
2705 # (Using the number is a performance hack for common cases)
2706 case 0: # self::COLON_STATE_TEXT:
2709 # Could be either a <start> tag or an </end> tag
2710 $state = self
::COLON_STATE_TAGSTART
;
2713 if ( $stack == 0 ) {
2715 $before = substr( $str, 0, $i );
2716 $after = substr( $str, $i +
1 );
2717 wfProfileOut( __METHOD__
);
2720 # Embedded in a tag; don't break it.
2723 # Skip ahead looking for something interesting
2724 $colon = strpos( $str, ':', $i );
2725 if ( $colon === false ) {
2726 # Nothing else interesting
2727 wfProfileOut( __METHOD__
);
2730 $lt = strpos( $str, '<', $i );
2731 if ( $stack === 0 ) {
2732 if ( $lt === false ||
$colon < $lt ) {
2734 $before = substr( $str, 0, $colon );
2735 $after = substr( $str, $colon +
1 );
2736 wfProfileOut( __METHOD__
);
2740 if ( $lt === false ) {
2741 # Nothing else interesting to find; abort!
2742 # We're nested, but there's no close tags left. Abort!
2745 # Skip ahead to next tag start
2747 $state = self
::COLON_STATE_TAGSTART
;
2750 case 1: # self::COLON_STATE_TAG:
2755 $state = self
::COLON_STATE_TEXT
;
2758 # Slash may be followed by >?
2759 $state = self
::COLON_STATE_TAGSLASH
;
2765 case 2: # self::COLON_STATE_TAGSTART:
2768 $state = self
::COLON_STATE_CLOSETAG
;
2771 $state = self
::COLON_STATE_COMMENT
;
2774 # Illegal early close? This shouldn't happen D:
2775 $state = self
::COLON_STATE_TEXT
;
2778 $state = self
::COLON_STATE_TAG
;
2781 case 3: # self::COLON_STATE_CLOSETAG:
2786 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2787 wfProfileOut( __METHOD__
);
2790 $state = self
::COLON_STATE_TEXT
;
2793 case self
::COLON_STATE_TAGSLASH
:
2795 # Yes, a self-closed tag <blah/>
2796 $state = self
::COLON_STATE_TEXT
;
2798 # Probably we're jumping the gun, and this is an attribute
2799 $state = self
::COLON_STATE_TAG
;
2802 case 5: # self::COLON_STATE_COMMENT:
2804 $state = self
::COLON_STATE_COMMENTDASH
;
2807 case self
::COLON_STATE_COMMENTDASH
:
2809 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2811 $state = self
::COLON_STATE_COMMENT
;
2814 case self
::COLON_STATE_COMMENTDASHDASH
:
2816 $state = self
::COLON_STATE_TEXT
;
2818 $state = self
::COLON_STATE_COMMENT
;
2822 wfProfileOut( __METHOD__
);
2823 throw new MWException( "State machine error in " . __METHOD__
);
2827 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2828 wfProfileOut( __METHOD__
);
2831 wfProfileOut( __METHOD__
);
2836 * Return value of a magic variable (like PAGENAME)
2841 * @param bool|PPFrame $frame
2843 * @throws MWException
2846 public function getVariableValue( $index, $frame = false ) {
2847 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2848 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2850 if ( is_null( $this->mTitle
) ) {
2851 // If no title set, bad things are going to happen
2852 // later. Title should always be set since this
2853 // should only be called in the middle of a parse
2854 // operation (but the unit-tests do funky stuff)
2855 throw new MWException( __METHOD__
. ' Should only be '
2856 . ' called while parsing (no title set)' );
2860 * Some of these require message or data lookups and can be
2861 * expensive to check many times.
2863 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2864 if ( isset( $this->mVarCache
[$index] ) ) {
2865 return $this->mVarCache
[$index];
2869 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2870 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2872 $pageLang = $this->getFunctionLang();
2878 case 'currentmonth':
2879 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2881 case 'currentmonth1':
2882 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2884 case 'currentmonthname':
2885 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2887 case 'currentmonthnamegen':
2888 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2890 case 'currentmonthabbrev':
2891 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2894 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2897 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2900 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2903 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2905 case 'localmonthname':
2906 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2908 case 'localmonthnamegen':
2909 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2911 case 'localmonthabbrev':
2912 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2915 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2918 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2921 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2924 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2926 case 'fullpagename':
2927 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2929 case 'fullpagenamee':
2930 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2933 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2935 case 'subpagenamee':
2936 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2938 case 'rootpagename':
2939 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2941 case 'rootpagenamee':
2942 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2945 $this->mTitle
->getRootText()
2948 case 'basepagename':
2949 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2951 case 'basepagenamee':
2952 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2955 $this->mTitle
->getBaseText()
2958 case 'talkpagename':
2959 if ( $this->mTitle
->canTalk() ) {
2960 $talkPage = $this->mTitle
->getTalkPage();
2961 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2966 case 'talkpagenamee':
2967 if ( $this->mTitle
->canTalk() ) {
2968 $talkPage = $this->mTitle
->getTalkPage();
2969 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2974 case 'subjectpagename':
2975 $subjPage = $this->mTitle
->getSubjectPage();
2976 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2978 case 'subjectpagenamee':
2979 $subjPage = $this->mTitle
->getSubjectPage();
2980 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2982 case 'pageid': // requested in bug 23427
2983 $pageid = $this->getTitle()->getArticleID();
2984 if ( $pageid == 0 ) {
2985 # 0 means the page doesn't exist in the database,
2986 # which means the user is previewing a new page.
2987 # The vary-revision flag must be set, because the magic word
2988 # will have a different value once the page is saved.
2989 $this->mOutput
->setFlag( 'vary-revision' );
2990 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2992 $value = $pageid ?
$pageid : null;
2995 # Let the edit saving system know we should parse the page
2996 # *after* a revision ID has been assigned.
2997 $this->mOutput
->setFlag( 'vary-revision' );
2998 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2999 $value = $this->mRevisionId
;
3002 # Let the edit saving system know we should parse the page
3003 # *after* a revision ID has been assigned. This is for null edits.
3004 $this->mOutput
->setFlag( 'vary-revision' );
3005 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3006 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3008 case 'revisionday2':
3009 # Let the edit saving system know we should parse the page
3010 # *after* a revision ID has been assigned. This is for null edits.
3011 $this->mOutput
->setFlag( 'vary-revision' );
3012 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3013 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3015 case 'revisionmonth':
3016 # Let the edit saving system know we should parse the page
3017 # *after* a revision ID has been assigned. This is for null edits.
3018 $this->mOutput
->setFlag( 'vary-revision' );
3019 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3020 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3022 case 'revisionmonth1':
3023 # Let the edit saving system know we should parse the page
3024 # *after* a revision ID has been assigned. This is for null edits.
3025 $this->mOutput
->setFlag( 'vary-revision' );
3026 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3027 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3029 case 'revisionyear':
3030 # Let the edit saving system know we should parse the page
3031 # *after* a revision ID has been assigned. This is for null edits.
3032 $this->mOutput
->setFlag( 'vary-revision' );
3033 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3034 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3036 case 'revisiontimestamp':
3037 # Let the edit saving system know we should parse the page
3038 # *after* a revision ID has been assigned. This is for null edits.
3039 $this->mOutput
->setFlag( 'vary-revision' );
3040 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3041 $value = $this->getRevisionTimestamp();
3043 case 'revisionuser':
3044 # Let the edit saving system know we should parse the page
3045 # *after* a revision ID has been assigned. This is for null edits.
3046 $this->mOutput
->setFlag( 'vary-revision' );
3047 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3048 $value = $this->getRevisionUser();
3050 case 'revisionsize':
3051 # Let the edit saving system know we should parse the page
3052 # *after* a revision ID has been assigned. This is for null edits.
3053 $this->mOutput
->setFlag( 'vary-revision' );
3054 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3055 $value = $this->getRevisionSize();
3058 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3061 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3063 case 'namespacenumber':
3064 $value = $this->mTitle
->getNamespace();
3067 $value = $this->mTitle
->canTalk()
3068 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3072 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3074 case 'subjectspace':
3075 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3077 case 'subjectspacee':
3078 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3080 case 'currentdayname':
3081 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3084 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3087 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3090 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3093 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3094 # int to remove the padding
3095 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3098 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3100 case 'localdayname':
3101 $value = $pageLang->getWeekdayName(
3102 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3106 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3109 $value = $pageLang->time(
3110 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3116 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3119 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3120 # int to remove the padding
3121 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3124 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3126 case 'numberofarticles':
3127 $value = $pageLang->formatNum( SiteStats
::articles() );
3129 case 'numberoffiles':
3130 $value = $pageLang->formatNum( SiteStats
::images() );
3132 case 'numberofusers':
3133 $value = $pageLang->formatNum( SiteStats
::users() );
3135 case 'numberofactiveusers':
3136 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3138 case 'numberofpages':
3139 $value = $pageLang->formatNum( SiteStats
::pages() );
3141 case 'numberofadmins':
3142 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3144 case 'numberofedits':
3145 $value = $pageLang->formatNum( SiteStats
::edits() );
3147 case 'numberofviews':
3148 global $wgDisableCounters;
3149 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3151 case 'currenttimestamp':
3152 $value = wfTimestamp( TS_MW
, $ts );
3154 case 'localtimestamp':
3155 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3157 case 'currentversion':
3158 $value = SpecialVersion
::getVersion();
3161 return $wgArticlePath;
3167 return $wgServerName;
3169 return $wgScriptPath;
3171 return $wgStylePath;
3172 case 'directionmark':
3173 return $pageLang->getDirMark();
3174 case 'contentlanguage':
3175 global $wgLanguageCode;
3176 return $wgLanguageCode;
3177 case 'cascadingsources':
3178 $value = CoreParserFunctions
::cascadingsources( $this );
3183 'ParserGetVariableValueSwitch',
3184 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3191 $this->mVarCache
[$index] = $value;
3198 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3202 public function initialiseVariables() {
3203 wfProfileIn( __METHOD__
);
3204 $variableIDs = MagicWord
::getVariableIDs();
3205 $substIDs = MagicWord
::getSubstIDs();
3207 $this->mVariables
= new MagicWordArray( $variableIDs );
3208 $this->mSubstWords
= new MagicWordArray( $substIDs );
3209 wfProfileOut( __METHOD__
);
3213 * Preprocess some wikitext and return the document tree.
3214 * This is the ghost of replace_variables().
3216 * @param string $text The text to parse
3217 * @param int $flags Bitwise combination of:
3218 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3219 * included. Default is to assume a direct page view.
3221 * The generated DOM tree must depend only on the input text and the flags.
3222 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3224 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3225 * change in the DOM tree for a given text, must be passed through the section identifier
3226 * in the section edit link and thus back to extractSections().
3228 * The output of this function is currently only cached in process memory, but a persistent
3229 * cache may be implemented at a later date which takes further advantage of these strict
3230 * dependency requirements.
3234 public function preprocessToDom( $text, $flags = 0 ) {
3235 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3240 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3246 public static function splitWhitespace( $s ) {
3247 $ltrimmed = ltrim( $s );
3248 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3249 $trimmed = rtrim( $ltrimmed );
3250 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3252 $w2 = substr( $ltrimmed, -$diff );
3256 return array( $w1, $trimmed, $w2 );
3260 * Replace magic variables, templates, and template arguments
3261 * with the appropriate text. Templates are substituted recursively,
3262 * taking care to avoid infinite loops.
3264 * Note that the substitution depends on value of $mOutputType:
3265 * self::OT_WIKI: only {{subst:}} templates
3266 * self::OT_PREPROCESS: templates but not extension tags
3267 * self::OT_HTML: all templates and extension tags
3269 * @param string $text The text to transform
3270 * @param bool|PPFrame $frame Object describing the arguments passed to the
3271 * template. Arguments may also be provided as an associative array, as
3272 * was the usual case before MW1.12. Providing arguments this way may be
3273 * useful for extensions wishing to perform variable replacement
3275 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3276 * double-brace expansion.
3279 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3280 # Is there any text? Also, Prevent too big inclusions!
3281 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3284 wfProfileIn( __METHOD__
);
3286 if ( $frame === false ) {
3287 $frame = $this->getPreprocessor()->newFrame();
3288 } elseif ( !( $frame instanceof PPFrame
) ) {
3289 wfDebug( __METHOD__
. " called using plain parameters instead of "
3290 . "a PPFrame instance. Creating custom frame.\n" );
3291 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3294 $dom = $this->preprocessToDom( $text );
3295 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3296 $text = $frame->expand( $dom, $flags );
3298 wfProfileOut( __METHOD__
);
3303 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3305 * @param array $args
3309 public static function createAssocArgs( $args ) {
3310 $assocArgs = array();
3312 foreach ( $args as $arg ) {
3313 $eqpos = strpos( $arg, '=' );
3314 if ( $eqpos === false ) {
3315 $assocArgs[$index++
] = $arg;
3317 $name = trim( substr( $arg, 0, $eqpos ) );
3318 $value = trim( substr( $arg, $eqpos +
1 ) );
3319 if ( $value === false ) {
3322 if ( $name !== false ) {
3323 $assocArgs[$name] = $value;
3332 * Warn the user when a parser limitation is reached
3333 * Will warn at most once the user per limitation type
3335 * @param string $limitationType Should be one of:
3336 * 'expensive-parserfunction' (corresponding messages:
3337 * 'expensive-parserfunction-warning',
3338 * 'expensive-parserfunction-category')
3339 * 'post-expand-template-argument' (corresponding messages:
3340 * 'post-expand-template-argument-warning',
3341 * 'post-expand-template-argument-category')
3342 * 'post-expand-template-inclusion' (corresponding messages:
3343 * 'post-expand-template-inclusion-warning',
3344 * 'post-expand-template-inclusion-category')
3345 * 'node-count-exceeded' (corresponding messages:
3346 * 'node-count-exceeded-warning',
3347 * 'node-count-exceeded-category')
3348 * 'expansion-depth-exceeded' (corresponding messages:
3349 * 'expansion-depth-exceeded-warning',
3350 * 'expansion-depth-exceeded-category')
3351 * @param string|int|null $current Current value
3352 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3353 * exceeded, provide the values (optional)
3355 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3356 # does no harm if $current and $max are present but are unnecessary for the message
3357 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3358 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3359 $this->mOutput
->addWarning( $warning );
3360 $this->addTrackingCategory( "$limitationType-category" );
3364 * Return the text of a template, after recursively
3365 * replacing any variables or templates within the template.
3367 * @param array $piece The parts of the template
3368 * $piece['title']: the title, i.e. the part before the |
3369 * $piece['parts']: the parameter array
3370 * $piece['lineStart']: whether the brace was at the start of a line
3371 * @param PPFrame $frame The current frame, contains template arguments
3373 * @return string The text of the template
3375 public function braceSubstitution( $piece, $frame ) {
3376 wfProfileIn( __METHOD__
);
3377 wfProfileIn( __METHOD__
. '-setup' );
3381 // $text has been filled
3383 // wiki markup in $text should be escaped
3385 // $text is HTML, armour it against wikitext transformation
3387 // Force interwiki transclusion to be done in raw mode not rendered
3388 $forceRawInterwiki = false;
3389 // $text is a DOM node needing expansion in a child frame
3390 $isChildObj = false;
3391 // $text is a DOM node needing expansion in the current frame
3392 $isLocalObj = false;
3394 # Title object, where $text came from
3397 # $part1 is the bit before the first |, and must contain only title characters.
3398 # Various prefixes will be stripped from it later.
3399 $titleWithSpaces = $frame->expand( $piece['title'] );
3400 $part1 = trim( $titleWithSpaces );
3403 # Original title text preserved for various purposes
3404 $originalTitle = $part1;
3406 # $args is a list of argument nodes, starting from index 0, not including $part1
3407 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3408 # below won't work b/c this $args isn't an object
3409 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3410 wfProfileOut( __METHOD__
. '-setup' );
3412 $titleProfileIn = null; // profile templates
3415 wfProfileIn( __METHOD__
. '-modifiers' );
3418 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3420 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3421 # Decide whether to expand template or keep wikitext as-is.
3422 if ( $this->ot
['wiki'] ) {
3423 if ( $substMatch === false ) {
3424 $literal = true; # literal when in PST with no prefix
3426 $literal = false; # expand when in PST with subst: or safesubst:
3429 if ( $substMatch == 'subst' ) {
3430 $literal = true; # literal when not in PST with plain subst:
3432 $literal = false; # expand when not in PST with safesubst: or no prefix
3436 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3443 if ( !$found && $args->getLength() == 0 ) {
3444 $id = $this->mVariables
->matchStartToEnd( $part1 );
3445 if ( $id !== false ) {
3446 $text = $this->getVariableValue( $id, $frame );
3447 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3448 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3454 # MSG, MSGNW and RAW
3457 $mwMsgnw = MagicWord
::get( 'msgnw' );
3458 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3461 # Remove obsolete MSG:
3462 $mwMsg = MagicWord
::get( 'msg' );
3463 $mwMsg->matchStartAndRemove( $part1 );
3467 $mwRaw = MagicWord
::get( 'raw' );
3468 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3469 $forceRawInterwiki = true;
3472 wfProfileOut( __METHOD__
. '-modifiers' );
3476 wfProfileIn( __METHOD__
. '-pfunc' );
3478 $colonPos = strpos( $part1, ':' );
3479 if ( $colonPos !== false ) {
3480 $func = substr( $part1, 0, $colonPos );
3481 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3482 for ( $i = 0; $i < $args->getLength(); $i++
) {
3483 $funcArgs[] = $args->item( $i );
3486 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3487 } catch ( Exception
$ex ) {
3488 wfProfileOut( __METHOD__
. '-pfunc' );
3489 wfProfileOut( __METHOD__
);
3493 # The interface for parser functions allows for extracting
3494 # flags into the local scope. Extract any forwarded flags
3498 wfProfileOut( __METHOD__
. '-pfunc' );
3501 # Finish mangling title and then check for loops.
3502 # Set $title to a Title object and $titleText to the PDBK
3505 # Split the title into page and subpage
3507 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3508 if ( $part1 !== $relative ) {
3510 $ns = $this->mTitle
->getNamespace();
3512 $title = Title
::newFromText( $part1, $ns );
3514 $titleText = $title->getPrefixedText();
3515 # Check for language variants if the template is not found
3516 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3517 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3519 # Do recursion depth check
3520 $limit = $this->mOptions
->getMaxTemplateDepth();
3521 if ( $frame->depth
>= $limit ) {
3523 $text = '<span class="error">'
3524 . wfMessage( 'parser-template-recursion-depth-warning' )
3525 ->numParams( $limit )->inContentLanguage()->text()
3531 # Load from database
3532 if ( !$found && $title ) {
3533 if ( !Profiler
::instance()->isPersistent() ) {
3534 # Too many unique items can kill profiling DBs/collectors
3535 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3536 wfProfileIn( $titleProfileIn ); // template in
3538 wfProfileIn( __METHOD__
. '-loadtpl' );
3539 if ( !$title->isExternal() ) {
3540 if ( $title->isSpecialPage()
3541 && $this->mOptions
->getAllowSpecialInclusion()
3542 && $this->ot
['html']
3544 // Pass the template arguments as URL parameters.
3545 // "uselang" will have no effect since the Language object
3546 // is forced to the one defined in ParserOptions.
3547 $pageArgs = array();
3548 $argsLength = $args->getLength();
3549 for ( $i = 0; $i < $argsLength; $i++
) {
3550 $bits = $args->item( $i )->splitArg();
3551 if ( strval( $bits['index'] ) === '' ) {
3552 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3553 $value = trim( $frame->expand( $bits['value'] ) );
3554 $pageArgs[$name] = $value;
3558 // Create a new context to execute the special page
3559 $context = new RequestContext
;
3560 $context->setTitle( $title );
3561 $context->setRequest( new FauxRequest( $pageArgs ) );
3562 $context->setUser( $this->getUser() );
3563 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3564 $ret = SpecialPageFactory
::capturePath( $title, $context );
3566 $text = $context->getOutput()->getHTML();
3567 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3570 $this->disableCache();
3572 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3573 $found = false; # access denied
3574 wfDebug( __METHOD__
. ": template inclusion denied for " .
3575 $title->getPrefixedDBkey() . "\n" );
3577 list( $text, $title ) = $this->getTemplateDom( $title );
3578 if ( $text !== false ) {
3584 # If the title is valid but undisplayable, make a link to it
3585 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3586 $text = "[[:$titleText]]";
3589 } elseif ( $title->isTrans() ) {
3590 # Interwiki transclusion
3591 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3592 $text = $this->interwikiTransclude( $title, 'render' );
3595 $text = $this->interwikiTransclude( $title, 'raw' );
3596 # Preprocess it like a template
3597 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3603 # Do infinite loop check
3604 # This has to be done after redirect resolution to avoid infinite loops via redirects
3605 if ( !$frame->loopCheck( $title ) ) {
3607 $text = '<span class="error">'
3608 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3610 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3612 wfProfileOut( __METHOD__
. '-loadtpl' );
3615 # If we haven't found text to substitute by now, we're done
3616 # Recover the source wikitext and return it
3618 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3619 if ( $titleProfileIn ) {
3620 wfProfileOut( $titleProfileIn ); // template out
3622 wfProfileOut( __METHOD__
);
3623 return array( 'object' => $text );
3626 # Expand DOM-style return values in a child frame
3627 if ( $isChildObj ) {
3628 # Clean up argument array
3629 $newFrame = $frame->newChild( $args, $title );
3632 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3633 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3634 # Expansion is eligible for the empty-frame cache
3635 $text = $newFrame->cachedExpand( $titleText, $text );
3637 # Uncached expansion
3638 $text = $newFrame->expand( $text );
3641 if ( $isLocalObj && $nowiki ) {
3642 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3643 $isLocalObj = false;
3646 if ( $titleProfileIn ) {
3647 wfProfileOut( $titleProfileIn ); // template out
3650 # Replace raw HTML by a placeholder
3652 $text = $this->insertStripItem( $text );
3653 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3654 # Escape nowiki-style return values
3655 $text = wfEscapeWikiText( $text );
3656 } elseif ( is_string( $text )
3657 && !$piece['lineStart']
3658 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3660 # Bug 529: if the template begins with a table or block-level
3661 # element, it should be treated as beginning a new line.
3662 # This behavior is somewhat controversial.
3663 $text = "\n" . $text;
3666 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3667 # Error, oversize inclusion
3668 if ( $titleText !== false ) {
3669 # Make a working, properly escaped link if possible (bug 23588)
3670 $text = "[[:$titleText]]";
3672 # This will probably not be a working link, but at least it may
3673 # provide some hint of where the problem is
3674 preg_replace( '/^:/', '', $originalTitle );
3675 $text = "[[:$originalTitle]]";
3677 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3678 . 'post-expand include size too large -->' );
3679 $this->limitationWarn( 'post-expand-template-inclusion' );
3682 if ( $isLocalObj ) {
3683 $ret = array( 'object' => $text );
3685 $ret = array( 'text' => $text );
3688 wfProfileOut( __METHOD__
);
3693 * Call a parser function and return an array with text and flags.
3695 * The returned array will always contain a boolean 'found', indicating
3696 * whether the parser function was found or not. It may also contain the
3698 * text: string|object, resulting wikitext or PP DOM object
3699 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3700 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3701 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3702 * nowiki: bool, wiki markup in $text should be escaped
3705 * @param PPFrame $frame The current frame, contains template arguments
3706 * @param string $function Function name
3707 * @param array $args Arguments to the function
3708 * @throws MWException
3711 public function callParserFunction( $frame, $function, array $args = array() ) {
3714 wfProfileIn( __METHOD__
);
3716 # Case sensitive functions
3717 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3718 $function = $this->mFunctionSynonyms
[1][$function];
3720 # Case insensitive functions
3721 $function = $wgContLang->lc( $function );
3722 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3723 $function = $this->mFunctionSynonyms
[0][$function];
3725 wfProfileOut( __METHOD__
);
3726 return array( 'found' => false );
3730 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3731 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3733 # Workaround for PHP bug 35229 and similar
3734 if ( !is_callable( $callback ) ) {
3735 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3736 wfProfileOut( __METHOD__
);
3737 throw new MWException( "Tag hook for $function is not callable\n" );
3740 $allArgs = array( &$this );
3741 if ( $flags & SFH_OBJECT_ARGS
) {
3742 # Convert arguments to PPNodes and collect for appending to $allArgs
3743 $funcArgs = array();
3744 foreach ( $args as $k => $v ) {
3745 if ( $v instanceof PPNode ||
$k === 0 ) {
3748 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3752 # Add a frame parameter, and pass the arguments as an array
3753 $allArgs[] = $frame;
3754 $allArgs[] = $funcArgs;
3756 # Convert arguments to plain text and append to $allArgs
3757 foreach ( $args as $k => $v ) {
3758 if ( $v instanceof PPNode
) {
3759 $allArgs[] = trim( $frame->expand( $v ) );
3760 } elseif ( is_int( $k ) && $k >= 0 ) {
3761 $allArgs[] = trim( $v );
3763 $allArgs[] = trim( "$k=$v" );
3768 $result = call_user_func_array( $callback, $allArgs );
3770 # The interface for function hooks allows them to return a wikitext
3771 # string or an array containing the string and any flags. This mungs
3772 # things around to match what this method should return.
3773 if ( !is_array( $result ) ) {
3779 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3780 $result['text'] = $result[0];
3782 unset( $result[0] );
3789 $preprocessFlags = 0;
3790 if ( isset( $result['noparse'] ) ) {
3791 $noparse = $result['noparse'];
3793 if ( isset( $result['preprocessFlags'] ) ) {
3794 $preprocessFlags = $result['preprocessFlags'];
3798 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3799 $result['isChildObj'] = true;
3801 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3802 wfProfileOut( __METHOD__
);
3808 * Get the semi-parsed DOM representation of a template with a given title,
3809 * and its redirect destination title. Cached.
3811 * @param Title $title
3815 public function getTemplateDom( $title ) {
3816 $cacheTitle = $title;
3817 $titleText = $title->getPrefixedDBkey();
3819 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3820 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3821 $title = Title
::makeTitle( $ns, $dbk );
3822 $titleText = $title->getPrefixedDBkey();
3824 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3825 return array( $this->mTplDomCache
[$titleText], $title );
3828 # Cache miss, go to the database
3829 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3831 if ( $text === false ) {
3832 $this->mTplDomCache
[$titleText] = false;
3833 return array( false, $title );
3836 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3837 $this->mTplDomCache
[$titleText] = $dom;
3839 if ( !$title->equals( $cacheTitle ) ) {
3840 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3841 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3844 return array( $dom, $title );
3848 * Fetch the unparsed text of a template and register a reference to it.
3849 * @param Title $title
3850 * @return array ( string or false, Title )
3852 public function fetchTemplateAndTitle( $title ) {
3853 // Defaults to Parser::statelessFetchTemplate()
3854 $templateCb = $this->mOptions
->getTemplateCallback();
3855 $stuff = call_user_func( $templateCb, $title, $this );
3856 $text = $stuff['text'];
3857 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3858 if ( isset( $stuff['deps'] ) ) {
3859 foreach ( $stuff['deps'] as $dep ) {
3860 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3861 if ( $dep['title']->equals( $this->getTitle() ) ) {
3862 // If we transclude ourselves, the final result
3863 // will change based on the new version of the page
3864 $this->mOutput
->setFlag( 'vary-revision' );
3868 return array( $text, $finalTitle );
3872 * Fetch the unparsed text of a template and register a reference to it.
3873 * @param Title $title
3874 * @return string|bool
3876 public function fetchTemplate( $title ) {
3877 $rv = $this->fetchTemplateAndTitle( $title );
3882 * Static function to get a template
3883 * Can be overridden via ParserOptions::setTemplateCallback().
3885 * @param Title $title
3886 * @param bool|Parser $parser
3890 public static function statelessFetchTemplate( $title, $parser = false ) {
3891 $text = $skip = false;
3892 $finalTitle = $title;
3895 # Loop to fetch the article, with up to 1 redirect
3896 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3897 # Give extensions a chance to select the revision instead
3898 $id = false; # Assume current
3899 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3900 array( $parser, $title, &$skip, &$id ) );
3906 'page_id' => $title->getArticleID(),
3913 ? Revision
::newFromId( $id )
3914 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3915 $rev_id = $rev ?
$rev->getId() : 0;
3916 # If there is no current revision, there is no page
3917 if ( $id === false && !$rev ) {
3918 $linkCache = LinkCache
::singleton();
3919 $linkCache->addBadLinkObj( $title );
3924 'page_id' => $title->getArticleID(),
3925 'rev_id' => $rev_id );
3926 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3927 # We fetched a rev from a different title; register it too...
3929 'title' => $rev->getTitle(),
3930 'page_id' => $rev->getPage(),
3931 'rev_id' => $rev_id );
3935 $content = $rev->getContent();
3936 $text = $content ?
$content->getWikitextForTransclusion() : null;
3938 if ( $text === false ||
$text === null ) {
3942 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3944 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3945 if ( !$message->exists() ) {
3949 $content = $message->content();
3950 $text = $message->plain();
3958 $finalTitle = $title;
3959 $title = $content->getRedirectTarget();
3963 'finalTitle' => $finalTitle,
3968 * Fetch a file and its title and register a reference to it.
3969 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3970 * @param Title $title
3971 * @param array $options Array of options to RepoGroup::findFile
3974 public function fetchFile( $title, $options = array() ) {
3975 $res = $this->fetchFileAndTitle( $title, $options );
3980 * Fetch a file and its title and register a reference to it.
3981 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3982 * @param Title $title
3983 * @param array $options Array of options to RepoGroup::findFile
3984 * @return array ( File or false, Title of file )
3986 public function fetchFileAndTitle( $title, $options = array() ) {
3987 $file = $this->fetchFileNoRegister( $title, $options );
3989 $time = $file ?
$file->getTimestamp() : false;
3990 $sha1 = $file ?
$file->getSha1() : false;
3991 # Register the file as a dependency...
3992 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3993 if ( $file && !$title->equals( $file->getTitle() ) ) {
3994 # Update fetched file title
3995 $title = $file->getTitle();
3996 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3998 return array( $file, $title );
4002 * Helper function for fetchFileAndTitle.
4004 * Also useful if you need to fetch a file but not use it yet,
4005 * for example to get the file's handler.
4007 * @param Title $title
4008 * @param array $options Array of options to RepoGroup::findFile
4011 protected function fetchFileNoRegister( $title, $options = array() ) {
4012 if ( isset( $options['broken'] ) ) {
4013 $file = false; // broken thumbnail forced by hook
4014 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4015 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4016 } else { // get by (name,timestamp)
4017 $file = wfFindFile( $title, $options );
4023 * Transclude an interwiki link.
4025 * @param Title $title
4026 * @param string $action
4030 public function interwikiTransclude( $title, $action ) {
4031 global $wgEnableScaryTranscluding;
4033 if ( !$wgEnableScaryTranscluding ) {
4034 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4037 $url = $title->getFullURL( array( 'action' => $action ) );
4039 if ( strlen( $url ) > 255 ) {
4040 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4042 return $this->fetchScaryTemplateMaybeFromCache( $url );
4046 * @param string $url
4047 * @return mixed|string
4049 public function fetchScaryTemplateMaybeFromCache( $url ) {
4050 global $wgTranscludeCacheExpiry;
4051 $dbr = wfGetDB( DB_SLAVE
);
4052 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4053 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4054 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4056 return $obj->tc_contents
;
4059 $req = MWHttpRequest
::factory( $url );
4060 $status = $req->execute(); // Status object
4061 if ( $status->isOK() ) {
4062 $text = $req->getContent();
4063 } elseif ( $req->getStatus() != 200 ) {
4064 // Though we failed to fetch the content, this status is useless.
4065 return wfMessage( 'scarytranscludefailed-httpstatus' )
4066 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4068 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4071 $dbw = wfGetDB( DB_MASTER
);
4072 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4074 'tc_time' => $dbw->timestamp( time() ),
4075 'tc_contents' => $text
4081 * Triple brace replacement -- used for template arguments
4084 * @param array $piece
4085 * @param PPFrame $frame
4089 public function argSubstitution( $piece, $frame ) {
4090 wfProfileIn( __METHOD__
);
4093 $parts = $piece['parts'];
4094 $nameWithSpaces = $frame->expand( $piece['title'] );
4095 $argName = trim( $nameWithSpaces );
4097 $text = $frame->getArgument( $argName );
4098 if ( $text === false && $parts->getLength() > 0
4099 && ( $this->ot
['html']
4101 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4104 # No match in frame, use the supplied default
4105 $object = $parts->item( 0 )->getChildren();
4107 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4108 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4109 $this->limitationWarn( 'post-expand-template-argument' );
4112 if ( $text === false && $object === false ) {
4114 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4116 if ( $error !== false ) {
4119 if ( $object !== false ) {
4120 $ret = array( 'object' => $object );
4122 $ret = array( 'text' => $text );
4125 wfProfileOut( __METHOD__
);
4130 * Return the text to be used for a given extension tag.
4131 * This is the ghost of strip().
4133 * @param array $params Associative array of parameters:
4134 * name PPNode for the tag name
4135 * attr PPNode for unparsed text where tag attributes are thought to be
4136 * attributes Optional associative array of parsed attributes
4137 * inner Contents of extension element
4138 * noClose Original text did not have a close tag
4139 * @param PPFrame $frame
4141 * @throws MWException
4144 public function extensionSubstitution( $params, $frame ) {
4145 $name = $frame->expand( $params['name'] );
4146 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4147 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4148 $marker = "{$this->mUniqPrefix}-$name-"
4149 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4151 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4152 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4153 if ( $isFunctionTag ) {
4154 $markerType = 'none';
4156 $markerType = 'general';
4158 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4159 $name = strtolower( $name );
4160 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4161 if ( isset( $params['attributes'] ) ) {
4162 $attributes = $attributes +
$params['attributes'];
4165 if ( isset( $this->mTagHooks
[$name] ) ) {
4166 # Workaround for PHP bug 35229 and similar
4167 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4168 throw new MWException( "Tag hook for $name is not callable\n" );
4170 $output = call_user_func_array( $this->mTagHooks
[$name],
4171 array( $content, $attributes, $this, $frame ) );
4172 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4173 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4174 if ( !is_callable( $callback ) ) {
4175 throw new MWException( "Tag hook for $name is not callable\n" );
4178 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4180 $output = '<span class="error">Invalid tag extension name: ' .
4181 htmlspecialchars( $name ) . '</span>';
4184 if ( is_array( $output ) ) {
4185 # Extract flags to local scope (to override $markerType)
4187 $output = $flags[0];
4192 if ( is_null( $attrText ) ) {
4195 if ( isset( $params['attributes'] ) ) {
4196 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4197 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4198 htmlspecialchars( $attrValue ) . '"';
4201 if ( $content === null ) {
4202 $output = "<$name$attrText/>";
4204 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4205 $output = "<$name$attrText>$content$close";
4209 if ( $markerType === 'none' ) {
4211 } elseif ( $markerType === 'nowiki' ) {
4212 $this->mStripState
->addNoWiki( $marker, $output );
4213 } elseif ( $markerType === 'general' ) {
4214 $this->mStripState
->addGeneral( $marker, $output );
4216 throw new MWException( __METHOD__
. ': invalid marker type' );
4222 * Increment an include size counter
4224 * @param string $type The type of expansion
4225 * @param int $size The size of the text
4226 * @return bool False if this inclusion would take it over the maximum, true otherwise
4228 public function incrementIncludeSize( $type, $size ) {
4229 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4232 $this->mIncludeSizes
[$type] +
= $size;
4238 * Increment the expensive function count
4240 * @return bool False if the limit has been exceeded
4242 public function incrementExpensiveFunctionCount() {
4243 $this->mExpensiveFunctionCount++
;
4244 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4248 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4249 * Fills $this->mDoubleUnderscores, returns the modified text
4251 * @param string $text
4255 public function doDoubleUnderscore( $text ) {
4256 wfProfileIn( __METHOD__
);
4258 # The position of __TOC__ needs to be recorded
4259 $mw = MagicWord
::get( 'toc' );
4260 if ( $mw->match( $text ) ) {
4261 $this->mShowToc
= true;
4262 $this->mForceTocPosition
= true;
4264 # Set a placeholder. At the end we'll fill it in with the TOC.
4265 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4267 # Only keep the first one.
4268 $text = $mw->replace( '', $text );
4271 # Now match and remove the rest of them
4272 $mwa = MagicWord
::getDoubleUnderscoreArray();
4273 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4275 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4276 $this->mOutput
->mNoGallery
= true;
4278 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4279 $this->mShowToc
= false;
4281 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4282 && $this->mTitle
->getNamespace() == NS_CATEGORY
4284 $this->addTrackingCategory( 'hidden-category-category' );
4286 # (bug 8068) Allow control over whether robots index a page.
4288 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4289 # is not desirable, the last one on the page should win.
4290 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4291 $this->mOutput
->setIndexPolicy( 'noindex' );
4292 $this->addTrackingCategory( 'noindex-category' );
4294 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4295 $this->mOutput
->setIndexPolicy( 'index' );
4296 $this->addTrackingCategory( 'index-category' );
4299 # Cache all double underscores in the database
4300 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4301 $this->mOutput
->setProperty( $key, '' );
4304 wfProfileOut( __METHOD__
);
4309 * Add a tracking category, getting the title from a system message,
4310 * or print a debug message if the title is invalid.
4312 * Please add any message that you use with this function to
4313 * $wgTrackingCategories. That way they will be listed on
4314 * Special:TrackingCategories.
4316 * @param string $msg Message key
4317 * @return bool Whether the addition was successful
4319 public function addTrackingCategory( $msg ) {
4320 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4321 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4324 // Important to parse with correct title (bug 31469)
4325 $cat = wfMessage( $msg )
4326 ->title( $this->getTitle() )
4327 ->inContentLanguage()
4330 # Allow tracking categories to be disabled by setting them to "-"
4331 if ( $cat === '-' ) {
4335 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4336 if ( $containerCategory ) {
4337 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4340 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4346 * This function accomplishes several tasks:
4347 * 1) Auto-number headings if that option is enabled
4348 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4349 * 3) Add a Table of contents on the top for users who have enabled the option
4350 * 4) Auto-anchor headings
4352 * It loops through all headlines, collects the necessary data, then splits up the
4353 * string and re-inserts the newly formatted headlines.
4355 * @param string $text
4356 * @param string $origText Original, untouched wikitext
4357 * @param bool $isMain
4358 * @return mixed|string
4361 public function formatHeadings( $text, $origText, $isMain = true ) {
4362 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4364 # Inhibit editsection links if requested in the page
4365 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4366 $maybeShowEditLink = $showEditLink = false;
4368 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4369 $showEditLink = $this->mOptions
->getEditSection();
4371 if ( $showEditLink ) {
4372 $this->mOutput
->setEditSectionTokens( true );
4375 # Get all headlines for numbering them and adding funky stuff like [edit]
4376 # links - this is for later, but we need the number of headlines right now
4378 $numMatches = preg_match_all(
4379 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4384 # if there are fewer than 4 headlines in the article, do not show TOC
4385 # unless it's been explicitly enabled.
4386 $enoughToc = $this->mShowToc
&&
4387 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4389 # Allow user to stipulate that a page should have a "new section"
4390 # link added via __NEWSECTIONLINK__
4391 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4392 $this->mOutput
->setNewSection( true );
4395 # Allow user to remove the "new section"
4396 # link via __NONEWSECTIONLINK__
4397 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4398 $this->mOutput
->hideNewSection( true );
4401 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4402 # override above conditions and always show TOC above first header
4403 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4404 $this->mShowToc
= true;
4412 # Ugh .. the TOC should have neat indentation levels which can be
4413 # passed to the skin functions. These are determined here
4417 $sublevelCount = array();
4418 $levelCount = array();
4423 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4424 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4425 $oldType = $this->mOutputType
;
4426 $this->setOutputType( self
::OT_WIKI
);
4427 $frame = $this->getPreprocessor()->newFrame();
4428 $root = $this->preprocessToDom( $origText );
4429 $node = $root->getFirstChild();
4434 foreach ( $matches[3] as $headline ) {
4435 $isTemplate = false;
4437 $sectionIndex = false;
4439 $markerMatches = array();
4440 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4441 $serial = $markerMatches[1];
4442 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4443 $isTemplate = ( $titleText != $baseTitleText );
4444 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4448 $prevlevel = $level;
4450 $level = $matches[1][$headlineCount];
4452 if ( $level > $prevlevel ) {
4453 # Increase TOC level
4455 $sublevelCount[$toclevel] = 0;
4456 if ( $toclevel < $wgMaxTocLevel ) {
4457 $prevtoclevel = $toclevel;
4458 $toc .= Linker
::tocIndent();
4461 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4462 # Decrease TOC level, find level to jump to
4464 for ( $i = $toclevel; $i > 0; $i-- ) {
4465 if ( $levelCount[$i] == $level ) {
4466 # Found last matching level
4469 } elseif ( $levelCount[$i] < $level ) {
4470 # Found first matching level below current level
4478 if ( $toclevel < $wgMaxTocLevel ) {
4479 if ( $prevtoclevel < $wgMaxTocLevel ) {
4480 # Unindent only if the previous toc level was shown :p
4481 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4482 $prevtoclevel = $toclevel;
4484 $toc .= Linker
::tocLineEnd();
4488 # No change in level, end TOC line
4489 if ( $toclevel < $wgMaxTocLevel ) {
4490 $toc .= Linker
::tocLineEnd();
4494 $levelCount[$toclevel] = $level;
4496 # count number of headlines for each level
4497 $sublevelCount[$toclevel]++
;
4499 for ( $i = 1; $i <= $toclevel; $i++
) {
4500 if ( !empty( $sublevelCount[$i] ) ) {
4504 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4509 # The safe header is a version of the header text safe to use for links
4511 # Remove link placeholders by the link text.
4512 # <!--LINK number-->
4514 # link text with suffix
4515 # Do this before unstrip since link text can contain strip markers
4516 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4518 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4519 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4521 # Strip out HTML (first regex removes any tag not allowed)
4523 # * <sup> and <sub> (bug 8393)
4526 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4528 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4529 # to allow setting directionality in toc items.
4530 $tocline = preg_replace(
4532 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4533 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4535 array( '', '<$1>' ),
4538 $tocline = trim( $tocline );
4540 # For the anchor, strip out HTML-y stuff period
4541 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4542 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4544 # Save headline for section edit hint before it's escaped
4545 $headlineHint = $safeHeadline;
4547 if ( $wgExperimentalHtmlIds ) {
4548 # For reverse compatibility, provide an id that's
4549 # HTML4-compatible, like we used to.
4551 # It may be worth noting, academically, that it's possible for
4552 # the legacy anchor to conflict with a non-legacy headline
4553 # anchor on the page. In this case likely the "correct" thing
4554 # would be to either drop the legacy anchors or make sure
4555 # they're numbered first. However, this would require people
4556 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4557 # manually, so let's not bother worrying about it.
4558 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4559 array( 'noninitial', 'legacy' ) );
4560 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4562 if ( $legacyHeadline == $safeHeadline ) {
4563 # No reason to have both (in fact, we can't)
4564 $legacyHeadline = false;
4567 $legacyHeadline = false;
4568 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4572 # HTML names must be case-insensitively unique (bug 10721).
4573 # This does not apply to Unicode characters per
4574 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4575 # @todo FIXME: We may be changing them depending on the current locale.
4576 $arrayKey = strtolower( $safeHeadline );
4577 if ( $legacyHeadline === false ) {
4578 $legacyArrayKey = false;
4580 $legacyArrayKey = strtolower( $legacyHeadline );
4583 # count how many in assoc. array so we can track dupes in anchors
4584 if ( isset( $refers[$arrayKey] ) ) {
4585 $refers[$arrayKey]++
;
4587 $refers[$arrayKey] = 1;
4589 if ( isset( $refers[$legacyArrayKey] ) ) {
4590 $refers[$legacyArrayKey]++
;
4592 $refers[$legacyArrayKey] = 1;
4595 # Don't number the heading if it is the only one (looks silly)
4596 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4597 # the two are different if the line contains a link
4598 $headline = Html
::element(
4600 array( 'class' => 'mw-headline-number' ),
4602 ) . ' ' . $headline;
4605 # Create the anchor for linking from the TOC to the section
4606 $anchor = $safeHeadline;
4607 $legacyAnchor = $legacyHeadline;
4608 if ( $refers[$arrayKey] > 1 ) {
4609 $anchor .= '_' . $refers[$arrayKey];
4611 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4612 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4614 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4615 $toc .= Linker
::tocLine( $anchor, $tocline,
4616 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4619 # Add the section to the section tree
4620 # Find the DOM node for this header
4621 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4622 while ( $node && !$noOffset ) {
4623 if ( $node->getName() === 'h' ) {
4624 $bits = $node->splitHeading();
4625 if ( $bits['i'] == $sectionIndex ) {
4629 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4630 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4631 $node = $node->getNextSibling();
4634 'toclevel' => $toclevel,
4637 'number' => $numbering,
4638 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4639 'fromtitle' => $titleText,
4640 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4641 'anchor' => $anchor,
4644 # give headline the correct <h#> tag
4645 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4646 // Output edit section links as markers with styles that can be customized by skins
4647 if ( $isTemplate ) {
4648 # Put a T flag in the section identifier, to indicate to extractSections()
4649 # that sections inside <includeonly> should be counted.
4650 $editsectionPage = $titleText;
4651 $editsectionSection = "T-$sectionIndex";
4652 $editsectionContent = null;
4654 $editsectionPage = $this->mTitle
->getPrefixedText();
4655 $editsectionSection = $sectionIndex;
4656 $editsectionContent = $headlineHint;
4658 // We use a bit of pesudo-xml for editsection markers. The
4659 // language converter is run later on. Using a UNIQ style marker
4660 // leads to the converter screwing up the tokens when it
4661 // converts stuff. And trying to insert strip tags fails too. At
4662 // this point all real inputted tags have already been escaped,
4663 // so we don't have to worry about a user trying to input one of
4664 // these markers directly. We use a page and section attribute
4665 // to stop the language converter from converting these
4666 // important bits of data, but put the headline hint inside a
4667 // content block because the language converter is supposed to
4668 // be able to convert that piece of data.
4669 // Gets replaced with html in ParserOutput::getText
4670 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4671 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4672 if ( $editsectionContent !== null ) {
4673 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4680 $head[$headlineCount] = Linker
::makeHeadline( $level,
4681 $matches['attrib'][$headlineCount], $anchor, $headline,
4682 $editlink, $legacyAnchor );
4687 $this->setOutputType( $oldType );
4689 # Never ever show TOC if no headers
4690 if ( $numVisible < 1 ) {
4695 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4696 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4698 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4699 $this->mOutput
->setTOCHTML( $toc );
4700 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4701 $this->mOutput
->addModules( 'mediawiki.toc' );
4705 $this->mOutput
->setSections( $tocraw );
4708 # split up and insert constructed headlines
4709 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4712 // build an array of document sections
4713 $sections = array();
4714 foreach ( $blocks as $block ) {
4715 // $head is zero-based, sections aren't.
4716 if ( empty( $head[$i - 1] ) ) {
4717 $sections[$i] = $block;
4719 $sections[$i] = $head[$i - 1] . $block;
4723 * Send a hook, one per section.
4724 * The idea here is to be able to make section-level DIVs, but to do so in a
4725 * lower-impact, more correct way than r50769
4728 * $section : the section number
4729 * &$sectionContent : ref to the content of the section
4730 * $showEditLinks : boolean describing whether this section has an edit link
4732 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4737 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4738 // append the TOC at the beginning
4739 // Top anchor now in skin
4740 $sections[0] = $sections[0] . $toc . "\n";
4743 $full .= join( '', $sections );
4745 if ( $this->mForceTocPosition
) {
4746 return str_replace( '<!--MWTOC-->', $toc, $full );
4753 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4754 * conversion, substitting signatures, {{subst:}} templates, etc.
4756 * @param string $text The text to transform
4757 * @param Title $title The Title object for the current article
4758 * @param User $user The User object describing the current user
4759 * @param ParserOptions $options Parsing options
4760 * @param bool $clearState Whether to clear the parser state first
4761 * @return string The altered wiki markup
4763 public function preSaveTransform( $text, Title
$title, User
$user,
4764 ParserOptions
$options, $clearState = true
4766 if ( $clearState ) {
4767 $magicScopeVariable = $this->lock();
4769 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4770 $this->setUser( $user );
4775 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4776 if ( $options->getPreSaveTransform() ) {
4777 $text = $this->pstPass2( $text, $user );
4779 $text = $this->mStripState
->unstripBoth( $text );
4781 $this->setUser( null ); #Reset
4787 * Pre-save transform helper function
4789 * @param string $text
4794 private function pstPass2( $text, $user ) {
4797 # Note: This is the timestamp saved as hardcoded wikitext to
4798 # the database, we use $wgContLang here in order to give
4799 # everyone the same signature and use the default one rather
4800 # than the one selected in each user's preferences.
4801 # (see also bug 12815)
4802 $ts = $this->mOptions
->getTimestamp();
4803 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4804 $ts = $timestamp->format( 'YmdHis' );
4805 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4807 # Allow translation of timezones through wiki. format() can return
4808 # whatever crap the system uses, localised or not, so we cannot
4809 # ship premade translations.
4810 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4811 $msg = wfMessage( $key )->inContentLanguage();
4812 if ( $msg->exists() ) {
4813 $tzMsg = $msg->text();
4816 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4818 # Variable replacement
4819 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4820 $text = $this->replaceVariables( $text );
4822 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4823 # which may corrupt this parser instance via its wfMessage()->text() call-
4826 $sigText = $this->getUserSig( $user );
4827 $text = strtr( $text, array(
4829 '~~~~' => "$sigText $d",
4833 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4834 $tc = '[' . Title
::legalChars() . ']';
4835 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4837 // [[ns:page (context)|]]
4838 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4839 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4840 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4841 // [[ns:page (context), context|]] (using either single or double-width comma)
4842 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4843 // [[|page]] (reverse pipe trick: add context from page title)
4844 $p2 = "/\[\[\\|($tc+)]]/";
4846 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4847 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4848 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4849 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4851 $t = $this->mTitle
->getText();
4853 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4854 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4855 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4856 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4858 # if there's no context, don't bother duplicating the title
4859 $text = preg_replace( $p2, '[[\\1]]', $text );
4862 # Trim trailing whitespace
4863 $text = rtrim( $text );
4869 * Fetch the user's signature text, if any, and normalize to
4870 * validated, ready-to-insert wikitext.
4871 * If you have pre-fetched the nickname or the fancySig option, you can
4872 * specify them here to save a database query.
4873 * Do not reuse this parser instance after calling getUserSig(),
4874 * as it may have changed if it's the $wgParser.
4877 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4878 * @param bool|null $fancySig whether the nicknname is the complete signature
4879 * or null to use default value
4882 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4883 global $wgMaxSigChars;
4885 $username = $user->getName();
4887 # If not given, retrieve from the user object.
4888 if ( $nickname === false ) {
4889 $nickname = $user->getOption( 'nickname' );
4892 if ( is_null( $fancySig ) ) {
4893 $fancySig = $user->getBoolOption( 'fancysig' );
4896 $nickname = $nickname == null ?
$username : $nickname;
4898 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4899 $nickname = $username;
4900 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4901 } elseif ( $fancySig !== false ) {
4902 # Sig. might contain markup; validate this
4903 if ( $this->validateSig( $nickname ) !== false ) {
4904 # Validated; clean up (if needed) and return it
4905 return $this->cleanSig( $nickname, true );
4907 # Failed to validate; fall back to the default
4908 $nickname = $username;
4909 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4913 # Make sure nickname doesnt get a sig in a sig
4914 $nickname = self
::cleanSigInSig( $nickname );
4916 # If we're still here, make it a link to the user page
4917 $userText = wfEscapeWikiText( $username );
4918 $nickText = wfEscapeWikiText( $nickname );
4919 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4921 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4922 ->title( $this->getTitle() )->text();
4926 * Check that the user's signature contains no bad XML
4928 * @param string $text
4929 * @return string|bool An expanded string, or false if invalid.
4931 public function validateSig( $text ) {
4932 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4936 * Clean up signature text
4938 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4939 * 2) Substitute all transclusions
4941 * @param string $text
4942 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4943 * @return string Signature text
4945 public function cleanSig( $text, $parsing = false ) {
4948 $magicScopeVariable = $this->lock();
4949 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4952 # Option to disable this feature
4953 if ( !$this->mOptions
->getCleanSignatures() ) {
4957 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4958 # => Move this logic to braceSubstitution()
4959 $substWord = MagicWord
::get( 'subst' );
4960 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4961 $substText = '{{' . $substWord->getSynonym( 0 );
4963 $text = preg_replace( $substRegex, $substText, $text );
4964 $text = self
::cleanSigInSig( $text );
4965 $dom = $this->preprocessToDom( $text );
4966 $frame = $this->getPreprocessor()->newFrame();
4967 $text = $frame->expand( $dom );
4970 $text = $this->mStripState
->unstripBoth( $text );
4977 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4979 * @param string $text
4980 * @return string Signature text with /~{3,5}/ removed
4982 public static function cleanSigInSig( $text ) {
4983 $text = preg_replace( '/~{3,5}/', '', $text );
4988 * Set up some variables which are usually set up in parse()
4989 * so that an external function can call some class members with confidence
4991 * @param Title|null $title
4992 * @param ParserOptions $options
4993 * @param int $outputType
4994 * @param bool $clearState
4996 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4997 $outputType, $clearState = true
4999 $this->startParse( $title, $options, $outputType, $clearState );
5003 * @param Title|null $title
5004 * @param ParserOptions $options
5005 * @param int $outputType
5006 * @param bool $clearState
5008 private function startParse( Title
$title = null, ParserOptions
$options,
5009 $outputType, $clearState = true
5011 $this->setTitle( $title );
5012 $this->mOptions
= $options;
5013 $this->setOutputType( $outputType );
5014 if ( $clearState ) {
5015 $this->clearState();
5020 * Wrapper for preprocess()
5022 * @param string $text The text to preprocess
5023 * @param ParserOptions $options Options
5024 * @param Title|null $title Title object or null to use $wgTitle
5027 public function transformMsg( $text, $options, $title = null ) {
5028 static $executing = false;
5030 # Guard against infinite recursion
5036 wfProfileIn( __METHOD__
);
5042 $text = $this->preprocess( $text, $title, $options );
5045 wfProfileOut( __METHOD__
);
5050 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5051 * The callback should have the following form:
5052 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5054 * Transform and return $text. Use $parser for any required context, e.g. use
5055 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5057 * Hooks may return extended information by returning an array, of which the
5058 * first numbered element (index 0) must be the return string, and all other
5059 * entries are extracted into local variables within an internal function
5060 * in the Parser class.
5062 * This interface (introduced r61913) appears to be undocumented, but
5063 * 'markerName' is used by some core tag hooks to override which strip
5064 * array their results are placed in. **Use great caution if attempting
5065 * this interface, as it is not documented and injudicious use could smash
5066 * private variables.**
5068 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5069 * @param callable $callback The callback function (and object) to use for the tag
5070 * @throws MWException
5071 * @return callable|null The old value of the mTagHooks array associated with the hook
5073 public function setHook( $tag, $callback ) {
5074 $tag = strtolower( $tag );
5075 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5076 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5078 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5079 $this->mTagHooks
[$tag] = $callback;
5080 if ( !in_array( $tag, $this->mStripList
) ) {
5081 $this->mStripList
[] = $tag;
5088 * As setHook(), but letting the contents be parsed.
5090 * Transparent tag hooks are like regular XML-style tag hooks, except they
5091 * operate late in the transformation sequence, on HTML instead of wikitext.
5093 * This is probably obsoleted by things dealing with parser frames?
5094 * The only extension currently using it is geoserver.
5097 * @todo better document or deprecate this
5099 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5100 * @param callable $callback The callback function (and object) to use for the tag
5101 * @throws MWException
5102 * @return callable|null The old value of the mTagHooks array associated with the hook
5104 public function setTransparentTagHook( $tag, $callback ) {
5105 $tag = strtolower( $tag );
5106 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5107 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5109 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5110 $this->mTransparentTagHooks
[$tag] = $callback;
5116 * Remove all tag hooks
5118 public function clearTagHooks() {
5119 $this->mTagHooks
= array();
5120 $this->mFunctionTagHooks
= array();
5121 $this->mStripList
= $this->mDefaultStripList
;
5125 * Create a function, e.g. {{sum:1|2|3}}
5126 * The callback function should have the form:
5127 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5129 * Or with SFH_OBJECT_ARGS:
5130 * function myParserFunction( $parser, $frame, $args ) { ... }
5132 * The callback may either return the text result of the function, or an array with the text
5133 * in element 0, and a number of flags in the other elements. The names of the flags are
5134 * specified in the keys. Valid flags are:
5135 * found The text returned is valid, stop processing the template. This
5137 * nowiki Wiki markup in the return value should be escaped
5138 * isHTML The returned text is HTML, armour it against wikitext transformation
5140 * @param string $id The magic word ID
5141 * @param callable $callback The callback function (and object) to use
5142 * @param int $flags A combination of the following flags:
5143 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5145 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5146 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5147 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5148 * the arguments, and to control the way they are expanded.
5150 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5151 * arguments, for instance:
5152 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5154 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5155 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5156 * working if/when this is changed.
5158 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5161 * Please read the documentation in includes/parser/Preprocessor.php for more information
5162 * about the methods available in PPFrame and PPNode.
5164 * @throws MWException
5165 * @return string|callable The old callback function for this name, if any
5167 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5170 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5171 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5173 # Add to function cache
5174 $mw = MagicWord
::get( $id );
5176 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5179 $synonyms = $mw->getSynonyms();
5180 $sensitive = intval( $mw->isCaseSensitive() );
5182 foreach ( $synonyms as $syn ) {
5184 if ( !$sensitive ) {
5185 $syn = $wgContLang->lc( $syn );
5188 if ( !( $flags & SFH_NO_HASH
) ) {
5191 # Remove trailing colon
5192 if ( substr( $syn, -1, 1 ) === ':' ) {
5193 $syn = substr( $syn, 0, -1 );
5195 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5201 * Get all registered function hook identifiers
5205 public function getFunctionHooks() {
5206 return array_keys( $this->mFunctionHooks
);
5210 * Create a tag function, e.g. "<test>some stuff</test>".
5211 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5212 * Unlike parser functions, their content is not preprocessed.
5213 * @param string $tag
5214 * @param callable $callback
5216 * @throws MWException
5219 public function setFunctionTagHook( $tag, $callback, $flags ) {
5220 $tag = strtolower( $tag );
5221 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5222 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5224 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5225 $this->mFunctionTagHooks
[$tag] : null;
5226 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5228 if ( !in_array( $tag, $this->mStripList
) ) {
5229 $this->mStripList
[] = $tag;
5236 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5237 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5238 * Placeholders created in Skin::makeLinkObj()
5240 * @param string $text
5241 * @param int $options
5243 * @return array Array of link CSS classes, indexed by PDBK.
5245 public function replaceLinkHolders( &$text, $options = 0 ) {
5246 return $this->mLinkHolders
->replace( $text );
5250 * Replace "<!--LINK-->" link placeholders with plain text of links
5251 * (not HTML-formatted).
5253 * @param string $text
5256 public function replaceLinkHoldersText( $text ) {
5257 return $this->mLinkHolders
->replaceText( $text );
5261 * Renders an image gallery from a text with one line per image.
5262 * text labels may be given by using |-style alternative text. E.g.
5263 * Image:one.jpg|The number "1"
5264 * Image:tree.jpg|A tree
5265 * given as text will return the HTML of a gallery with two images,
5266 * labeled 'The number "1"' and
5269 * @param string $text
5270 * @param array $params
5271 * @return string HTML
5273 public function renderImageGallery( $text, $params ) {
5274 wfProfileIn( __METHOD__
);
5277 if ( isset( $params['mode'] ) ) {
5278 $mode = $params['mode'];
5282 $ig = ImageGalleryBase
::factory( $mode );
5283 } catch ( MWException
$e ) {
5284 // If invalid type set, fallback to default.
5285 $ig = ImageGalleryBase
::factory( false );
5288 $ig->setContextTitle( $this->mTitle
);
5289 $ig->setShowBytes( false );
5290 $ig->setShowFilename( false );
5291 $ig->setParser( $this );
5292 $ig->setHideBadImages();
5293 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5295 if ( isset( $params['showfilename'] ) ) {
5296 $ig->setShowFilename( true );
5298 $ig->setShowFilename( false );
5300 if ( isset( $params['caption'] ) ) {
5301 $caption = $params['caption'];
5302 $caption = htmlspecialchars( $caption );
5303 $caption = $this->replaceInternalLinks( $caption );
5304 $ig->setCaptionHtml( $caption );
5306 if ( isset( $params['perrow'] ) ) {
5307 $ig->setPerRow( $params['perrow'] );
5309 if ( isset( $params['widths'] ) ) {
5310 $ig->setWidths( $params['widths'] );
5312 if ( isset( $params['heights'] ) ) {
5313 $ig->setHeights( $params['heights'] );
5315 $ig->setAdditionalOptions( $params );
5317 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5319 $lines = StringUtils
::explode( "\n", $text );
5320 foreach ( $lines as $line ) {
5321 # match lines like these:
5322 # Image:someimage.jpg|This is some image
5324 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5326 if ( count( $matches ) == 0 ) {
5330 if ( strpos( $matches[0], '%' ) !== false ) {
5331 $matches[1] = rawurldecode( $matches[1] );
5333 $title = Title
::newFromText( $matches[1], NS_FILE
);
5334 if ( is_null( $title ) ) {
5335 # Bogus title. Ignore these so we don't bomb out later.
5339 # We need to get what handler the file uses, to figure out parameters.
5340 # Note, a hook can overide the file name, and chose an entirely different
5341 # file (which potentially could be of a different type and have different handler).
5344 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5345 array( $this, $title, &$options, &$descQuery ) );
5346 # Don't register it now, as ImageGallery does that later.
5347 $file = $this->fetchFileNoRegister( $title, $options );
5348 $handler = $file ?
$file->getHandler() : false;
5350 wfProfileIn( __METHOD__
. '-getMagicWord' );
5352 'img_alt' => 'gallery-internal-alt',
5353 'img_link' => 'gallery-internal-link',
5356 $paramMap = $paramMap +
$handler->getParamMap();
5357 // We don't want people to specify per-image widths.
5358 // Additionally the width parameter would need special casing anyhow.
5359 unset( $paramMap['img_width'] );
5362 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5363 wfProfileOut( __METHOD__
. '-getMagicWord' );
5368 $handlerOptions = array();
5369 if ( isset( $matches[3] ) ) {
5370 // look for an |alt= definition while trying not to break existing
5371 // captions with multiple pipes (|) in it, until a more sensible grammar
5372 // is defined for images in galleries
5374 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5375 // splitting on '|' is a bit odd, and different from makeImage.
5376 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5377 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5379 foreach ( $parameterMatches as $parameterMatch ) {
5380 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5382 $paramName = $paramMap[$magicName];
5384 switch ( $paramName ) {
5385 case 'gallery-internal-alt':
5386 $alt = $this->stripAltText( $match, false );
5388 case 'gallery-internal-link':
5389 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5390 $chars = self
::EXT_LINK_URL_CLASS
;
5391 $prots = $this->mUrlProtocols
;
5392 //check to see if link matches an absolute url, if not then it must be a wiki link.
5393 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5396 $localLinkTitle = Title
::newFromText( $linkValue );
5397 if ( $localLinkTitle !== null ) {
5398 $link = $localLinkTitle->getLinkURL();
5403 // Must be a handler specific parameter.
5404 if ( $handler->validateParam( $paramName, $match ) ) {
5405 $handlerOptions[$paramName] = $match;
5407 // Guess not. Append it to the caption.
5408 wfDebug( "$parameterMatch failed parameter validation\n" );
5409 $label .= '|' . $parameterMatch;
5414 // concatenate all other pipes
5415 $label .= '|' . $parameterMatch;
5418 // remove the first pipe
5419 $label = substr( $label, 1 );
5422 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5424 $html = $ig->toHTML();
5425 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5426 wfProfileOut( __METHOD__
);
5431 * @param string $handler
5434 public function getImageParams( $handler ) {
5436 $handlerClass = get_class( $handler );
5440 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5441 # Initialise static lists
5442 static $internalParamNames = array(
5443 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5444 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5445 'bottom', 'text-bottom' ),
5446 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5447 'upright', 'border', 'link', 'alt', 'class' ),
5449 static $internalParamMap;
5450 if ( !$internalParamMap ) {
5451 $internalParamMap = array();
5452 foreach ( $internalParamNames as $type => $names ) {
5453 foreach ( $names as $name ) {
5454 $magicName = str_replace( '-', '_', "img_$name" );
5455 $internalParamMap[$magicName] = array( $type, $name );
5460 # Add handler params
5461 $paramMap = $internalParamMap;
5463 $handlerParamMap = $handler->getParamMap();
5464 foreach ( $handlerParamMap as $magic => $paramName ) {
5465 $paramMap[$magic] = array( 'handler', $paramName );
5468 $this->mImageParams
[$handlerClass] = $paramMap;
5469 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5471 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5475 * Parse image options text and use it to make an image
5477 * @param Title $title
5478 * @param string $options
5479 * @param LinkHolderArray|bool $holders
5480 * @return string HTML
5482 public function makeImage( $title, $options, $holders = false ) {
5483 # Check if the options text is of the form "options|alt text"
5485 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5486 # * left no resizing, just left align. label is used for alt= only
5487 # * right same, but right aligned
5488 # * none same, but not aligned
5489 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5490 # * center center the image
5491 # * frame Keep original image size, no magnify-button.
5492 # * framed Same as "frame"
5493 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5494 # * upright reduce width for upright images, rounded to full __0 px
5495 # * border draw a 1px border around the image
5496 # * alt Text for HTML alt attribute (defaults to empty)
5497 # * class Set a class for img node
5498 # * link Set the target of the image link. Can be external, interwiki, or local
5499 # vertical-align values (no % or length right now):
5509 $parts = StringUtils
::explode( "|", $options );
5511 # Give extensions a chance to select the file revision for us
5514 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5515 array( $this, $title, &$options, &$descQuery ) );
5516 # Fetch and register the file (file title may be different via hooks)
5517 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5520 $handler = $file ?
$file->getHandler() : false;
5522 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5525 $this->addTrackingCategory( 'broken-file-category' );
5528 # Process the input parameters
5530 $params = array( 'frame' => array(), 'handler' => array(),
5531 'horizAlign' => array(), 'vertAlign' => array() );
5532 $seenformat = false;
5533 foreach ( $parts as $part ) {
5534 $part = trim( $part );
5535 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5537 if ( isset( $paramMap[$magicName] ) ) {
5538 list( $type, $paramName ) = $paramMap[$magicName];
5540 # Special case; width and height come in one variable together
5541 if ( $type === 'handler' && $paramName === 'width' ) {
5542 $parsedWidthParam = $this->parseWidthParam( $value );
5543 if ( isset( $parsedWidthParam['width'] ) ) {
5544 $width = $parsedWidthParam['width'];
5545 if ( $handler->validateParam( 'width', $width ) ) {
5546 $params[$type]['width'] = $width;
5550 if ( isset( $parsedWidthParam['height'] ) ) {
5551 $height = $parsedWidthParam['height'];
5552 if ( $handler->validateParam( 'height', $height ) ) {
5553 $params[$type]['height'] = $height;
5557 # else no validation -- bug 13436
5559 if ( $type === 'handler' ) {
5560 # Validate handler parameter
5561 $validated = $handler->validateParam( $paramName, $value );
5563 # Validate internal parameters
5564 switch ( $paramName ) {
5568 # @todo FIXME: Possibly check validity here for
5569 # manualthumb? downstream behavior seems odd with
5570 # missing manual thumbs.
5572 $value = $this->stripAltText( $value, $holders );
5575 $chars = self
::EXT_LINK_URL_CLASS
;
5576 $prots = $this->mUrlProtocols
;
5577 if ( $value === '' ) {
5578 $paramName = 'no-link';
5581 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5582 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5583 $paramName = 'link-url';
5584 $this->mOutput
->addExternalLink( $value );
5585 if ( $this->mOptions
->getExternalLinkTarget() ) {
5586 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5591 $linkTitle = Title
::newFromText( $value );
5593 $paramName = 'link-title';
5594 $value = $linkTitle;
5595 $this->mOutput
->addLink( $linkTitle );
5603 // use first appearing option, discard others.
5604 $validated = ! $seenformat;
5608 # Most other things appear to be empty or numeric...
5609 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5614 $params[$type][$paramName] = $value;
5618 if ( !$validated ) {
5623 # Process alignment parameters
5624 if ( $params['horizAlign'] ) {
5625 $params['frame']['align'] = key( $params['horizAlign'] );
5627 if ( $params['vertAlign'] ) {
5628 $params['frame']['valign'] = key( $params['vertAlign'] );
5631 $params['frame']['caption'] = $caption;
5633 # Will the image be presented in a frame, with the caption below?
5634 $imageIsFramed = isset( $params['frame']['frame'] )
5635 ||
isset( $params['frame']['framed'] )
5636 ||
isset( $params['frame']['thumbnail'] )
5637 ||
isset( $params['frame']['manualthumb'] );
5639 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5640 # came to also set the caption, ordinary text after the image -- which
5641 # makes no sense, because that just repeats the text multiple times in
5642 # screen readers. It *also* came to set the title attribute.
5644 # Now that we have an alt attribute, we should not set the alt text to
5645 # equal the caption: that's worse than useless, it just repeats the
5646 # text. This is the framed/thumbnail case. If there's no caption, we
5647 # use the unnamed parameter for alt text as well, just for the time be-
5648 # ing, if the unnamed param is set and the alt param is not.
5650 # For the future, we need to figure out if we want to tweak this more,
5651 # e.g., introducing a title= parameter for the title; ignoring the un-
5652 # named parameter entirely for images without a caption; adding an ex-
5653 # plicit caption= parameter and preserving the old magic unnamed para-
5655 if ( $imageIsFramed ) { # Framed image
5656 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5657 # No caption or alt text, add the filename as the alt text so
5658 # that screen readers at least get some description of the image
5659 $params['frame']['alt'] = $title->getText();
5661 # Do not set $params['frame']['title'] because tooltips don't make sense
5663 } else { # Inline image
5664 if ( !isset( $params['frame']['alt'] ) ) {
5665 # No alt text, use the "caption" for the alt text
5666 if ( $caption !== '' ) {
5667 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5669 # No caption, fall back to using the filename for the
5671 $params['frame']['alt'] = $title->getText();
5674 # Use the "caption" for the tooltip text
5675 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5678 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5680 # Linker does the rest
5681 $time = isset( $options['time'] ) ?
$options['time'] : false;
5682 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5683 $time, $descQuery, $this->mOptions
->getThumbSize() );
5685 # Give the handler a chance to modify the parser object
5687 $handler->parserTransformHook( $this, $file );
5694 * @param string $caption
5695 * @param LinkHolderArray|bool $holders
5696 * @return mixed|string
5698 protected function stripAltText( $caption, $holders ) {
5699 # Strip bad stuff out of the title (tooltip). We can't just use
5700 # replaceLinkHoldersText() here, because if this function is called
5701 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5703 $tooltip = $holders->replaceText( $caption );
5705 $tooltip = $this->replaceLinkHoldersText( $caption );
5708 # make sure there are no placeholders in thumbnail attributes
5709 # that are later expanded to html- so expand them now and
5711 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5712 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5718 * Set a flag in the output object indicating that the content is dynamic and
5719 * shouldn't be cached.
5721 public function disableCache() {
5722 wfDebug( "Parser output marked as uncacheable.\n" );
5723 if ( !$this->mOutput
) {
5724 throw new MWException( __METHOD__
.
5725 " can only be called when actually parsing something" );
5727 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5728 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5732 * Callback from the Sanitizer for expanding items found in HTML attribute
5733 * values, so they can be safely tested and escaped.
5735 * @param string $text
5736 * @param bool|PPFrame $frame
5739 public function attributeStripCallback( &$text, $frame = false ) {
5740 $text = $this->replaceVariables( $text, $frame );
5741 $text = $this->mStripState
->unstripBoth( $text );
5750 public function getTags() {
5752 array_keys( $this->mTransparentTagHooks
),
5753 array_keys( $this->mTagHooks
),
5754 array_keys( $this->mFunctionTagHooks
)
5759 * Replace transparent tags in $text with the values given by the callbacks.
5761 * Transparent tag hooks are like regular XML-style tag hooks, except they
5762 * operate late in the transformation sequence, on HTML instead of wikitext.
5764 * @param string $text
5768 public function replaceTransparentTags( $text ) {
5770 $elements = array_keys( $this->mTransparentTagHooks
);
5771 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5772 $replacements = array();
5774 foreach ( $matches as $marker => $data ) {
5775 list( $element, $content, $params, $tag ) = $data;
5776 $tagName = strtolower( $element );
5777 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5778 $output = call_user_func_array(
5779 $this->mTransparentTagHooks
[$tagName],
5780 array( $content, $params, $this )
5785 $replacements[$marker] = $output;
5787 return strtr( $text, $replacements );
5791 * Break wikitext input into sections, and either pull or replace
5792 * some particular section's text.
5794 * External callers should use the getSection and replaceSection methods.
5796 * @param string $text Page wikitext
5797 * @param string|number $sectionId A section identifier string of the form:
5798 * "<flag1> - <flag2> - ... - <section number>"
5800 * Currently the only recognised flag is "T", which means the target section number
5801 * was derived during a template inclusion parse, in other words this is a template
5802 * section edit link. If no flags are given, it was an ordinary section edit link.
5803 * This flag is required to avoid a section numbering mismatch when a section is
5804 * enclosed by "<includeonly>" (bug 6563).
5806 * The section number 0 pulls the text before the first heading; other numbers will
5807 * pull the given section along with its lower-level subsections. If the section is
5808 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5810 * Section 0 is always considered to exist, even if it only contains the empty
5811 * string. If $text is the empty string and section 0 is replaced, $newText is
5814 * @param string $mode One of "get" or "replace"
5815 * @param string $newText Replacement text for section data.
5816 * @return string For "get", the extracted section text.
5817 * for "replace", the whole page with the section replaced.
5819 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5820 global $wgTitle; # not generally used but removes an ugly failure mode
5822 $magicScopeVariable = $this->lock();
5823 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5825 $frame = $this->getPreprocessor()->newFrame();
5827 # Process section extraction flags
5829 $sectionParts = explode( '-', $sectionId );
5830 $sectionIndex = array_pop( $sectionParts );
5831 foreach ( $sectionParts as $part ) {
5832 if ( $part === 'T' ) {
5833 $flags |
= self
::PTD_FOR_INCLUSION
;
5837 # Check for empty input
5838 if ( strval( $text ) === '' ) {
5839 # Only sections 0 and T-0 exist in an empty document
5840 if ( $sectionIndex == 0 ) {
5841 if ( $mode === 'get' ) {
5847 if ( $mode === 'get' ) {
5855 # Preprocess the text
5856 $root = $this->preprocessToDom( $text, $flags );
5858 # <h> nodes indicate section breaks
5859 # They can only occur at the top level, so we can find them by iterating the root's children
5860 $node = $root->getFirstChild();
5862 # Find the target section
5863 if ( $sectionIndex == 0 ) {
5864 # Section zero doesn't nest, level=big
5865 $targetLevel = 1000;
5868 if ( $node->getName() === 'h' ) {
5869 $bits = $node->splitHeading();
5870 if ( $bits['i'] == $sectionIndex ) {
5871 $targetLevel = $bits['level'];
5875 if ( $mode === 'replace' ) {
5876 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5878 $node = $node->getNextSibling();
5884 if ( $mode === 'get' ) {
5891 # Find the end of the section, including nested sections
5893 if ( $node->getName() === 'h' ) {
5894 $bits = $node->splitHeading();
5895 $curLevel = $bits['level'];
5896 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5900 if ( $mode === 'get' ) {
5901 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5903 $node = $node->getNextSibling();
5906 # Write out the remainder (in replace mode only)
5907 if ( $mode === 'replace' ) {
5908 # Output the replacement text
5909 # Add two newlines on -- trailing whitespace in $newText is conventionally
5910 # stripped by the editor, so we need both newlines to restore the paragraph gap
5911 # Only add trailing whitespace if there is newText
5912 if ( $newText != "" ) {
5913 $outText .= $newText . "\n\n";
5917 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5918 $node = $node->getNextSibling();
5922 if ( is_string( $outText ) ) {
5923 # Re-insert stripped tags
5924 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5931 * This function returns the text of a section, specified by a number ($section).
5932 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5933 * the first section before any such heading (section 0).
5935 * If a section contains subsections, these are also returned.
5937 * @param string $text Text to look in
5938 * @param string|number $sectionId Section identifier as a number or string
5939 * (e.g. 0, 1 or 'T-1').
5940 * @param string $defaultText Default to return if section is not found
5942 * @return string Text of the requested section
5944 public function getSection( $text, $sectionId, $defaultText = '' ) {
5945 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5949 * This function returns $oldtext after the content of the section
5950 * specified by $section has been replaced with $text. If the target
5951 * section does not exist, $oldtext is returned unchanged.
5953 * @param string $oldText Former text of the article
5954 * @param string|number $sectionId Section identifier as a number or string
5955 * (e.g. 0, 1 or 'T-1').
5956 * @param string $newText Replacing text
5958 * @return string Modified text
5960 public function replaceSection( $oldText, $sectionId, $newText ) {
5961 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5965 * Get the ID of the revision we are parsing
5969 public function getRevisionId() {
5970 return $this->mRevisionId
;
5974 * Get the revision object for $this->mRevisionId
5976 * @return Revision|null Either a Revision object or null
5977 * @since 1.23 (public since 1.23)
5979 public function getRevisionObject() {
5980 if ( !is_null( $this->mRevisionObject
) ) {
5981 return $this->mRevisionObject
;
5983 if ( is_null( $this->mRevisionId
) ) {
5987 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5988 return $this->mRevisionObject
;
5992 * Get the timestamp associated with the current revision, adjusted for
5993 * the default server-local timestamp
5996 public function getRevisionTimestamp() {
5997 if ( is_null( $this->mRevisionTimestamp
) ) {
5998 wfProfileIn( __METHOD__
);
6002 $revObject = $this->getRevisionObject();
6003 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6005 # The cryptic '' timezone parameter tells to use the site-default
6006 # timezone offset instead of the user settings.
6008 # Since this value will be saved into the parser cache, served
6009 # to other users, and potentially even used inside links and such,
6010 # it needs to be consistent for all visitors.
6011 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6013 wfProfileOut( __METHOD__
);
6015 return $this->mRevisionTimestamp
;
6019 * Get the name of the user that edited the last revision
6021 * @return string User name
6023 public function getRevisionUser() {
6024 if ( is_null( $this->mRevisionUser
) ) {
6025 $revObject = $this->getRevisionObject();
6027 # if this template is subst: the revision id will be blank,
6028 # so just use the current user's name
6030 $this->mRevisionUser
= $revObject->getUserText();
6031 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6032 $this->mRevisionUser
= $this->getUser()->getName();
6035 return $this->mRevisionUser
;
6039 * Get the size of the revision
6041 * @return int|null Revision size
6043 public function getRevisionSize() {
6044 if ( is_null( $this->mRevisionSize
) ) {
6045 $revObject = $this->getRevisionObject();
6047 # if this variable is subst: the revision id will be blank,
6048 # so just use the parser input size, because the own substituation
6049 # will change the size.
6051 $this->mRevisionSize
= $revObject->getSize();
6052 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6053 $this->mRevisionSize
= $this->mInputSize
;
6056 return $this->mRevisionSize
;
6060 * Mutator for $mDefaultSort
6062 * @param string $sort New value
6064 public function setDefaultSort( $sort ) {
6065 $this->mDefaultSort
= $sort;
6066 $this->mOutput
->setProperty( 'defaultsort', $sort );
6070 * Accessor for $mDefaultSort
6071 * Will use the empty string if none is set.
6073 * This value is treated as a prefix, so the
6074 * empty string is equivalent to sorting by
6079 public function getDefaultSort() {
6080 if ( $this->mDefaultSort
!== false ) {
6081 return $this->mDefaultSort
;
6088 * Accessor for $mDefaultSort
6089 * Unlike getDefaultSort(), will return false if none is set
6091 * @return string|bool
6093 public function getCustomDefaultSort() {
6094 return $this->mDefaultSort
;
6098 * Try to guess the section anchor name based on a wikitext fragment
6099 * presumably extracted from a heading, for example "Header" from
6102 * @param string $text
6106 public function guessSectionNameFromWikiText( $text ) {
6107 # Strip out wikitext links(they break the anchor)
6108 $text = $this->stripSectionName( $text );
6109 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6110 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6114 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6115 * instead. For use in redirects, since IE6 interprets Redirect: headers
6116 * as something other than UTF-8 (apparently?), resulting in breakage.
6118 * @param string $text The section name
6119 * @return string An anchor
6121 public function guessLegacySectionNameFromWikiText( $text ) {
6122 # Strip out wikitext links(they break the anchor)
6123 $text = $this->stripSectionName( $text );
6124 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6125 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6129 * Strips a text string of wikitext for use in a section anchor
6131 * Accepts a text string and then removes all wikitext from the
6132 * string and leaves only the resultant text (i.e. the result of
6133 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6134 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6135 * to create valid section anchors by mimicing the output of the
6136 * parser when headings are parsed.
6138 * @param string $text Text string to be stripped of wikitext
6139 * for use in a Section anchor
6140 * @return string Filtered text string
6142 public function stripSectionName( $text ) {
6143 # Strip internal link markup
6144 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6145 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6147 # Strip external link markup
6148 # @todo FIXME: Not tolerant to blank link text
6149 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6150 # on how many empty links there are on the page - need to figure that out.
6151 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6153 # Parse wikitext quotes (italics & bold)
6154 $text = $this->doQuotes( $text );
6157 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6162 * strip/replaceVariables/unstrip for preprocessor regression testing
6164 * @param string $text
6165 * @param Title $title
6166 * @param ParserOptions $options
6167 * @param int $outputType
6171 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6172 $magicScopeVariable = $this->lock();
6173 $this->startParse( $title, $options, $outputType, true );
6175 $text = $this->replaceVariables( $text );
6176 $text = $this->mStripState
->unstripBoth( $text );
6177 $text = Sanitizer
::removeHTMLtags( $text );
6182 * @param string $text
6183 * @param Title $title
6184 * @param ParserOptions $options
6187 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6188 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6192 * @param string $text
6193 * @param Title $title
6194 * @param ParserOptions $options
6197 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6198 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6202 * Call a callback function on all regions of the given text that are not
6203 * inside strip markers, and replace those regions with the return value
6204 * of the callback. For example, with input:
6208 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6209 * two strings will be replaced with the value returned by the callback in
6213 * @param callable $callback
6217 public function markerSkipCallback( $s, $callback ) {
6220 while ( $i < strlen( $s ) ) {
6221 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6222 if ( $markerStart === false ) {
6223 $out .= call_user_func( $callback, substr( $s, $i ) );
6226 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6227 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6228 if ( $markerEnd === false ) {
6229 $out .= substr( $s, $markerStart );
6232 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6233 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6242 * Remove any strip markers found in the given text.
6244 * @param string $text Input string
6247 public function killMarkers( $text ) {
6248 return $this->mStripState
->killMarkers( $text );
6252 * Save the parser state required to convert the given half-parsed text to
6253 * HTML. "Half-parsed" in this context means the output of
6254 * recursiveTagParse() or internalParse(). This output has strip markers
6255 * from replaceVariables (extensionSubstitution() etc.), and link
6256 * placeholders from replaceLinkHolders().
6258 * Returns an array which can be serialized and stored persistently. This
6259 * array can later be loaded into another parser instance with
6260 * unserializeHalfParsedText(). The text can then be safely incorporated into
6261 * the return value of a parser hook.
6263 * @param string $text
6267 public function serializeHalfParsedText( $text ) {
6268 wfProfileIn( __METHOD__
);
6271 'version' => self
::HALF_PARSED_VERSION
,
6272 'stripState' => $this->mStripState
->getSubState( $text ),
6273 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6275 wfProfileOut( __METHOD__
);
6280 * Load the parser state given in the $data array, which is assumed to
6281 * have been generated by serializeHalfParsedText(). The text contents is
6282 * extracted from the array, and its markers are transformed into markers
6283 * appropriate for the current Parser instance. This transformed text is
6284 * returned, and can be safely included in the return value of a parser
6287 * If the $data array has been stored persistently, the caller should first
6288 * check whether it is still valid, by calling isValidHalfParsedText().
6290 * @param array $data Serialized data
6291 * @throws MWException
6294 public function unserializeHalfParsedText( $data ) {
6295 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6296 throw new MWException( __METHOD__
. ': invalid version' );
6299 # First, extract the strip state.
6300 $texts = array( $data['text'] );
6301 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6303 # Now renumber links
6304 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6306 # Should be good to go.
6311 * Returns true if the given array, presumed to be generated by
6312 * serializeHalfParsedText(), is compatible with the current version of the
6315 * @param array $data
6319 public function isValidHalfParsedText( $data ) {
6320 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6324 * Parsed a width param of imagelink like 300px or 200x300px
6326 * @param string $value
6331 public function parseWidthParam( $value ) {
6332 $parsedWidthParam = array();
6333 if ( $value === '' ) {
6334 return $parsedWidthParam;
6337 # (bug 13500) In both cases (width/height and width only),
6338 # permit trailing "px" for backward compatibility.
6339 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6340 $width = intval( $m[1] );
6341 $height = intval( $m[2] );
6342 $parsedWidthParam['width'] = $width;
6343 $parsedWidthParam['height'] = $height;
6344 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6345 $width = intval( $value );
6346 $parsedWidthParam['width'] = $width;
6348 return $parsedWidthParam;
6352 * Lock the current instance of the parser.
6354 * This is meant to stop someone from calling the parser
6355 * recursively and messing up all the strip state.
6357 * @throws MWException If parser is in a parse
6358 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6360 protected function lock() {
6361 if ( $this->mInParse
) {
6362 throw new MWException( "Parser state cleared while parsing. "
6363 . "Did you call Parser::parse recursively?" );
6365 $this->mInParse
= true;
6368 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6369 $that->mInParse
= false;
6372 return $recursiveCheck;
6376 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6378 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6379 * or if there is more than one <p/> tag in the input HTML.
6381 * @param string $html
6385 public static function stripOuterParagraph( $html ) {
6387 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6388 if ( strpos( $m[1], '</p>' ) === false ) {
6397 * Return this parser if it is not doing anything, otherwise
6398 * get a fresh parser. You can use this method by doing
6399 * $myParser = $wgParser->getFreshParser(), or more simply
6400 * $wgParser->getFreshParser()->parse( ... );
6401 * if you're unsure if $wgParser is safe to use.
6404 * @return Parser A parser object that is not parsing anything
6406 public function getFreshParser() {
6407 global $wgParserConf;
6408 if ( $this->mInParse
) {
6409 return new $wgParserConf['class']( $wgParserConf );