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.
116 * Prefix for temporary replacement strings generated by the preprocessor
117 * ("strip markers"). Using \x7f at the front gives us a little extra
118 * robustness since it shouldn't match when butted up against
119 * identifier-like string constructs.
121 * Must not consist of all title characters, or else it will change
122 * the behavior of <nowiki> in a link.
124 const MARKER_PREFIX
= "\x7fUNIQ";
125 /** Suffix for strip markers */
126 const MARKER_SUFFIX
= "-QINU\x7f";
127 /** Regex which matches the state ID part of strip markers */
128 const MARKER_STATE_ID_REGEX
= '[0-9a-f]{16}';
130 # Markers used for wrapping the table of contents
131 const TOC_START
= '<mw:toc>';
132 const TOC_END
= '</mw:toc>';
135 public $mTagHooks = array();
136 public $mTransparentTagHooks = array();
137 public $mFunctionHooks = array();
138 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
139 public $mFunctionTagHooks = array();
140 public $mStripList = array();
141 public $mDefaultStripList = array();
142 public $mVarCache = array();
143 public $mImageParams = array();
144 public $mImageParamsMagicArray = array();
145 public $mMarkerIndex = 0;
146 public $mFirstCall = true;
148 # Initialised by initialiseVariables()
151 * @var MagicWordArray
156 * @var MagicWordArray
159 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
161 # Cleared with clearState():
166 public $mAutonumber, $mDTopen;
173 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
175 * @var LinkHolderArray
177 public $mLinkHolders;
180 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
181 public $mDefaultSort;
182 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
183 public $mExpensiveFunctionCount; # number of expensive parser function calls
184 public $mShowToc, $mForceTocPosition;
189 public $mUser; # User object; only used when doing pre-save transform
192 # These are variables reset at least once per parse regardless of $clearState
202 public $mTitle; # Title context, used for self-link rendering and similar things
203 public $mOutputType; # Output type, one of the OT_xxx constants
204 public $ot; # Shortcut alias, see setOutputType()
205 public $mRevisionObject; # The revision object of the specified revision ID
206 public $mRevisionId; # ID to display in {{REVISIONID}} tags
207 public $mRevisionTimestamp; # The timestamp of the specified revision ID
208 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
209 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
210 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
211 public $mInputSize = false; # For {{PAGESIZE}} on current page.
219 * @var array Array with the language name of each language link (i.e. the
220 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
221 * duplicate language links to the ParserOutput.
223 public $mLangLinkLanguages;
226 * @var MapCacheLRU|null
229 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
231 public $currentRevisionCache;
234 * @var bool Recursive call protection.
235 * This variable should be treated as if it were private.
237 public $mInParse = false;
242 public function __construct( $conf = array() ) {
243 $this->mConf
= $conf;
244 $this->mUrlProtocols
= wfUrlProtocols();
245 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
246 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
247 if ( isset( $conf['preprocessorClass'] ) ) {
248 $this->mPreprocessorClass
= $conf['preprocessorClass'];
249 } elseif ( defined( 'HPHP_VERSION' ) ) {
250 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
251 $this->mPreprocessorClass
= 'Preprocessor_Hash';
252 } elseif ( extension_loaded( 'domxml' ) ) {
253 # PECL extension that conflicts with the core DOM extension (bug 13770)
254 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
255 $this->mPreprocessorClass
= 'Preprocessor_Hash';
256 } elseif ( extension_loaded( 'dom' ) ) {
257 $this->mPreprocessorClass
= 'Preprocessor_DOM';
259 $this->mPreprocessorClass
= 'Preprocessor_Hash';
261 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
265 * Reduce memory usage to reduce the impact of circular references
267 public function __destruct() {
268 if ( isset( $this->mLinkHolders
) ) {
269 unset( $this->mLinkHolders
);
271 foreach ( $this as $name => $value ) {
272 unset( $this->$name );
277 * Allow extensions to clean up when the parser is cloned
279 public function __clone() {
280 $this->mInParse
= false;
282 // Bug 56226: When you create a reference "to" an object field, that
283 // makes the object field itself be a reference too (until the other
284 // reference goes out of scope). When cloning, any field that's a
285 // reference is copied as a reference in the new object. Both of these
286 // are defined PHP5 behaviors, as inconvenient as it is for us when old
287 // hooks from PHP4 days are passing fields by reference.
288 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
289 // Make a non-reference copy of the field, then rebind the field to
290 // reference the new copy.
296 wfRunHooks( 'ParserCloned', array( $this ) );
300 * Do various kinds of initialisation on the first call of the parser
302 public function firstCallInit() {
303 if ( !$this->mFirstCall
) {
306 $this->mFirstCall
= false;
308 wfProfileIn( __METHOD__
);
310 CoreParserFunctions
::register( $this );
311 CoreTagHooks
::register( $this );
312 $this->initialiseVariables();
314 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
315 wfProfileOut( __METHOD__
);
323 public function clearState() {
324 wfProfileIn( __METHOD__
);
325 if ( $this->mFirstCall
) {
326 $this->firstCallInit();
328 $this->mOutput
= new ParserOutput
;
329 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
330 $this->mAutonumber
= 0;
331 $this->mLastSection
= '';
332 $this->mDTopen
= false;
333 $this->mIncludeCount
= array();
334 $this->mArgStack
= false;
335 $this->mInPre
= false;
336 $this->mLinkHolders
= new LinkHolderArray( $this );
338 $this->mRevisionObject
= $this->mRevisionTimestamp
=
339 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
340 $this->mVarCache
= array();
342 $this->mLangLinkLanguages
= array();
343 $this->currentRevisionCache
= null;
345 $stripId = self
::getRandomString();
346 $this->mUniqPrefix
= self
::MARKER_PREFIX
. $stripId;
347 $this->mStripState
= new StripState( $stripId );
349 # Clear these on every parse, bug 4549
350 $this->mTplRedirCache
= $this->mTplDomCache
= array();
352 $this->mShowToc
= true;
353 $this->mForceTocPosition
= false;
354 $this->mIncludeSizes
= array(
358 $this->mPPNodeCount
= 0;
359 $this->mGeneratedPPNodeCount
= 0;
360 $this->mHighestExpansionDepth
= 0;
361 $this->mDefaultSort
= false;
362 $this->mHeadings
= array();
363 $this->mDoubleUnderscores
= array();
364 $this->mExpensiveFunctionCount
= 0;
367 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
368 $this->mPreprocessor
= null;
371 wfRunHooks( 'ParserClearState', array( &$this ) );
372 wfProfileOut( __METHOD__
);
376 * Convert wikitext to HTML
377 * Do not call this function recursively.
379 * @param string $text Text we want to parse
380 * @param Title $title
381 * @param ParserOptions $options
382 * @param bool $linestart
383 * @param bool $clearState
384 * @param int $revid Number to pass in {{REVISIONID}}
385 * @return ParserOutput A ParserOutput
387 public function parse( $text, Title
$title, ParserOptions
$options,
388 $linestart = true, $clearState = true, $revid = null
391 * First pass--just handle <nowiki> sections, pass the rest off
392 * to internalParse() which does all the real work.
395 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
396 $fname = __METHOD__
. '-' . wfGetCaller();
397 wfProfileIn( __METHOD__
);
398 wfProfileIn( $fname );
401 $magicScopeVariable = $this->lock();
404 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
406 $this->currentRevisionCache
= null;
407 $this->mInputSize
= strlen( $text );
408 if ( $this->mOptions
->getEnableLimitReport() ) {
409 $this->mOutput
->resetParseStartTime();
412 # Remove the strip marker tag prefix from the input, if present.
414 $text = str_replace( $this->mUniqPrefix
, '', $text );
417 $oldRevisionId = $this->mRevisionId
;
418 $oldRevisionObject = $this->mRevisionObject
;
419 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
420 $oldRevisionUser = $this->mRevisionUser
;
421 $oldRevisionSize = $this->mRevisionSize
;
422 if ( $revid !== null ) {
423 $this->mRevisionId
= $revid;
424 $this->mRevisionObject
= null;
425 $this->mRevisionTimestamp
= null;
426 $this->mRevisionUser
= null;
427 $this->mRevisionSize
= null;
430 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
432 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
433 $text = $this->internalParse( $text );
434 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
436 $text = $this->mStripState
->unstripGeneral( $text );
438 # Clean up special characters, only run once, next-to-last before doBlockLevels
440 # french spaces, last one Guillemet-left
441 # only if there is something before the space
442 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
443 # french spaces, Guillemet-right
444 '/(\\302\\253) /' => '\\1 ',
445 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
447 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
449 $text = $this->doBlockLevels( $text, $linestart );
451 $this->replaceLinkHolders( $text );
454 * The input doesn't get language converted if
456 * b) Content isn't converted
457 * c) It's a conversion table
458 * d) it is an interface message (which is in the user language)
460 if ( !( $options->getDisableContentConversion()
461 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
463 if ( !$this->mOptions
->getInterfaceMessage() ) {
464 # The position of the convert() call should not be changed. it
465 # assumes that the links are all replaced and the only thing left
466 # is the <nowiki> mark.
467 $text = $this->getConverterLanguage()->convert( $text );
472 * A converted title will be provided in the output object if title and
473 * content conversion are enabled, the article text does not contain
474 * a conversion-suppressing double-underscore tag, and no
475 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
476 * automatic link conversion.
478 if ( !( $options->getDisableTitleConversion()
479 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
480 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
481 ||
$this->mOutput
->getDisplayTitle() !== false )
483 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
484 if ( $convruletitle ) {
485 $this->mOutput
->setTitleText( $convruletitle );
487 $titleText = $this->getConverterLanguage()->convertTitle( $title );
488 $this->mOutput
->setTitleText( $titleText );
492 $text = $this->mStripState
->unstripNoWiki( $text );
494 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
496 $text = $this->replaceTransparentTags( $text );
497 $text = $this->mStripState
->unstripGeneral( $text );
499 $text = Sanitizer
::normalizeCharReferences( $text );
501 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
502 $text = MWTidy
::tidy( $text );
504 # attempt to sanitize at least some nesting problems
505 # (bug #2702 and quite a few others)
507 # ''Something [http://www.cool.com cool''] -->
508 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
509 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
510 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
511 # fix up an anchor inside another anchor, only
512 # at least for a single single nested link (bug 3695)
513 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
514 '\\1\\2</a>\\3</a>\\1\\4</a>',
515 # fix div inside inline elements- doBlockLevels won't wrap a line which
516 # contains a div, so fix it up here; replace
517 # div with escaped text
518 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
519 '\\1\\3<div\\5>\\6</div>\\8\\9',
520 # remove empty italic or bold tag pairs, some
521 # introduced by rules above
522 '/<([bi])><\/\\1>/' => '',
525 $text = preg_replace(
526 array_keys( $tidyregs ),
527 array_values( $tidyregs ),
531 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
532 $this->limitationWarn( 'expensive-parserfunction',
533 $this->mExpensiveFunctionCount
,
534 $this->mOptions
->getExpensiveParserFunctionLimit()
538 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
540 # Information on include size limits, for the benefit of users who try to skirt them
541 if ( $this->mOptions
->getEnableLimitReport() ) {
542 $max = $this->mOptions
->getMaxIncludeSize();
544 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
545 if ( $cpuTime !== null ) {
546 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
547 sprintf( "%.3f", $cpuTime )
551 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
552 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
553 sprintf( "%.3f", $wallTime )
556 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
557 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
559 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
560 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
562 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
563 array( $this->mIncludeSizes
['post-expand'], $max )
565 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
566 array( $this->mIncludeSizes
['arg'], $max )
568 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
569 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
571 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
572 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
574 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
576 $limitReport = "NewPP limit report\n";
577 if ( $wgShowHostnames ) {
578 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
580 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
581 if ( wfRunHooks( 'ParserLimitReportFormat',
582 array( $key, &$value, &$limitReport, false, false )
584 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
585 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
586 ->inLanguage( 'en' )->useDatabase( false );
587 if ( !$valueMsg->exists() ) {
588 $valueMsg = new RawMessage( '$1' );
590 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
591 $valueMsg->params( $value );
592 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
596 // Since we're not really outputting HTML, decode the entities and
597 // then re-encode the things that need hiding inside HTML comments.
598 $limitReport = htmlspecialchars_decode( $limitReport );
599 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
601 // Sanitize for comment. Note '‐' in the replacement is U+2010,
602 // which looks much like the problematic '-'.
603 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
604 $text .= "\n<!-- \n$limitReport-->\n";
606 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
607 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
608 $this->mTitle
->getPrefixedDBkey() );
611 $this->mOutput
->setText( $text );
613 $this->mRevisionId
= $oldRevisionId;
614 $this->mRevisionObject
= $oldRevisionObject;
615 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
616 $this->mRevisionUser
= $oldRevisionUser;
617 $this->mRevisionSize
= $oldRevisionSize;
618 $this->mInputSize
= false;
619 $this->currentRevisionCache
= null;
620 wfProfileOut( $fname );
621 wfProfileOut( __METHOD__
);
623 return $this->mOutput
;
627 * Recursive parser entry point that can be called from an extension tag
630 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
632 * @param string $text Text extension wants to have parsed
633 * @param bool|PPFrame $frame The frame to use for expanding any template variables
637 public function recursiveTagParse( $text, $frame = false ) {
638 wfProfileIn( __METHOD__
);
639 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
640 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
641 $text = $this->internalParse( $text, false, $frame );
642 wfProfileOut( __METHOD__
);
647 * Expand templates and variables in the text, producing valid, static wikitext.
648 * Also removes comments.
649 * Do not call this function recursively.
650 * @param string $text
651 * @param Title $title
652 * @param ParserOptions $options
653 * @param int|null $revid
654 * @param bool|PPFrame $frame
655 * @return mixed|string
657 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
658 wfProfileIn( __METHOD__
);
659 $magicScopeVariable = $this->lock();
660 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
661 if ( $revid !== null ) {
662 $this->mRevisionId
= $revid;
664 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
665 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
666 $text = $this->replaceVariables( $text, $frame );
667 $text = $this->mStripState
->unstripBoth( $text );
668 wfProfileOut( __METHOD__
);
673 * Recursive parser entry point that can be called from an extension tag
676 * @param string $text Text to be expanded
677 * @param bool|PPFrame $frame The frame to use for expanding any template variables
681 public function recursivePreprocess( $text, $frame = false ) {
682 wfProfileIn( __METHOD__
);
683 $text = $this->replaceVariables( $text, $frame );
684 $text = $this->mStripState
->unstripBoth( $text );
685 wfProfileOut( __METHOD__
);
690 * Process the wikitext for the "?preload=" feature. (bug 5210)
692 * "<noinclude>", "<includeonly>" etc. are parsed as for template
693 * transclusion, comments, templates, arguments, tags hooks and parser
694 * functions are untouched.
696 * @param string $text
697 * @param Title $title
698 * @param ParserOptions $options
699 * @param array $params
702 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
703 $msg = new RawMessage( $text );
704 $text = $msg->params( $params )->plain();
706 # Parser (re)initialisation
707 $magicScopeVariable = $this->lock();
708 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
710 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
711 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
712 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
713 $text = $this->mStripState
->unstripBoth( $text );
718 * Get a random string
722 public static function getRandomString() {
723 return wfRandomString( 16 );
727 * Set the current user.
728 * Should only be used when doing pre-save transform.
730 * @param User|null $user User object or null (to reset)
732 public function setUser( $user ) {
733 $this->mUser
= $user;
737 * Accessor for mUniqPrefix.
741 public function uniqPrefix() {
742 if ( !isset( $this->mUniqPrefix
) ) {
743 # @todo FIXME: This is probably *horribly wrong*
744 # LanguageConverter seems to want $wgParser's uniqPrefix, however
745 # if this is called for a parser cache hit, the parser may not
746 # have ever been initialized in the first place.
747 # Not really sure what the heck is supposed to be going on here.
749 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
751 return $this->mUniqPrefix
;
755 * Set the context title
759 public function setTitle( $t ) {
761 $t = Title
::newFromText( 'NO TITLE' );
764 if ( $t->hasFragment() ) {
765 # Strip the fragment to avoid various odd effects
766 $this->mTitle
= clone $t;
767 $this->mTitle
->setFragment( '' );
774 * Accessor for the Title object
778 public function getTitle() {
779 return $this->mTitle
;
783 * Accessor/mutator for the Title object
785 * @param Title $x Title object or null to just get the current one
788 public function Title( $x = null ) {
789 return wfSetVar( $this->mTitle
, $x );
793 * Set the output type
795 * @param int $ot New value
797 public function setOutputType( $ot ) {
798 $this->mOutputType
= $ot;
801 'html' => $ot == self
::OT_HTML
,
802 'wiki' => $ot == self
::OT_WIKI
,
803 'pre' => $ot == self
::OT_PREPROCESS
,
804 'plain' => $ot == self
::OT_PLAIN
,
809 * Accessor/mutator for the output type
811 * @param int|null $x New value or null to just get the current one
814 public function OutputType( $x = null ) {
815 return wfSetVar( $this->mOutputType
, $x );
819 * Get the ParserOutput object
821 * @return ParserOutput
823 public function getOutput() {
824 return $this->mOutput
;
828 * Get the ParserOptions object
830 * @return ParserOptions
832 public function getOptions() {
833 return $this->mOptions
;
837 * Accessor/mutator for the ParserOptions object
839 * @param ParserOptions $x New value or null to just get the current one
840 * @return ParserOptions Current ParserOptions object
842 public function Options( $x = null ) {
843 return wfSetVar( $this->mOptions
, $x );
849 public function nextLinkID() {
850 return $this->mLinkID++
;
856 public function setLinkID( $id ) {
857 $this->mLinkID
= $id;
861 * Get a language object for use in parser functions such as {{FORMATNUM:}}
864 public function getFunctionLang() {
865 return $this->getTargetLanguage();
869 * Get the target language for the content being parsed. This is usually the
870 * language that the content is in.
874 * @throws MWException
877 public function getTargetLanguage() {
878 $target = $this->mOptions
->getTargetLanguage();
880 if ( $target !== null ) {
882 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
883 return $this->mOptions
->getUserLangObj();
884 } elseif ( is_null( $this->mTitle
) ) {
885 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
888 return $this->mTitle
->getPageLanguage();
892 * Get the language object for language conversion
893 * @return Language|null
895 public function getConverterLanguage() {
896 return $this->getTargetLanguage();
900 * Get a User object either from $this->mUser, if set, or from the
901 * ParserOptions object otherwise
905 public function getUser() {
906 if ( !is_null( $this->mUser
) ) {
909 return $this->mOptions
->getUser();
913 * Get a preprocessor object
915 * @return Preprocessor
917 public function getPreprocessor() {
918 if ( !isset( $this->mPreprocessor
) ) {
919 $class = $this->mPreprocessorClass
;
920 $this->mPreprocessor
= new $class( $this );
922 return $this->mPreprocessor
;
926 * Replaces all occurrences of HTML-style comments and the given tags
927 * in the text with a random marker and returns the next text. The output
928 * parameter $matches will be an associative array filled with data in
932 * 'UNIQ-xxxxx' => array(
935 * array( 'param' => 'x' ),
936 * '<element param="x">tag content</element>' ) )
939 * @param array $elements List of element names. Comments are always extracted.
940 * @param string $text Source text string.
941 * @param array $matches Out parameter, Array: extracted tags
942 * @param string $uniq_prefix
943 * @return string Stripped text
945 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
950 $taglist = implode( '|', $elements );
951 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
953 while ( $text != '' ) {
954 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
956 if ( count( $p ) < 5 ) {
959 if ( count( $p ) > 5 ) {
973 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
974 $stripped .= $marker;
976 if ( $close === '/>' ) {
977 # Empty element tag, <tag />
982 if ( $element === '!--' ) {
985 $end = "/(<\\/$element\\s*>)/i";
987 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
989 if ( count( $q ) < 3 ) {
990 # No end tag -- let it run out to the end of the text.
999 $matches[$marker] = array( $element,
1001 Sanitizer
::decodeTagAttributes( $attributes ),
1002 "<$element$attributes$close$content$tail" );
1008 * Get a list of strippable XML-like elements
1012 public function getStripList() {
1013 return $this->mStripList
;
1017 * Add an item to the strip state
1018 * Returns the unique tag which must be inserted into the stripped text
1019 * The tag will be replaced with the original text in unstrip()
1021 * @param string $text
1025 public function insertStripItem( $text ) {
1026 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1027 $this->mMarkerIndex++
;
1028 $this->mStripState
->addGeneral( $rnd, $text );
1033 * parse the wiki syntax used to render tables
1036 * @param string $text
1039 public function doTableStuff( $text ) {
1040 wfProfileIn( __METHOD__
);
1042 $lines = StringUtils
::explode( "\n", $text );
1044 $td_history = array(); # Is currently a td tag open?
1045 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1046 $tr_history = array(); # Is currently a tr tag open?
1047 $tr_attributes = array(); # history of tr attributes
1048 $has_opened_tr = array(); # Did this table open a <tr> element?
1049 $indent_level = 0; # indent level of the table
1051 foreach ( $lines as $outLine ) {
1052 $line = trim( $outLine );
1054 if ( $line === '' ) { # empty line, go to next line
1055 $out .= $outLine . "\n";
1059 $first_character = $line[0];
1062 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1063 # First check if we are starting a new table
1064 $indent_level = strlen( $matches[1] );
1066 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1067 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1069 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1070 array_push( $td_history, false );
1071 array_push( $last_tag_history, '' );
1072 array_push( $tr_history, false );
1073 array_push( $tr_attributes, '' );
1074 array_push( $has_opened_tr, false );
1075 } elseif ( count( $td_history ) == 0 ) {
1076 # Don't do any of the following
1077 $out .= $outLine . "\n";
1079 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1080 # We are ending a table
1081 $line = '</table>' . substr( $line, 2 );
1082 $last_tag = array_pop( $last_tag_history );
1084 if ( !array_pop( $has_opened_tr ) ) {
1085 $line = "<tr><td></td></tr>{$line}";
1088 if ( array_pop( $tr_history ) ) {
1089 $line = "</tr>{$line}";
1092 if ( array_pop( $td_history ) ) {
1093 $line = "</{$last_tag}>{$line}";
1095 array_pop( $tr_attributes );
1096 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1097 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1098 # Now we have a table row
1099 $line = preg_replace( '#^\|-+#', '', $line );
1101 # Whats after the tag is now only attributes
1102 $attributes = $this->mStripState
->unstripBoth( $line );
1103 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1104 array_pop( $tr_attributes );
1105 array_push( $tr_attributes, $attributes );
1108 $last_tag = array_pop( $last_tag_history );
1109 array_pop( $has_opened_tr );
1110 array_push( $has_opened_tr, true );
1112 if ( array_pop( $tr_history ) ) {
1116 if ( array_pop( $td_history ) ) {
1117 $line = "</{$last_tag}>{$line}";
1121 array_push( $tr_history, false );
1122 array_push( $td_history, false );
1123 array_push( $last_tag_history, '' );
1124 } elseif ( $first_character === '|'
1125 ||
$first_character === '!'
1126 ||
substr( $line, 0, 2 ) === '|+'
1128 # This might be cell elements, td, th or captions
1129 if ( substr( $line, 0, 2 ) === '|+' ) {
1130 $first_character = '+';
1131 $line = substr( $line, 1 );
1134 $line = substr( $line, 1 );
1136 if ( $first_character === '!' ) {
1137 $line = str_replace( '!!', '||', $line );
1140 # Split up multiple cells on the same line.
1141 # FIXME : This can result in improper nesting of tags processed
1142 # by earlier parser steps, but should avoid splitting up eg
1143 # attribute values containing literal "||".
1144 $cells = StringUtils
::explodeMarkup( '||', $line );
1148 # Loop through each table cell
1149 foreach ( $cells as $cell ) {
1151 if ( $first_character !== '+' ) {
1152 $tr_after = array_pop( $tr_attributes );
1153 if ( !array_pop( $tr_history ) ) {
1154 $previous = "<tr{$tr_after}>\n";
1156 array_push( $tr_history, true );
1157 array_push( $tr_attributes, '' );
1158 array_pop( $has_opened_tr );
1159 array_push( $has_opened_tr, true );
1162 $last_tag = array_pop( $last_tag_history );
1164 if ( array_pop( $td_history ) ) {
1165 $previous = "</{$last_tag}>\n{$previous}";
1168 if ( $first_character === '|' ) {
1170 } elseif ( $first_character === '!' ) {
1172 } elseif ( $first_character === '+' ) {
1173 $last_tag = 'caption';
1178 array_push( $last_tag_history, $last_tag );
1180 # A cell could contain both parameters and data
1181 $cell_data = explode( '|', $cell, 2 );
1183 # Bug 553: Note that a '|' inside an invalid link should not
1184 # be mistaken as delimiting cell parameters
1185 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1186 $cell = "{$previous}<{$last_tag}>{$cell}";
1187 } elseif ( count( $cell_data ) == 1 ) {
1188 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1190 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1191 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1192 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1196 array_push( $td_history, true );
1199 $out .= $outLine . "\n";
1202 # Closing open td, tr && table
1203 while ( count( $td_history ) > 0 ) {
1204 if ( array_pop( $td_history ) ) {
1207 if ( array_pop( $tr_history ) ) {
1210 if ( !array_pop( $has_opened_tr ) ) {
1211 $out .= "<tr><td></td></tr>\n";
1214 $out .= "</table>\n";
1217 # Remove trailing line-ending (b/c)
1218 if ( substr( $out, -1 ) === "\n" ) {
1219 $out = substr( $out, 0, -1 );
1222 # special case: don't return empty table
1223 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1227 wfProfileOut( __METHOD__
);
1233 * Helper function for parse() that transforms wiki markup into
1234 * HTML. Only called for $mOutputType == self::OT_HTML.
1238 * @param string $text
1239 * @param bool $isMain
1240 * @param bool $frame
1244 public function internalParse( $text, $isMain = true, $frame = false ) {
1245 wfProfileIn( __METHOD__
);
1249 # Hook to suspend the parser in this state
1250 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1251 wfProfileOut( __METHOD__
);
1255 # if $frame is provided, then use $frame for replacing any variables
1257 # use frame depth to infer how include/noinclude tags should be handled
1258 # depth=0 means this is the top-level document; otherwise it's an included document
1259 if ( !$frame->depth
) {
1262 $flag = Parser
::PTD_FOR_INCLUSION
;
1264 $dom = $this->preprocessToDom( $text, $flag );
1265 $text = $frame->expand( $dom );
1267 # if $frame is not provided, then use old-style replaceVariables
1268 $text = $this->replaceVariables( $text );
1271 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1272 $text = Sanitizer
::removeHTMLtags(
1274 array( &$this, 'attributeStripCallback' ),
1276 array_keys( $this->mTransparentTagHooks
)
1278 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1280 # Tables need to come after variable replacement for things to work
1281 # properly; putting them before other transformations should keep
1282 # exciting things like link expansions from showing up in surprising
1284 $text = $this->doTableStuff( $text );
1286 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1288 $text = $this->doDoubleUnderscore( $text );
1290 $text = $this->doHeadings( $text );
1291 $text = $this->replaceInternalLinks( $text );
1292 $text = $this->doAllQuotes( $text );
1293 $text = $this->replaceExternalLinks( $text );
1295 # replaceInternalLinks may sometimes leave behind
1296 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1297 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1299 $text = $this->doMagicLinks( $text );
1300 $text = $this->formatHeadings( $text, $origText, $isMain );
1302 wfProfileOut( __METHOD__
);
1307 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1308 * magic external links.
1313 * @param string $text
1317 public function doMagicLinks( $text ) {
1318 wfProfileIn( __METHOD__
);
1319 $prots = wfUrlProtocolsWithoutProtRel();
1320 $urlChar = self
::EXT_LINK_URL_CLASS
;
1321 $text = preg_replace_callback(
1323 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1324 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1325 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1326 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1327 ISBN\s+(\b # m[5]: ISBN, capture number
1328 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1329 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1330 [0-9Xx] # check digit
1332 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1333 wfProfileOut( __METHOD__
);
1338 * @throws MWException
1340 * @return HTML|string
1342 public function magicLinkCallback( $m ) {
1343 if ( isset( $m[1] ) && $m[1] !== '' ) {
1346 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1349 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1350 # Free external link
1351 return $this->makeFreeExternalLink( $m[0] );
1352 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1354 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1357 $cssClass = 'mw-magiclink-rfc';
1359 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1361 $urlmsg = 'pubmedurl';
1362 $cssClass = 'mw-magiclink-pmid';
1365 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1366 substr( $m[0], 0, 20 ) . '"' );
1368 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1369 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1370 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1373 $num = strtr( $isbn, array(
1378 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1379 return '<a href="' .
1380 htmlspecialchars( $titleObj->getLocalURL() ) .
1381 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1388 * Make a free external link, given a user-supplied URL
1390 * @param string $url
1392 * @return string HTML
1395 public function makeFreeExternalLink( $url ) {
1396 wfProfileIn( __METHOD__
);
1400 # The characters '<' and '>' (which were escaped by
1401 # removeHTMLtags()) should not be included in
1402 # URLs, per RFC 2396.
1404 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1405 $trail = substr( $url, $m2[0][1] ) . $trail;
1406 $url = substr( $url, 0, $m2[0][1] );
1409 # Move trailing punctuation to $trail
1411 # If there is no left bracket, then consider right brackets fair game too
1412 if ( strpos( $url, '(' ) === false ) {
1416 $numSepChars = strspn( strrev( $url ), $sep );
1417 if ( $numSepChars ) {
1418 $trail = substr( $url, -$numSepChars ) . $trail;
1419 $url = substr( $url, 0, -$numSepChars );
1422 $url = Sanitizer
::cleanUrl( $url );
1424 # Is this an external image?
1425 $text = $this->maybeMakeExternalImage( $url );
1426 if ( $text === false ) {
1427 # Not an image, make a link
1428 $text = Linker
::makeExternalLink( $url,
1429 $this->getConverterLanguage()->markNoConversion( $url, true ),
1431 $this->getExternalLinkAttribs( $url ) );
1432 # Register it in the output object...
1433 # Replace unnecessary URL escape codes with their equivalent characters
1434 $pasteurized = self
::normalizeLinkUrl( $url );
1435 $this->mOutput
->addExternalLink( $pasteurized );
1437 wfProfileOut( __METHOD__
);
1438 return $text . $trail;
1442 * Parse headers and return html
1446 * @param string $text
1450 public function doHeadings( $text ) {
1451 wfProfileIn( __METHOD__
);
1452 for ( $i = 6; $i >= 1; --$i ) {
1453 $h = str_repeat( '=', $i );
1454 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1456 wfProfileOut( __METHOD__
);
1461 * Replace single quotes with HTML markup
1464 * @param string $text
1466 * @return string The altered text
1468 public function doAllQuotes( $text ) {
1469 wfProfileIn( __METHOD__
);
1471 $lines = StringUtils
::explode( "\n", $text );
1472 foreach ( $lines as $line ) {
1473 $outtext .= $this->doQuotes( $line ) . "\n";
1475 $outtext = substr( $outtext, 0, -1 );
1476 wfProfileOut( __METHOD__
);
1481 * Helper function for doAllQuotes()
1483 * @param string $text
1487 public function doQuotes( $text ) {
1488 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1489 $countarr = count( $arr );
1490 if ( $countarr == 1 ) {
1494 // First, do some preliminary work. This may shift some apostrophes from
1495 // being mark-up to being text. It also counts the number of occurrences
1496 // of bold and italics mark-ups.
1499 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1500 $thislen = strlen( $arr[$i] );
1501 // If there are ever four apostrophes, assume the first is supposed to
1502 // be text, and the remaining three constitute mark-up for bold text.
1503 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1504 if ( $thislen == 4 ) {
1505 $arr[$i - 1] .= "'";
1508 } elseif ( $thislen > 5 ) {
1509 // If there are more than 5 apostrophes in a row, assume they're all
1510 // text except for the last 5.
1511 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1512 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1516 // Count the number of occurrences of bold and italics mark-ups.
1517 if ( $thislen == 2 ) {
1519 } elseif ( $thislen == 3 ) {
1521 } elseif ( $thislen == 5 ) {
1527 // If there is an odd number of both bold and italics, it is likely
1528 // that one of the bold ones was meant to be an apostrophe followed
1529 // by italics. Which one we cannot know for certain, but it is more
1530 // likely to be one that has a single-letter word before it.
1531 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1532 $firstsingleletterword = -1;
1533 $firstmultiletterword = -1;
1535 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1536 if ( strlen( $arr[$i] ) == 3 ) {
1537 $x1 = substr( $arr[$i - 1], -1 );
1538 $x2 = substr( $arr[$i - 1], -2, 1 );
1539 if ( $x1 === ' ' ) {
1540 if ( $firstspace == -1 ) {
1543 } elseif ( $x2 === ' ' ) {
1544 if ( $firstsingleletterword == -1 ) {
1545 $firstsingleletterword = $i;
1546 // if $firstsingleletterword is set, we don't
1547 // look at the other options, so we can bail early.
1551 if ( $firstmultiletterword == -1 ) {
1552 $firstmultiletterword = $i;
1558 // If there is a single-letter word, use it!
1559 if ( $firstsingleletterword > -1 ) {
1560 $arr[$firstsingleletterword] = "''";
1561 $arr[$firstsingleletterword - 1] .= "'";
1562 } elseif ( $firstmultiletterword > -1 ) {
1563 // If not, but there's a multi-letter word, use that one.
1564 $arr[$firstmultiletterword] = "''";
1565 $arr[$firstmultiletterword - 1] .= "'";
1566 } elseif ( $firstspace > -1 ) {
1567 // ... otherwise use the first one that has neither.
1568 // (notice that it is possible for all three to be -1 if, for example,
1569 // there is only one pentuple-apostrophe in the line)
1570 $arr[$firstspace] = "''";
1571 $arr[$firstspace - 1] .= "'";
1575 // Now let's actually convert our apostrophic mush to HTML!
1580 foreach ( $arr as $r ) {
1581 if ( ( $i %
2 ) == 0 ) {
1582 if ( $state === 'both' ) {
1588 $thislen = strlen( $r );
1589 if ( $thislen == 2 ) {
1590 if ( $state === 'i' ) {
1593 } elseif ( $state === 'bi' ) {
1596 } elseif ( $state === 'ib' ) {
1597 $output .= '</b></i><b>';
1599 } elseif ( $state === 'both' ) {
1600 $output .= '<b><i>' . $buffer . '</i>';
1602 } else { // $state can be 'b' or ''
1606 } elseif ( $thislen == 3 ) {
1607 if ( $state === 'b' ) {
1610 } elseif ( $state === 'bi' ) {
1611 $output .= '</i></b><i>';
1613 } elseif ( $state === 'ib' ) {
1616 } elseif ( $state === 'both' ) {
1617 $output .= '<i><b>' . $buffer . '</b>';
1619 } else { // $state can be 'i' or ''
1623 } elseif ( $thislen == 5 ) {
1624 if ( $state === 'b' ) {
1625 $output .= '</b><i>';
1627 } elseif ( $state === 'i' ) {
1628 $output .= '</i><b>';
1630 } elseif ( $state === 'bi' ) {
1631 $output .= '</i></b>';
1633 } elseif ( $state === 'ib' ) {
1634 $output .= '</b></i>';
1636 } elseif ( $state === 'both' ) {
1637 $output .= '<i><b>' . $buffer . '</b></i>';
1639 } else { // ($state == '')
1647 // Now close all remaining tags. Notice that the order is important.
1648 if ( $state === 'b' ||
$state === 'ib' ) {
1651 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1654 if ( $state === 'bi' ) {
1657 // There might be lonely ''''', so make sure we have a buffer
1658 if ( $state === 'both' && $buffer ) {
1659 $output .= '<b><i>' . $buffer . '</i></b>';
1665 * Replace external links (REL)
1667 * Note: this is all very hackish and the order of execution matters a lot.
1668 * Make sure to run tests/parserTests.php if you change this code.
1672 * @param string $text
1674 * @throws MWException
1677 public function replaceExternalLinks( $text ) {
1678 wfProfileIn( __METHOD__
);
1680 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1681 if ( $bits === false ) {
1682 wfProfileOut( __METHOD__
);
1683 throw new MWException( "PCRE needs to be compiled with "
1684 . "--enable-unicode-properties in order for MediaWiki to function" );
1686 $s = array_shift( $bits );
1689 while ( $i < count( $bits ) ) {
1692 $text = $bits[$i++
];
1693 $trail = $bits[$i++
];
1695 # The characters '<' and '>' (which were escaped by
1696 # removeHTMLtags()) should not be included in
1697 # URLs, per RFC 2396.
1699 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1700 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1701 $url = substr( $url, 0, $m2[0][1] );
1704 # If the link text is an image URL, replace it with an <img> tag
1705 # This happened by accident in the original parser, but some people used it extensively
1706 $img = $this->maybeMakeExternalImage( $text );
1707 if ( $img !== false ) {
1713 # Set linktype for CSS - if URL==text, link is essentially free
1714 $linktype = ( $text === $url ) ?
'free' : 'text';
1716 # No link text, e.g. [http://domain.tld/some.link]
1717 if ( $text == '' ) {
1719 $langObj = $this->getTargetLanguage();
1720 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1721 $linktype = 'autonumber';
1723 # Have link text, e.g. [http://domain.tld/some.link text]s
1725 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1728 $text = $this->getConverterLanguage()->markNoConversion( $text );
1730 $url = Sanitizer
::cleanUrl( $url );
1732 # Use the encoded URL
1733 # This means that users can paste URLs directly into the text
1734 # Funny characters like ö aren't valid in URLs anyway
1735 # This was changed in August 2004
1736 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1737 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1739 # Register link in the output object.
1740 # Replace unnecessary URL escape codes with the referenced character
1741 # This prevents spammers from hiding links from the filters
1742 $pasteurized = self
::normalizeLinkUrl( $url );
1743 $this->mOutput
->addExternalLink( $pasteurized );
1746 wfProfileOut( __METHOD__
);
1751 * Get the rel attribute for a particular external link.
1754 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1755 * nofollow if appropriate
1756 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1757 * @return string|null Rel attribute for $url
1759 public static function getExternalLinkRel( $url = false, $title = null ) {
1760 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1761 $ns = $title ?
$title->getNamespace() : false;
1762 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1763 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1771 * Get an associative array of additional HTML attributes appropriate for a
1772 * particular external link. This currently may include rel => nofollow
1773 * (depending on configuration, namespace, and the URL's domain) and/or a
1774 * target attribute (depending on configuration).
1776 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1777 * nofollow if appropriate
1778 * @return array Associative array of HTML attributes
1780 public function getExternalLinkAttribs( $url = false ) {
1782 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1784 if ( $this->mOptions
->getExternalLinkTarget() ) {
1785 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1791 * Replace unusual escape codes in a URL with their equivalent characters
1793 * @deprecated since 1.24, use normalizeLinkUrl
1794 * @param string $url
1797 public static function replaceUnusualEscapes( $url ) {
1798 wfDeprecated( __METHOD__
, '1.24' );
1799 return self
::normalizeLinkUrl( $url );
1803 * Replace unusual escape codes in a URL with their equivalent characters
1805 * This generally follows the syntax defined in RFC 3986, with special
1806 * consideration for HTTP query strings.
1808 * @param string $url
1811 public static function normalizeLinkUrl( $url ) {
1812 # First, make sure unsafe characters are encoded
1813 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1815 return rawurlencode( $m[0] );
1821 $end = strlen( $url );
1823 # Fragment part - 'fragment'
1824 $start = strpos( $url, '#' );
1825 if ( $start !== false && $start < $end ) {
1826 $ret = self
::normalizeUrlComponent(
1827 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1831 # Query part - 'query' minus &=+;
1832 $start = strpos( $url, '?' );
1833 if ( $start !== false && $start < $end ) {
1834 $ret = self
::normalizeUrlComponent(
1835 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1839 # Scheme and path part - 'pchar'
1840 # (we assume no userinfo or encoded colons in the host)
1841 $ret = self
::normalizeUrlComponent(
1842 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1847 private static function normalizeUrlComponent( $component, $unsafe ) {
1848 $callback = function ( $matches ) use ( $unsafe ) {
1849 $char = urldecode( $matches[0] );
1850 $ord = ord( $char );
1851 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1855 # Leave it escaped, but use uppercase for a-f
1856 return strtoupper( $matches[0] );
1859 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1863 * make an image if it's allowed, either through the global
1864 * option, through the exception, or through the on-wiki whitelist
1866 * @param string $url
1870 private function maybeMakeExternalImage( $url ) {
1871 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1872 $imagesexception = !empty( $imagesfrom );
1874 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1875 if ( $imagesexception && is_array( $imagesfrom ) ) {
1876 $imagematch = false;
1877 foreach ( $imagesfrom as $match ) {
1878 if ( strpos( $url, $match ) === 0 ) {
1883 } elseif ( $imagesexception ) {
1884 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1886 $imagematch = false;
1889 if ( $this->mOptions
->getAllowExternalImages()
1890 ||
( $imagesexception && $imagematch )
1892 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1894 $text = Linker
::makeExternalImage( $url );
1897 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1898 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1900 $whitelist = explode(
1902 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1905 foreach ( $whitelist as $entry ) {
1906 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1907 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1910 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1911 # Image matches a whitelist entry
1912 $text = Linker
::makeExternalImage( $url );
1921 * Process [[ ]] wikilinks
1925 * @return string Processed text
1929 public function replaceInternalLinks( $s ) {
1930 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1935 * Process [[ ]] wikilinks (RIL)
1937 * @throws MWException
1938 * @return LinkHolderArray
1942 public function replaceInternalLinks2( &$s ) {
1943 global $wgExtraInterlanguageLinkPrefixes;
1944 wfProfileIn( __METHOD__
);
1946 wfProfileIn( __METHOD__
. '-setup' );
1947 static $tc = false, $e1, $e1_img;
1948 # the % is needed to support urlencoded titles as well
1950 $tc = Title
::legalChars() . '#%';
1951 # Match a link having the form [[namespace:link|alternate]]trail
1952 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1953 # Match cases where there is no "]]", which might still be images
1954 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1957 $holders = new LinkHolderArray( $this );
1959 # split the entire text string on occurrences of [[
1960 $a = StringUtils
::explode( '[[', ' ' . $s );
1961 # get the first element (all text up to first [[), and remove the space we added
1964 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1965 $s = substr( $s, 1 );
1967 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1969 if ( $useLinkPrefixExtension ) {
1970 # Match the end of a line for a word that's not followed by whitespace,
1971 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1973 $charset = $wgContLang->linkPrefixCharset();
1974 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1977 if ( is_null( $this->mTitle
) ) {
1978 wfProfileOut( __METHOD__
. '-setup' );
1979 wfProfileOut( __METHOD__
);
1980 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1982 $nottalk = !$this->mTitle
->isTalkPage();
1984 if ( $useLinkPrefixExtension ) {
1986 if ( preg_match( $e2, $s, $m ) ) {
1987 $first_prefix = $m[2];
1989 $first_prefix = false;
1995 $useSubpages = $this->areSubpagesAllowed();
1996 wfProfileOut( __METHOD__
. '-setup' );
1998 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1999 # Loop for each link
2000 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2001 // @codingStandardsIgnoreStart
2003 # Check for excessive memory usage
2004 if ( $holders->isBig() ) {
2006 # Do the existence check, replace the link holders and clear the array
2007 $holders->replace( $s );
2011 if ( $useLinkPrefixExtension ) {
2012 wfProfileIn( __METHOD__
. '-prefixhandling' );
2013 if ( preg_match( $e2, $s, $m ) ) {
2020 if ( $first_prefix ) {
2021 $prefix = $first_prefix;
2022 $first_prefix = false;
2024 wfProfileOut( __METHOD__
. '-prefixhandling' );
2027 $might_be_img = false;
2029 wfProfileIn( __METHOD__
. "-e1" );
2030 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2032 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2033 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2034 # the real problem is with the $e1 regex
2037 # Still some problems for cases where the ] is meant to be outside punctuation,
2038 # and no image is in sight. See bug 2095.
2041 && substr( $m[3], 0, 1 ) === ']'
2042 && strpos( $text, '[' ) !== false
2044 $text .= ']'; # so that replaceExternalLinks($text) works later
2045 $m[3] = substr( $m[3], 1 );
2047 # fix up urlencoded title texts
2048 if ( strpos( $m[1], '%' ) !== false ) {
2049 # Should anchors '#' also be rejected?
2050 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2053 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2054 # Invalid, but might be an image with a link in its caption
2055 $might_be_img = true;
2057 if ( strpos( $m[1], '%' ) !== false ) {
2058 $m[1] = rawurldecode( $m[1] );
2061 } else { # Invalid form; output directly
2062 $s .= $prefix . '[[' . $line;
2063 wfProfileOut( __METHOD__
. "-e1" );
2066 wfProfileOut( __METHOD__
. "-e1" );
2067 wfProfileIn( __METHOD__
. "-misc" );
2071 # Don't allow internal links to pages containing
2072 # PROTO: where PROTO is a valid URL protocol; these
2073 # should be external links.
2074 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2075 $s .= $prefix . '[[' . $line;
2076 wfProfileOut( __METHOD__
. "-misc" );
2080 # Make subpage if necessary
2081 if ( $useSubpages ) {
2082 $link = $this->maybeDoSubpageLink( $origLink, $text );
2087 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2089 # Strip off leading ':'
2090 $link = substr( $link, 1 );
2093 wfProfileOut( __METHOD__
. "-misc" );
2094 wfProfileIn( __METHOD__
. "-title" );
2095 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2096 if ( $nt === null ) {
2097 $s .= $prefix . '[[' . $line;
2098 wfProfileOut( __METHOD__
. "-title" );
2102 $ns = $nt->getNamespace();
2103 $iw = $nt->getInterwiki();
2104 wfProfileOut( __METHOD__
. "-title" );
2106 if ( $might_be_img ) { # if this is actually an invalid link
2107 wfProfileIn( __METHOD__
. "-might_be_img" );
2108 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2111 # look at the next 'line' to see if we can close it there
2113 $next_line = $a->current();
2114 if ( $next_line === false ||
$next_line === null ) {
2117 $m = explode( ']]', $next_line, 3 );
2118 if ( count( $m ) == 3 ) {
2119 # the first ]] closes the inner link, the second the image
2121 $text .= "[[{$m[0]}]]{$m[1]}";
2124 } elseif ( count( $m ) == 2 ) {
2125 # if there's exactly one ]] that's fine, we'll keep looking
2126 $text .= "[[{$m[0]}]]{$m[1]}";
2128 # if $next_line is invalid too, we need look no further
2129 $text .= '[[' . $next_line;
2134 # we couldn't find the end of this imageLink, so output it raw
2135 # but don't ignore what might be perfectly normal links in the text we've examined
2136 $holders->merge( $this->replaceInternalLinks2( $text ) );
2137 $s .= "{$prefix}[[$link|$text";
2138 # note: no $trail, because without an end, there *is* no trail
2139 wfProfileOut( __METHOD__
. "-might_be_img" );
2142 } else { # it's not an image, so output it raw
2143 $s .= "{$prefix}[[$link|$text";
2144 # note: no $trail, because without an end, there *is* no trail
2145 wfProfileOut( __METHOD__
. "-might_be_img" );
2148 wfProfileOut( __METHOD__
. "-might_be_img" );
2151 $wasblank = ( $text == '' );
2155 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2156 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2157 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2158 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2159 $text = $this->doQuotes( $text );
2162 # Link not escaped by : , create the various objects
2163 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2165 wfProfileIn( __METHOD__
. "-interwiki" );
2167 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2168 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2169 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2172 # Bug 24502: filter duplicates
2173 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2174 $this->mLangLinkLanguages
[$iw] = true;
2175 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2178 $s = rtrim( $s . $prefix );
2179 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2180 wfProfileOut( __METHOD__
. "-interwiki" );
2183 wfProfileOut( __METHOD__
. "-interwiki" );
2185 if ( $ns == NS_FILE
) {
2186 wfProfileIn( __METHOD__
. "-image" );
2187 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2189 # if no parameters were passed, $text
2190 # becomes something like "File:Foo.png",
2191 # which we don't want to pass on to the
2195 # recursively parse links inside the image caption
2196 # actually, this will parse them in any other parameters, too,
2197 # but it might be hard to fix that, and it doesn't matter ATM
2198 $text = $this->replaceExternalLinks( $text );
2199 $holders->merge( $this->replaceInternalLinks2( $text ) );
2201 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2202 $s .= $prefix . $this->armorLinks(
2203 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2205 $s .= $prefix . $trail;
2207 wfProfileOut( __METHOD__
. "-image" );
2211 if ( $ns == NS_CATEGORY
) {
2212 wfProfileIn( __METHOD__
. "-category" );
2213 $s = rtrim( $s . "\n" ); # bug 87
2216 $sortkey = $this->getDefaultSort();
2220 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2221 $sortkey = str_replace( "\n", '', $sortkey );
2222 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2223 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2226 * Strip the whitespace Category links produce, see bug 87
2228 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2230 wfProfileOut( __METHOD__
. "-category" );
2235 # Self-link checking. For some languages, variants of the title are checked in
2236 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2237 # for linking to a different variant.
2238 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2239 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2243 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2244 # @todo FIXME: Should do batch file existence checks, see comment below
2245 if ( $ns == NS_MEDIA
) {
2246 wfProfileIn( __METHOD__
. "-media" );
2247 # Give extensions a chance to select the file revision for us
2250 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2251 array( $this, $nt, &$options, &$descQuery ) );
2252 # Fetch and register the file (file title may be different via hooks)
2253 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2254 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2255 $s .= $prefix . $this->armorLinks(
2256 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2257 wfProfileOut( __METHOD__
. "-media" );
2261 wfProfileIn( __METHOD__
. "-always_known" );
2262 # Some titles, such as valid special pages or files in foreign repos, should
2263 # be shown as bluelinks even though they're not included in the page table
2265 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2266 # batch file existence checks for NS_FILE and NS_MEDIA
2267 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2268 $this->mOutput
->addLink( $nt );
2269 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2271 # Links will be added to the output link list after checking
2272 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2274 wfProfileOut( __METHOD__
. "-always_known" );
2276 wfProfileOut( __METHOD__
);
2281 * Render a forced-blue link inline; protect against double expansion of
2282 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2283 * Since this little disaster has to split off the trail text to avoid
2284 * breaking URLs in the following text without breaking trails on the
2285 * wiki links, it's been made into a horrible function.
2288 * @param string $text
2289 * @param array|string $query
2290 * @param string $trail
2291 * @param string $prefix
2292 * @return string HTML-wikitext mix oh yuck
2294 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2295 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2297 if ( is_string( $query ) ) {
2298 $query = wfCgiToArray( $query );
2300 if ( $text == '' ) {
2301 $text = htmlspecialchars( $nt->getPrefixedText() );
2304 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2306 return $this->armorLinks( $link ) . $trail;
2310 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2311 * going to go through further parsing steps before inline URL expansion.
2313 * Not needed quite as much as it used to be since free links are a bit
2314 * more sensible these days. But bracketed links are still an issue.
2316 * @param string $text More-or-less HTML
2317 * @return string Less-or-more HTML with NOPARSE bits
2319 public function armorLinks( $text ) {
2320 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2321 "{$this->mUniqPrefix}NOPARSE$1", $text );
2325 * Return true if subpage links should be expanded on this page.
2328 public function areSubpagesAllowed() {
2329 # Some namespaces don't allow subpages
2330 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2334 * Handle link to subpage if necessary
2336 * @param string $target The source of the link
2337 * @param string &$text The link text, modified as necessary
2338 * @return string The full name of the link
2341 public function maybeDoSubpageLink( $target, &$text ) {
2342 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2346 * Used by doBlockLevels()
2351 public function closeParagraph() {
2353 if ( $this->mLastSection
!= '' ) {
2354 $result = '</' . $this->mLastSection
. ">\n";
2356 $this->mInPre
= false;
2357 $this->mLastSection
= '';
2362 * getCommon() returns the length of the longest common substring
2363 * of both arguments, starting at the beginning of both.
2366 * @param string $st1
2367 * @param string $st2
2371 public function getCommon( $st1, $st2 ) {
2372 $fl = strlen( $st1 );
2373 $shorter = strlen( $st2 );
2374 if ( $fl < $shorter ) {
2378 for ( $i = 0; $i < $shorter; ++
$i ) {
2379 if ( $st1[$i] != $st2[$i] ) {
2387 * These next three functions open, continue, and close the list
2388 * element appropriate to the prefix character passed into them.
2391 * @param string $char
2395 public function openList( $char ) {
2396 $result = $this->closeParagraph();
2398 if ( '*' === $char ) {
2399 $result .= "<ul><li>";
2400 } elseif ( '#' === $char ) {
2401 $result .= "<ol><li>";
2402 } elseif ( ':' === $char ) {
2403 $result .= "<dl><dd>";
2404 } elseif ( ';' === $char ) {
2405 $result .= "<dl><dt>";
2406 $this->mDTopen
= true;
2408 $result = '<!-- ERR 1 -->';
2416 * @param string $char
2421 public function nextItem( $char ) {
2422 if ( '*' === $char ||
'#' === $char ) {
2423 return "</li>\n<li>";
2424 } elseif ( ':' === $char ||
';' === $char ) {
2426 if ( $this->mDTopen
) {
2429 if ( ';' === $char ) {
2430 $this->mDTopen
= true;
2431 return $close . '<dt>';
2433 $this->mDTopen
= false;
2434 return $close . '<dd>';
2437 return '<!-- ERR 2 -->';
2442 * @param string $char
2447 public function closeList( $char ) {
2448 if ( '*' === $char ) {
2449 $text = "</li></ul>";
2450 } elseif ( '#' === $char ) {
2451 $text = "</li></ol>";
2452 } elseif ( ':' === $char ) {
2453 if ( $this->mDTopen
) {
2454 $this->mDTopen
= false;
2455 $text = "</dt></dl>";
2457 $text = "</dd></dl>";
2460 return '<!-- ERR 3 -->';
2467 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2469 * @param string $text
2470 * @param bool $linestart Whether or not this is at the start of a line.
2472 * @return string The lists rendered as HTML
2474 public function doBlockLevels( $text, $linestart ) {
2475 wfProfileIn( __METHOD__
);
2477 # Parsing through the text line by line. The main thing
2478 # happening here is handling of block-level elements p, pre,
2479 # and making lists from lines starting with * # : etc.
2481 $textLines = StringUtils
::explode( "\n", $text );
2483 $lastPrefix = $output = '';
2484 $this->mDTopen
= $inBlockElem = false;
2486 $paragraphStack = false;
2487 $inBlockquote = false;
2489 foreach ( $textLines as $oLine ) {
2491 if ( !$linestart ) {
2501 $lastPrefixLength = strlen( $lastPrefix );
2502 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2503 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2504 # If not in a <pre> element, scan for and figure out what prefixes are there.
2505 if ( !$this->mInPre
) {
2506 # Multiple prefixes may abut each other for nested lists.
2507 $prefixLength = strspn( $oLine, '*#:;' );
2508 $prefix = substr( $oLine, 0, $prefixLength );
2511 # ; and : are both from definition-lists, so they're equivalent
2512 # for the purposes of determining whether or not we need to open/close
2514 $prefix2 = str_replace( ';', ':', $prefix );
2515 $t = substr( $oLine, $prefixLength );
2516 $this->mInPre
= (bool)$preOpenMatch;
2518 # Don't interpret any other prefixes in preformatted text
2520 $prefix = $prefix2 = '';
2525 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2526 # Same as the last item, so no need to deal with nesting or opening stuff
2527 $output .= $this->nextItem( substr( $prefix, -1 ) );
2528 $paragraphStack = false;
2530 if ( substr( $prefix, -1 ) === ';' ) {
2531 # The one nasty exception: definition lists work like this:
2532 # ; title : definition text
2533 # So we check for : in the remainder text to split up the
2534 # title and definition, without b0rking links.
2536 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2538 $output .= $term . $this->nextItem( ':' );
2541 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2542 # We need to open or close prefixes, or both.
2544 # Either open or close a level...
2545 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2546 $paragraphStack = false;
2548 # Close all the prefixes which aren't shared.
2549 while ( $commonPrefixLength < $lastPrefixLength ) {
2550 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2551 --$lastPrefixLength;
2554 # Continue the current prefix if appropriate.
2555 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2556 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2559 # Open prefixes where appropriate.
2560 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2563 while ( $prefixLength > $commonPrefixLength ) {
2564 $char = substr( $prefix, $commonPrefixLength, 1 );
2565 $output .= $this->openList( $char );
2567 if ( ';' === $char ) {
2568 # @todo FIXME: This is dupe of code above
2569 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2571 $output .= $term . $this->nextItem( ':' );
2574 ++
$commonPrefixLength;
2576 if ( !$prefixLength && $lastPrefix ) {
2579 $lastPrefix = $prefix2;
2582 # If we have no prefixes, go to paragraph mode.
2583 if ( 0 == $prefixLength ) {
2584 wfProfileIn( __METHOD__
. "-paragraph" );
2585 # No prefix (not in list)--go to paragraph mode
2586 # XXX: use a stack for nestable elements like span, table and div
2587 $openmatch = preg_match(
2588 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2589 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2592 $closematch = preg_match(
2593 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2594 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2595 . $this->mUniqPrefix
2596 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2600 if ( $openmatch or $closematch ) {
2601 $paragraphStack = false;
2602 # @todo bug 5718: paragraph closed
2603 $output .= $this->closeParagraph();
2604 if ( $preOpenMatch and !$preCloseMatch ) {
2605 $this->mInPre
= true;
2608 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2609 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2610 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2612 $inBlockElem = !$closematch;
2613 } elseif ( !$inBlockElem && !$this->mInPre
) {
2614 if ( ' ' == substr( $t, 0, 1 )
2615 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2619 if ( $this->mLastSection
!== 'pre' ) {
2620 $paragraphStack = false;
2621 $output .= $this->closeParagraph() . '<pre>';
2622 $this->mLastSection
= 'pre';
2624 $t = substr( $t, 1 );
2627 if ( trim( $t ) === '' ) {
2628 if ( $paragraphStack ) {
2629 $output .= $paragraphStack . '<br />';
2630 $paragraphStack = false;
2631 $this->mLastSection
= 'p';
2633 if ( $this->mLastSection
!== 'p' ) {
2634 $output .= $this->closeParagraph();
2635 $this->mLastSection
= '';
2636 $paragraphStack = '<p>';
2638 $paragraphStack = '</p><p>';
2642 if ( $paragraphStack ) {
2643 $output .= $paragraphStack;
2644 $paragraphStack = false;
2645 $this->mLastSection
= 'p';
2646 } elseif ( $this->mLastSection
!== 'p' ) {
2647 $output .= $this->closeParagraph() . '<p>';
2648 $this->mLastSection
= 'p';
2653 wfProfileOut( __METHOD__
. "-paragraph" );
2655 # somewhere above we forget to get out of pre block (bug 785)
2656 if ( $preCloseMatch && $this->mInPre
) {
2657 $this->mInPre
= false;
2659 if ( $paragraphStack === false ) {
2661 if ( $prefixLength === 0 ) {
2666 while ( $prefixLength ) {
2667 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2669 if ( !$prefixLength ) {
2673 if ( $this->mLastSection
!= '' ) {
2674 $output .= '</' . $this->mLastSection
. '>';
2675 $this->mLastSection
= '';
2678 wfProfileOut( __METHOD__
);
2683 * Split up a string on ':', ignoring any occurrences inside tags
2684 * to prevent illegal overlapping.
2686 * @param string $str The string to split
2687 * @param string &$before Set to everything before the ':'
2688 * @param string &$after Set to everything after the ':'
2689 * @throws MWException
2690 * @return string The position of the ':', or false if none found
2692 public function findColonNoLinks( $str, &$before, &$after ) {
2693 wfProfileIn( __METHOD__
);
2695 $pos = strpos( $str, ':' );
2696 if ( $pos === false ) {
2698 wfProfileOut( __METHOD__
);
2702 $lt = strpos( $str, '<' );
2703 if ( $lt === false ||
$lt > $pos ) {
2704 # Easy; no tag nesting to worry about
2705 $before = substr( $str, 0, $pos );
2706 $after = substr( $str, $pos +
1 );
2707 wfProfileOut( __METHOD__
);
2711 # Ugly state machine to walk through avoiding tags.
2712 $state = self
::COLON_STATE_TEXT
;
2714 $len = strlen( $str );
2715 for ( $i = 0; $i < $len; $i++
) {
2719 # (Using the number is a performance hack for common cases)
2720 case 0: # self::COLON_STATE_TEXT:
2723 # Could be either a <start> tag or an </end> tag
2724 $state = self
::COLON_STATE_TAGSTART
;
2727 if ( $stack == 0 ) {
2729 $before = substr( $str, 0, $i );
2730 $after = substr( $str, $i +
1 );
2731 wfProfileOut( __METHOD__
);
2734 # Embedded in a tag; don't break it.
2737 # Skip ahead looking for something interesting
2738 $colon = strpos( $str, ':', $i );
2739 if ( $colon === false ) {
2740 # Nothing else interesting
2741 wfProfileOut( __METHOD__
);
2744 $lt = strpos( $str, '<', $i );
2745 if ( $stack === 0 ) {
2746 if ( $lt === false ||
$colon < $lt ) {
2748 $before = substr( $str, 0, $colon );
2749 $after = substr( $str, $colon +
1 );
2750 wfProfileOut( __METHOD__
);
2754 if ( $lt === false ) {
2755 # Nothing else interesting to find; abort!
2756 # We're nested, but there's no close tags left. Abort!
2759 # Skip ahead to next tag start
2761 $state = self
::COLON_STATE_TAGSTART
;
2764 case 1: # self::COLON_STATE_TAG:
2769 $state = self
::COLON_STATE_TEXT
;
2772 # Slash may be followed by >?
2773 $state = self
::COLON_STATE_TAGSLASH
;
2779 case 2: # self::COLON_STATE_TAGSTART:
2782 $state = self
::COLON_STATE_CLOSETAG
;
2785 $state = self
::COLON_STATE_COMMENT
;
2788 # Illegal early close? This shouldn't happen D:
2789 $state = self
::COLON_STATE_TEXT
;
2792 $state = self
::COLON_STATE_TAG
;
2795 case 3: # self::COLON_STATE_CLOSETAG:
2800 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2801 wfProfileOut( __METHOD__
);
2804 $state = self
::COLON_STATE_TEXT
;
2807 case self
::COLON_STATE_TAGSLASH
:
2809 # Yes, a self-closed tag <blah/>
2810 $state = self
::COLON_STATE_TEXT
;
2812 # Probably we're jumping the gun, and this is an attribute
2813 $state = self
::COLON_STATE_TAG
;
2816 case 5: # self::COLON_STATE_COMMENT:
2818 $state = self
::COLON_STATE_COMMENTDASH
;
2821 case self
::COLON_STATE_COMMENTDASH
:
2823 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2825 $state = self
::COLON_STATE_COMMENT
;
2828 case self
::COLON_STATE_COMMENTDASHDASH
:
2830 $state = self
::COLON_STATE_TEXT
;
2832 $state = self
::COLON_STATE_COMMENT
;
2836 wfProfileOut( __METHOD__
);
2837 throw new MWException( "State machine error in " . __METHOD__
);
2841 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2842 wfProfileOut( __METHOD__
);
2845 wfProfileOut( __METHOD__
);
2850 * Return value of a magic variable (like PAGENAME)
2855 * @param bool|PPFrame $frame
2857 * @throws MWException
2860 public function getVariableValue( $index, $frame = false ) {
2861 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2862 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2864 if ( is_null( $this->mTitle
) ) {
2865 // If no title set, bad things are going to happen
2866 // later. Title should always be set since this
2867 // should only be called in the middle of a parse
2868 // operation (but the unit-tests do funky stuff)
2869 throw new MWException( __METHOD__
. ' Should only be '
2870 . ' called while parsing (no title set)' );
2874 * Some of these require message or data lookups and can be
2875 * expensive to check many times.
2877 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2878 if ( isset( $this->mVarCache
[$index] ) ) {
2879 return $this->mVarCache
[$index];
2883 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2884 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2886 $pageLang = $this->getFunctionLang();
2892 case 'currentmonth':
2893 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2895 case 'currentmonth1':
2896 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2898 case 'currentmonthname':
2899 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2901 case 'currentmonthnamegen':
2902 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2904 case 'currentmonthabbrev':
2905 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2908 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2911 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2914 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2917 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2919 case 'localmonthname':
2920 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2922 case 'localmonthnamegen':
2923 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2925 case 'localmonthabbrev':
2926 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2929 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2932 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2935 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2938 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2940 case 'fullpagename':
2941 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2943 case 'fullpagenamee':
2944 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2947 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2949 case 'subpagenamee':
2950 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2952 case 'rootpagename':
2953 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2955 case 'rootpagenamee':
2956 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2959 $this->mTitle
->getRootText()
2962 case 'basepagename':
2963 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2965 case 'basepagenamee':
2966 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2969 $this->mTitle
->getBaseText()
2972 case 'talkpagename':
2973 if ( $this->mTitle
->canTalk() ) {
2974 $talkPage = $this->mTitle
->getTalkPage();
2975 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2980 case 'talkpagenamee':
2981 if ( $this->mTitle
->canTalk() ) {
2982 $talkPage = $this->mTitle
->getTalkPage();
2983 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2988 case 'subjectpagename':
2989 $subjPage = $this->mTitle
->getSubjectPage();
2990 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2992 case 'subjectpagenamee':
2993 $subjPage = $this->mTitle
->getSubjectPage();
2994 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2996 case 'pageid': // requested in bug 23427
2997 $pageid = $this->getTitle()->getArticleID();
2998 if ( $pageid == 0 ) {
2999 # 0 means the page doesn't exist in the database,
3000 # which means the user is previewing a new page.
3001 # The vary-revision flag must be set, because the magic word
3002 # will have a different value once the page is saved.
3003 $this->mOutput
->setFlag( 'vary-revision' );
3004 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3006 $value = $pageid ?
$pageid : null;
3009 # Let the edit saving system know we should parse the page
3010 # *after* a revision ID has been assigned.
3011 $this->mOutput
->setFlag( 'vary-revision' );
3012 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3013 $value = $this->mRevisionId
;
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__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3020 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3022 case 'revisionday2':
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__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3027 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3029 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3034 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3036 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3041 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3043 case 'revisionyear':
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__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3048 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3050 case 'revisiontimestamp':
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__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3055 $value = $this->getRevisionTimestamp();
3057 case 'revisionuser':
3058 # Let the edit saving system know we should parse the page
3059 # *after* a revision ID has been assigned. This is for null edits.
3060 $this->mOutput
->setFlag( 'vary-revision' );
3061 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3062 $value = $this->getRevisionUser();
3064 case 'revisionsize':
3065 # Let the edit saving system know we should parse the page
3066 # *after* a revision ID has been assigned. This is for null edits.
3067 $this->mOutput
->setFlag( 'vary-revision' );
3068 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3069 $value = $this->getRevisionSize();
3072 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3075 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3077 case 'namespacenumber':
3078 $value = $this->mTitle
->getNamespace();
3081 $value = $this->mTitle
->canTalk()
3082 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3086 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3088 case 'subjectspace':
3089 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3091 case 'subjectspacee':
3092 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3094 case 'currentdayname':
3095 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3098 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3101 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3104 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3107 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3108 # int to remove the padding
3109 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3112 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3114 case 'localdayname':
3115 $value = $pageLang->getWeekdayName(
3116 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3120 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3123 $value = $pageLang->time(
3124 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3130 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3133 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3134 # int to remove the padding
3135 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3138 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3140 case 'numberofarticles':
3141 $value = $pageLang->formatNum( SiteStats
::articles() );
3143 case 'numberoffiles':
3144 $value = $pageLang->formatNum( SiteStats
::images() );
3146 case 'numberofusers':
3147 $value = $pageLang->formatNum( SiteStats
::users() );
3149 case 'numberofactiveusers':
3150 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3152 case 'numberofpages':
3153 $value = $pageLang->formatNum( SiteStats
::pages() );
3155 case 'numberofadmins':
3156 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3158 case 'numberofedits':
3159 $value = $pageLang->formatNum( SiteStats
::edits() );
3161 case 'numberofviews':
3162 global $wgDisableCounters;
3163 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3165 case 'currenttimestamp':
3166 $value = wfTimestamp( TS_MW
, $ts );
3168 case 'localtimestamp':
3169 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3171 case 'currentversion':
3172 $value = SpecialVersion
::getVersion();
3175 return $wgArticlePath;
3181 return $wgServerName;
3183 return $wgScriptPath;
3185 return $wgStylePath;
3186 case 'directionmark':
3187 return $pageLang->getDirMark();
3188 case 'contentlanguage':
3189 global $wgLanguageCode;
3190 return $wgLanguageCode;
3191 case 'cascadingsources':
3192 $value = CoreParserFunctions
::cascadingsources( $this );
3197 'ParserGetVariableValueSwitch',
3198 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3205 $this->mVarCache
[$index] = $value;
3212 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3216 public function initialiseVariables() {
3217 wfProfileIn( __METHOD__
);
3218 $variableIDs = MagicWord
::getVariableIDs();
3219 $substIDs = MagicWord
::getSubstIDs();
3221 $this->mVariables
= new MagicWordArray( $variableIDs );
3222 $this->mSubstWords
= new MagicWordArray( $substIDs );
3223 wfProfileOut( __METHOD__
);
3227 * Preprocess some wikitext and return the document tree.
3228 * This is the ghost of replace_variables().
3230 * @param string $text The text to parse
3231 * @param int $flags Bitwise combination of:
3232 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3233 * included. Default is to assume a direct page view.
3235 * The generated DOM tree must depend only on the input text and the flags.
3236 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3238 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3239 * change in the DOM tree for a given text, must be passed through the section identifier
3240 * in the section edit link and thus back to extractSections().
3242 * The output of this function is currently only cached in process memory, but a persistent
3243 * cache may be implemented at a later date which takes further advantage of these strict
3244 * dependency requirements.
3248 public function preprocessToDom( $text, $flags = 0 ) {
3249 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3254 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3260 public static function splitWhitespace( $s ) {
3261 $ltrimmed = ltrim( $s );
3262 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3263 $trimmed = rtrim( $ltrimmed );
3264 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3266 $w2 = substr( $ltrimmed, -$diff );
3270 return array( $w1, $trimmed, $w2 );
3274 * Replace magic variables, templates, and template arguments
3275 * with the appropriate text. Templates are substituted recursively,
3276 * taking care to avoid infinite loops.
3278 * Note that the substitution depends on value of $mOutputType:
3279 * self::OT_WIKI: only {{subst:}} templates
3280 * self::OT_PREPROCESS: templates but not extension tags
3281 * self::OT_HTML: all templates and extension tags
3283 * @param string $text The text to transform
3284 * @param bool|PPFrame $frame Object describing the arguments passed to the
3285 * template. Arguments may also be provided as an associative array, as
3286 * was the usual case before MW1.12. Providing arguments this way may be
3287 * useful for extensions wishing to perform variable replacement
3289 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3290 * double-brace expansion.
3293 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3294 # Is there any text? Also, Prevent too big inclusions!
3295 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3298 wfProfileIn( __METHOD__
);
3300 if ( $frame === false ) {
3301 $frame = $this->getPreprocessor()->newFrame();
3302 } elseif ( !( $frame instanceof PPFrame
) ) {
3303 wfDebug( __METHOD__
. " called using plain parameters instead of "
3304 . "a PPFrame instance. Creating custom frame.\n" );
3305 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3308 $dom = $this->preprocessToDom( $text );
3309 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3310 $text = $frame->expand( $dom, $flags );
3312 wfProfileOut( __METHOD__
);
3317 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3319 * @param array $args
3323 public static function createAssocArgs( $args ) {
3324 $assocArgs = array();
3326 foreach ( $args as $arg ) {
3327 $eqpos = strpos( $arg, '=' );
3328 if ( $eqpos === false ) {
3329 $assocArgs[$index++
] = $arg;
3331 $name = trim( substr( $arg, 0, $eqpos ) );
3332 $value = trim( substr( $arg, $eqpos +
1 ) );
3333 if ( $value === false ) {
3336 if ( $name !== false ) {
3337 $assocArgs[$name] = $value;
3346 * Warn the user when a parser limitation is reached
3347 * Will warn at most once the user per limitation type
3349 * @param string $limitationType Should be one of:
3350 * 'expensive-parserfunction' (corresponding messages:
3351 * 'expensive-parserfunction-warning',
3352 * 'expensive-parserfunction-category')
3353 * 'post-expand-template-argument' (corresponding messages:
3354 * 'post-expand-template-argument-warning',
3355 * 'post-expand-template-argument-category')
3356 * 'post-expand-template-inclusion' (corresponding messages:
3357 * 'post-expand-template-inclusion-warning',
3358 * 'post-expand-template-inclusion-category')
3359 * 'node-count-exceeded' (corresponding messages:
3360 * 'node-count-exceeded-warning',
3361 * 'node-count-exceeded-category')
3362 * 'expansion-depth-exceeded' (corresponding messages:
3363 * 'expansion-depth-exceeded-warning',
3364 * 'expansion-depth-exceeded-category')
3365 * @param string|int|null $current Current value
3366 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3367 * exceeded, provide the values (optional)
3369 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3370 # does no harm if $current and $max are present but are unnecessary for the message
3371 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3372 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3373 $this->mOutput
->addWarning( $warning );
3374 $this->addTrackingCategory( "$limitationType-category" );
3378 * Return the text of a template, after recursively
3379 * replacing any variables or templates within the template.
3381 * @param array $piece The parts of the template
3382 * $piece['title']: the title, i.e. the part before the |
3383 * $piece['parts']: the parameter array
3384 * $piece['lineStart']: whether the brace was at the start of a line
3385 * @param PPFrame $frame The current frame, contains template arguments
3387 * @return string The text of the template
3389 public function braceSubstitution( $piece, $frame ) {
3390 wfProfileIn( __METHOD__
);
3391 wfProfileIn( __METHOD__
. '-setup' );
3395 // $text has been filled
3397 // wiki markup in $text should be escaped
3399 // $text is HTML, armour it against wikitext transformation
3401 // Force interwiki transclusion to be done in raw mode not rendered
3402 $forceRawInterwiki = false;
3403 // $text is a DOM node needing expansion in a child frame
3404 $isChildObj = false;
3405 // $text is a DOM node needing expansion in the current frame
3406 $isLocalObj = false;
3408 # Title object, where $text came from
3411 # $part1 is the bit before the first |, and must contain only title characters.
3412 # Various prefixes will be stripped from it later.
3413 $titleWithSpaces = $frame->expand( $piece['title'] );
3414 $part1 = trim( $titleWithSpaces );
3417 # Original title text preserved for various purposes
3418 $originalTitle = $part1;
3420 # $args is a list of argument nodes, starting from index 0, not including $part1
3421 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3422 # below won't work b/c this $args isn't an object
3423 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3424 wfProfileOut( __METHOD__
. '-setup' );
3426 $titleProfileIn = null; // profile templates
3429 wfProfileIn( __METHOD__
. '-modifiers' );
3432 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3434 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3435 # Decide whether to expand template or keep wikitext as-is.
3436 if ( $this->ot
['wiki'] ) {
3437 if ( $substMatch === false ) {
3438 $literal = true; # literal when in PST with no prefix
3440 $literal = false; # expand when in PST with subst: or safesubst:
3443 if ( $substMatch == 'subst' ) {
3444 $literal = true; # literal when not in PST with plain subst:
3446 $literal = false; # expand when not in PST with safesubst: or no prefix
3450 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3457 if ( !$found && $args->getLength() == 0 ) {
3458 $id = $this->mVariables
->matchStartToEnd( $part1 );
3459 if ( $id !== false ) {
3460 $text = $this->getVariableValue( $id, $frame );
3461 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3462 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3468 # MSG, MSGNW and RAW
3471 $mwMsgnw = MagicWord
::get( 'msgnw' );
3472 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3475 # Remove obsolete MSG:
3476 $mwMsg = MagicWord
::get( 'msg' );
3477 $mwMsg->matchStartAndRemove( $part1 );
3481 $mwRaw = MagicWord
::get( 'raw' );
3482 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3483 $forceRawInterwiki = true;
3486 wfProfileOut( __METHOD__
. '-modifiers' );
3490 wfProfileIn( __METHOD__
. '-pfunc' );
3492 $colonPos = strpos( $part1, ':' );
3493 if ( $colonPos !== false ) {
3494 $func = substr( $part1, 0, $colonPos );
3495 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3496 for ( $i = 0; $i < $args->getLength(); $i++
) {
3497 $funcArgs[] = $args->item( $i );
3500 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3501 } catch ( Exception
$ex ) {
3502 wfProfileOut( __METHOD__
. '-pfunc' );
3503 wfProfileOut( __METHOD__
);
3507 # The interface for parser functions allows for extracting
3508 # flags into the local scope. Extract any forwarded flags
3512 wfProfileOut( __METHOD__
. '-pfunc' );
3515 # Finish mangling title and then check for loops.
3516 # Set $title to a Title object and $titleText to the PDBK
3519 # Split the title into page and subpage
3521 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3522 if ( $part1 !== $relative ) {
3524 $ns = $this->mTitle
->getNamespace();
3526 $title = Title
::newFromText( $part1, $ns );
3528 $titleText = $title->getPrefixedText();
3529 # Check for language variants if the template is not found
3530 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3531 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3533 # Do recursion depth check
3534 $limit = $this->mOptions
->getMaxTemplateDepth();
3535 if ( $frame->depth
>= $limit ) {
3537 $text = '<span class="error">'
3538 . wfMessage( 'parser-template-recursion-depth-warning' )
3539 ->numParams( $limit )->inContentLanguage()->text()
3545 # Load from database
3546 if ( !$found && $title ) {
3547 if ( !Profiler
::instance()->isPersistent() ) {
3548 # Too many unique items can kill profiling DBs/collectors
3549 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3550 wfProfileIn( $titleProfileIn ); // template in
3552 wfProfileIn( __METHOD__
. '-loadtpl' );
3553 if ( !$title->isExternal() ) {
3554 if ( $title->isSpecialPage()
3555 && $this->mOptions
->getAllowSpecialInclusion()
3556 && $this->ot
['html']
3558 // Pass the template arguments as URL parameters.
3559 // "uselang" will have no effect since the Language object
3560 // is forced to the one defined in ParserOptions.
3561 $pageArgs = array();
3562 $argsLength = $args->getLength();
3563 for ( $i = 0; $i < $argsLength; $i++
) {
3564 $bits = $args->item( $i )->splitArg();
3565 if ( strval( $bits['index'] ) === '' ) {
3566 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3567 $value = trim( $frame->expand( $bits['value'] ) );
3568 $pageArgs[$name] = $value;
3572 // Create a new context to execute the special page
3573 $context = new RequestContext
;
3574 $context->setTitle( $title );
3575 $context->setRequest( new FauxRequest( $pageArgs ) );
3576 $context->setUser( $this->getUser() );
3577 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3578 $ret = SpecialPageFactory
::capturePath( $title, $context );
3580 $text = $context->getOutput()->getHTML();
3581 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3584 $this->disableCache();
3586 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3587 $found = false; # access denied
3588 wfDebug( __METHOD__
. ": template inclusion denied for " .
3589 $title->getPrefixedDBkey() . "\n" );
3591 list( $text, $title ) = $this->getTemplateDom( $title );
3592 if ( $text !== false ) {
3598 # If the title is valid but undisplayable, make a link to it
3599 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3600 $text = "[[:$titleText]]";
3603 } elseif ( $title->isTrans() ) {
3604 # Interwiki transclusion
3605 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3606 $text = $this->interwikiTransclude( $title, 'render' );
3609 $text = $this->interwikiTransclude( $title, 'raw' );
3610 # Preprocess it like a template
3611 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3617 # Do infinite loop check
3618 # This has to be done after redirect resolution to avoid infinite loops via redirects
3619 if ( !$frame->loopCheck( $title ) ) {
3621 $text = '<span class="error">'
3622 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3624 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3626 wfProfileOut( __METHOD__
. '-loadtpl' );
3629 # If we haven't found text to substitute by now, we're done
3630 # Recover the source wikitext and return it
3632 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3633 if ( $titleProfileIn ) {
3634 wfProfileOut( $titleProfileIn ); // template out
3636 wfProfileOut( __METHOD__
);
3637 return array( 'object' => $text );
3640 # Expand DOM-style return values in a child frame
3641 if ( $isChildObj ) {
3642 # Clean up argument array
3643 $newFrame = $frame->newChild( $args, $title );
3646 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3647 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3648 # Expansion is eligible for the empty-frame cache
3649 $text = $newFrame->cachedExpand( $titleText, $text );
3651 # Uncached expansion
3652 $text = $newFrame->expand( $text );
3655 if ( $isLocalObj && $nowiki ) {
3656 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3657 $isLocalObj = false;
3660 if ( $titleProfileIn ) {
3661 wfProfileOut( $titleProfileIn ); // template out
3664 # Replace raw HTML by a placeholder
3666 $text = $this->insertStripItem( $text );
3667 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3668 # Escape nowiki-style return values
3669 $text = wfEscapeWikiText( $text );
3670 } elseif ( is_string( $text )
3671 && !$piece['lineStart']
3672 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3674 # Bug 529: if the template begins with a table or block-level
3675 # element, it should be treated as beginning a new line.
3676 # This behavior is somewhat controversial.
3677 $text = "\n" . $text;
3680 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3681 # Error, oversize inclusion
3682 if ( $titleText !== false ) {
3683 # Make a working, properly escaped link if possible (bug 23588)
3684 $text = "[[:$titleText]]";
3686 # This will probably not be a working link, but at least it may
3687 # provide some hint of where the problem is
3688 preg_replace( '/^:/', '', $originalTitle );
3689 $text = "[[:$originalTitle]]";
3691 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3692 . 'post-expand include size too large -->' );
3693 $this->limitationWarn( 'post-expand-template-inclusion' );
3696 if ( $isLocalObj ) {
3697 $ret = array( 'object' => $text );
3699 $ret = array( 'text' => $text );
3702 wfProfileOut( __METHOD__
);
3707 * Call a parser function and return an array with text and flags.
3709 * The returned array will always contain a boolean 'found', indicating
3710 * whether the parser function was found or not. It may also contain the
3712 * text: string|object, resulting wikitext or PP DOM object
3713 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3714 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3715 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3716 * nowiki: bool, wiki markup in $text should be escaped
3719 * @param PPFrame $frame The current frame, contains template arguments
3720 * @param string $function Function name
3721 * @param array $args Arguments to the function
3722 * @throws MWException
3725 public function callParserFunction( $frame, $function, array $args = array() ) {
3728 wfProfileIn( __METHOD__
);
3730 # Case sensitive functions
3731 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3732 $function = $this->mFunctionSynonyms
[1][$function];
3734 # Case insensitive functions
3735 $function = $wgContLang->lc( $function );
3736 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3737 $function = $this->mFunctionSynonyms
[0][$function];
3739 wfProfileOut( __METHOD__
);
3740 return array( 'found' => false );
3744 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3745 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3747 # Workaround for PHP bug 35229 and similar
3748 if ( !is_callable( $callback ) ) {
3749 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3750 wfProfileOut( __METHOD__
);
3751 throw new MWException( "Tag hook for $function is not callable\n" );
3754 $allArgs = array( &$this );
3755 if ( $flags & SFH_OBJECT_ARGS
) {
3756 # Convert arguments to PPNodes and collect for appending to $allArgs
3757 $funcArgs = array();
3758 foreach ( $args as $k => $v ) {
3759 if ( $v instanceof PPNode ||
$k === 0 ) {
3762 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3766 # Add a frame parameter, and pass the arguments as an array
3767 $allArgs[] = $frame;
3768 $allArgs[] = $funcArgs;
3770 # Convert arguments to plain text and append to $allArgs
3771 foreach ( $args as $k => $v ) {
3772 if ( $v instanceof PPNode
) {
3773 $allArgs[] = trim( $frame->expand( $v ) );
3774 } elseif ( is_int( $k ) && $k >= 0 ) {
3775 $allArgs[] = trim( $v );
3777 $allArgs[] = trim( "$k=$v" );
3782 $result = call_user_func_array( $callback, $allArgs );
3784 # The interface for function hooks allows them to return a wikitext
3785 # string or an array containing the string and any flags. This mungs
3786 # things around to match what this method should return.
3787 if ( !is_array( $result ) ) {
3793 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3794 $result['text'] = $result[0];
3796 unset( $result[0] );
3803 $preprocessFlags = 0;
3804 if ( isset( $result['noparse'] ) ) {
3805 $noparse = $result['noparse'];
3807 if ( isset( $result['preprocessFlags'] ) ) {
3808 $preprocessFlags = $result['preprocessFlags'];
3812 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3813 $result['isChildObj'] = true;
3815 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3816 wfProfileOut( __METHOD__
);
3822 * Get the semi-parsed DOM representation of a template with a given title,
3823 * and its redirect destination title. Cached.
3825 * @param Title $title
3829 public function getTemplateDom( $title ) {
3830 $cacheTitle = $title;
3831 $titleText = $title->getPrefixedDBkey();
3833 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3834 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3835 $title = Title
::makeTitle( $ns, $dbk );
3836 $titleText = $title->getPrefixedDBkey();
3838 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3839 return array( $this->mTplDomCache
[$titleText], $title );
3842 # Cache miss, go to the database
3843 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3845 if ( $text === false ) {
3846 $this->mTplDomCache
[$titleText] = false;
3847 return array( false, $title );
3850 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3851 $this->mTplDomCache
[$titleText] = $dom;
3853 if ( !$title->equals( $cacheTitle ) ) {
3854 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3855 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3858 return array( $dom, $title );
3862 * Fetch the current revision of a given title. Note that the revision
3863 * (and even the title) may not exist in the database, so everything
3864 * contributing to the output of the parser should use this method
3865 * where possible, rather than getting the revisions themselves. This
3866 * method also caches its results, so using it benefits performance.
3869 * @param Title $title
3872 public function fetchCurrentRevisionOfTitle( $title ) {
3873 $cacheKey = $title->getPrefixedDBkey();
3874 if ( !$this->currentRevisionCache
) {
3875 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3877 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3878 $this->currentRevisionCache
->set( $cacheKey,
3879 // Defaults to Parser::statelessFetchRevision()
3880 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3883 return $this->currentRevisionCache
->get( $cacheKey );
3887 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3888 * without passing them on to it.
3891 * @param Title $title
3892 * @param Parser|bool $parser
3895 public static function statelessFetchRevision( $title, $parser = false ) {
3896 return Revision
::newFromTitle( $title );
3900 * Fetch the unparsed text of a template and register a reference to it.
3901 * @param Title $title
3902 * @return array ( string or false, Title )
3904 public function fetchTemplateAndTitle( $title ) {
3905 // Defaults to Parser::statelessFetchTemplate()
3906 $templateCb = $this->mOptions
->getTemplateCallback();
3907 $stuff = call_user_func( $templateCb, $title, $this );
3908 $text = $stuff['text'];
3909 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3910 if ( isset( $stuff['deps'] ) ) {
3911 foreach ( $stuff['deps'] as $dep ) {
3912 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3913 if ( $dep['title']->equals( $this->getTitle() ) ) {
3914 // If we transclude ourselves, the final result
3915 // will change based on the new version of the page
3916 $this->mOutput
->setFlag( 'vary-revision' );
3920 return array( $text, $finalTitle );
3924 * Fetch the unparsed text of a template and register a reference to it.
3925 * @param Title $title
3926 * @return string|bool
3928 public function fetchTemplate( $title ) {
3929 $rv = $this->fetchTemplateAndTitle( $title );
3934 * Static function to get a template
3935 * Can be overridden via ParserOptions::setTemplateCallback().
3937 * @param Title $title
3938 * @param bool|Parser $parser
3942 public static function statelessFetchTemplate( $title, $parser = false ) {
3943 $text = $skip = false;
3944 $finalTitle = $title;
3947 # Loop to fetch the article, with up to 1 redirect
3948 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3949 # Give extensions a chance to select the revision instead
3950 $id = false; # Assume current
3951 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3952 array( $parser, $title, &$skip, &$id ) );
3958 'page_id' => $title->getArticleID(),
3965 $rev = Revision
::newFromId( $id );
3966 } elseif ( $parser ) {
3967 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3969 $rev = Revision
::newFromTitle( $title );
3971 $rev_id = $rev ?
$rev->getId() : 0;
3972 # If there is no current revision, there is no page
3973 if ( $id === false && !$rev ) {
3974 $linkCache = LinkCache
::singleton();
3975 $linkCache->addBadLinkObj( $title );
3980 'page_id' => $title->getArticleID(),
3981 'rev_id' => $rev_id );
3982 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3983 # We fetched a rev from a different title; register it too...
3985 'title' => $rev->getTitle(),
3986 'page_id' => $rev->getPage(),
3987 'rev_id' => $rev_id );
3991 $content = $rev->getContent();
3992 $text = $content ?
$content->getWikitextForTransclusion() : null;
3994 if ( $text === false ||
$text === null ) {
3998 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4000 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4001 if ( !$message->exists() ) {
4005 $content = $message->content();
4006 $text = $message->plain();
4014 $finalTitle = $title;
4015 $title = $content->getRedirectTarget();
4019 'finalTitle' => $finalTitle,
4024 * Fetch a file and its title and register a reference to it.
4025 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4026 * @param Title $title
4027 * @param array $options Array of options to RepoGroup::findFile
4030 public function fetchFile( $title, $options = array() ) {
4031 $res = $this->fetchFileAndTitle( $title, $options );
4036 * Fetch a file and its title and register a reference to it.
4037 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4038 * @param Title $title
4039 * @param array $options Array of options to RepoGroup::findFile
4040 * @return array ( File or false, Title of file )
4042 public function fetchFileAndTitle( $title, $options = array() ) {
4043 $file = $this->fetchFileNoRegister( $title, $options );
4045 $time = $file ?
$file->getTimestamp() : false;
4046 $sha1 = $file ?
$file->getSha1() : false;
4047 # Register the file as a dependency...
4048 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4049 if ( $file && !$title->equals( $file->getTitle() ) ) {
4050 # Update fetched file title
4051 $title = $file->getTitle();
4052 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4054 return array( $file, $title );
4058 * Helper function for fetchFileAndTitle.
4060 * Also useful if you need to fetch a file but not use it yet,
4061 * for example to get the file's handler.
4063 * @param Title $title
4064 * @param array $options Array of options to RepoGroup::findFile
4067 protected function fetchFileNoRegister( $title, $options = array() ) {
4068 if ( isset( $options['broken'] ) ) {
4069 $file = false; // broken thumbnail forced by hook
4070 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4071 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4072 } else { // get by (name,timestamp)
4073 $file = wfFindFile( $title, $options );
4079 * Transclude an interwiki link.
4081 * @param Title $title
4082 * @param string $action
4086 public function interwikiTransclude( $title, $action ) {
4087 global $wgEnableScaryTranscluding;
4089 if ( !$wgEnableScaryTranscluding ) {
4090 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4093 $url = $title->getFullURL( array( 'action' => $action ) );
4095 if ( strlen( $url ) > 255 ) {
4096 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4098 return $this->fetchScaryTemplateMaybeFromCache( $url );
4102 * @param string $url
4103 * @return mixed|string
4105 public function fetchScaryTemplateMaybeFromCache( $url ) {
4106 global $wgTranscludeCacheExpiry;
4107 $dbr = wfGetDB( DB_SLAVE
);
4108 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4109 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4110 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4112 return $obj->tc_contents
;
4115 $req = MWHttpRequest
::factory( $url );
4116 $status = $req->execute(); // Status object
4117 if ( $status->isOK() ) {
4118 $text = $req->getContent();
4119 } elseif ( $req->getStatus() != 200 ) {
4120 // Though we failed to fetch the content, this status is useless.
4121 return wfMessage( 'scarytranscludefailed-httpstatus' )
4122 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4124 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4127 $dbw = wfGetDB( DB_MASTER
);
4128 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4130 'tc_time' => $dbw->timestamp( time() ),
4131 'tc_contents' => $text
4137 * Triple brace replacement -- used for template arguments
4140 * @param array $piece
4141 * @param PPFrame $frame
4145 public function argSubstitution( $piece, $frame ) {
4146 wfProfileIn( __METHOD__
);
4149 $parts = $piece['parts'];
4150 $nameWithSpaces = $frame->expand( $piece['title'] );
4151 $argName = trim( $nameWithSpaces );
4153 $text = $frame->getArgument( $argName );
4154 if ( $text === false && $parts->getLength() > 0
4155 && ( $this->ot
['html']
4157 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4160 # No match in frame, use the supplied default
4161 $object = $parts->item( 0 )->getChildren();
4163 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4164 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4165 $this->limitationWarn( 'post-expand-template-argument' );
4168 if ( $text === false && $object === false ) {
4170 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4172 if ( $error !== false ) {
4175 if ( $object !== false ) {
4176 $ret = array( 'object' => $object );
4178 $ret = array( 'text' => $text );
4181 wfProfileOut( __METHOD__
);
4186 * Return the text to be used for a given extension tag.
4187 * This is the ghost of strip().
4189 * @param array $params Associative array of parameters:
4190 * name PPNode for the tag name
4191 * attr PPNode for unparsed text where tag attributes are thought to be
4192 * attributes Optional associative array of parsed attributes
4193 * inner Contents of extension element
4194 * noClose Original text did not have a close tag
4195 * @param PPFrame $frame
4197 * @throws MWException
4200 public function extensionSubstitution( $params, $frame ) {
4201 $name = $frame->expand( $params['name'] );
4202 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4203 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4204 $marker = "{$this->mUniqPrefix}-$name-"
4205 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4207 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4208 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4209 if ( $isFunctionTag ) {
4210 $markerType = 'none';
4212 $markerType = 'general';
4214 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4215 $name = strtolower( $name );
4216 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4217 if ( isset( $params['attributes'] ) ) {
4218 $attributes = $attributes +
$params['attributes'];
4221 if ( isset( $this->mTagHooks
[$name] ) ) {
4222 # Workaround for PHP bug 35229 and similar
4223 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4224 throw new MWException( "Tag hook for $name is not callable\n" );
4226 $output = call_user_func_array( $this->mTagHooks
[$name],
4227 array( $content, $attributes, $this, $frame ) );
4228 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4229 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4230 if ( !is_callable( $callback ) ) {
4231 throw new MWException( "Tag hook for $name is not callable\n" );
4234 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4236 $output = '<span class="error">Invalid tag extension name: ' .
4237 htmlspecialchars( $name ) . '</span>';
4240 if ( is_array( $output ) ) {
4241 # Extract flags to local scope (to override $markerType)
4243 $output = $flags[0];
4248 if ( is_null( $attrText ) ) {
4251 if ( isset( $params['attributes'] ) ) {
4252 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4253 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4254 htmlspecialchars( $attrValue ) . '"';
4257 if ( $content === null ) {
4258 $output = "<$name$attrText/>";
4260 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4261 $output = "<$name$attrText>$content$close";
4265 if ( $markerType === 'none' ) {
4267 } elseif ( $markerType === 'nowiki' ) {
4268 $this->mStripState
->addNoWiki( $marker, $output );
4269 } elseif ( $markerType === 'general' ) {
4270 $this->mStripState
->addGeneral( $marker, $output );
4272 throw new MWException( __METHOD__
. ': invalid marker type' );
4278 * Increment an include size counter
4280 * @param string $type The type of expansion
4281 * @param int $size The size of the text
4282 * @return bool False if this inclusion would take it over the maximum, true otherwise
4284 public function incrementIncludeSize( $type, $size ) {
4285 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4288 $this->mIncludeSizes
[$type] +
= $size;
4294 * Increment the expensive function count
4296 * @return bool False if the limit has been exceeded
4298 public function incrementExpensiveFunctionCount() {
4299 $this->mExpensiveFunctionCount++
;
4300 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4304 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4305 * Fills $this->mDoubleUnderscores, returns the modified text
4307 * @param string $text
4311 public function doDoubleUnderscore( $text ) {
4312 wfProfileIn( __METHOD__
);
4314 # The position of __TOC__ needs to be recorded
4315 $mw = MagicWord
::get( 'toc' );
4316 if ( $mw->match( $text ) ) {
4317 $this->mShowToc
= true;
4318 $this->mForceTocPosition
= true;
4320 # Set a placeholder. At the end we'll fill it in with the TOC.
4321 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4323 # Only keep the first one.
4324 $text = $mw->replace( '', $text );
4327 # Now match and remove the rest of them
4328 $mwa = MagicWord
::getDoubleUnderscoreArray();
4329 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4331 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4332 $this->mOutput
->mNoGallery
= true;
4334 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4335 $this->mShowToc
= false;
4337 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4338 && $this->mTitle
->getNamespace() == NS_CATEGORY
4340 $this->addTrackingCategory( 'hidden-category-category' );
4342 # (bug 8068) Allow control over whether robots index a page.
4344 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4345 # is not desirable, the last one on the page should win.
4346 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4347 $this->mOutput
->setIndexPolicy( 'noindex' );
4348 $this->addTrackingCategory( 'noindex-category' );
4350 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4351 $this->mOutput
->setIndexPolicy( 'index' );
4352 $this->addTrackingCategory( 'index-category' );
4355 # Cache all double underscores in the database
4356 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4357 $this->mOutput
->setProperty( $key, '' );
4360 wfProfileOut( __METHOD__
);
4365 * @see ParserOutput::addTrackingCategory()
4366 * @param string $msg Message key
4367 * @return bool Whether the addition was successful
4369 public function addTrackingCategory( $msg ) {
4370 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4374 * This function accomplishes several tasks:
4375 * 1) Auto-number headings if that option is enabled
4376 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4377 * 3) Add a Table of contents on the top for users who have enabled the option
4378 * 4) Auto-anchor headings
4380 * It loops through all headlines, collects the necessary data, then splits up the
4381 * string and re-inserts the newly formatted headlines.
4383 * @param string $text
4384 * @param string $origText Original, untouched wikitext
4385 * @param bool $isMain
4386 * @return mixed|string
4389 public function formatHeadings( $text, $origText, $isMain = true ) {
4390 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4392 # Inhibit editsection links if requested in the page
4393 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4394 $maybeShowEditLink = $showEditLink = false;
4396 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4397 $showEditLink = $this->mOptions
->getEditSection();
4399 if ( $showEditLink ) {
4400 $this->mOutput
->setEditSectionTokens( true );
4403 # Get all headlines for numbering them and adding funky stuff like [edit]
4404 # links - this is for later, but we need the number of headlines right now
4406 $numMatches = preg_match_all(
4407 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4412 # if there are fewer than 4 headlines in the article, do not show TOC
4413 # unless it's been explicitly enabled.
4414 $enoughToc = $this->mShowToc
&&
4415 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4417 # Allow user to stipulate that a page should have a "new section"
4418 # link added via __NEWSECTIONLINK__
4419 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4420 $this->mOutput
->setNewSection( true );
4423 # Allow user to remove the "new section"
4424 # link via __NONEWSECTIONLINK__
4425 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4426 $this->mOutput
->hideNewSection( true );
4429 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4430 # override above conditions and always show TOC above first header
4431 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4432 $this->mShowToc
= true;
4440 # Ugh .. the TOC should have neat indentation levels which can be
4441 # passed to the skin functions. These are determined here
4445 $sublevelCount = array();
4446 $levelCount = array();
4451 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4452 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4453 $oldType = $this->mOutputType
;
4454 $this->setOutputType( self
::OT_WIKI
);
4455 $frame = $this->getPreprocessor()->newFrame();
4456 $root = $this->preprocessToDom( $origText );
4457 $node = $root->getFirstChild();
4462 foreach ( $matches[3] as $headline ) {
4463 $isTemplate = false;
4465 $sectionIndex = false;
4467 $markerMatches = array();
4468 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4469 $serial = $markerMatches[1];
4470 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4471 $isTemplate = ( $titleText != $baseTitleText );
4472 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4476 $prevlevel = $level;
4478 $level = $matches[1][$headlineCount];
4480 if ( $level > $prevlevel ) {
4481 # Increase TOC level
4483 $sublevelCount[$toclevel] = 0;
4484 if ( $toclevel < $wgMaxTocLevel ) {
4485 $prevtoclevel = $toclevel;
4486 $toc .= Linker
::tocIndent();
4489 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4490 # Decrease TOC level, find level to jump to
4492 for ( $i = $toclevel; $i > 0; $i-- ) {
4493 if ( $levelCount[$i] == $level ) {
4494 # Found last matching level
4497 } elseif ( $levelCount[$i] < $level ) {
4498 # Found first matching level below current level
4506 if ( $toclevel < $wgMaxTocLevel ) {
4507 if ( $prevtoclevel < $wgMaxTocLevel ) {
4508 # Unindent only if the previous toc level was shown :p
4509 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4510 $prevtoclevel = $toclevel;
4512 $toc .= Linker
::tocLineEnd();
4516 # No change in level, end TOC line
4517 if ( $toclevel < $wgMaxTocLevel ) {
4518 $toc .= Linker
::tocLineEnd();
4522 $levelCount[$toclevel] = $level;
4524 # count number of headlines for each level
4525 $sublevelCount[$toclevel]++
;
4527 for ( $i = 1; $i <= $toclevel; $i++
) {
4528 if ( !empty( $sublevelCount[$i] ) ) {
4532 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4537 # The safe header is a version of the header text safe to use for links
4539 # Remove link placeholders by the link text.
4540 # <!--LINK number-->
4542 # link text with suffix
4543 # Do this before unstrip since link text can contain strip markers
4544 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4546 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4547 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4549 # Strip out HTML (first regex removes any tag not allowed)
4551 # * <sup> and <sub> (bug 8393)
4554 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4556 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4557 # to allow setting directionality in toc items.
4558 $tocline = preg_replace(
4560 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4561 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4563 array( '', '<$1>' ),
4566 $tocline = trim( $tocline );
4568 # For the anchor, strip out HTML-y stuff period
4569 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4570 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4572 # Save headline for section edit hint before it's escaped
4573 $headlineHint = $safeHeadline;
4575 if ( $wgExperimentalHtmlIds ) {
4576 # For reverse compatibility, provide an id that's
4577 # HTML4-compatible, like we used to.
4579 # It may be worth noting, academically, that it's possible for
4580 # the legacy anchor to conflict with a non-legacy headline
4581 # anchor on the page. In this case likely the "correct" thing
4582 # would be to either drop the legacy anchors or make sure
4583 # they're numbered first. However, this would require people
4584 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4585 # manually, so let's not bother worrying about it.
4586 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4587 array( 'noninitial', 'legacy' ) );
4588 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4590 if ( $legacyHeadline == $safeHeadline ) {
4591 # No reason to have both (in fact, we can't)
4592 $legacyHeadline = false;
4595 $legacyHeadline = false;
4596 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4600 # HTML names must be case-insensitively unique (bug 10721).
4601 # This does not apply to Unicode characters per
4602 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4603 # @todo FIXME: We may be changing them depending on the current locale.
4604 $arrayKey = strtolower( $safeHeadline );
4605 if ( $legacyHeadline === false ) {
4606 $legacyArrayKey = false;
4608 $legacyArrayKey = strtolower( $legacyHeadline );
4611 # count how many in assoc. array so we can track dupes in anchors
4612 if ( isset( $refers[$arrayKey] ) ) {
4613 $refers[$arrayKey]++
;
4615 $refers[$arrayKey] = 1;
4617 if ( isset( $refers[$legacyArrayKey] ) ) {
4618 $refers[$legacyArrayKey]++
;
4620 $refers[$legacyArrayKey] = 1;
4623 # Don't number the heading if it is the only one (looks silly)
4624 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4625 # the two are different if the line contains a link
4626 $headline = Html
::element(
4628 array( 'class' => 'mw-headline-number' ),
4630 ) . ' ' . $headline;
4633 # Create the anchor for linking from the TOC to the section
4634 $anchor = $safeHeadline;
4635 $legacyAnchor = $legacyHeadline;
4636 if ( $refers[$arrayKey] > 1 ) {
4637 $anchor .= '_' . $refers[$arrayKey];
4639 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4640 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4642 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4643 $toc .= Linker
::tocLine( $anchor, $tocline,
4644 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4647 # Add the section to the section tree
4648 # Find the DOM node for this header
4649 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4650 while ( $node && !$noOffset ) {
4651 if ( $node->getName() === 'h' ) {
4652 $bits = $node->splitHeading();
4653 if ( $bits['i'] == $sectionIndex ) {
4657 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4658 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4659 $node = $node->getNextSibling();
4662 'toclevel' => $toclevel,
4665 'number' => $numbering,
4666 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4667 'fromtitle' => $titleText,
4668 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4669 'anchor' => $anchor,
4672 # give headline the correct <h#> tag
4673 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4674 // Output edit section links as markers with styles that can be customized by skins
4675 if ( $isTemplate ) {
4676 # Put a T flag in the section identifier, to indicate to extractSections()
4677 # that sections inside <includeonly> should be counted.
4678 $editsectionPage = $titleText;
4679 $editsectionSection = "T-$sectionIndex";
4680 $editsectionContent = null;
4682 $editsectionPage = $this->mTitle
->getPrefixedText();
4683 $editsectionSection = $sectionIndex;
4684 $editsectionContent = $headlineHint;
4686 // We use a bit of pesudo-xml for editsection markers. The
4687 // language converter is run later on. Using a UNIQ style marker
4688 // leads to the converter screwing up the tokens when it
4689 // converts stuff. And trying to insert strip tags fails too. At
4690 // this point all real inputted tags have already been escaped,
4691 // so we don't have to worry about a user trying to input one of
4692 // these markers directly. We use a page and section attribute
4693 // to stop the language converter from converting these
4694 // important bits of data, but put the headline hint inside a
4695 // content block because the language converter is supposed to
4696 // be able to convert that piece of data.
4697 // Gets replaced with html in ParserOutput::getText
4698 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4699 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4700 if ( $editsectionContent !== null ) {
4701 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4708 $head[$headlineCount] = Linker
::makeHeadline( $level,
4709 $matches['attrib'][$headlineCount], $anchor, $headline,
4710 $editlink, $legacyAnchor );
4715 $this->setOutputType( $oldType );
4717 # Never ever show TOC if no headers
4718 if ( $numVisible < 1 ) {
4723 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4724 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4726 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4727 $this->mOutput
->setTOCHTML( $toc );
4728 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4729 $this->mOutput
->addModules( 'mediawiki.toc' );
4733 $this->mOutput
->setSections( $tocraw );
4736 # split up and insert constructed headlines
4737 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4740 // build an array of document sections
4741 $sections = array();
4742 foreach ( $blocks as $block ) {
4743 // $head is zero-based, sections aren't.
4744 if ( empty( $head[$i - 1] ) ) {
4745 $sections[$i] = $block;
4747 $sections[$i] = $head[$i - 1] . $block;
4751 * Send a hook, one per section.
4752 * The idea here is to be able to make section-level DIVs, but to do so in a
4753 * lower-impact, more correct way than r50769
4756 * $section : the section number
4757 * &$sectionContent : ref to the content of the section
4758 * $showEditLinks : boolean describing whether this section has an edit link
4760 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4765 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4766 // append the TOC at the beginning
4767 // Top anchor now in skin
4768 $sections[0] = $sections[0] . $toc . "\n";
4771 $full .= join( '', $sections );
4773 if ( $this->mForceTocPosition
) {
4774 return str_replace( '<!--MWTOC-->', $toc, $full );
4781 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4782 * conversion, substitting signatures, {{subst:}} templates, etc.
4784 * @param string $text The text to transform
4785 * @param Title $title The Title object for the current article
4786 * @param User $user The User object describing the current user
4787 * @param ParserOptions $options Parsing options
4788 * @param bool $clearState Whether to clear the parser state first
4789 * @return string The altered wiki markup
4791 public function preSaveTransform( $text, Title
$title, User
$user,
4792 ParserOptions
$options, $clearState = true
4794 if ( $clearState ) {
4795 $magicScopeVariable = $this->lock();
4797 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4798 $this->setUser( $user );
4803 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4804 if ( $options->getPreSaveTransform() ) {
4805 $text = $this->pstPass2( $text, $user );
4807 $text = $this->mStripState
->unstripBoth( $text );
4809 $this->setUser( null ); #Reset
4815 * Pre-save transform helper function
4817 * @param string $text
4822 private function pstPass2( $text, $user ) {
4825 # Note: This is the timestamp saved as hardcoded wikitext to
4826 # the database, we use $wgContLang here in order to give
4827 # everyone the same signature and use the default one rather
4828 # than the one selected in each user's preferences.
4829 # (see also bug 12815)
4830 $ts = $this->mOptions
->getTimestamp();
4831 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4832 $ts = $timestamp->format( 'YmdHis' );
4833 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4835 # Allow translation of timezones through wiki. format() can return
4836 # whatever crap the system uses, localised or not, so we cannot
4837 # ship premade translations.
4838 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4839 $msg = wfMessage( $key )->inContentLanguage();
4840 if ( $msg->exists() ) {
4841 $tzMsg = $msg->text();
4844 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4846 # Variable replacement
4847 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4848 $text = $this->replaceVariables( $text );
4850 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4851 # which may corrupt this parser instance via its wfMessage()->text() call-
4854 $sigText = $this->getUserSig( $user );
4855 $text = strtr( $text, array(
4857 '~~~~' => "$sigText $d",
4861 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4862 $tc = '[' . Title
::legalChars() . ']';
4863 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4865 // [[ns:page (context)|]]
4866 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4867 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4868 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4869 // [[ns:page (context), context|]] (using either single or double-width comma)
4870 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4871 // [[|page]] (reverse pipe trick: add context from page title)
4872 $p2 = "/\[\[\\|($tc+)]]/";
4874 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4875 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4876 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4877 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4879 $t = $this->mTitle
->getText();
4881 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4882 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4883 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4884 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4886 # if there's no context, don't bother duplicating the title
4887 $text = preg_replace( $p2, '[[\\1]]', $text );
4890 # Trim trailing whitespace
4891 $text = rtrim( $text );
4897 * Fetch the user's signature text, if any, and normalize to
4898 * validated, ready-to-insert wikitext.
4899 * If you have pre-fetched the nickname or the fancySig option, you can
4900 * specify them here to save a database query.
4901 * Do not reuse this parser instance after calling getUserSig(),
4902 * as it may have changed if it's the $wgParser.
4905 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4906 * @param bool|null $fancySig whether the nicknname is the complete signature
4907 * or null to use default value
4910 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4911 global $wgMaxSigChars;
4913 $username = $user->getName();
4915 # If not given, retrieve from the user object.
4916 if ( $nickname === false ) {
4917 $nickname = $user->getOption( 'nickname' );
4920 if ( is_null( $fancySig ) ) {
4921 $fancySig = $user->getBoolOption( 'fancysig' );
4924 $nickname = $nickname == null ?
$username : $nickname;
4926 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4927 $nickname = $username;
4928 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4929 } elseif ( $fancySig !== false ) {
4930 # Sig. might contain markup; validate this
4931 if ( $this->validateSig( $nickname ) !== false ) {
4932 # Validated; clean up (if needed) and return it
4933 return $this->cleanSig( $nickname, true );
4935 # Failed to validate; fall back to the default
4936 $nickname = $username;
4937 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4941 # Make sure nickname doesnt get a sig in a sig
4942 $nickname = self
::cleanSigInSig( $nickname );
4944 # If we're still here, make it a link to the user page
4945 $userText = wfEscapeWikiText( $username );
4946 $nickText = wfEscapeWikiText( $nickname );
4947 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4949 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4950 ->title( $this->getTitle() )->text();
4954 * Check that the user's signature contains no bad XML
4956 * @param string $text
4957 * @return string|bool An expanded string, or false if invalid.
4959 public function validateSig( $text ) {
4960 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4964 * Clean up signature text
4966 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4967 * 2) Substitute all transclusions
4969 * @param string $text
4970 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4971 * @return string Signature text
4973 public function cleanSig( $text, $parsing = false ) {
4976 $magicScopeVariable = $this->lock();
4977 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4980 # Option to disable this feature
4981 if ( !$this->mOptions
->getCleanSignatures() ) {
4985 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4986 # => Move this logic to braceSubstitution()
4987 $substWord = MagicWord
::get( 'subst' );
4988 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4989 $substText = '{{' . $substWord->getSynonym( 0 );
4991 $text = preg_replace( $substRegex, $substText, $text );
4992 $text = self
::cleanSigInSig( $text );
4993 $dom = $this->preprocessToDom( $text );
4994 $frame = $this->getPreprocessor()->newFrame();
4995 $text = $frame->expand( $dom );
4998 $text = $this->mStripState
->unstripBoth( $text );
5005 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5007 * @param string $text
5008 * @return string Signature text with /~{3,5}/ removed
5010 public static function cleanSigInSig( $text ) {
5011 $text = preg_replace( '/~{3,5}/', '', $text );
5016 * Set up some variables which are usually set up in parse()
5017 * so that an external function can call some class members with confidence
5019 * @param Title|null $title
5020 * @param ParserOptions $options
5021 * @param int $outputType
5022 * @param bool $clearState
5024 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5025 $outputType, $clearState = true
5027 $this->startParse( $title, $options, $outputType, $clearState );
5031 * @param Title|null $title
5032 * @param ParserOptions $options
5033 * @param int $outputType
5034 * @param bool $clearState
5036 private function startParse( Title
$title = null, ParserOptions
$options,
5037 $outputType, $clearState = true
5039 $this->setTitle( $title );
5040 $this->mOptions
= $options;
5041 $this->setOutputType( $outputType );
5042 if ( $clearState ) {
5043 $this->clearState();
5048 * Wrapper for preprocess()
5050 * @param string $text The text to preprocess
5051 * @param ParserOptions $options Options
5052 * @param Title|null $title Title object or null to use $wgTitle
5055 public function transformMsg( $text, $options, $title = null ) {
5056 static $executing = false;
5058 # Guard against infinite recursion
5064 wfProfileIn( __METHOD__
);
5070 $text = $this->preprocess( $text, $title, $options );
5073 wfProfileOut( __METHOD__
);
5078 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5079 * The callback should have the following form:
5080 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5082 * Transform and return $text. Use $parser for any required context, e.g. use
5083 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5085 * Hooks may return extended information by returning an array, of which the
5086 * first numbered element (index 0) must be the return string, and all other
5087 * entries are extracted into local variables within an internal function
5088 * in the Parser class.
5090 * This interface (introduced r61913) appears to be undocumented, but
5091 * 'markerName' is used by some core tag hooks to override which strip
5092 * array their results are placed in. **Use great caution if attempting
5093 * this interface, as it is not documented and injudicious use could smash
5094 * private variables.**
5096 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5097 * @param callable $callback The callback function (and object) to use for the tag
5098 * @throws MWException
5099 * @return callable|null The old value of the mTagHooks array associated with the hook
5101 public function setHook( $tag, $callback ) {
5102 $tag = strtolower( $tag );
5103 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5104 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5106 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5107 $this->mTagHooks
[$tag] = $callback;
5108 if ( !in_array( $tag, $this->mStripList
) ) {
5109 $this->mStripList
[] = $tag;
5116 * As setHook(), but letting the contents be parsed.
5118 * Transparent tag hooks are like regular XML-style tag hooks, except they
5119 * operate late in the transformation sequence, on HTML instead of wikitext.
5121 * This is probably obsoleted by things dealing with parser frames?
5122 * The only extension currently using it is geoserver.
5125 * @todo better document or deprecate this
5127 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5128 * @param callable $callback The callback function (and object) to use for the tag
5129 * @throws MWException
5130 * @return callable|null The old value of the mTagHooks array associated with the hook
5132 public function setTransparentTagHook( $tag, $callback ) {
5133 $tag = strtolower( $tag );
5134 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5135 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5137 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5138 $this->mTransparentTagHooks
[$tag] = $callback;
5144 * Remove all tag hooks
5146 public function clearTagHooks() {
5147 $this->mTagHooks
= array();
5148 $this->mFunctionTagHooks
= array();
5149 $this->mStripList
= $this->mDefaultStripList
;
5153 * Create a function, e.g. {{sum:1|2|3}}
5154 * The callback function should have the form:
5155 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5157 * Or with SFH_OBJECT_ARGS:
5158 * function myParserFunction( $parser, $frame, $args ) { ... }
5160 * The callback may either return the text result of the function, or an array with the text
5161 * in element 0, and a number of flags in the other elements. The names of the flags are
5162 * specified in the keys. Valid flags are:
5163 * found The text returned is valid, stop processing the template. This
5165 * nowiki Wiki markup in the return value should be escaped
5166 * isHTML The returned text is HTML, armour it against wikitext transformation
5168 * @param string $id The magic word ID
5169 * @param callable $callback The callback function (and object) to use
5170 * @param int $flags A combination of the following flags:
5171 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5173 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5174 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5175 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5176 * the arguments, and to control the way they are expanded.
5178 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5179 * arguments, for instance:
5180 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5182 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5183 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5184 * working if/when this is changed.
5186 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5189 * Please read the documentation in includes/parser/Preprocessor.php for more information
5190 * about the methods available in PPFrame and PPNode.
5192 * @throws MWException
5193 * @return string|callable The old callback function for this name, if any
5195 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5198 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5199 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5201 # Add to function cache
5202 $mw = MagicWord
::get( $id );
5204 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5207 $synonyms = $mw->getSynonyms();
5208 $sensitive = intval( $mw->isCaseSensitive() );
5210 foreach ( $synonyms as $syn ) {
5212 if ( !$sensitive ) {
5213 $syn = $wgContLang->lc( $syn );
5216 if ( !( $flags & SFH_NO_HASH
) ) {
5219 # Remove trailing colon
5220 if ( substr( $syn, -1, 1 ) === ':' ) {
5221 $syn = substr( $syn, 0, -1 );
5223 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5229 * Get all registered function hook identifiers
5233 public function getFunctionHooks() {
5234 return array_keys( $this->mFunctionHooks
);
5238 * Create a tag function, e.g. "<test>some stuff</test>".
5239 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5240 * Unlike parser functions, their content is not preprocessed.
5241 * @param string $tag
5242 * @param callable $callback
5244 * @throws MWException
5247 public function setFunctionTagHook( $tag, $callback, $flags ) {
5248 $tag = strtolower( $tag );
5249 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5250 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5252 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5253 $this->mFunctionTagHooks
[$tag] : null;
5254 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5256 if ( !in_array( $tag, $this->mStripList
) ) {
5257 $this->mStripList
[] = $tag;
5264 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5265 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5266 * Placeholders created in Skin::makeLinkObj()
5268 * @param string $text
5269 * @param int $options
5271 * @return array Array of link CSS classes, indexed by PDBK.
5273 public function replaceLinkHolders( &$text, $options = 0 ) {
5274 return $this->mLinkHolders
->replace( $text );
5278 * Replace "<!--LINK-->" link placeholders with plain text of links
5279 * (not HTML-formatted).
5281 * @param string $text
5284 public function replaceLinkHoldersText( $text ) {
5285 return $this->mLinkHolders
->replaceText( $text );
5289 * Renders an image gallery from a text with one line per image.
5290 * text labels may be given by using |-style alternative text. E.g.
5291 * Image:one.jpg|The number "1"
5292 * Image:tree.jpg|A tree
5293 * given as text will return the HTML of a gallery with two images,
5294 * labeled 'The number "1"' and
5297 * @param string $text
5298 * @param array $params
5299 * @return string HTML
5301 public function renderImageGallery( $text, $params ) {
5302 wfProfileIn( __METHOD__
);
5305 if ( isset( $params['mode'] ) ) {
5306 $mode = $params['mode'];
5310 $ig = ImageGalleryBase
::factory( $mode );
5311 } catch ( MWException
$e ) {
5312 // If invalid type set, fallback to default.
5313 $ig = ImageGalleryBase
::factory( false );
5316 $ig->setContextTitle( $this->mTitle
);
5317 $ig->setShowBytes( false );
5318 $ig->setShowFilename( false );
5319 $ig->setParser( $this );
5320 $ig->setHideBadImages();
5321 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5323 if ( isset( $params['showfilename'] ) ) {
5324 $ig->setShowFilename( true );
5326 $ig->setShowFilename( false );
5328 if ( isset( $params['caption'] ) ) {
5329 $caption = $params['caption'];
5330 $caption = htmlspecialchars( $caption );
5331 $caption = $this->replaceInternalLinks( $caption );
5332 $ig->setCaptionHtml( $caption );
5334 if ( isset( $params['perrow'] ) ) {
5335 $ig->setPerRow( $params['perrow'] );
5337 if ( isset( $params['widths'] ) ) {
5338 $ig->setWidths( $params['widths'] );
5340 if ( isset( $params['heights'] ) ) {
5341 $ig->setHeights( $params['heights'] );
5343 $ig->setAdditionalOptions( $params );
5345 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5347 $lines = StringUtils
::explode( "\n", $text );
5348 foreach ( $lines as $line ) {
5349 # match lines like these:
5350 # Image:someimage.jpg|This is some image
5352 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5354 if ( count( $matches ) == 0 ) {
5358 if ( strpos( $matches[0], '%' ) !== false ) {
5359 $matches[1] = rawurldecode( $matches[1] );
5361 $title = Title
::newFromText( $matches[1], NS_FILE
);
5362 if ( is_null( $title ) ) {
5363 # Bogus title. Ignore these so we don't bomb out later.
5367 # We need to get what handler the file uses, to figure out parameters.
5368 # Note, a hook can overide the file name, and chose an entirely different
5369 # file (which potentially could be of a different type and have different handler).
5372 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5373 array( $this, $title, &$options, &$descQuery ) );
5374 # Don't register it now, as ImageGallery does that later.
5375 $file = $this->fetchFileNoRegister( $title, $options );
5376 $handler = $file ?
$file->getHandler() : false;
5378 wfProfileIn( __METHOD__
. '-getMagicWord' );
5380 'img_alt' => 'gallery-internal-alt',
5381 'img_link' => 'gallery-internal-link',
5384 $paramMap = $paramMap +
$handler->getParamMap();
5385 // We don't want people to specify per-image widths.
5386 // Additionally the width parameter would need special casing anyhow.
5387 unset( $paramMap['img_width'] );
5390 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5391 wfProfileOut( __METHOD__
. '-getMagicWord' );
5396 $handlerOptions = array();
5397 if ( isset( $matches[3] ) ) {
5398 // look for an |alt= definition while trying not to break existing
5399 // captions with multiple pipes (|) in it, until a more sensible grammar
5400 // is defined for images in galleries
5402 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5403 // splitting on '|' is a bit odd, and different from makeImage.
5404 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5405 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5407 foreach ( $parameterMatches as $parameterMatch ) {
5408 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5410 $paramName = $paramMap[$magicName];
5412 switch ( $paramName ) {
5413 case 'gallery-internal-alt':
5414 $alt = $this->stripAltText( $match, false );
5416 case 'gallery-internal-link':
5417 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5418 $chars = self
::EXT_LINK_URL_CLASS
;
5419 $prots = $this->mUrlProtocols
;
5420 //check to see if link matches an absolute url, if not then it must be a wiki link.
5421 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5424 $localLinkTitle = Title
::newFromText( $linkValue );
5425 if ( $localLinkTitle !== null ) {
5426 $link = $localLinkTitle->getLinkURL();
5431 // Must be a handler specific parameter.
5432 if ( $handler->validateParam( $paramName, $match ) ) {
5433 $handlerOptions[$paramName] = $match;
5435 // Guess not. Append it to the caption.
5436 wfDebug( "$parameterMatch failed parameter validation\n" );
5437 $label .= '|' . $parameterMatch;
5442 // concatenate all other pipes
5443 $label .= '|' . $parameterMatch;
5446 // remove the first pipe
5447 $label = substr( $label, 1 );
5450 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5452 $html = $ig->toHTML();
5453 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5454 wfProfileOut( __METHOD__
);
5459 * @param string $handler
5462 public function getImageParams( $handler ) {
5464 $handlerClass = get_class( $handler );
5468 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5469 # Initialise static lists
5470 static $internalParamNames = array(
5471 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5472 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5473 'bottom', 'text-bottom' ),
5474 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5475 'upright', 'border', 'link', 'alt', 'class' ),
5477 static $internalParamMap;
5478 if ( !$internalParamMap ) {
5479 $internalParamMap = array();
5480 foreach ( $internalParamNames as $type => $names ) {
5481 foreach ( $names as $name ) {
5482 $magicName = str_replace( '-', '_', "img_$name" );
5483 $internalParamMap[$magicName] = array( $type, $name );
5488 # Add handler params
5489 $paramMap = $internalParamMap;
5491 $handlerParamMap = $handler->getParamMap();
5492 foreach ( $handlerParamMap as $magic => $paramName ) {
5493 $paramMap[$magic] = array( 'handler', $paramName );
5496 $this->mImageParams
[$handlerClass] = $paramMap;
5497 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5499 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5503 * Parse image options text and use it to make an image
5505 * @param Title $title
5506 * @param string $options
5507 * @param LinkHolderArray|bool $holders
5508 * @return string HTML
5510 public function makeImage( $title, $options, $holders = false ) {
5511 # Check if the options text is of the form "options|alt text"
5513 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5514 # * left no resizing, just left align. label is used for alt= only
5515 # * right same, but right aligned
5516 # * none same, but not aligned
5517 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5518 # * center center the image
5519 # * frame Keep original image size, no magnify-button.
5520 # * framed Same as "frame"
5521 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5522 # * upright reduce width for upright images, rounded to full __0 px
5523 # * border draw a 1px border around the image
5524 # * alt Text for HTML alt attribute (defaults to empty)
5525 # * class Set a class for img node
5526 # * link Set the target of the image link. Can be external, interwiki, or local
5527 # vertical-align values (no % or length right now):
5537 $parts = StringUtils
::explode( "|", $options );
5539 # Give extensions a chance to select the file revision for us
5542 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5543 array( $this, $title, &$options, &$descQuery ) );
5544 # Fetch and register the file (file title may be different via hooks)
5545 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5548 $handler = $file ?
$file->getHandler() : false;
5550 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5553 $this->addTrackingCategory( 'broken-file-category' );
5556 # Process the input parameters
5558 $params = array( 'frame' => array(), 'handler' => array(),
5559 'horizAlign' => array(), 'vertAlign' => array() );
5560 $seenformat = false;
5561 foreach ( $parts as $part ) {
5562 $part = trim( $part );
5563 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5565 if ( isset( $paramMap[$magicName] ) ) {
5566 list( $type, $paramName ) = $paramMap[$magicName];
5568 # Special case; width and height come in one variable together
5569 if ( $type === 'handler' && $paramName === 'width' ) {
5570 $parsedWidthParam = $this->parseWidthParam( $value );
5571 if ( isset( $parsedWidthParam['width'] ) ) {
5572 $width = $parsedWidthParam['width'];
5573 if ( $handler->validateParam( 'width', $width ) ) {
5574 $params[$type]['width'] = $width;
5578 if ( isset( $parsedWidthParam['height'] ) ) {
5579 $height = $parsedWidthParam['height'];
5580 if ( $handler->validateParam( 'height', $height ) ) {
5581 $params[$type]['height'] = $height;
5585 # else no validation -- bug 13436
5587 if ( $type === 'handler' ) {
5588 # Validate handler parameter
5589 $validated = $handler->validateParam( $paramName, $value );
5591 # Validate internal parameters
5592 switch ( $paramName ) {
5596 # @todo FIXME: Possibly check validity here for
5597 # manualthumb? downstream behavior seems odd with
5598 # missing manual thumbs.
5600 $value = $this->stripAltText( $value, $holders );
5603 $chars = self
::EXT_LINK_URL_CLASS
;
5604 $prots = $this->mUrlProtocols
;
5605 if ( $value === '' ) {
5606 $paramName = 'no-link';
5609 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5610 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5611 $paramName = 'link-url';
5612 $this->mOutput
->addExternalLink( $value );
5613 if ( $this->mOptions
->getExternalLinkTarget() ) {
5614 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5619 $linkTitle = Title
::newFromText( $value );
5621 $paramName = 'link-title';
5622 $value = $linkTitle;
5623 $this->mOutput
->addLink( $linkTitle );
5631 // use first appearing option, discard others.
5632 $validated = ! $seenformat;
5636 # Most other things appear to be empty or numeric...
5637 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5642 $params[$type][$paramName] = $value;
5646 if ( !$validated ) {
5651 # Process alignment parameters
5652 if ( $params['horizAlign'] ) {
5653 $params['frame']['align'] = key( $params['horizAlign'] );
5655 if ( $params['vertAlign'] ) {
5656 $params['frame']['valign'] = key( $params['vertAlign'] );
5659 $params['frame']['caption'] = $caption;
5661 # Will the image be presented in a frame, with the caption below?
5662 $imageIsFramed = isset( $params['frame']['frame'] )
5663 ||
isset( $params['frame']['framed'] )
5664 ||
isset( $params['frame']['thumbnail'] )
5665 ||
isset( $params['frame']['manualthumb'] );
5667 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5668 # came to also set the caption, ordinary text after the image -- which
5669 # makes no sense, because that just repeats the text multiple times in
5670 # screen readers. It *also* came to set the title attribute.
5672 # Now that we have an alt attribute, we should not set the alt text to
5673 # equal the caption: that's worse than useless, it just repeats the
5674 # text. This is the framed/thumbnail case. If there's no caption, we
5675 # use the unnamed parameter for alt text as well, just for the time be-
5676 # ing, if the unnamed param is set and the alt param is not.
5678 # For the future, we need to figure out if we want to tweak this more,
5679 # e.g., introducing a title= parameter for the title; ignoring the un-
5680 # named parameter entirely for images without a caption; adding an ex-
5681 # plicit caption= parameter and preserving the old magic unnamed para-
5683 if ( $imageIsFramed ) { # Framed image
5684 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5685 # No caption or alt text, add the filename as the alt text so
5686 # that screen readers at least get some description of the image
5687 $params['frame']['alt'] = $title->getText();
5689 # Do not set $params['frame']['title'] because tooltips don't make sense
5691 } else { # Inline image
5692 if ( !isset( $params['frame']['alt'] ) ) {
5693 # No alt text, use the "caption" for the alt text
5694 if ( $caption !== '' ) {
5695 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5697 # No caption, fall back to using the filename for the
5699 $params['frame']['alt'] = $title->getText();
5702 # Use the "caption" for the tooltip text
5703 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5706 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5708 # Linker does the rest
5709 $time = isset( $options['time'] ) ?
$options['time'] : false;
5710 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5711 $time, $descQuery, $this->mOptions
->getThumbSize() );
5713 # Give the handler a chance to modify the parser object
5715 $handler->parserTransformHook( $this, $file );
5722 * @param string $caption
5723 * @param LinkHolderArray|bool $holders
5724 * @return mixed|string
5726 protected function stripAltText( $caption, $holders ) {
5727 # Strip bad stuff out of the title (tooltip). We can't just use
5728 # replaceLinkHoldersText() here, because if this function is called
5729 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5731 $tooltip = $holders->replaceText( $caption );
5733 $tooltip = $this->replaceLinkHoldersText( $caption );
5736 # make sure there are no placeholders in thumbnail attributes
5737 # that are later expanded to html- so expand them now and
5739 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5740 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5746 * Set a flag in the output object indicating that the content is dynamic and
5747 * shouldn't be cached.
5749 public function disableCache() {
5750 wfDebug( "Parser output marked as uncacheable.\n" );
5751 if ( !$this->mOutput
) {
5752 throw new MWException( __METHOD__
.
5753 " can only be called when actually parsing something" );
5755 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5756 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5760 * Callback from the Sanitizer for expanding items found in HTML attribute
5761 * values, so they can be safely tested and escaped.
5763 * @param string $text
5764 * @param bool|PPFrame $frame
5767 public function attributeStripCallback( &$text, $frame = false ) {
5768 $text = $this->replaceVariables( $text, $frame );
5769 $text = $this->mStripState
->unstripBoth( $text );
5778 public function getTags() {
5780 array_keys( $this->mTransparentTagHooks
),
5781 array_keys( $this->mTagHooks
),
5782 array_keys( $this->mFunctionTagHooks
)
5787 * Replace transparent tags in $text with the values given by the callbacks.
5789 * Transparent tag hooks are like regular XML-style tag hooks, except they
5790 * operate late in the transformation sequence, on HTML instead of wikitext.
5792 * @param string $text
5796 public function replaceTransparentTags( $text ) {
5798 $elements = array_keys( $this->mTransparentTagHooks
);
5799 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5800 $replacements = array();
5802 foreach ( $matches as $marker => $data ) {
5803 list( $element, $content, $params, $tag ) = $data;
5804 $tagName = strtolower( $element );
5805 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5806 $output = call_user_func_array(
5807 $this->mTransparentTagHooks
[$tagName],
5808 array( $content, $params, $this )
5813 $replacements[$marker] = $output;
5815 return strtr( $text, $replacements );
5819 * Break wikitext input into sections, and either pull or replace
5820 * some particular section's text.
5822 * External callers should use the getSection and replaceSection methods.
5824 * @param string $text Page wikitext
5825 * @param string|number $sectionId A section identifier string of the form:
5826 * "<flag1> - <flag2> - ... - <section number>"
5828 * Currently the only recognised flag is "T", which means the target section number
5829 * was derived during a template inclusion parse, in other words this is a template
5830 * section edit link. If no flags are given, it was an ordinary section edit link.
5831 * This flag is required to avoid a section numbering mismatch when a section is
5832 * enclosed by "<includeonly>" (bug 6563).
5834 * The section number 0 pulls the text before the first heading; other numbers will
5835 * pull the given section along with its lower-level subsections. If the section is
5836 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5838 * Section 0 is always considered to exist, even if it only contains the empty
5839 * string. If $text is the empty string and section 0 is replaced, $newText is
5842 * @param string $mode One of "get" or "replace"
5843 * @param string $newText Replacement text for section data.
5844 * @return string For "get", the extracted section text.
5845 * for "replace", the whole page with the section replaced.
5847 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5848 global $wgTitle; # not generally used but removes an ugly failure mode
5850 $magicScopeVariable = $this->lock();
5851 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5853 $frame = $this->getPreprocessor()->newFrame();
5855 # Process section extraction flags
5857 $sectionParts = explode( '-', $sectionId );
5858 $sectionIndex = array_pop( $sectionParts );
5859 foreach ( $sectionParts as $part ) {
5860 if ( $part === 'T' ) {
5861 $flags |
= self
::PTD_FOR_INCLUSION
;
5865 # Check for empty input
5866 if ( strval( $text ) === '' ) {
5867 # Only sections 0 and T-0 exist in an empty document
5868 if ( $sectionIndex == 0 ) {
5869 if ( $mode === 'get' ) {
5875 if ( $mode === 'get' ) {
5883 # Preprocess the text
5884 $root = $this->preprocessToDom( $text, $flags );
5886 # <h> nodes indicate section breaks
5887 # They can only occur at the top level, so we can find them by iterating the root's children
5888 $node = $root->getFirstChild();
5890 # Find the target section
5891 if ( $sectionIndex == 0 ) {
5892 # Section zero doesn't nest, level=big
5893 $targetLevel = 1000;
5896 if ( $node->getName() === 'h' ) {
5897 $bits = $node->splitHeading();
5898 if ( $bits['i'] == $sectionIndex ) {
5899 $targetLevel = $bits['level'];
5903 if ( $mode === 'replace' ) {
5904 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5906 $node = $node->getNextSibling();
5912 if ( $mode === 'get' ) {
5919 # Find the end of the section, including nested sections
5921 if ( $node->getName() === 'h' ) {
5922 $bits = $node->splitHeading();
5923 $curLevel = $bits['level'];
5924 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5928 if ( $mode === 'get' ) {
5929 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5931 $node = $node->getNextSibling();
5934 # Write out the remainder (in replace mode only)
5935 if ( $mode === 'replace' ) {
5936 # Output the replacement text
5937 # Add two newlines on -- trailing whitespace in $newText is conventionally
5938 # stripped by the editor, so we need both newlines to restore the paragraph gap
5939 # Only add trailing whitespace if there is newText
5940 if ( $newText != "" ) {
5941 $outText .= $newText . "\n\n";
5945 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5946 $node = $node->getNextSibling();
5950 if ( is_string( $outText ) ) {
5951 # Re-insert stripped tags
5952 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5959 * This function returns the text of a section, specified by a number ($section).
5960 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5961 * the first section before any such heading (section 0).
5963 * If a section contains subsections, these are also returned.
5965 * @param string $text Text to look in
5966 * @param string|number $sectionId Section identifier as a number or string
5967 * (e.g. 0, 1 or 'T-1').
5968 * @param string $defaultText Default to return if section is not found
5970 * @return string Text of the requested section
5972 public function getSection( $text, $sectionId, $defaultText = '' ) {
5973 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5977 * This function returns $oldtext after the content of the section
5978 * specified by $section has been replaced with $text. If the target
5979 * section does not exist, $oldtext is returned unchanged.
5981 * @param string $oldText Former text of the article
5982 * @param string|number $sectionId Section identifier as a number or string
5983 * (e.g. 0, 1 or 'T-1').
5984 * @param string $newText Replacing text
5986 * @return string Modified text
5988 public function replaceSection( $oldText, $sectionId, $newText ) {
5989 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5993 * Get the ID of the revision we are parsing
5997 public function getRevisionId() {
5998 return $this->mRevisionId
;
6002 * Get the revision object for $this->mRevisionId
6004 * @return Revision|null Either a Revision object or null
6005 * @since 1.23 (public since 1.23)
6007 public function getRevisionObject() {
6008 if ( !is_null( $this->mRevisionObject
) ) {
6009 return $this->mRevisionObject
;
6011 if ( is_null( $this->mRevisionId
) ) {
6015 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6016 return $this->mRevisionObject
;
6020 * Get the timestamp associated with the current revision, adjusted for
6021 * the default server-local timestamp
6024 public function getRevisionTimestamp() {
6025 if ( is_null( $this->mRevisionTimestamp
) ) {
6026 wfProfileIn( __METHOD__
);
6030 $revObject = $this->getRevisionObject();
6031 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6033 # The cryptic '' timezone parameter tells to use the site-default
6034 # timezone offset instead of the user settings.
6036 # Since this value will be saved into the parser cache, served
6037 # to other users, and potentially even used inside links and such,
6038 # it needs to be consistent for all visitors.
6039 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6041 wfProfileOut( __METHOD__
);
6043 return $this->mRevisionTimestamp
;
6047 * Get the name of the user that edited the last revision
6049 * @return string User name
6051 public function getRevisionUser() {
6052 if ( is_null( $this->mRevisionUser
) ) {
6053 $revObject = $this->getRevisionObject();
6055 # if this template is subst: the revision id will be blank,
6056 # so just use the current user's name
6058 $this->mRevisionUser
= $revObject->getUserText();
6059 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6060 $this->mRevisionUser
= $this->getUser()->getName();
6063 return $this->mRevisionUser
;
6067 * Get the size of the revision
6069 * @return int|null Revision size
6071 public function getRevisionSize() {
6072 if ( is_null( $this->mRevisionSize
) ) {
6073 $revObject = $this->getRevisionObject();
6075 # if this variable is subst: the revision id will be blank,
6076 # so just use the parser input size, because the own substituation
6077 # will change the size.
6079 $this->mRevisionSize
= $revObject->getSize();
6080 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6081 $this->mRevisionSize
= $this->mInputSize
;
6084 return $this->mRevisionSize
;
6088 * Mutator for $mDefaultSort
6090 * @param string $sort New value
6092 public function setDefaultSort( $sort ) {
6093 $this->mDefaultSort
= $sort;
6094 $this->mOutput
->setProperty( 'defaultsort', $sort );
6098 * Accessor for $mDefaultSort
6099 * Will use the empty string if none is set.
6101 * This value is treated as a prefix, so the
6102 * empty string is equivalent to sorting by
6107 public function getDefaultSort() {
6108 if ( $this->mDefaultSort
!== false ) {
6109 return $this->mDefaultSort
;
6116 * Accessor for $mDefaultSort
6117 * Unlike getDefaultSort(), will return false if none is set
6119 * @return string|bool
6121 public function getCustomDefaultSort() {
6122 return $this->mDefaultSort
;
6126 * Try to guess the section anchor name based on a wikitext fragment
6127 * presumably extracted from a heading, for example "Header" from
6130 * @param string $text
6134 public function guessSectionNameFromWikiText( $text ) {
6135 # Strip out wikitext links(they break the anchor)
6136 $text = $this->stripSectionName( $text );
6137 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6138 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6142 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6143 * instead. For use in redirects, since IE6 interprets Redirect: headers
6144 * as something other than UTF-8 (apparently?), resulting in breakage.
6146 * @param string $text The section name
6147 * @return string An anchor
6149 public function guessLegacySectionNameFromWikiText( $text ) {
6150 # Strip out wikitext links(they break the anchor)
6151 $text = $this->stripSectionName( $text );
6152 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6153 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6157 * Strips a text string of wikitext for use in a section anchor
6159 * Accepts a text string and then removes all wikitext from the
6160 * string and leaves only the resultant text (i.e. the result of
6161 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6162 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6163 * to create valid section anchors by mimicing the output of the
6164 * parser when headings are parsed.
6166 * @param string $text Text string to be stripped of wikitext
6167 * for use in a Section anchor
6168 * @return string Filtered text string
6170 public function stripSectionName( $text ) {
6171 # Strip internal link markup
6172 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6173 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6175 # Strip external link markup
6176 # @todo FIXME: Not tolerant to blank link text
6177 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6178 # on how many empty links there are on the page - need to figure that out.
6179 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6181 # Parse wikitext quotes (italics & bold)
6182 $text = $this->doQuotes( $text );
6185 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6190 * strip/replaceVariables/unstrip for preprocessor regression testing
6192 * @param string $text
6193 * @param Title $title
6194 * @param ParserOptions $options
6195 * @param int $outputType
6199 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6200 $magicScopeVariable = $this->lock();
6201 $this->startParse( $title, $options, $outputType, true );
6203 $text = $this->replaceVariables( $text );
6204 $text = $this->mStripState
->unstripBoth( $text );
6205 $text = Sanitizer
::removeHTMLtags( $text );
6210 * @param string $text
6211 * @param Title $title
6212 * @param ParserOptions $options
6215 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6216 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6220 * @param string $text
6221 * @param Title $title
6222 * @param ParserOptions $options
6225 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6226 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6230 * Call a callback function on all regions of the given text that are not
6231 * inside strip markers, and replace those regions with the return value
6232 * of the callback. For example, with input:
6236 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6237 * two strings will be replaced with the value returned by the callback in
6241 * @param callable $callback
6245 public function markerSkipCallback( $s, $callback ) {
6248 while ( $i < strlen( $s ) ) {
6249 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6250 if ( $markerStart === false ) {
6251 $out .= call_user_func( $callback, substr( $s, $i ) );
6254 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6255 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6256 if ( $markerEnd === false ) {
6257 $out .= substr( $s, $markerStart );
6260 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6261 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6270 * Remove any strip markers found in the given text.
6272 * @param string $text Input string
6275 public function killMarkers( $text ) {
6276 return $this->mStripState
->killMarkers( $text );
6280 * Save the parser state required to convert the given half-parsed text to
6281 * HTML. "Half-parsed" in this context means the output of
6282 * recursiveTagParse() or internalParse(). This output has strip markers
6283 * from replaceVariables (extensionSubstitution() etc.), and link
6284 * placeholders from replaceLinkHolders().
6286 * Returns an array which can be serialized and stored persistently. This
6287 * array can later be loaded into another parser instance with
6288 * unserializeHalfParsedText(). The text can then be safely incorporated into
6289 * the return value of a parser hook.
6291 * @param string $text
6295 public function serializeHalfParsedText( $text ) {
6296 wfProfileIn( __METHOD__
);
6299 'version' => self
::HALF_PARSED_VERSION
,
6300 'stripState' => $this->mStripState
->getSubState( $text ),
6301 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6303 wfProfileOut( __METHOD__
);
6308 * Load the parser state given in the $data array, which is assumed to
6309 * have been generated by serializeHalfParsedText(). The text contents is
6310 * extracted from the array, and its markers are transformed into markers
6311 * appropriate for the current Parser instance. This transformed text is
6312 * returned, and can be safely included in the return value of a parser
6315 * If the $data array has been stored persistently, the caller should first
6316 * check whether it is still valid, by calling isValidHalfParsedText().
6318 * @param array $data Serialized data
6319 * @throws MWException
6322 public function unserializeHalfParsedText( $data ) {
6323 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6324 throw new MWException( __METHOD__
. ': invalid version' );
6327 # First, extract the strip state.
6328 $texts = array( $data['text'] );
6329 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6331 # Now renumber links
6332 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6334 # Should be good to go.
6339 * Returns true if the given array, presumed to be generated by
6340 * serializeHalfParsedText(), is compatible with the current version of the
6343 * @param array $data
6347 public function isValidHalfParsedText( $data ) {
6348 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6352 * Parsed a width param of imagelink like 300px or 200x300px
6354 * @param string $value
6359 public function parseWidthParam( $value ) {
6360 $parsedWidthParam = array();
6361 if ( $value === '' ) {
6362 return $parsedWidthParam;
6365 # (bug 13500) In both cases (width/height and width only),
6366 # permit trailing "px" for backward compatibility.
6367 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6368 $width = intval( $m[1] );
6369 $height = intval( $m[2] );
6370 $parsedWidthParam['width'] = $width;
6371 $parsedWidthParam['height'] = $height;
6372 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6373 $width = intval( $value );
6374 $parsedWidthParam['width'] = $width;
6376 return $parsedWidthParam;
6380 * Lock the current instance of the parser.
6382 * This is meant to stop someone from calling the parser
6383 * recursively and messing up all the strip state.
6385 * @throws MWException If parser is in a parse
6386 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6388 protected function lock() {
6389 if ( $this->mInParse
) {
6390 throw new MWException( "Parser state cleared while parsing. "
6391 . "Did you call Parser::parse recursively?" );
6393 $this->mInParse
= true;
6396 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6397 $that->mInParse
= false;
6400 return $recursiveCheck;
6404 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6406 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6407 * or if there is more than one <p/> tag in the input HTML.
6409 * @param string $html
6413 public static function stripOuterParagraph( $html ) {
6415 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6416 if ( strpos( $m[1], '</p>' ) === false ) {
6425 * Return this parser if it is not doing anything, otherwise
6426 * get a fresh parser. You can use this method by doing
6427 * $myParser = $wgParser->getFreshParser(), or more simply
6428 * $wgParser->getFreshParser()->parse( ... );
6429 * if you're unsure if $wgParser is safe to use.
6432 * @return Parser A parser object that is not parsing anything
6434 public function getFreshParser() {
6435 global $wgParserConf;
6436 if ( $this->mInParse
) {
6437 return new $wgParserConf['class']( $wgParserConf );