3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
118 # Markers used for wrapping the table of contents
119 const TOC_START
= '<mw:toc>';
120 const TOC_END
= '</mw:toc>';
123 public $mTagHooks = array();
124 public $mTransparentTagHooks = array();
125 public $mFunctionHooks = array();
126 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
127 public $mFunctionTagHooks = array();
128 public $mStripList = array();
129 public $mDefaultStripList = array();
130 public $mVarCache = array();
131 public $mImageParams = array();
132 public $mImageParamsMagicArray = array();
133 public $mMarkerIndex = 0;
134 public $mFirstCall = true;
136 # Initialised by initialiseVariables()
139 * @var MagicWordArray
144 * @var MagicWordArray
147 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
149 # Cleared with clearState():
154 public $mAutonumber, $mDTopen;
161 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
163 * @var LinkHolderArray
165 public $mLinkHolders;
168 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
169 public $mDefaultSort;
170 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
171 public $mExpensiveFunctionCount; # number of expensive parser function calls
172 public $mShowToc, $mForceTocPosition;
177 public $mUser; # User object; only used when doing pre-save transform
180 # These are variables reset at least once per parse regardless of $clearState
190 public $mTitle; # Title context, used for self-link rendering and similar things
191 public $mOutputType; # Output type, one of the OT_xxx constants
192 public $ot; # Shortcut alias, see setOutputType()
193 public $mRevisionObject; # The revision object of the specified revision ID
194 public $mRevisionId; # ID to display in {{REVISIONID}} tags
195 public $mRevisionTimestamp; # The timestamp of the specified revision ID
196 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
197 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
198 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
199 public $mInputSize = false; # For {{PAGESIZE}} on current page.
207 * @var array Array with the language name of each language link (i.e. the
208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
209 * duplicate language links to the ParserOutput.
211 public $mLangLinkLanguages;
214 * @var MapCacheLRU|null
217 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
219 public $currentRevisionCache;
222 * @var bool Recursive call protection.
223 * This variable should be treated as if it were private.
225 public $mInParse = false;
230 public function __construct( $conf = array() ) {
231 $this->mConf
= $conf;
232 $this->mUrlProtocols
= wfUrlProtocols();
233 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
234 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
235 if ( isset( $conf['preprocessorClass'] ) ) {
236 $this->mPreprocessorClass
= $conf['preprocessorClass'];
237 } elseif ( defined( 'HPHP_VERSION' ) ) {
238 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
239 $this->mPreprocessorClass
= 'Preprocessor_Hash';
240 } elseif ( extension_loaded( 'domxml' ) ) {
241 # PECL extension that conflicts with the core DOM extension (bug 13770)
242 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
243 $this->mPreprocessorClass
= 'Preprocessor_Hash';
244 } elseif ( extension_loaded( 'dom' ) ) {
245 $this->mPreprocessorClass
= 'Preprocessor_DOM';
247 $this->mPreprocessorClass
= 'Preprocessor_Hash';
249 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
253 * Reduce memory usage to reduce the impact of circular references
255 public function __destruct() {
256 if ( isset( $this->mLinkHolders
) ) {
257 unset( $this->mLinkHolders
);
259 foreach ( $this as $name => $value ) {
260 unset( $this->$name );
265 * Allow extensions to clean up when the parser is cloned
267 public function __clone() {
268 $this->mInParse
= false;
270 // Bug 56226: When you create a reference "to" an object field, that
271 // makes the object field itself be a reference too (until the other
272 // reference goes out of scope). When cloning, any field that's a
273 // reference is copied as a reference in the new object. Both of these
274 // are defined PHP5 behaviors, as inconvenient as it is for us when old
275 // hooks from PHP4 days are passing fields by reference.
276 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
277 // Make a non-reference copy of the field, then rebind the field to
278 // reference the new copy.
284 wfRunHooks( 'ParserCloned', array( $this ) );
288 * Do various kinds of initialisation on the first call of the parser
290 public function firstCallInit() {
291 if ( !$this->mFirstCall
) {
294 $this->mFirstCall
= false;
296 wfProfileIn( __METHOD__
);
298 CoreParserFunctions
::register( $this );
299 CoreTagHooks
::register( $this );
300 $this->initialiseVariables();
302 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
303 wfProfileOut( __METHOD__
);
311 public function clearState() {
312 wfProfileIn( __METHOD__
);
313 if ( $this->mFirstCall
) {
314 $this->firstCallInit();
316 $this->mOutput
= new ParserOutput
;
317 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
318 $this->mAutonumber
= 0;
319 $this->mLastSection
= '';
320 $this->mDTopen
= false;
321 $this->mIncludeCount
= array();
322 $this->mArgStack
= false;
323 $this->mInPre
= false;
324 $this->mLinkHolders
= new LinkHolderArray( $this );
326 $this->mRevisionObject
= $this->mRevisionTimestamp
=
327 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
328 $this->mVarCache
= array();
330 $this->mLangLinkLanguages
= array();
331 $this->currentRevisionCache
= null;
334 * Prefix for temporary replacement strings for the multipass parser.
335 * \x07 should never appear in input as it's disallowed in XML.
336 * Using it at the front also gives us a little extra robustness
337 * since it shouldn't match when butted up against identifier-like
340 * Must not consist of all title characters, or else it will change
341 * the behavior of <nowiki> in a link.
343 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
344 $this->mStripState
= new StripState( $this->mUniqPrefix
);
346 # Clear these on every parse, bug 4549
347 $this->mTplRedirCache
= $this->mTplDomCache
= array();
349 $this->mShowToc
= true;
350 $this->mForceTocPosition
= false;
351 $this->mIncludeSizes
= array(
355 $this->mPPNodeCount
= 0;
356 $this->mGeneratedPPNodeCount
= 0;
357 $this->mHighestExpansionDepth
= 0;
358 $this->mDefaultSort
= false;
359 $this->mHeadings
= array();
360 $this->mDoubleUnderscores
= array();
361 $this->mExpensiveFunctionCount
= 0;
364 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
365 $this->mPreprocessor
= null;
368 wfRunHooks( 'ParserClearState', array( &$this ) );
369 wfProfileOut( __METHOD__
);
373 * Convert wikitext to HTML
374 * Do not call this function recursively.
376 * @param string $text Text we want to parse
377 * @param Title $title
378 * @param ParserOptions $options
379 * @param bool $linestart
380 * @param bool $clearState
381 * @param int $revid Number to pass in {{REVISIONID}}
382 * @return ParserOutput A ParserOutput
384 public function parse( $text, Title
$title, ParserOptions
$options,
385 $linestart = true, $clearState = true, $revid = null
388 * First pass--just handle <nowiki> sections, pass the rest off
389 * to internalParse() which does all the real work.
392 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
393 $fname = __METHOD__
. '-' . wfGetCaller();
394 wfProfileIn( __METHOD__
);
395 wfProfileIn( $fname );
398 $magicScopeVariable = $this->lock();
401 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
403 $this->currentRevisionCache
= null;
404 $this->mInputSize
= strlen( $text );
405 if ( $this->mOptions
->getEnableLimitReport() ) {
406 $this->mOutput
->resetParseStartTime();
409 # Remove the strip marker tag prefix from the input, if present.
411 $text = str_replace( $this->mUniqPrefix
, '', $text );
414 $oldRevisionId = $this->mRevisionId
;
415 $oldRevisionObject = $this->mRevisionObject
;
416 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
417 $oldRevisionUser = $this->mRevisionUser
;
418 $oldRevisionSize = $this->mRevisionSize
;
419 if ( $revid !== null ) {
420 $this->mRevisionId
= $revid;
421 $this->mRevisionObject
= null;
422 $this->mRevisionTimestamp
= null;
423 $this->mRevisionUser
= null;
424 $this->mRevisionSize
= null;
427 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
429 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
430 $text = $this->internalParse( $text );
431 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
433 $text = $this->mStripState
->unstripGeneral( $text );
435 # Clean up special characters, only run once, next-to-last before doBlockLevels
437 # french spaces, last one Guillemet-left
438 # only if there is something before the space
439 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
440 # french spaces, Guillemet-right
441 '/(\\302\\253) /' => '\\1 ',
442 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
444 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
446 $text = $this->doBlockLevels( $text, $linestart );
448 $this->replaceLinkHolders( $text );
451 * The input doesn't get language converted if
453 * b) Content isn't converted
454 * c) It's a conversion table
455 * d) it is an interface message (which is in the user language)
457 if ( !( $options->getDisableContentConversion()
458 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
460 if ( !$this->mOptions
->getInterfaceMessage() ) {
461 # The position of the convert() call should not be changed. it
462 # assumes that the links are all replaced and the only thing left
463 # is the <nowiki> mark.
464 $text = $this->getConverterLanguage()->convert( $text );
469 * A converted title will be provided in the output object if title and
470 * content conversion are enabled, the article text does not contain
471 * a conversion-suppressing double-underscore tag, and no
472 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
473 * automatic link conversion.
475 if ( !( $options->getDisableTitleConversion()
476 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
477 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
478 ||
$this->mOutput
->getDisplayTitle() !== false )
480 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
481 if ( $convruletitle ) {
482 $this->mOutput
->setTitleText( $convruletitle );
484 $titleText = $this->getConverterLanguage()->convertTitle( $title );
485 $this->mOutput
->setTitleText( $titleText );
489 $text = $this->mStripState
->unstripNoWiki( $text );
491 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
493 $text = $this->replaceTransparentTags( $text );
494 $text = $this->mStripState
->unstripGeneral( $text );
496 $text = Sanitizer
::normalizeCharReferences( $text );
498 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
499 $text = MWTidy
::tidy( $text );
501 # attempt to sanitize at least some nesting problems
502 # (bug #2702 and quite a few others)
504 # ''Something [http://www.cool.com cool''] -->
505 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
506 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
507 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
508 # fix up an anchor inside another anchor, only
509 # at least for a single single nested link (bug 3695)
510 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
511 '\\1\\2</a>\\3</a>\\1\\4</a>',
512 # fix div inside inline elements- doBlockLevels won't wrap a line which
513 # contains a div, so fix it up here; replace
514 # div with escaped text
515 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
516 '\\1\\3<div\\5>\\6</div>\\8\\9',
517 # remove empty italic or bold tag pairs, some
518 # introduced by rules above
519 '/<([bi])><\/\\1>/' => '',
522 $text = preg_replace(
523 array_keys( $tidyregs ),
524 array_values( $tidyregs ),
528 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
529 $this->limitationWarn( 'expensive-parserfunction',
530 $this->mExpensiveFunctionCount
,
531 $this->mOptions
->getExpensiveParserFunctionLimit()
535 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
537 # Information on include size limits, for the benefit of users who try to skirt them
538 if ( $this->mOptions
->getEnableLimitReport() ) {
539 $max = $this->mOptions
->getMaxIncludeSize();
541 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
542 if ( $cpuTime !== null ) {
543 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
544 sprintf( "%.3f", $cpuTime )
548 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
549 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
550 sprintf( "%.3f", $wallTime )
553 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
554 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
556 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
557 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
559 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
560 array( $this->mIncludeSizes
['post-expand'], $max )
562 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
563 array( $this->mIncludeSizes
['arg'], $max )
565 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
566 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
568 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
569 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
571 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
573 $limitReport = "NewPP limit report\n";
574 if ( $wgShowHostnames ) {
575 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
577 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
578 if ( wfRunHooks( 'ParserLimitReportFormat',
579 array( $key, &$value, &$limitReport, false, false )
581 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
582 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
583 ->inLanguage( 'en' )->useDatabase( false );
584 if ( !$valueMsg->exists() ) {
585 $valueMsg = new RawMessage( '$1' );
587 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
588 $valueMsg->params( $value );
589 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
593 // Since we're not really outputting HTML, decode the entities and
594 // then re-encode the things that need hiding inside HTML comments.
595 $limitReport = htmlspecialchars_decode( $limitReport );
596 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
598 // Sanitize for comment. Note '‐' in the replacement is U+2010,
599 // which looks much like the problematic '-'.
600 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
601 $text .= "\n<!-- \n$limitReport-->\n";
603 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
604 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
605 $this->mTitle
->getPrefixedDBkey() );
608 $this->mOutput
->setText( $text );
610 $this->mRevisionId
= $oldRevisionId;
611 $this->mRevisionObject
= $oldRevisionObject;
612 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
613 $this->mRevisionUser
= $oldRevisionUser;
614 $this->mRevisionSize
= $oldRevisionSize;
615 $this->mInputSize
= false;
616 $this->currentRevisionCache
= null;
617 wfProfileOut( $fname );
618 wfProfileOut( __METHOD__
);
620 return $this->mOutput
;
624 * Recursive parser entry point that can be called from an extension tag
627 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
629 * @param string $text Text extension wants to have parsed
630 * @param bool|PPFrame $frame The frame to use for expanding any template variables
634 public function recursiveTagParse( $text, $frame = false ) {
635 wfProfileIn( __METHOD__
);
636 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
637 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
638 $text = $this->internalParse( $text, false, $frame );
639 wfProfileOut( __METHOD__
);
644 * Expand templates and variables in the text, producing valid, static wikitext.
645 * Also removes comments.
646 * Do not call this function recursively.
647 * @param string $text
648 * @param Title $title
649 * @param ParserOptions $options
650 * @param int|null $revid
651 * @param bool|PPFrame $frame
652 * @return mixed|string
654 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
655 wfProfileIn( __METHOD__
);
656 $magicScopeVariable = $this->lock();
657 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
658 if ( $revid !== null ) {
659 $this->mRevisionId
= $revid;
661 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
662 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
663 $text = $this->replaceVariables( $text, $frame );
664 $text = $this->mStripState
->unstripBoth( $text );
665 wfProfileOut( __METHOD__
);
670 * Recursive parser entry point that can be called from an extension tag
673 * @param string $text Text to be expanded
674 * @param bool|PPFrame $frame The frame to use for expanding any template variables
678 public function recursivePreprocess( $text, $frame = false ) {
679 wfProfileIn( __METHOD__
);
680 $text = $this->replaceVariables( $text, $frame );
681 $text = $this->mStripState
->unstripBoth( $text );
682 wfProfileOut( __METHOD__
);
687 * Process the wikitext for the "?preload=" feature. (bug 5210)
689 * "<noinclude>", "<includeonly>" etc. are parsed as for template
690 * transclusion, comments, templates, arguments, tags hooks and parser
691 * functions are untouched.
693 * @param string $text
694 * @param Title $title
695 * @param ParserOptions $options
696 * @param array $params
699 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
700 $msg = new RawMessage( $text );
701 $text = $msg->params( $params )->plain();
703 # Parser (re)initialisation
704 $magicScopeVariable = $this->lock();
705 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
707 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
708 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
709 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
710 $text = $this->mStripState
->unstripBoth( $text );
715 * Get a random string
719 public static function getRandomString() {
720 return wfRandomString( 16 );
724 * Set the current user.
725 * Should only be used when doing pre-save transform.
727 * @param User|null $user User object or null (to reset)
729 public function setUser( $user ) {
730 $this->mUser
= $user;
734 * Accessor for mUniqPrefix.
738 public function uniqPrefix() {
739 if ( !isset( $this->mUniqPrefix
) ) {
740 # @todo FIXME: This is probably *horribly wrong*
741 # LanguageConverter seems to want $wgParser's uniqPrefix, however
742 # if this is called for a parser cache hit, the parser may not
743 # have ever been initialized in the first place.
744 # Not really sure what the heck is supposed to be going on here.
746 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
748 return $this->mUniqPrefix
;
752 * Set the context title
756 public function setTitle( $t ) {
758 $t = Title
::newFromText( 'NO TITLE' );
761 if ( $t->hasFragment() ) {
762 # Strip the fragment to avoid various odd effects
763 $this->mTitle
= clone $t;
764 $this->mTitle
->setFragment( '' );
771 * Accessor for the Title object
775 public function getTitle() {
776 return $this->mTitle
;
780 * Accessor/mutator for the Title object
782 * @param Title $x Title object or null to just get the current one
785 public function Title( $x = null ) {
786 return wfSetVar( $this->mTitle
, $x );
790 * Set the output type
792 * @param int $ot New value
794 public function setOutputType( $ot ) {
795 $this->mOutputType
= $ot;
798 'html' => $ot == self
::OT_HTML
,
799 'wiki' => $ot == self
::OT_WIKI
,
800 'pre' => $ot == self
::OT_PREPROCESS
,
801 'plain' => $ot == self
::OT_PLAIN
,
806 * Accessor/mutator for the output type
808 * @param int|null $x New value or null to just get the current one
811 public function OutputType( $x = null ) {
812 return wfSetVar( $this->mOutputType
, $x );
816 * Get the ParserOutput object
818 * @return ParserOutput
820 public function getOutput() {
821 return $this->mOutput
;
825 * Get the ParserOptions object
827 * @return ParserOptions
829 public function getOptions() {
830 return $this->mOptions
;
834 * Accessor/mutator for the ParserOptions object
836 * @param ParserOptions $x New value or null to just get the current one
837 * @return ParserOptions Current ParserOptions object
839 public function Options( $x = null ) {
840 return wfSetVar( $this->mOptions
, $x );
846 public function nextLinkID() {
847 return $this->mLinkID++
;
853 public function setLinkID( $id ) {
854 $this->mLinkID
= $id;
858 * Get a language object for use in parser functions such as {{FORMATNUM:}}
861 public function getFunctionLang() {
862 return $this->getTargetLanguage();
866 * Get the target language for the content being parsed. This is usually the
867 * language that the content is in.
871 * @throws MWException
874 public function getTargetLanguage() {
875 $target = $this->mOptions
->getTargetLanguage();
877 if ( $target !== null ) {
879 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
880 return $this->mOptions
->getUserLangObj();
881 } elseif ( is_null( $this->mTitle
) ) {
882 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
885 return $this->mTitle
->getPageLanguage();
889 * Get the language object for language conversion
890 * @return Language|null
892 public function getConverterLanguage() {
893 return $this->getTargetLanguage();
897 * Get a User object either from $this->mUser, if set, or from the
898 * ParserOptions object otherwise
902 public function getUser() {
903 if ( !is_null( $this->mUser
) ) {
906 return $this->mOptions
->getUser();
910 * Get a preprocessor object
912 * @return Preprocessor
914 public function getPreprocessor() {
915 if ( !isset( $this->mPreprocessor
) ) {
916 $class = $this->mPreprocessorClass
;
917 $this->mPreprocessor
= new $class( $this );
919 return $this->mPreprocessor
;
923 * Replaces all occurrences of HTML-style comments and the given tags
924 * in the text with a random marker and returns the next text. The output
925 * parameter $matches will be an associative array filled with data in
929 * 'UNIQ-xxxxx' => array(
932 * array( 'param' => 'x' ),
933 * '<element param="x">tag content</element>' ) )
936 * @param array $elements List of element names. Comments are always extracted.
937 * @param string $text Source text string.
938 * @param array $matches Out parameter, Array: extracted tags
939 * @param string $uniq_prefix
940 * @return string Stripped text
942 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
947 $taglist = implode( '|', $elements );
948 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
950 while ( $text != '' ) {
951 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
953 if ( count( $p ) < 5 ) {
956 if ( count( $p ) > 5 ) {
970 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
971 $stripped .= $marker;
973 if ( $close === '/>' ) {
974 # Empty element tag, <tag />
979 if ( $element === '!--' ) {
982 $end = "/(<\\/$element\\s*>)/i";
984 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
986 if ( count( $q ) < 3 ) {
987 # No end tag -- let it run out to the end of the text.
996 $matches[$marker] = array( $element,
998 Sanitizer
::decodeTagAttributes( $attributes ),
999 "<$element$attributes$close$content$tail" );
1005 * Get a list of strippable XML-like elements
1009 public function getStripList() {
1010 return $this->mStripList
;
1014 * Add an item to the strip state
1015 * Returns the unique tag which must be inserted into the stripped text
1016 * The tag will be replaced with the original text in unstrip()
1018 * @param string $text
1022 public function insertStripItem( $text ) {
1023 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1024 $this->mMarkerIndex++
;
1025 $this->mStripState
->addGeneral( $rnd, $text );
1030 * parse the wiki syntax used to render tables
1033 * @param string $text
1036 public function doTableStuff( $text ) {
1037 wfProfileIn( __METHOD__
);
1039 $lines = StringUtils
::explode( "\n", $text );
1041 $td_history = array(); # Is currently a td tag open?
1042 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1043 $tr_history = array(); # Is currently a tr tag open?
1044 $tr_attributes = array(); # history of tr attributes
1045 $has_opened_tr = array(); # Did this table open a <tr> element?
1046 $indent_level = 0; # indent level of the table
1048 foreach ( $lines as $outLine ) {
1049 $line = trim( $outLine );
1051 if ( $line === '' ) { # empty line, go to next line
1052 $out .= $outLine . "\n";
1056 $first_character = $line[0];
1059 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1060 # First check if we are starting a new table
1061 $indent_level = strlen( $matches[1] );
1063 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1064 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1066 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1067 array_push( $td_history, false );
1068 array_push( $last_tag_history, '' );
1069 array_push( $tr_history, false );
1070 array_push( $tr_attributes, '' );
1071 array_push( $has_opened_tr, false );
1072 } elseif ( count( $td_history ) == 0 ) {
1073 # Don't do any of the following
1074 $out .= $outLine . "\n";
1076 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1077 # We are ending a table
1078 $line = '</table>' . substr( $line, 2 );
1079 $last_tag = array_pop( $last_tag_history );
1081 if ( !array_pop( $has_opened_tr ) ) {
1082 $line = "<tr><td></td></tr>{$line}";
1085 if ( array_pop( $tr_history ) ) {
1086 $line = "</tr>{$line}";
1089 if ( array_pop( $td_history ) ) {
1090 $line = "</{$last_tag}>{$line}";
1092 array_pop( $tr_attributes );
1093 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1094 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1095 # Now we have a table row
1096 $line = preg_replace( '#^\|-+#', '', $line );
1098 # Whats after the tag is now only attributes
1099 $attributes = $this->mStripState
->unstripBoth( $line );
1100 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1101 array_pop( $tr_attributes );
1102 array_push( $tr_attributes, $attributes );
1105 $last_tag = array_pop( $last_tag_history );
1106 array_pop( $has_opened_tr );
1107 array_push( $has_opened_tr, true );
1109 if ( array_pop( $tr_history ) ) {
1113 if ( array_pop( $td_history ) ) {
1114 $line = "</{$last_tag}>{$line}";
1118 array_push( $tr_history, false );
1119 array_push( $td_history, false );
1120 array_push( $last_tag_history, '' );
1121 } elseif ( $first_character === '|'
1122 ||
$first_character === '!'
1123 ||
substr( $line, 0, 2 ) === '|+'
1125 # This might be cell elements, td, th or captions
1126 if ( substr( $line, 0, 2 ) === '|+' ) {
1127 $first_character = '+';
1128 $line = substr( $line, 1 );
1131 $line = substr( $line, 1 );
1133 if ( $first_character === '!' ) {
1134 $line = str_replace( '!!', '||', $line );
1137 # Split up multiple cells on the same line.
1138 # FIXME : This can result in improper nesting of tags processed
1139 # by earlier parser steps, but should avoid splitting up eg
1140 # attribute values containing literal "||".
1141 $cells = StringUtils
::explodeMarkup( '||', $line );
1145 # Loop through each table cell
1146 foreach ( $cells as $cell ) {
1148 if ( $first_character !== '+' ) {
1149 $tr_after = array_pop( $tr_attributes );
1150 if ( !array_pop( $tr_history ) ) {
1151 $previous = "<tr{$tr_after}>\n";
1153 array_push( $tr_history, true );
1154 array_push( $tr_attributes, '' );
1155 array_pop( $has_opened_tr );
1156 array_push( $has_opened_tr, true );
1159 $last_tag = array_pop( $last_tag_history );
1161 if ( array_pop( $td_history ) ) {
1162 $previous = "</{$last_tag}>\n{$previous}";
1165 if ( $first_character === '|' ) {
1167 } elseif ( $first_character === '!' ) {
1169 } elseif ( $first_character === '+' ) {
1170 $last_tag = 'caption';
1175 array_push( $last_tag_history, $last_tag );
1177 # A cell could contain both parameters and data
1178 $cell_data = explode( '|', $cell, 2 );
1180 # Bug 553: Note that a '|' inside an invalid link should not
1181 # be mistaken as delimiting cell parameters
1182 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1183 $cell = "{$previous}<{$last_tag}>{$cell}";
1184 } elseif ( count( $cell_data ) == 1 ) {
1185 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1187 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1188 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1189 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1193 array_push( $td_history, true );
1196 $out .= $outLine . "\n";
1199 # Closing open td, tr && table
1200 while ( count( $td_history ) > 0 ) {
1201 if ( array_pop( $td_history ) ) {
1204 if ( array_pop( $tr_history ) ) {
1207 if ( !array_pop( $has_opened_tr ) ) {
1208 $out .= "<tr><td></td></tr>\n";
1211 $out .= "</table>\n";
1214 # Remove trailing line-ending (b/c)
1215 if ( substr( $out, -1 ) === "\n" ) {
1216 $out = substr( $out, 0, -1 );
1219 # special case: don't return empty table
1220 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1224 wfProfileOut( __METHOD__
);
1230 * Helper function for parse() that transforms wiki markup into
1231 * HTML. Only called for $mOutputType == self::OT_HTML.
1235 * @param string $text
1236 * @param bool $isMain
1237 * @param bool $frame
1241 public function internalParse( $text, $isMain = true, $frame = false ) {
1242 wfProfileIn( __METHOD__
);
1246 # Hook to suspend the parser in this state
1247 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1248 wfProfileOut( __METHOD__
);
1252 # if $frame is provided, then use $frame for replacing any variables
1254 # use frame depth to infer how include/noinclude tags should be handled
1255 # depth=0 means this is the top-level document; otherwise it's an included document
1256 if ( !$frame->depth
) {
1259 $flag = Parser
::PTD_FOR_INCLUSION
;
1261 $dom = $this->preprocessToDom( $text, $flag );
1262 $text = $frame->expand( $dom );
1264 # if $frame is not provided, then use old-style replaceVariables
1265 $text = $this->replaceVariables( $text );
1268 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1269 $text = Sanitizer
::removeHTMLtags(
1271 array( &$this, 'attributeStripCallback' ),
1273 array_keys( $this->mTransparentTagHooks
)
1275 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1277 # Tables need to come after variable replacement for things to work
1278 # properly; putting them before other transformations should keep
1279 # exciting things like link expansions from showing up in surprising
1281 $text = $this->doTableStuff( $text );
1283 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1285 $text = $this->doDoubleUnderscore( $text );
1287 $text = $this->doHeadings( $text );
1288 $text = $this->replaceInternalLinks( $text );
1289 $text = $this->doAllQuotes( $text );
1290 $text = $this->replaceExternalLinks( $text );
1292 # replaceInternalLinks may sometimes leave behind
1293 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1294 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1296 $text = $this->doMagicLinks( $text );
1297 $text = $this->formatHeadings( $text, $origText, $isMain );
1299 wfProfileOut( __METHOD__
);
1304 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1305 * magic external links.
1310 * @param string $text
1314 public function doMagicLinks( $text ) {
1315 wfProfileIn( __METHOD__
);
1316 $prots = wfUrlProtocolsWithoutProtRel();
1317 $urlChar = self
::EXT_LINK_URL_CLASS
;
1318 $text = preg_replace_callback(
1320 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1321 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1322 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1323 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1324 ISBN\s+(\b # m[5]: ISBN, capture number
1325 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1326 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1327 [0-9Xx] # check digit
1329 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1330 wfProfileOut( __METHOD__
);
1335 * @throws MWException
1337 * @return HTML|string
1339 public function magicLinkCallback( $m ) {
1340 if ( isset( $m[1] ) && $m[1] !== '' ) {
1343 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1346 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1347 # Free external link
1348 return $this->makeFreeExternalLink( $m[0] );
1349 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1351 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1354 $cssClass = 'mw-magiclink-rfc';
1356 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1358 $urlmsg = 'pubmedurl';
1359 $cssClass = 'mw-magiclink-pmid';
1362 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1363 substr( $m[0], 0, 20 ) . '"' );
1365 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1366 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1367 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1370 $num = strtr( $isbn, array(
1375 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1376 return '<a href="' .
1377 htmlspecialchars( $titleObj->getLocalURL() ) .
1378 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1385 * Make a free external link, given a user-supplied URL
1387 * @param string $url
1389 * @return string HTML
1392 public function makeFreeExternalLink( $url ) {
1393 wfProfileIn( __METHOD__
);
1397 # The characters '<' and '>' (which were escaped by
1398 # removeHTMLtags()) should not be included in
1399 # URLs, per RFC 2396.
1401 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1402 $trail = substr( $url, $m2[0][1] ) . $trail;
1403 $url = substr( $url, 0, $m2[0][1] );
1406 # Move trailing punctuation to $trail
1408 # If there is no left bracket, then consider right brackets fair game too
1409 if ( strpos( $url, '(' ) === false ) {
1413 $numSepChars = strspn( strrev( $url ), $sep );
1414 if ( $numSepChars ) {
1415 $trail = substr( $url, -$numSepChars ) . $trail;
1416 $url = substr( $url, 0, -$numSepChars );
1419 $url = Sanitizer
::cleanUrl( $url );
1421 # Is this an external image?
1422 $text = $this->maybeMakeExternalImage( $url );
1423 if ( $text === false ) {
1424 # Not an image, make a link
1425 $text = Linker
::makeExternalLink( $url,
1426 $this->getConverterLanguage()->markNoConversion( $url, true ),
1428 $this->getExternalLinkAttribs( $url ) );
1429 # Register it in the output object...
1430 # Replace unnecessary URL escape codes with their equivalent characters
1431 $pasteurized = self
::normalizeLinkUrl( $url );
1432 $this->mOutput
->addExternalLink( $pasteurized );
1434 wfProfileOut( __METHOD__
);
1435 return $text . $trail;
1439 * Parse headers and return html
1443 * @param string $text
1447 public function doHeadings( $text ) {
1448 wfProfileIn( __METHOD__
);
1449 for ( $i = 6; $i >= 1; --$i ) {
1450 $h = str_repeat( '=', $i );
1451 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1453 wfProfileOut( __METHOD__
);
1458 * Replace single quotes with HTML markup
1461 * @param string $text
1463 * @return string The altered text
1465 public function doAllQuotes( $text ) {
1466 wfProfileIn( __METHOD__
);
1468 $lines = StringUtils
::explode( "\n", $text );
1469 foreach ( $lines as $line ) {
1470 $outtext .= $this->doQuotes( $line ) . "\n";
1472 $outtext = substr( $outtext, 0, -1 );
1473 wfProfileOut( __METHOD__
);
1478 * Helper function for doAllQuotes()
1480 * @param string $text
1484 public function doQuotes( $text ) {
1485 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1486 $countarr = count( $arr );
1487 if ( $countarr == 1 ) {
1491 // First, do some preliminary work. This may shift some apostrophes from
1492 // being mark-up to being text. It also counts the number of occurrences
1493 // of bold and italics mark-ups.
1496 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1497 $thislen = strlen( $arr[$i] );
1498 // If there are ever four apostrophes, assume the first is supposed to
1499 // be text, and the remaining three constitute mark-up for bold text.
1500 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1501 if ( $thislen == 4 ) {
1502 $arr[$i - 1] .= "'";
1505 } elseif ( $thislen > 5 ) {
1506 // If there are more than 5 apostrophes in a row, assume they're all
1507 // text except for the last 5.
1508 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1509 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1513 // Count the number of occurrences of bold and italics mark-ups.
1514 if ( $thislen == 2 ) {
1516 } elseif ( $thislen == 3 ) {
1518 } elseif ( $thislen == 5 ) {
1524 // If there is an odd number of both bold and italics, it is likely
1525 // that one of the bold ones was meant to be an apostrophe followed
1526 // by italics. Which one we cannot know for certain, but it is more
1527 // likely to be one that has a single-letter word before it.
1528 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1529 $firstsingleletterword = -1;
1530 $firstmultiletterword = -1;
1532 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1533 if ( strlen( $arr[$i] ) == 3 ) {
1534 $x1 = substr( $arr[$i - 1], -1 );
1535 $x2 = substr( $arr[$i - 1], -2, 1 );
1536 if ( $x1 === ' ' ) {
1537 if ( $firstspace == -1 ) {
1540 } elseif ( $x2 === ' ' ) {
1541 if ( $firstsingleletterword == -1 ) {
1542 $firstsingleletterword = $i;
1543 // if $firstsingleletterword is set, we don't
1544 // look at the other options, so we can bail early.
1548 if ( $firstmultiletterword == -1 ) {
1549 $firstmultiletterword = $i;
1555 // If there is a single-letter word, use it!
1556 if ( $firstsingleletterword > -1 ) {
1557 $arr[$firstsingleletterword] = "''";
1558 $arr[$firstsingleletterword - 1] .= "'";
1559 } elseif ( $firstmultiletterword > -1 ) {
1560 // If not, but there's a multi-letter word, use that one.
1561 $arr[$firstmultiletterword] = "''";
1562 $arr[$firstmultiletterword - 1] .= "'";
1563 } elseif ( $firstspace > -1 ) {
1564 // ... otherwise use the first one that has neither.
1565 // (notice that it is possible for all three to be -1 if, for example,
1566 // there is only one pentuple-apostrophe in the line)
1567 $arr[$firstspace] = "''";
1568 $arr[$firstspace - 1] .= "'";
1572 // Now let's actually convert our apostrophic mush to HTML!
1577 foreach ( $arr as $r ) {
1578 if ( ( $i %
2 ) == 0 ) {
1579 if ( $state === 'both' ) {
1585 $thislen = strlen( $r );
1586 if ( $thislen == 2 ) {
1587 if ( $state === 'i' ) {
1590 } elseif ( $state === 'bi' ) {
1593 } elseif ( $state === 'ib' ) {
1594 $output .= '</b></i><b>';
1596 } elseif ( $state === 'both' ) {
1597 $output .= '<b><i>' . $buffer . '</i>';
1599 } else { // $state can be 'b' or ''
1603 } elseif ( $thislen == 3 ) {
1604 if ( $state === 'b' ) {
1607 } elseif ( $state === 'bi' ) {
1608 $output .= '</i></b><i>';
1610 } elseif ( $state === 'ib' ) {
1613 } elseif ( $state === 'both' ) {
1614 $output .= '<i><b>' . $buffer . '</b>';
1616 } else { // $state can be 'i' or ''
1620 } elseif ( $thislen == 5 ) {
1621 if ( $state === 'b' ) {
1622 $output .= '</b><i>';
1624 } elseif ( $state === 'i' ) {
1625 $output .= '</i><b>';
1627 } elseif ( $state === 'bi' ) {
1628 $output .= '</i></b>';
1630 } elseif ( $state === 'ib' ) {
1631 $output .= '</b></i>';
1633 } elseif ( $state === 'both' ) {
1634 $output .= '<i><b>' . $buffer . '</b></i>';
1636 } else { // ($state == '')
1644 // Now close all remaining tags. Notice that the order is important.
1645 if ( $state === 'b' ||
$state === 'ib' ) {
1648 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1651 if ( $state === 'bi' ) {
1654 // There might be lonely ''''', so make sure we have a buffer
1655 if ( $state === 'both' && $buffer ) {
1656 $output .= '<b><i>' . $buffer . '</i></b>';
1662 * Replace external links (REL)
1664 * Note: this is all very hackish and the order of execution matters a lot.
1665 * Make sure to run tests/parserTests.php if you change this code.
1669 * @param string $text
1671 * @throws MWException
1674 public function replaceExternalLinks( $text ) {
1675 wfProfileIn( __METHOD__
);
1677 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1678 if ( $bits === false ) {
1679 wfProfileOut( __METHOD__
);
1680 throw new MWException( "PCRE needs to be compiled with "
1681 . "--enable-unicode-properties in order for MediaWiki to function" );
1683 $s = array_shift( $bits );
1686 while ( $i < count( $bits ) ) {
1689 $text = $bits[$i++
];
1690 $trail = $bits[$i++
];
1692 # The characters '<' and '>' (which were escaped by
1693 # removeHTMLtags()) should not be included in
1694 # URLs, per RFC 2396.
1696 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1697 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1698 $url = substr( $url, 0, $m2[0][1] );
1701 # If the link text is an image URL, replace it with an <img> tag
1702 # This happened by accident in the original parser, but some people used it extensively
1703 $img = $this->maybeMakeExternalImage( $text );
1704 if ( $img !== false ) {
1710 # Set linktype for CSS - if URL==text, link is essentially free
1711 $linktype = ( $text === $url ) ?
'free' : 'text';
1713 # No link text, e.g. [http://domain.tld/some.link]
1714 if ( $text == '' ) {
1716 $langObj = $this->getTargetLanguage();
1717 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1718 $linktype = 'autonumber';
1720 # Have link text, e.g. [http://domain.tld/some.link text]s
1722 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1725 $text = $this->getConverterLanguage()->markNoConversion( $text );
1727 $url = Sanitizer
::cleanUrl( $url );
1729 # Use the encoded URL
1730 # This means that users can paste URLs directly into the text
1731 # Funny characters like ö aren't valid in URLs anyway
1732 # This was changed in August 2004
1733 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1734 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1736 # Register link in the output object.
1737 # Replace unnecessary URL escape codes with the referenced character
1738 # This prevents spammers from hiding links from the filters
1739 $pasteurized = self
::normalizeLinkUrl( $url );
1740 $this->mOutput
->addExternalLink( $pasteurized );
1743 wfProfileOut( __METHOD__
);
1748 * Get the rel attribute for a particular external link.
1751 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1752 * nofollow if appropriate
1753 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1754 * @return string|null Rel attribute for $url
1756 public static function getExternalLinkRel( $url = false, $title = null ) {
1757 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1758 $ns = $title ?
$title->getNamespace() : false;
1759 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1760 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1768 * Get an associative array of additional HTML attributes appropriate for a
1769 * particular external link. This currently may include rel => nofollow
1770 * (depending on configuration, namespace, and the URL's domain) and/or a
1771 * target attribute (depending on configuration).
1773 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1774 * nofollow if appropriate
1775 * @return array Associative array of HTML attributes
1777 public function getExternalLinkAttribs( $url = false ) {
1779 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1781 if ( $this->mOptions
->getExternalLinkTarget() ) {
1782 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1788 * Replace unusual escape codes in a URL with their equivalent characters
1790 * @deprecated since 1.24, use normalizeLinkUrl
1791 * @param string $url
1794 public static function replaceUnusualEscapes( $url ) {
1795 wfDeprecated( __METHOD__
, '1.24' );
1796 return self
::normalizeLinkUrl( $url );
1800 * Replace unusual escape codes in a URL with their equivalent characters
1802 * This generally follows the syntax defined in RFC 3986, with special
1803 * consideration for HTTP query strings.
1805 * @param string $url
1808 public static function normalizeLinkUrl( $url ) {
1809 # First, make sure unsafe characters are encoded
1810 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1812 return rawurlencode( $m[0] );
1818 $end = strlen( $url );
1820 # Fragment part - 'fragment'
1821 $start = strpos( $url, '#' );
1822 if ( $start !== false && $start < $end ) {
1823 $ret = self
::normalizeUrlComponent(
1824 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1828 # Query part - 'query' minus &=+;
1829 $start = strpos( $url, '?' );
1830 if ( $start !== false && $start < $end ) {
1831 $ret = self
::normalizeUrlComponent(
1832 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1836 # Scheme and path part - 'pchar'
1837 # (we assume no userinfo or encoded colons in the host)
1838 $ret = self
::normalizeUrlComponent(
1839 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1844 private static function normalizeUrlComponent( $component, $unsafe ) {
1845 $callback = function ( $matches ) use ( $unsafe ) {
1846 $char = urldecode( $matches[0] );
1847 $ord = ord( $char );
1848 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1852 # Leave it escaped, but use uppercase for a-f
1853 return strtoupper( $matches[0] );
1856 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1860 * make an image if it's allowed, either through the global
1861 * option, through the exception, or through the on-wiki whitelist
1863 * @param string $url
1867 private function maybeMakeExternalImage( $url ) {
1868 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1869 $imagesexception = !empty( $imagesfrom );
1871 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1872 if ( $imagesexception && is_array( $imagesfrom ) ) {
1873 $imagematch = false;
1874 foreach ( $imagesfrom as $match ) {
1875 if ( strpos( $url, $match ) === 0 ) {
1880 } elseif ( $imagesexception ) {
1881 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1883 $imagematch = false;
1886 if ( $this->mOptions
->getAllowExternalImages()
1887 ||
( $imagesexception && $imagematch )
1889 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1891 $text = Linker
::makeExternalImage( $url );
1894 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1895 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1897 $whitelist = explode(
1899 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1902 foreach ( $whitelist as $entry ) {
1903 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1904 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1907 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1908 # Image matches a whitelist entry
1909 $text = Linker
::makeExternalImage( $url );
1918 * Process [[ ]] wikilinks
1922 * @return string Processed text
1926 public function replaceInternalLinks( $s ) {
1927 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1932 * Process [[ ]] wikilinks (RIL)
1934 * @throws MWException
1935 * @return LinkHolderArray
1939 public function replaceInternalLinks2( &$s ) {
1940 global $wgExtraInterlanguageLinkPrefixes;
1941 wfProfileIn( __METHOD__
);
1943 wfProfileIn( __METHOD__
. '-setup' );
1944 static $tc = false, $e1, $e1_img;
1945 # the % is needed to support urlencoded titles as well
1947 $tc = Title
::legalChars() . '#%';
1948 # Match a link having the form [[namespace:link|alternate]]trail
1949 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1950 # Match cases where there is no "]]", which might still be images
1951 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1954 $holders = new LinkHolderArray( $this );
1956 # split the entire text string on occurrences of [[
1957 $a = StringUtils
::explode( '[[', ' ' . $s );
1958 # get the first element (all text up to first [[), and remove the space we added
1961 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1962 $s = substr( $s, 1 );
1964 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1966 if ( $useLinkPrefixExtension ) {
1967 # Match the end of a line for a word that's not followed by whitespace,
1968 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1970 $charset = $wgContLang->linkPrefixCharset();
1971 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1974 if ( is_null( $this->mTitle
) ) {
1975 wfProfileOut( __METHOD__
. '-setup' );
1976 wfProfileOut( __METHOD__
);
1977 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1979 $nottalk = !$this->mTitle
->isTalkPage();
1981 if ( $useLinkPrefixExtension ) {
1983 if ( preg_match( $e2, $s, $m ) ) {
1984 $first_prefix = $m[2];
1986 $first_prefix = false;
1992 $useSubpages = $this->areSubpagesAllowed();
1993 wfProfileOut( __METHOD__
. '-setup' );
1995 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1996 # Loop for each link
1997 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1998 // @codingStandardsIgnoreStart
2000 # Check for excessive memory usage
2001 if ( $holders->isBig() ) {
2003 # Do the existence check, replace the link holders and clear the array
2004 $holders->replace( $s );
2008 if ( $useLinkPrefixExtension ) {
2009 wfProfileIn( __METHOD__
. '-prefixhandling' );
2010 if ( preg_match( $e2, $s, $m ) ) {
2017 if ( $first_prefix ) {
2018 $prefix = $first_prefix;
2019 $first_prefix = false;
2021 wfProfileOut( __METHOD__
. '-prefixhandling' );
2024 $might_be_img = false;
2026 wfProfileIn( __METHOD__
. "-e1" );
2027 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2029 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2030 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2031 # the real problem is with the $e1 regex
2034 # Still some problems for cases where the ] is meant to be outside punctuation,
2035 # and no image is in sight. See bug 2095.
2038 && substr( $m[3], 0, 1 ) === ']'
2039 && strpos( $text, '[' ) !== false
2041 $text .= ']'; # so that replaceExternalLinks($text) works later
2042 $m[3] = substr( $m[3], 1 );
2044 # fix up urlencoded title texts
2045 if ( strpos( $m[1], '%' ) !== false ) {
2046 # Should anchors '#' also be rejected?
2047 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2050 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2051 # Invalid, but might be an image with a link in its caption
2052 $might_be_img = true;
2054 if ( strpos( $m[1], '%' ) !== false ) {
2055 $m[1] = rawurldecode( $m[1] );
2058 } else { # Invalid form; output directly
2059 $s .= $prefix . '[[' . $line;
2060 wfProfileOut( __METHOD__
. "-e1" );
2063 wfProfileOut( __METHOD__
. "-e1" );
2064 wfProfileIn( __METHOD__
. "-misc" );
2068 # Don't allow internal links to pages containing
2069 # PROTO: where PROTO is a valid URL protocol; these
2070 # should be external links.
2071 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2072 $s .= $prefix . '[[' . $line;
2073 wfProfileOut( __METHOD__
. "-misc" );
2077 # Make subpage if necessary
2078 if ( $useSubpages ) {
2079 $link = $this->maybeDoSubpageLink( $origLink, $text );
2084 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2086 # Strip off leading ':'
2087 $link = substr( $link, 1 );
2090 wfProfileOut( __METHOD__
. "-misc" );
2091 wfProfileIn( __METHOD__
. "-title" );
2092 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2093 if ( $nt === null ) {
2094 $s .= $prefix . '[[' . $line;
2095 wfProfileOut( __METHOD__
. "-title" );
2099 $ns = $nt->getNamespace();
2100 $iw = $nt->getInterwiki();
2101 wfProfileOut( __METHOD__
. "-title" );
2103 if ( $might_be_img ) { # if this is actually an invalid link
2104 wfProfileIn( __METHOD__
. "-might_be_img" );
2105 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2108 # look at the next 'line' to see if we can close it there
2110 $next_line = $a->current();
2111 if ( $next_line === false ||
$next_line === null ) {
2114 $m = explode( ']]', $next_line, 3 );
2115 if ( count( $m ) == 3 ) {
2116 # the first ]] closes the inner link, the second the image
2118 $text .= "[[{$m[0]}]]{$m[1]}";
2121 } elseif ( count( $m ) == 2 ) {
2122 # if there's exactly one ]] that's fine, we'll keep looking
2123 $text .= "[[{$m[0]}]]{$m[1]}";
2125 # if $next_line is invalid too, we need look no further
2126 $text .= '[[' . $next_line;
2131 # we couldn't find the end of this imageLink, so output it raw
2132 # but don't ignore what might be perfectly normal links in the text we've examined
2133 $holders->merge( $this->replaceInternalLinks2( $text ) );
2134 $s .= "{$prefix}[[$link|$text";
2135 # note: no $trail, because without an end, there *is* no trail
2136 wfProfileOut( __METHOD__
. "-might_be_img" );
2139 } else { # it's not an image, so output it raw
2140 $s .= "{$prefix}[[$link|$text";
2141 # note: no $trail, because without an end, there *is* no trail
2142 wfProfileOut( __METHOD__
. "-might_be_img" );
2145 wfProfileOut( __METHOD__
. "-might_be_img" );
2148 $wasblank = ( $text == '' );
2152 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2153 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2154 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2155 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2156 $text = $this->doQuotes( $text );
2159 # Link not escaped by : , create the various objects
2160 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2162 wfProfileIn( __METHOD__
. "-interwiki" );
2164 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2165 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2166 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2169 # Bug 24502: filter duplicates
2170 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2171 $this->mLangLinkLanguages
[$iw] = true;
2172 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2175 $s = rtrim( $s . $prefix );
2176 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2177 wfProfileOut( __METHOD__
. "-interwiki" );
2180 wfProfileOut( __METHOD__
. "-interwiki" );
2182 if ( $ns == NS_FILE
) {
2183 wfProfileIn( __METHOD__
. "-image" );
2184 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2186 # if no parameters were passed, $text
2187 # becomes something like "File:Foo.png",
2188 # which we don't want to pass on to the
2192 # recursively parse links inside the image caption
2193 # actually, this will parse them in any other parameters, too,
2194 # but it might be hard to fix that, and it doesn't matter ATM
2195 $text = $this->replaceExternalLinks( $text );
2196 $holders->merge( $this->replaceInternalLinks2( $text ) );
2198 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2199 $s .= $prefix . $this->armorLinks(
2200 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2202 $s .= $prefix . $trail;
2204 wfProfileOut( __METHOD__
. "-image" );
2208 if ( $ns == NS_CATEGORY
) {
2209 wfProfileIn( __METHOD__
. "-category" );
2210 $s = rtrim( $s . "\n" ); # bug 87
2213 $sortkey = $this->getDefaultSort();
2217 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2218 $sortkey = str_replace( "\n", '', $sortkey );
2219 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2220 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2223 * Strip the whitespace Category links produce, see bug 87
2225 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2227 wfProfileOut( __METHOD__
. "-category" );
2232 # Self-link checking. For some languages, variants of the title are checked in
2233 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2234 # for linking to a different variant.
2235 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2236 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2240 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2241 # @todo FIXME: Should do batch file existence checks, see comment below
2242 if ( $ns == NS_MEDIA
) {
2243 wfProfileIn( __METHOD__
. "-media" );
2244 # Give extensions a chance to select the file revision for us
2247 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2248 array( $this, $nt, &$options, &$descQuery ) );
2249 # Fetch and register the file (file title may be different via hooks)
2250 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2251 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2252 $s .= $prefix . $this->armorLinks(
2253 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2254 wfProfileOut( __METHOD__
. "-media" );
2258 wfProfileIn( __METHOD__
. "-always_known" );
2259 # Some titles, such as valid special pages or files in foreign repos, should
2260 # be shown as bluelinks even though they're not included in the page table
2262 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2263 # batch file existence checks for NS_FILE and NS_MEDIA
2264 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2265 $this->mOutput
->addLink( $nt );
2266 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2268 # Links will be added to the output link list after checking
2269 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2271 wfProfileOut( __METHOD__
. "-always_known" );
2273 wfProfileOut( __METHOD__
);
2278 * Render a forced-blue link inline; protect against double expansion of
2279 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2280 * Since this little disaster has to split off the trail text to avoid
2281 * breaking URLs in the following text without breaking trails on the
2282 * wiki links, it's been made into a horrible function.
2285 * @param string $text
2286 * @param array|string $query
2287 * @param string $trail
2288 * @param string $prefix
2289 * @return string HTML-wikitext mix oh yuck
2291 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2292 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2294 if ( is_string( $query ) ) {
2295 $query = wfCgiToArray( $query );
2297 if ( $text == '' ) {
2298 $text = htmlspecialchars( $nt->getPrefixedText() );
2301 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2303 return $this->armorLinks( $link ) . $trail;
2307 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2308 * going to go through further parsing steps before inline URL expansion.
2310 * Not needed quite as much as it used to be since free links are a bit
2311 * more sensible these days. But bracketed links are still an issue.
2313 * @param string $text More-or-less HTML
2314 * @return string Less-or-more HTML with NOPARSE bits
2316 public function armorLinks( $text ) {
2317 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2318 "{$this->mUniqPrefix}NOPARSE$1", $text );
2322 * Return true if subpage links should be expanded on this page.
2325 public function areSubpagesAllowed() {
2326 # Some namespaces don't allow subpages
2327 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2331 * Handle link to subpage if necessary
2333 * @param string $target The source of the link
2334 * @param string &$text The link text, modified as necessary
2335 * @return string The full name of the link
2338 public function maybeDoSubpageLink( $target, &$text ) {
2339 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2343 * Used by doBlockLevels()
2348 public function closeParagraph() {
2350 if ( $this->mLastSection
!= '' ) {
2351 $result = '</' . $this->mLastSection
. ">\n";
2353 $this->mInPre
= false;
2354 $this->mLastSection
= '';
2359 * getCommon() returns the length of the longest common substring
2360 * of both arguments, starting at the beginning of both.
2363 * @param string $st1
2364 * @param string $st2
2368 public function getCommon( $st1, $st2 ) {
2369 $fl = strlen( $st1 );
2370 $shorter = strlen( $st2 );
2371 if ( $fl < $shorter ) {
2375 for ( $i = 0; $i < $shorter; ++
$i ) {
2376 if ( $st1[$i] != $st2[$i] ) {
2384 * These next three functions open, continue, and close the list
2385 * element appropriate to the prefix character passed into them.
2388 * @param string $char
2392 public function openList( $char ) {
2393 $result = $this->closeParagraph();
2395 if ( '*' === $char ) {
2396 $result .= "<ul><li>";
2397 } elseif ( '#' === $char ) {
2398 $result .= "<ol><li>";
2399 } elseif ( ':' === $char ) {
2400 $result .= "<dl><dd>";
2401 } elseif ( ';' === $char ) {
2402 $result .= "<dl><dt>";
2403 $this->mDTopen
= true;
2405 $result = '<!-- ERR 1 -->';
2413 * @param string $char
2418 public function nextItem( $char ) {
2419 if ( '*' === $char ||
'#' === $char ) {
2420 return "</li>\n<li>";
2421 } elseif ( ':' === $char ||
';' === $char ) {
2423 if ( $this->mDTopen
) {
2426 if ( ';' === $char ) {
2427 $this->mDTopen
= true;
2428 return $close . '<dt>';
2430 $this->mDTopen
= false;
2431 return $close . '<dd>';
2434 return '<!-- ERR 2 -->';
2439 * @param string $char
2444 public function closeList( $char ) {
2445 if ( '*' === $char ) {
2446 $text = "</li></ul>";
2447 } elseif ( '#' === $char ) {
2448 $text = "</li></ol>";
2449 } elseif ( ':' === $char ) {
2450 if ( $this->mDTopen
) {
2451 $this->mDTopen
= false;
2452 $text = "</dt></dl>";
2454 $text = "</dd></dl>";
2457 return '<!-- ERR 3 -->';
2464 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2466 * @param string $text
2467 * @param bool $linestart Whether or not this is at the start of a line.
2469 * @return string The lists rendered as HTML
2471 public function doBlockLevels( $text, $linestart ) {
2472 wfProfileIn( __METHOD__
);
2474 # Parsing through the text line by line. The main thing
2475 # happening here is handling of block-level elements p, pre,
2476 # and making lists from lines starting with * # : etc.
2478 $textLines = StringUtils
::explode( "\n", $text );
2480 $lastPrefix = $output = '';
2481 $this->mDTopen
= $inBlockElem = false;
2483 $paragraphStack = false;
2484 $inBlockquote = false;
2486 foreach ( $textLines as $oLine ) {
2488 if ( !$linestart ) {
2498 $lastPrefixLength = strlen( $lastPrefix );
2499 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2500 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2501 # If not in a <pre> element, scan for and figure out what prefixes are there.
2502 if ( !$this->mInPre
) {
2503 # Multiple prefixes may abut each other for nested lists.
2504 $prefixLength = strspn( $oLine, '*#:;' );
2505 $prefix = substr( $oLine, 0, $prefixLength );
2508 # ; and : are both from definition-lists, so they're equivalent
2509 # for the purposes of determining whether or not we need to open/close
2511 $prefix2 = str_replace( ';', ':', $prefix );
2512 $t = substr( $oLine, $prefixLength );
2513 $this->mInPre
= (bool)$preOpenMatch;
2515 # Don't interpret any other prefixes in preformatted text
2517 $prefix = $prefix2 = '';
2522 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2523 # Same as the last item, so no need to deal with nesting or opening stuff
2524 $output .= $this->nextItem( substr( $prefix, -1 ) );
2525 $paragraphStack = false;
2527 if ( substr( $prefix, -1 ) === ';' ) {
2528 # The one nasty exception: definition lists work like this:
2529 # ; title : definition text
2530 # So we check for : in the remainder text to split up the
2531 # title and definition, without b0rking links.
2533 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2535 $output .= $term . $this->nextItem( ':' );
2538 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2539 # We need to open or close prefixes, or both.
2541 # Either open or close a level...
2542 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2543 $paragraphStack = false;
2545 # Close all the prefixes which aren't shared.
2546 while ( $commonPrefixLength < $lastPrefixLength ) {
2547 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2548 --$lastPrefixLength;
2551 # Continue the current prefix if appropriate.
2552 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2553 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2556 # Open prefixes where appropriate.
2557 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2560 while ( $prefixLength > $commonPrefixLength ) {
2561 $char = substr( $prefix, $commonPrefixLength, 1 );
2562 $output .= $this->openList( $char );
2564 if ( ';' === $char ) {
2565 # @todo FIXME: This is dupe of code above
2566 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2568 $output .= $term . $this->nextItem( ':' );
2571 ++
$commonPrefixLength;
2573 if ( !$prefixLength && $lastPrefix ) {
2576 $lastPrefix = $prefix2;
2579 # If we have no prefixes, go to paragraph mode.
2580 if ( 0 == $prefixLength ) {
2581 wfProfileIn( __METHOD__
. "-paragraph" );
2582 # No prefix (not in list)--go to paragraph mode
2583 # XXX: use a stack for nestable elements like span, table and div
2584 $openmatch = preg_match(
2585 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2586 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2589 $closematch = preg_match(
2590 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2591 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2592 . $this->mUniqPrefix
2593 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2597 if ( $openmatch or $closematch ) {
2598 $paragraphStack = false;
2599 # @todo bug 5718: paragraph closed
2600 $output .= $this->closeParagraph();
2601 if ( $preOpenMatch and !$preCloseMatch ) {
2602 $this->mInPre
= true;
2605 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2606 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2607 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2609 $inBlockElem = !$closematch;
2610 } elseif ( !$inBlockElem && !$this->mInPre
) {
2611 if ( ' ' == substr( $t, 0, 1 )
2612 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2616 if ( $this->mLastSection
!== 'pre' ) {
2617 $paragraphStack = false;
2618 $output .= $this->closeParagraph() . '<pre>';
2619 $this->mLastSection
= 'pre';
2621 $t = substr( $t, 1 );
2624 if ( trim( $t ) === '' ) {
2625 if ( $paragraphStack ) {
2626 $output .= $paragraphStack . '<br />';
2627 $paragraphStack = false;
2628 $this->mLastSection
= 'p';
2630 if ( $this->mLastSection
!== 'p' ) {
2631 $output .= $this->closeParagraph();
2632 $this->mLastSection
= '';
2633 $paragraphStack = '<p>';
2635 $paragraphStack = '</p><p>';
2639 if ( $paragraphStack ) {
2640 $output .= $paragraphStack;
2641 $paragraphStack = false;
2642 $this->mLastSection
= 'p';
2643 } elseif ( $this->mLastSection
!== 'p' ) {
2644 $output .= $this->closeParagraph() . '<p>';
2645 $this->mLastSection
= 'p';
2650 wfProfileOut( __METHOD__
. "-paragraph" );
2652 # somewhere above we forget to get out of pre block (bug 785)
2653 if ( $preCloseMatch && $this->mInPre
) {
2654 $this->mInPre
= false;
2656 if ( $paragraphStack === false ) {
2658 if ( $prefixLength === 0 ) {
2663 while ( $prefixLength ) {
2664 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2666 if ( !$prefixLength ) {
2670 if ( $this->mLastSection
!= '' ) {
2671 $output .= '</' . $this->mLastSection
. '>';
2672 $this->mLastSection
= '';
2675 wfProfileOut( __METHOD__
);
2680 * Split up a string on ':', ignoring any occurrences inside tags
2681 * to prevent illegal overlapping.
2683 * @param string $str The string to split
2684 * @param string &$before Set to everything before the ':'
2685 * @param string &$after Set to everything after the ':'
2686 * @throws MWException
2687 * @return string The position of the ':', or false if none found
2689 public function findColonNoLinks( $str, &$before, &$after ) {
2690 wfProfileIn( __METHOD__
);
2692 $pos = strpos( $str, ':' );
2693 if ( $pos === false ) {
2695 wfProfileOut( __METHOD__
);
2699 $lt = strpos( $str, '<' );
2700 if ( $lt === false ||
$lt > $pos ) {
2701 # Easy; no tag nesting to worry about
2702 $before = substr( $str, 0, $pos );
2703 $after = substr( $str, $pos +
1 );
2704 wfProfileOut( __METHOD__
);
2708 # Ugly state machine to walk through avoiding tags.
2709 $state = self
::COLON_STATE_TEXT
;
2711 $len = strlen( $str );
2712 for ( $i = 0; $i < $len; $i++
) {
2716 # (Using the number is a performance hack for common cases)
2717 case 0: # self::COLON_STATE_TEXT:
2720 # Could be either a <start> tag or an </end> tag
2721 $state = self
::COLON_STATE_TAGSTART
;
2724 if ( $stack == 0 ) {
2726 $before = substr( $str, 0, $i );
2727 $after = substr( $str, $i +
1 );
2728 wfProfileOut( __METHOD__
);
2731 # Embedded in a tag; don't break it.
2734 # Skip ahead looking for something interesting
2735 $colon = strpos( $str, ':', $i );
2736 if ( $colon === false ) {
2737 # Nothing else interesting
2738 wfProfileOut( __METHOD__
);
2741 $lt = strpos( $str, '<', $i );
2742 if ( $stack === 0 ) {
2743 if ( $lt === false ||
$colon < $lt ) {
2745 $before = substr( $str, 0, $colon );
2746 $after = substr( $str, $colon +
1 );
2747 wfProfileOut( __METHOD__
);
2751 if ( $lt === false ) {
2752 # Nothing else interesting to find; abort!
2753 # We're nested, but there's no close tags left. Abort!
2756 # Skip ahead to next tag start
2758 $state = self
::COLON_STATE_TAGSTART
;
2761 case 1: # self::COLON_STATE_TAG:
2766 $state = self
::COLON_STATE_TEXT
;
2769 # Slash may be followed by >?
2770 $state = self
::COLON_STATE_TAGSLASH
;
2776 case 2: # self::COLON_STATE_TAGSTART:
2779 $state = self
::COLON_STATE_CLOSETAG
;
2782 $state = self
::COLON_STATE_COMMENT
;
2785 # Illegal early close? This shouldn't happen D:
2786 $state = self
::COLON_STATE_TEXT
;
2789 $state = self
::COLON_STATE_TAG
;
2792 case 3: # self::COLON_STATE_CLOSETAG:
2797 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2798 wfProfileOut( __METHOD__
);
2801 $state = self
::COLON_STATE_TEXT
;
2804 case self
::COLON_STATE_TAGSLASH
:
2806 # Yes, a self-closed tag <blah/>
2807 $state = self
::COLON_STATE_TEXT
;
2809 # Probably we're jumping the gun, and this is an attribute
2810 $state = self
::COLON_STATE_TAG
;
2813 case 5: # self::COLON_STATE_COMMENT:
2815 $state = self
::COLON_STATE_COMMENTDASH
;
2818 case self
::COLON_STATE_COMMENTDASH
:
2820 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2822 $state = self
::COLON_STATE_COMMENT
;
2825 case self
::COLON_STATE_COMMENTDASHDASH
:
2827 $state = self
::COLON_STATE_TEXT
;
2829 $state = self
::COLON_STATE_COMMENT
;
2833 wfProfileOut( __METHOD__
);
2834 throw new MWException( "State machine error in " . __METHOD__
);
2838 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2839 wfProfileOut( __METHOD__
);
2842 wfProfileOut( __METHOD__
);
2847 * Return value of a magic variable (like PAGENAME)
2852 * @param bool|PPFrame $frame
2854 * @throws MWException
2857 public function getVariableValue( $index, $frame = false ) {
2858 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2859 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2861 if ( is_null( $this->mTitle
) ) {
2862 // If no title set, bad things are going to happen
2863 // later. Title should always be set since this
2864 // should only be called in the middle of a parse
2865 // operation (but the unit-tests do funky stuff)
2866 throw new MWException( __METHOD__
. ' Should only be '
2867 . ' called while parsing (no title set)' );
2871 * Some of these require message or data lookups and can be
2872 * expensive to check many times.
2874 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2875 if ( isset( $this->mVarCache
[$index] ) ) {
2876 return $this->mVarCache
[$index];
2880 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2881 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2883 $pageLang = $this->getFunctionLang();
2889 case 'currentmonth':
2890 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2892 case 'currentmonth1':
2893 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2895 case 'currentmonthname':
2896 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2898 case 'currentmonthnamegen':
2899 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2901 case 'currentmonthabbrev':
2902 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2905 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2908 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2911 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2914 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2916 case 'localmonthname':
2917 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2919 case 'localmonthnamegen':
2920 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2922 case 'localmonthabbrev':
2923 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2926 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2929 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2932 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2935 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2937 case 'fullpagename':
2938 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2940 case 'fullpagenamee':
2941 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2944 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2946 case 'subpagenamee':
2947 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2949 case 'rootpagename':
2950 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2952 case 'rootpagenamee':
2953 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2956 $this->mTitle
->getRootText()
2959 case 'basepagename':
2960 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2962 case 'basepagenamee':
2963 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2966 $this->mTitle
->getBaseText()
2969 case 'talkpagename':
2970 if ( $this->mTitle
->canTalk() ) {
2971 $talkPage = $this->mTitle
->getTalkPage();
2972 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2977 case 'talkpagenamee':
2978 if ( $this->mTitle
->canTalk() ) {
2979 $talkPage = $this->mTitle
->getTalkPage();
2980 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2985 case 'subjectpagename':
2986 $subjPage = $this->mTitle
->getSubjectPage();
2987 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2989 case 'subjectpagenamee':
2990 $subjPage = $this->mTitle
->getSubjectPage();
2991 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2993 case 'pageid': // requested in bug 23427
2994 $pageid = $this->getTitle()->getArticleID();
2995 if ( $pageid == 0 ) {
2996 # 0 means the page doesn't exist in the database,
2997 # which means the user is previewing a new page.
2998 # The vary-revision flag must be set, because the magic word
2999 # will have a different value once the page is saved.
3000 $this->mOutput
->setFlag( 'vary-revision' );
3001 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3003 $value = $pageid ?
$pageid : null;
3006 # Let the edit saving system know we should parse the page
3007 # *after* a revision ID has been assigned.
3008 $this->mOutput
->setFlag( 'vary-revision' );
3009 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3010 $value = $this->mRevisionId
;
3013 # Let the edit saving system know we should parse the page
3014 # *after* a revision ID has been assigned. This is for null edits.
3015 $this->mOutput
->setFlag( 'vary-revision' );
3016 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3017 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3019 case 'revisionday2':
3020 # Let the edit saving system know we should parse the page
3021 # *after* a revision ID has been assigned. This is for null edits.
3022 $this->mOutput
->setFlag( 'vary-revision' );
3023 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3024 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3026 case 'revisionmonth':
3027 # Let the edit saving system know we should parse the page
3028 # *after* a revision ID has been assigned. This is for null edits.
3029 $this->mOutput
->setFlag( 'vary-revision' );
3030 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3031 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3033 case 'revisionmonth1':
3034 # Let the edit saving system know we should parse the page
3035 # *after* a revision ID has been assigned. This is for null edits.
3036 $this->mOutput
->setFlag( 'vary-revision' );
3037 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3038 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3040 case 'revisionyear':
3041 # Let the edit saving system know we should parse the page
3042 # *after* a revision ID has been assigned. This is for null edits.
3043 $this->mOutput
->setFlag( 'vary-revision' );
3044 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3045 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3047 case 'revisiontimestamp':
3048 # Let the edit saving system know we should parse the page
3049 # *after* a revision ID has been assigned. This is for null edits.
3050 $this->mOutput
->setFlag( 'vary-revision' );
3051 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3052 $value = $this->getRevisionTimestamp();
3054 case 'revisionuser':
3055 # Let the edit saving system know we should parse the page
3056 # *after* a revision ID has been assigned. This is for null edits.
3057 $this->mOutput
->setFlag( 'vary-revision' );
3058 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3059 $value = $this->getRevisionUser();
3061 case 'revisionsize':
3062 # Let the edit saving system know we should parse the page
3063 # *after* a revision ID has been assigned. This is for null edits.
3064 $this->mOutput
->setFlag( 'vary-revision' );
3065 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3066 $value = $this->getRevisionSize();
3069 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3072 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3074 case 'namespacenumber':
3075 $value = $this->mTitle
->getNamespace();
3078 $value = $this->mTitle
->canTalk()
3079 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3083 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3085 case 'subjectspace':
3086 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3088 case 'subjectspacee':
3089 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3091 case 'currentdayname':
3092 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3095 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3098 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3101 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3104 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3105 # int to remove the padding
3106 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3109 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3111 case 'localdayname':
3112 $value = $pageLang->getWeekdayName(
3113 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3117 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3120 $value = $pageLang->time(
3121 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3127 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3130 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3131 # int to remove the padding
3132 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3135 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3137 case 'numberofarticles':
3138 $value = $pageLang->formatNum( SiteStats
::articles() );
3140 case 'numberoffiles':
3141 $value = $pageLang->formatNum( SiteStats
::images() );
3143 case 'numberofusers':
3144 $value = $pageLang->formatNum( SiteStats
::users() );
3146 case 'numberofactiveusers':
3147 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3149 case 'numberofpages':
3150 $value = $pageLang->formatNum( SiteStats
::pages() );
3152 case 'numberofadmins':
3153 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3155 case 'numberofedits':
3156 $value = $pageLang->formatNum( SiteStats
::edits() );
3158 case 'numberofviews':
3159 global $wgDisableCounters;
3160 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3162 case 'currenttimestamp':
3163 $value = wfTimestamp( TS_MW
, $ts );
3165 case 'localtimestamp':
3166 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3168 case 'currentversion':
3169 $value = SpecialVersion
::getVersion();
3172 return $wgArticlePath;
3178 return $wgServerName;
3180 return $wgScriptPath;
3182 return $wgStylePath;
3183 case 'directionmark':
3184 return $pageLang->getDirMark();
3185 case 'contentlanguage':
3186 global $wgLanguageCode;
3187 return $wgLanguageCode;
3188 case 'cascadingsources':
3189 $value = CoreParserFunctions
::cascadingsources( $this );
3194 'ParserGetVariableValueSwitch',
3195 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3202 $this->mVarCache
[$index] = $value;
3209 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3213 public function initialiseVariables() {
3214 wfProfileIn( __METHOD__
);
3215 $variableIDs = MagicWord
::getVariableIDs();
3216 $substIDs = MagicWord
::getSubstIDs();
3218 $this->mVariables
= new MagicWordArray( $variableIDs );
3219 $this->mSubstWords
= new MagicWordArray( $substIDs );
3220 wfProfileOut( __METHOD__
);
3224 * Preprocess some wikitext and return the document tree.
3225 * This is the ghost of replace_variables().
3227 * @param string $text The text to parse
3228 * @param int $flags Bitwise combination of:
3229 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3230 * included. Default is to assume a direct page view.
3232 * The generated DOM tree must depend only on the input text and the flags.
3233 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3235 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3236 * change in the DOM tree for a given text, must be passed through the section identifier
3237 * in the section edit link and thus back to extractSections().
3239 * The output of this function is currently only cached in process memory, but a persistent
3240 * cache may be implemented at a later date which takes further advantage of these strict
3241 * dependency requirements.
3245 public function preprocessToDom( $text, $flags = 0 ) {
3246 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3251 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3257 public static function splitWhitespace( $s ) {
3258 $ltrimmed = ltrim( $s );
3259 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3260 $trimmed = rtrim( $ltrimmed );
3261 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3263 $w2 = substr( $ltrimmed, -$diff );
3267 return array( $w1, $trimmed, $w2 );
3271 * Replace magic variables, templates, and template arguments
3272 * with the appropriate text. Templates are substituted recursively,
3273 * taking care to avoid infinite loops.
3275 * Note that the substitution depends on value of $mOutputType:
3276 * self::OT_WIKI: only {{subst:}} templates
3277 * self::OT_PREPROCESS: templates but not extension tags
3278 * self::OT_HTML: all templates and extension tags
3280 * @param string $text The text to transform
3281 * @param bool|PPFrame $frame Object describing the arguments passed to the
3282 * template. Arguments may also be provided as an associative array, as
3283 * was the usual case before MW1.12. Providing arguments this way may be
3284 * useful for extensions wishing to perform variable replacement
3286 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3287 * double-brace expansion.
3290 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3291 # Is there any text? Also, Prevent too big inclusions!
3292 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3295 wfProfileIn( __METHOD__
);
3297 if ( $frame === false ) {
3298 $frame = $this->getPreprocessor()->newFrame();
3299 } elseif ( !( $frame instanceof PPFrame
) ) {
3300 wfDebug( __METHOD__
. " called using plain parameters instead of "
3301 . "a PPFrame instance. Creating custom frame.\n" );
3302 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3305 $dom = $this->preprocessToDom( $text );
3306 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3307 $text = $frame->expand( $dom, $flags );
3309 wfProfileOut( __METHOD__
);
3314 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3316 * @param array $args
3320 public static function createAssocArgs( $args ) {
3321 $assocArgs = array();
3323 foreach ( $args as $arg ) {
3324 $eqpos = strpos( $arg, '=' );
3325 if ( $eqpos === false ) {
3326 $assocArgs[$index++
] = $arg;
3328 $name = trim( substr( $arg, 0, $eqpos ) );
3329 $value = trim( substr( $arg, $eqpos +
1 ) );
3330 if ( $value === false ) {
3333 if ( $name !== false ) {
3334 $assocArgs[$name] = $value;
3343 * Warn the user when a parser limitation is reached
3344 * Will warn at most once the user per limitation type
3346 * @param string $limitationType Should be one of:
3347 * 'expensive-parserfunction' (corresponding messages:
3348 * 'expensive-parserfunction-warning',
3349 * 'expensive-parserfunction-category')
3350 * 'post-expand-template-argument' (corresponding messages:
3351 * 'post-expand-template-argument-warning',
3352 * 'post-expand-template-argument-category')
3353 * 'post-expand-template-inclusion' (corresponding messages:
3354 * 'post-expand-template-inclusion-warning',
3355 * 'post-expand-template-inclusion-category')
3356 * 'node-count-exceeded' (corresponding messages:
3357 * 'node-count-exceeded-warning',
3358 * 'node-count-exceeded-category')
3359 * 'expansion-depth-exceeded' (corresponding messages:
3360 * 'expansion-depth-exceeded-warning',
3361 * 'expansion-depth-exceeded-category')
3362 * @param string|int|null $current Current value
3363 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3364 * exceeded, provide the values (optional)
3366 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3367 # does no harm if $current and $max are present but are unnecessary for the message
3368 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3369 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3370 $this->mOutput
->addWarning( $warning );
3371 $this->addTrackingCategory( "$limitationType-category" );
3375 * Return the text of a template, after recursively
3376 * replacing any variables or templates within the template.
3378 * @param array $piece The parts of the template
3379 * $piece['title']: the title, i.e. the part before the |
3380 * $piece['parts']: the parameter array
3381 * $piece['lineStart']: whether the brace was at the start of a line
3382 * @param PPFrame $frame The current frame, contains template arguments
3384 * @return string The text of the template
3386 public function braceSubstitution( $piece, $frame ) {
3387 wfProfileIn( __METHOD__
);
3388 wfProfileIn( __METHOD__
. '-setup' );
3392 // $text has been filled
3394 // wiki markup in $text should be escaped
3396 // $text is HTML, armour it against wikitext transformation
3398 // Force interwiki transclusion to be done in raw mode not rendered
3399 $forceRawInterwiki = false;
3400 // $text is a DOM node needing expansion in a child frame
3401 $isChildObj = false;
3402 // $text is a DOM node needing expansion in the current frame
3403 $isLocalObj = false;
3405 # Title object, where $text came from
3408 # $part1 is the bit before the first |, and must contain only title characters.
3409 # Various prefixes will be stripped from it later.
3410 $titleWithSpaces = $frame->expand( $piece['title'] );
3411 $part1 = trim( $titleWithSpaces );
3414 # Original title text preserved for various purposes
3415 $originalTitle = $part1;
3417 # $args is a list of argument nodes, starting from index 0, not including $part1
3418 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3419 # below won't work b/c this $args isn't an object
3420 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3421 wfProfileOut( __METHOD__
. '-setup' );
3423 $titleProfileIn = null; // profile templates
3426 wfProfileIn( __METHOD__
. '-modifiers' );
3429 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3431 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3432 # Decide whether to expand template or keep wikitext as-is.
3433 if ( $this->ot
['wiki'] ) {
3434 if ( $substMatch === false ) {
3435 $literal = true; # literal when in PST with no prefix
3437 $literal = false; # expand when in PST with subst: or safesubst:
3440 if ( $substMatch == 'subst' ) {
3441 $literal = true; # literal when not in PST with plain subst:
3443 $literal = false; # expand when not in PST with safesubst: or no prefix
3447 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3454 if ( !$found && $args->getLength() == 0 ) {
3455 $id = $this->mVariables
->matchStartToEnd( $part1 );
3456 if ( $id !== false ) {
3457 $text = $this->getVariableValue( $id, $frame );
3458 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3459 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3465 # MSG, MSGNW and RAW
3468 $mwMsgnw = MagicWord
::get( 'msgnw' );
3469 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3472 # Remove obsolete MSG:
3473 $mwMsg = MagicWord
::get( 'msg' );
3474 $mwMsg->matchStartAndRemove( $part1 );
3478 $mwRaw = MagicWord
::get( 'raw' );
3479 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3480 $forceRawInterwiki = true;
3483 wfProfileOut( __METHOD__
. '-modifiers' );
3487 wfProfileIn( __METHOD__
. '-pfunc' );
3489 $colonPos = strpos( $part1, ':' );
3490 if ( $colonPos !== false ) {
3491 $func = substr( $part1, 0, $colonPos );
3492 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3493 for ( $i = 0; $i < $args->getLength(); $i++
) {
3494 $funcArgs[] = $args->item( $i );
3497 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3498 } catch ( Exception
$ex ) {
3499 wfProfileOut( __METHOD__
. '-pfunc' );
3500 wfProfileOut( __METHOD__
);
3504 # The interface for parser functions allows for extracting
3505 # flags into the local scope. Extract any forwarded flags
3509 wfProfileOut( __METHOD__
. '-pfunc' );
3512 # Finish mangling title and then check for loops.
3513 # Set $title to a Title object and $titleText to the PDBK
3516 # Split the title into page and subpage
3518 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3519 if ( $part1 !== $relative ) {
3521 $ns = $this->mTitle
->getNamespace();
3523 $title = Title
::newFromText( $part1, $ns );
3525 $titleText = $title->getPrefixedText();
3526 # Check for language variants if the template is not found
3527 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3528 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3530 # Do recursion depth check
3531 $limit = $this->mOptions
->getMaxTemplateDepth();
3532 if ( $frame->depth
>= $limit ) {
3534 $text = '<span class="error">'
3535 . wfMessage( 'parser-template-recursion-depth-warning' )
3536 ->numParams( $limit )->inContentLanguage()->text()
3542 # Load from database
3543 if ( !$found && $title ) {
3544 if ( !Profiler
::instance()->isPersistent() ) {
3545 # Too many unique items can kill profiling DBs/collectors
3546 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3547 wfProfileIn( $titleProfileIn ); // template in
3549 wfProfileIn( __METHOD__
. '-loadtpl' );
3550 if ( !$title->isExternal() ) {
3551 if ( $title->isSpecialPage()
3552 && $this->mOptions
->getAllowSpecialInclusion()
3553 && $this->ot
['html']
3555 // Pass the template arguments as URL parameters.
3556 // "uselang" will have no effect since the Language object
3557 // is forced to the one defined in ParserOptions.
3558 $pageArgs = array();
3559 $argsLength = $args->getLength();
3560 for ( $i = 0; $i < $argsLength; $i++
) {
3561 $bits = $args->item( $i )->splitArg();
3562 if ( strval( $bits['index'] ) === '' ) {
3563 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3564 $value = trim( $frame->expand( $bits['value'] ) );
3565 $pageArgs[$name] = $value;
3569 // Create a new context to execute the special page
3570 $context = new RequestContext
;
3571 $context->setTitle( $title );
3572 $context->setRequest( new FauxRequest( $pageArgs ) );
3573 $context->setUser( $this->getUser() );
3574 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3575 $ret = SpecialPageFactory
::capturePath( $title, $context );
3577 $text = $context->getOutput()->getHTML();
3578 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3581 $this->disableCache();
3583 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3584 $found = false; # access denied
3585 wfDebug( __METHOD__
. ": template inclusion denied for " .
3586 $title->getPrefixedDBkey() . "\n" );
3588 list( $text, $title ) = $this->getTemplateDom( $title );
3589 if ( $text !== false ) {
3595 # If the title is valid but undisplayable, make a link to it
3596 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3597 $text = "[[:$titleText]]";
3600 } elseif ( $title->isTrans() ) {
3601 # Interwiki transclusion
3602 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3603 $text = $this->interwikiTransclude( $title, 'render' );
3606 $text = $this->interwikiTransclude( $title, 'raw' );
3607 # Preprocess it like a template
3608 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3614 # Do infinite loop check
3615 # This has to be done after redirect resolution to avoid infinite loops via redirects
3616 if ( !$frame->loopCheck( $title ) ) {
3618 $text = '<span class="error">'
3619 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3621 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3623 wfProfileOut( __METHOD__
. '-loadtpl' );
3626 # If we haven't found text to substitute by now, we're done
3627 # Recover the source wikitext and return it
3629 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3630 if ( $titleProfileIn ) {
3631 wfProfileOut( $titleProfileIn ); // template out
3633 wfProfileOut( __METHOD__
);
3634 return array( 'object' => $text );
3637 # Expand DOM-style return values in a child frame
3638 if ( $isChildObj ) {
3639 # Clean up argument array
3640 $newFrame = $frame->newChild( $args, $title );
3643 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3644 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3645 # Expansion is eligible for the empty-frame cache
3646 $text = $newFrame->cachedExpand( $titleText, $text );
3648 # Uncached expansion
3649 $text = $newFrame->expand( $text );
3652 if ( $isLocalObj && $nowiki ) {
3653 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3654 $isLocalObj = false;
3657 if ( $titleProfileIn ) {
3658 wfProfileOut( $titleProfileIn ); // template out
3661 # Replace raw HTML by a placeholder
3663 $text = $this->insertStripItem( $text );
3664 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3665 # Escape nowiki-style return values
3666 $text = wfEscapeWikiText( $text );
3667 } elseif ( is_string( $text )
3668 && !$piece['lineStart']
3669 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3671 # Bug 529: if the template begins with a table or block-level
3672 # element, it should be treated as beginning a new line.
3673 # This behavior is somewhat controversial.
3674 $text = "\n" . $text;
3677 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3678 # Error, oversize inclusion
3679 if ( $titleText !== false ) {
3680 # Make a working, properly escaped link if possible (bug 23588)
3681 $text = "[[:$titleText]]";
3683 # This will probably not be a working link, but at least it may
3684 # provide some hint of where the problem is
3685 preg_replace( '/^:/', '', $originalTitle );
3686 $text = "[[:$originalTitle]]";
3688 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3689 . 'post-expand include size too large -->' );
3690 $this->limitationWarn( 'post-expand-template-inclusion' );
3693 if ( $isLocalObj ) {
3694 $ret = array( 'object' => $text );
3696 $ret = array( 'text' => $text );
3699 wfProfileOut( __METHOD__
);
3704 * Call a parser function and return an array with text and flags.
3706 * The returned array will always contain a boolean 'found', indicating
3707 * whether the parser function was found or not. It may also contain the
3709 * text: string|object, resulting wikitext or PP DOM object
3710 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3711 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3712 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3713 * nowiki: bool, wiki markup in $text should be escaped
3716 * @param PPFrame $frame The current frame, contains template arguments
3717 * @param string $function Function name
3718 * @param array $args Arguments to the function
3719 * @throws MWException
3722 public function callParserFunction( $frame, $function, array $args = array() ) {
3725 wfProfileIn( __METHOD__
);
3727 # Case sensitive functions
3728 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3729 $function = $this->mFunctionSynonyms
[1][$function];
3731 # Case insensitive functions
3732 $function = $wgContLang->lc( $function );
3733 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3734 $function = $this->mFunctionSynonyms
[0][$function];
3736 wfProfileOut( __METHOD__
);
3737 return array( 'found' => false );
3741 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3742 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3744 # Workaround for PHP bug 35229 and similar
3745 if ( !is_callable( $callback ) ) {
3746 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3747 wfProfileOut( __METHOD__
);
3748 throw new MWException( "Tag hook for $function is not callable\n" );
3751 $allArgs = array( &$this );
3752 if ( $flags & SFH_OBJECT_ARGS
) {
3753 # Convert arguments to PPNodes and collect for appending to $allArgs
3754 $funcArgs = array();
3755 foreach ( $args as $k => $v ) {
3756 if ( $v instanceof PPNode ||
$k === 0 ) {
3759 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3763 # Add a frame parameter, and pass the arguments as an array
3764 $allArgs[] = $frame;
3765 $allArgs[] = $funcArgs;
3767 # Convert arguments to plain text and append to $allArgs
3768 foreach ( $args as $k => $v ) {
3769 if ( $v instanceof PPNode
) {
3770 $allArgs[] = trim( $frame->expand( $v ) );
3771 } elseif ( is_int( $k ) && $k >= 0 ) {
3772 $allArgs[] = trim( $v );
3774 $allArgs[] = trim( "$k=$v" );
3779 $result = call_user_func_array( $callback, $allArgs );
3781 # The interface for function hooks allows them to return a wikitext
3782 # string or an array containing the string and any flags. This mungs
3783 # things around to match what this method should return.
3784 if ( !is_array( $result ) ) {
3790 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3791 $result['text'] = $result[0];
3793 unset( $result[0] );
3800 $preprocessFlags = 0;
3801 if ( isset( $result['noparse'] ) ) {
3802 $noparse = $result['noparse'];
3804 if ( isset( $result['preprocessFlags'] ) ) {
3805 $preprocessFlags = $result['preprocessFlags'];
3809 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3810 $result['isChildObj'] = true;
3812 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3813 wfProfileOut( __METHOD__
);
3819 * Get the semi-parsed DOM representation of a template with a given title,
3820 * and its redirect destination title. Cached.
3822 * @param Title $title
3826 public function getTemplateDom( $title ) {
3827 $cacheTitle = $title;
3828 $titleText = $title->getPrefixedDBkey();
3830 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3831 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3832 $title = Title
::makeTitle( $ns, $dbk );
3833 $titleText = $title->getPrefixedDBkey();
3835 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3836 return array( $this->mTplDomCache
[$titleText], $title );
3839 # Cache miss, go to the database
3840 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3842 if ( $text === false ) {
3843 $this->mTplDomCache
[$titleText] = false;
3844 return array( false, $title );
3847 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3848 $this->mTplDomCache
[$titleText] = $dom;
3850 if ( !$title->equals( $cacheTitle ) ) {
3851 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3852 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3855 return array( $dom, $title );
3859 * Fetch the current revision of a given title. Note that the revision
3860 * (and even the title) may not exist in the database, so everything
3861 * contributing to the output of the parser should use this method
3862 * where possible, rather than getting the revisions themselves. This
3863 * method also caches its results, so using it benefits performance.
3866 * @param Title $title
3869 public function fetchCurrentRevisionOfTitle( $title ) {
3870 $cacheKey = $title->getPrefixedDBkey();
3871 if ( !$this->currentRevisionCache
) {
3872 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3874 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3875 $this->currentRevisionCache
->set( $cacheKey,
3876 // Defaults to Parser::statelessFetchRevision()
3877 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3880 return $this->currentRevisionCache
->get( $cacheKey );
3884 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3885 * without passing them on to it.
3888 * @param Title $title
3889 * @param Parser|bool $parser
3892 public static function statelessFetchRevision( $title, $parser = false ) {
3893 return Revision
::newFromTitle( $title );
3897 * Fetch the unparsed text of a template and register a reference to it.
3898 * @param Title $title
3899 * @return array ( string or false, Title )
3901 public function fetchTemplateAndTitle( $title ) {
3902 // Defaults to Parser::statelessFetchTemplate()
3903 $templateCb = $this->mOptions
->getTemplateCallback();
3904 $stuff = call_user_func( $templateCb, $title, $this );
3905 $text = $stuff['text'];
3906 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3907 if ( isset( $stuff['deps'] ) ) {
3908 foreach ( $stuff['deps'] as $dep ) {
3909 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3910 if ( $dep['title']->equals( $this->getTitle() ) ) {
3911 // If we transclude ourselves, the final result
3912 // will change based on the new version of the page
3913 $this->mOutput
->setFlag( 'vary-revision' );
3917 return array( $text, $finalTitle );
3921 * Fetch the unparsed text of a template and register a reference to it.
3922 * @param Title $title
3923 * @return string|bool
3925 public function fetchTemplate( $title ) {
3926 $rv = $this->fetchTemplateAndTitle( $title );
3931 * Static function to get a template
3932 * Can be overridden via ParserOptions::setTemplateCallback().
3934 * @param Title $title
3935 * @param bool|Parser $parser
3939 public static function statelessFetchTemplate( $title, $parser = false ) {
3940 $text = $skip = false;
3941 $finalTitle = $title;
3944 # Loop to fetch the article, with up to 1 redirect
3945 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3946 # Give extensions a chance to select the revision instead
3947 $id = false; # Assume current
3948 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3949 array( $parser, $title, &$skip, &$id ) );
3955 'page_id' => $title->getArticleID(),
3962 $rev = Revision
::newFromId( $id );
3963 } elseif ( $parser ) {
3964 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3966 $rev = Revision
::newFromTitle( $title );
3968 $rev_id = $rev ?
$rev->getId() : 0;
3969 # If there is no current revision, there is no page
3970 if ( $id === false && !$rev ) {
3971 $linkCache = LinkCache
::singleton();
3972 $linkCache->addBadLinkObj( $title );
3977 'page_id' => $title->getArticleID(),
3978 'rev_id' => $rev_id );
3979 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3980 # We fetched a rev from a different title; register it too...
3982 'title' => $rev->getTitle(),
3983 'page_id' => $rev->getPage(),
3984 'rev_id' => $rev_id );
3988 $content = $rev->getContent();
3989 $text = $content ?
$content->getWikitextForTransclusion() : null;
3991 if ( $text === false ||
$text === null ) {
3995 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3997 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3998 if ( !$message->exists() ) {
4002 $content = $message->content();
4003 $text = $message->plain();
4011 $finalTitle = $title;
4012 $title = $content->getRedirectTarget();
4016 'finalTitle' => $finalTitle,
4021 * Fetch a file and its title and register a reference to it.
4022 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4023 * @param Title $title
4024 * @param array $options Array of options to RepoGroup::findFile
4027 public function fetchFile( $title, $options = array() ) {
4028 $res = $this->fetchFileAndTitle( $title, $options );
4033 * Fetch a file and its title and register a reference to it.
4034 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4035 * @param Title $title
4036 * @param array $options Array of options to RepoGroup::findFile
4037 * @return array ( File or false, Title of file )
4039 public function fetchFileAndTitle( $title, $options = array() ) {
4040 $file = $this->fetchFileNoRegister( $title, $options );
4042 $time = $file ?
$file->getTimestamp() : false;
4043 $sha1 = $file ?
$file->getSha1() : false;
4044 # Register the file as a dependency...
4045 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4046 if ( $file && !$title->equals( $file->getTitle() ) ) {
4047 # Update fetched file title
4048 $title = $file->getTitle();
4049 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4051 return array( $file, $title );
4055 * Helper function for fetchFileAndTitle.
4057 * Also useful if you need to fetch a file but not use it yet,
4058 * for example to get the file's handler.
4060 * @param Title $title
4061 * @param array $options Array of options to RepoGroup::findFile
4064 protected function fetchFileNoRegister( $title, $options = array() ) {
4065 if ( isset( $options['broken'] ) ) {
4066 $file = false; // broken thumbnail forced by hook
4067 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4068 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4069 } else { // get by (name,timestamp)
4070 $file = wfFindFile( $title, $options );
4076 * Transclude an interwiki link.
4078 * @param Title $title
4079 * @param string $action
4083 public function interwikiTransclude( $title, $action ) {
4084 global $wgEnableScaryTranscluding;
4086 if ( !$wgEnableScaryTranscluding ) {
4087 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4090 $url = $title->getFullURL( array( 'action' => $action ) );
4092 if ( strlen( $url ) > 255 ) {
4093 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4095 return $this->fetchScaryTemplateMaybeFromCache( $url );
4099 * @param string $url
4100 * @return mixed|string
4102 public function fetchScaryTemplateMaybeFromCache( $url ) {
4103 global $wgTranscludeCacheExpiry;
4104 $dbr = wfGetDB( DB_SLAVE
);
4105 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4106 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4107 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4109 return $obj->tc_contents
;
4112 $req = MWHttpRequest
::factory( $url );
4113 $status = $req->execute(); // Status object
4114 if ( $status->isOK() ) {
4115 $text = $req->getContent();
4116 } elseif ( $req->getStatus() != 200 ) {
4117 // Though we failed to fetch the content, this status is useless.
4118 return wfMessage( 'scarytranscludefailed-httpstatus' )
4119 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4121 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4124 $dbw = wfGetDB( DB_MASTER
);
4125 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4127 'tc_time' => $dbw->timestamp( time() ),
4128 'tc_contents' => $text
4134 * Triple brace replacement -- used for template arguments
4137 * @param array $piece
4138 * @param PPFrame $frame
4142 public function argSubstitution( $piece, $frame ) {
4143 wfProfileIn( __METHOD__
);
4146 $parts = $piece['parts'];
4147 $nameWithSpaces = $frame->expand( $piece['title'] );
4148 $argName = trim( $nameWithSpaces );
4150 $text = $frame->getArgument( $argName );
4151 if ( $text === false && $parts->getLength() > 0
4152 && ( $this->ot
['html']
4154 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4157 # No match in frame, use the supplied default
4158 $object = $parts->item( 0 )->getChildren();
4160 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4161 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4162 $this->limitationWarn( 'post-expand-template-argument' );
4165 if ( $text === false && $object === false ) {
4167 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4169 if ( $error !== false ) {
4172 if ( $object !== false ) {
4173 $ret = array( 'object' => $object );
4175 $ret = array( 'text' => $text );
4178 wfProfileOut( __METHOD__
);
4183 * Return the text to be used for a given extension tag.
4184 * This is the ghost of strip().
4186 * @param array $params Associative array of parameters:
4187 * name PPNode for the tag name
4188 * attr PPNode for unparsed text where tag attributes are thought to be
4189 * attributes Optional associative array of parsed attributes
4190 * inner Contents of extension element
4191 * noClose Original text did not have a close tag
4192 * @param PPFrame $frame
4194 * @throws MWException
4197 public function extensionSubstitution( $params, $frame ) {
4198 $name = $frame->expand( $params['name'] );
4199 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4200 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4201 $marker = "{$this->mUniqPrefix}-$name-"
4202 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4204 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4205 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4206 if ( $isFunctionTag ) {
4207 $markerType = 'none';
4209 $markerType = 'general';
4211 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4212 $name = strtolower( $name );
4213 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4214 if ( isset( $params['attributes'] ) ) {
4215 $attributes = $attributes +
$params['attributes'];
4218 if ( isset( $this->mTagHooks
[$name] ) ) {
4219 # Workaround for PHP bug 35229 and similar
4220 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4221 throw new MWException( "Tag hook for $name is not callable\n" );
4223 $output = call_user_func_array( $this->mTagHooks
[$name],
4224 array( $content, $attributes, $this, $frame ) );
4225 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4226 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4227 if ( !is_callable( $callback ) ) {
4228 throw new MWException( "Tag hook for $name is not callable\n" );
4231 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4233 $output = '<span class="error">Invalid tag extension name: ' .
4234 htmlspecialchars( $name ) . '</span>';
4237 if ( is_array( $output ) ) {
4238 # Extract flags to local scope (to override $markerType)
4240 $output = $flags[0];
4245 if ( is_null( $attrText ) ) {
4248 if ( isset( $params['attributes'] ) ) {
4249 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4250 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4251 htmlspecialchars( $attrValue ) . '"';
4254 if ( $content === null ) {
4255 $output = "<$name$attrText/>";
4257 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4258 $output = "<$name$attrText>$content$close";
4262 if ( $markerType === 'none' ) {
4264 } elseif ( $markerType === 'nowiki' ) {
4265 $this->mStripState
->addNoWiki( $marker, $output );
4266 } elseif ( $markerType === 'general' ) {
4267 $this->mStripState
->addGeneral( $marker, $output );
4269 throw new MWException( __METHOD__
. ': invalid marker type' );
4275 * Increment an include size counter
4277 * @param string $type The type of expansion
4278 * @param int $size The size of the text
4279 * @return bool False if this inclusion would take it over the maximum, true otherwise
4281 public function incrementIncludeSize( $type, $size ) {
4282 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4285 $this->mIncludeSizes
[$type] +
= $size;
4291 * Increment the expensive function count
4293 * @return bool False if the limit has been exceeded
4295 public function incrementExpensiveFunctionCount() {
4296 $this->mExpensiveFunctionCount++
;
4297 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4301 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4302 * Fills $this->mDoubleUnderscores, returns the modified text
4304 * @param string $text
4308 public function doDoubleUnderscore( $text ) {
4309 wfProfileIn( __METHOD__
);
4311 # The position of __TOC__ needs to be recorded
4312 $mw = MagicWord
::get( 'toc' );
4313 if ( $mw->match( $text ) ) {
4314 $this->mShowToc
= true;
4315 $this->mForceTocPosition
= true;
4317 # Set a placeholder. At the end we'll fill it in with the TOC.
4318 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4320 # Only keep the first one.
4321 $text = $mw->replace( '', $text );
4324 # Now match and remove the rest of them
4325 $mwa = MagicWord
::getDoubleUnderscoreArray();
4326 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4328 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4329 $this->mOutput
->mNoGallery
= true;
4331 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4332 $this->mShowToc
= false;
4334 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4335 && $this->mTitle
->getNamespace() == NS_CATEGORY
4337 $this->addTrackingCategory( 'hidden-category-category' );
4339 # (bug 8068) Allow control over whether robots index a page.
4341 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4342 # is not desirable, the last one on the page should win.
4343 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4344 $this->mOutput
->setIndexPolicy( 'noindex' );
4345 $this->addTrackingCategory( 'noindex-category' );
4347 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4348 $this->mOutput
->setIndexPolicy( 'index' );
4349 $this->addTrackingCategory( 'index-category' );
4352 # Cache all double underscores in the database
4353 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4354 $this->mOutput
->setProperty( $key, '' );
4357 wfProfileOut( __METHOD__
);
4362 * @see ParserOutput::addTrackingCategory()
4363 * @param string $msg Message key
4364 * @return bool Whether the addition was successful
4366 public function addTrackingCategory( $msg ) {
4367 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4371 * This function accomplishes several tasks:
4372 * 1) Auto-number headings if that option is enabled
4373 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4374 * 3) Add a Table of contents on the top for users who have enabled the option
4375 * 4) Auto-anchor headings
4377 * It loops through all headlines, collects the necessary data, then splits up the
4378 * string and re-inserts the newly formatted headlines.
4380 * @param string $text
4381 * @param string $origText Original, untouched wikitext
4382 * @param bool $isMain
4383 * @return mixed|string
4386 public function formatHeadings( $text, $origText, $isMain = true ) {
4387 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4389 # Inhibit editsection links if requested in the page
4390 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4391 $maybeShowEditLink = $showEditLink = false;
4393 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4394 $showEditLink = $this->mOptions
->getEditSection();
4396 if ( $showEditLink ) {
4397 $this->mOutput
->setEditSectionTokens( true );
4400 # Get all headlines for numbering them and adding funky stuff like [edit]
4401 # links - this is for later, but we need the number of headlines right now
4403 $numMatches = preg_match_all(
4404 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4409 # if there are fewer than 4 headlines in the article, do not show TOC
4410 # unless it's been explicitly enabled.
4411 $enoughToc = $this->mShowToc
&&
4412 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4414 # Allow user to stipulate that a page should have a "new section"
4415 # link added via __NEWSECTIONLINK__
4416 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4417 $this->mOutput
->setNewSection( true );
4420 # Allow user to remove the "new section"
4421 # link via __NONEWSECTIONLINK__
4422 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4423 $this->mOutput
->hideNewSection( true );
4426 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4427 # override above conditions and always show TOC above first header
4428 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4429 $this->mShowToc
= true;
4437 # Ugh .. the TOC should have neat indentation levels which can be
4438 # passed to the skin functions. These are determined here
4442 $sublevelCount = array();
4443 $levelCount = array();
4448 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4449 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4450 $oldType = $this->mOutputType
;
4451 $this->setOutputType( self
::OT_WIKI
);
4452 $frame = $this->getPreprocessor()->newFrame();
4453 $root = $this->preprocessToDom( $origText );
4454 $node = $root->getFirstChild();
4459 foreach ( $matches[3] as $headline ) {
4460 $isTemplate = false;
4462 $sectionIndex = false;
4464 $markerMatches = array();
4465 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4466 $serial = $markerMatches[1];
4467 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4468 $isTemplate = ( $titleText != $baseTitleText );
4469 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4473 $prevlevel = $level;
4475 $level = $matches[1][$headlineCount];
4477 if ( $level > $prevlevel ) {
4478 # Increase TOC level
4480 $sublevelCount[$toclevel] = 0;
4481 if ( $toclevel < $wgMaxTocLevel ) {
4482 $prevtoclevel = $toclevel;
4483 $toc .= Linker
::tocIndent();
4486 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4487 # Decrease TOC level, find level to jump to
4489 for ( $i = $toclevel; $i > 0; $i-- ) {
4490 if ( $levelCount[$i] == $level ) {
4491 # Found last matching level
4494 } elseif ( $levelCount[$i] < $level ) {
4495 # Found first matching level below current level
4503 if ( $toclevel < $wgMaxTocLevel ) {
4504 if ( $prevtoclevel < $wgMaxTocLevel ) {
4505 # Unindent only if the previous toc level was shown :p
4506 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4507 $prevtoclevel = $toclevel;
4509 $toc .= Linker
::tocLineEnd();
4513 # No change in level, end TOC line
4514 if ( $toclevel < $wgMaxTocLevel ) {
4515 $toc .= Linker
::tocLineEnd();
4519 $levelCount[$toclevel] = $level;
4521 # count number of headlines for each level
4522 $sublevelCount[$toclevel]++
;
4524 for ( $i = 1; $i <= $toclevel; $i++
) {
4525 if ( !empty( $sublevelCount[$i] ) ) {
4529 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4534 # The safe header is a version of the header text safe to use for links
4536 # Remove link placeholders by the link text.
4537 # <!--LINK number-->
4539 # link text with suffix
4540 # Do this before unstrip since link text can contain strip markers
4541 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4543 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4544 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4546 # Strip out HTML (first regex removes any tag not allowed)
4548 # * <sup> and <sub> (bug 8393)
4551 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4553 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4554 # to allow setting directionality in toc items.
4555 $tocline = preg_replace(
4557 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4558 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4560 array( '', '<$1>' ),
4563 $tocline = trim( $tocline );
4565 # For the anchor, strip out HTML-y stuff period
4566 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4567 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4569 # Save headline for section edit hint before it's escaped
4570 $headlineHint = $safeHeadline;
4572 if ( $wgExperimentalHtmlIds ) {
4573 # For reverse compatibility, provide an id that's
4574 # HTML4-compatible, like we used to.
4576 # It may be worth noting, academically, that it's possible for
4577 # the legacy anchor to conflict with a non-legacy headline
4578 # anchor on the page. In this case likely the "correct" thing
4579 # would be to either drop the legacy anchors or make sure
4580 # they're numbered first. However, this would require people
4581 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4582 # manually, so let's not bother worrying about it.
4583 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4584 array( 'noninitial', 'legacy' ) );
4585 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4587 if ( $legacyHeadline == $safeHeadline ) {
4588 # No reason to have both (in fact, we can't)
4589 $legacyHeadline = false;
4592 $legacyHeadline = false;
4593 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4597 # HTML names must be case-insensitively unique (bug 10721).
4598 # This does not apply to Unicode characters per
4599 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4600 # @todo FIXME: We may be changing them depending on the current locale.
4601 $arrayKey = strtolower( $safeHeadline );
4602 if ( $legacyHeadline === false ) {
4603 $legacyArrayKey = false;
4605 $legacyArrayKey = strtolower( $legacyHeadline );
4608 # count how many in assoc. array so we can track dupes in anchors
4609 if ( isset( $refers[$arrayKey] ) ) {
4610 $refers[$arrayKey]++
;
4612 $refers[$arrayKey] = 1;
4614 if ( isset( $refers[$legacyArrayKey] ) ) {
4615 $refers[$legacyArrayKey]++
;
4617 $refers[$legacyArrayKey] = 1;
4620 # Don't number the heading if it is the only one (looks silly)
4621 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4622 # the two are different if the line contains a link
4623 $headline = Html
::element(
4625 array( 'class' => 'mw-headline-number' ),
4627 ) . ' ' . $headline;
4630 # Create the anchor for linking from the TOC to the section
4631 $anchor = $safeHeadline;
4632 $legacyAnchor = $legacyHeadline;
4633 if ( $refers[$arrayKey] > 1 ) {
4634 $anchor .= '_' . $refers[$arrayKey];
4636 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4637 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4639 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4640 $toc .= Linker
::tocLine( $anchor, $tocline,
4641 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4644 # Add the section to the section tree
4645 # Find the DOM node for this header
4646 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4647 while ( $node && !$noOffset ) {
4648 if ( $node->getName() === 'h' ) {
4649 $bits = $node->splitHeading();
4650 if ( $bits['i'] == $sectionIndex ) {
4654 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4655 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4656 $node = $node->getNextSibling();
4659 'toclevel' => $toclevel,
4662 'number' => $numbering,
4663 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4664 'fromtitle' => $titleText,
4665 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4666 'anchor' => $anchor,
4669 # give headline the correct <h#> tag
4670 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4671 // Output edit section links as markers with styles that can be customized by skins
4672 if ( $isTemplate ) {
4673 # Put a T flag in the section identifier, to indicate to extractSections()
4674 # that sections inside <includeonly> should be counted.
4675 $editsectionPage = $titleText;
4676 $editsectionSection = "T-$sectionIndex";
4677 $editsectionContent = null;
4679 $editsectionPage = $this->mTitle
->getPrefixedText();
4680 $editsectionSection = $sectionIndex;
4681 $editsectionContent = $headlineHint;
4683 // We use a bit of pesudo-xml for editsection markers. The
4684 // language converter is run later on. Using a UNIQ style marker
4685 // leads to the converter screwing up the tokens when it
4686 // converts stuff. And trying to insert strip tags fails too. At
4687 // this point all real inputted tags have already been escaped,
4688 // so we don't have to worry about a user trying to input one of
4689 // these markers directly. We use a page and section attribute
4690 // to stop the language converter from converting these
4691 // important bits of data, but put the headline hint inside a
4692 // content block because the language converter is supposed to
4693 // be able to convert that piece of data.
4694 // Gets replaced with html in ParserOutput::getText
4695 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4696 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4697 if ( $editsectionContent !== null ) {
4698 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4705 $head[$headlineCount] = Linker
::makeHeadline( $level,
4706 $matches['attrib'][$headlineCount], $anchor, $headline,
4707 $editlink, $legacyAnchor );
4712 $this->setOutputType( $oldType );
4714 # Never ever show TOC if no headers
4715 if ( $numVisible < 1 ) {
4720 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4721 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4723 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4724 $this->mOutput
->setTOCHTML( $toc );
4725 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4726 $this->mOutput
->addModules( 'mediawiki.toc' );
4730 $this->mOutput
->setSections( $tocraw );
4733 # split up and insert constructed headlines
4734 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4737 // build an array of document sections
4738 $sections = array();
4739 foreach ( $blocks as $block ) {
4740 // $head is zero-based, sections aren't.
4741 if ( empty( $head[$i - 1] ) ) {
4742 $sections[$i] = $block;
4744 $sections[$i] = $head[$i - 1] . $block;
4748 * Send a hook, one per section.
4749 * The idea here is to be able to make section-level DIVs, but to do so in a
4750 * lower-impact, more correct way than r50769
4753 * $section : the section number
4754 * &$sectionContent : ref to the content of the section
4755 * $showEditLinks : boolean describing whether this section has an edit link
4757 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4762 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4763 // append the TOC at the beginning
4764 // Top anchor now in skin
4765 $sections[0] = $sections[0] . $toc . "\n";
4768 $full .= join( '', $sections );
4770 if ( $this->mForceTocPosition
) {
4771 return str_replace( '<!--MWTOC-->', $toc, $full );
4778 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4779 * conversion, substitting signatures, {{subst:}} templates, etc.
4781 * @param string $text The text to transform
4782 * @param Title $title The Title object for the current article
4783 * @param User $user The User object describing the current user
4784 * @param ParserOptions $options Parsing options
4785 * @param bool $clearState Whether to clear the parser state first
4786 * @return string The altered wiki markup
4788 public function preSaveTransform( $text, Title
$title, User
$user,
4789 ParserOptions
$options, $clearState = true
4791 if ( $clearState ) {
4792 $magicScopeVariable = $this->lock();
4794 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4795 $this->setUser( $user );
4800 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4801 if ( $options->getPreSaveTransform() ) {
4802 $text = $this->pstPass2( $text, $user );
4804 $text = $this->mStripState
->unstripBoth( $text );
4806 $this->setUser( null ); #Reset
4812 * Pre-save transform helper function
4814 * @param string $text
4819 private function pstPass2( $text, $user ) {
4822 # Note: This is the timestamp saved as hardcoded wikitext to
4823 # the database, we use $wgContLang here in order to give
4824 # everyone the same signature and use the default one rather
4825 # than the one selected in each user's preferences.
4826 # (see also bug 12815)
4827 $ts = $this->mOptions
->getTimestamp();
4828 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4829 $ts = $timestamp->format( 'YmdHis' );
4830 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4832 # Allow translation of timezones through wiki. format() can return
4833 # whatever crap the system uses, localised or not, so we cannot
4834 # ship premade translations.
4835 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4836 $msg = wfMessage( $key )->inContentLanguage();
4837 if ( $msg->exists() ) {
4838 $tzMsg = $msg->text();
4841 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4843 # Variable replacement
4844 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4845 $text = $this->replaceVariables( $text );
4847 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4848 # which may corrupt this parser instance via its wfMessage()->text() call-
4851 $sigText = $this->getUserSig( $user );
4852 $text = strtr( $text, array(
4854 '~~~~' => "$sigText $d",
4858 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4859 $tc = '[' . Title
::legalChars() . ']';
4860 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4862 // [[ns:page (context)|]]
4863 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4864 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4865 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4866 // [[ns:page (context), context|]] (using either single or double-width comma)
4867 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4868 // [[|page]] (reverse pipe trick: add context from page title)
4869 $p2 = "/\[\[\\|($tc+)]]/";
4871 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4872 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4873 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4874 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4876 $t = $this->mTitle
->getText();
4878 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4879 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4880 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4881 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4883 # if there's no context, don't bother duplicating the title
4884 $text = preg_replace( $p2, '[[\\1]]', $text );
4887 # Trim trailing whitespace
4888 $text = rtrim( $text );
4894 * Fetch the user's signature text, if any, and normalize to
4895 * validated, ready-to-insert wikitext.
4896 * If you have pre-fetched the nickname or the fancySig option, you can
4897 * specify them here to save a database query.
4898 * Do not reuse this parser instance after calling getUserSig(),
4899 * as it may have changed if it's the $wgParser.
4902 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4903 * @param bool|null $fancySig whether the nicknname is the complete signature
4904 * or null to use default value
4907 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4908 global $wgMaxSigChars;
4910 $username = $user->getName();
4912 # If not given, retrieve from the user object.
4913 if ( $nickname === false ) {
4914 $nickname = $user->getOption( 'nickname' );
4917 if ( is_null( $fancySig ) ) {
4918 $fancySig = $user->getBoolOption( 'fancysig' );
4921 $nickname = $nickname == null ?
$username : $nickname;
4923 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4924 $nickname = $username;
4925 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4926 } elseif ( $fancySig !== false ) {
4927 # Sig. might contain markup; validate this
4928 if ( $this->validateSig( $nickname ) !== false ) {
4929 # Validated; clean up (if needed) and return it
4930 return $this->cleanSig( $nickname, true );
4932 # Failed to validate; fall back to the default
4933 $nickname = $username;
4934 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4938 # Make sure nickname doesnt get a sig in a sig
4939 $nickname = self
::cleanSigInSig( $nickname );
4941 # If we're still here, make it a link to the user page
4942 $userText = wfEscapeWikiText( $username );
4943 $nickText = wfEscapeWikiText( $nickname );
4944 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4946 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4947 ->title( $this->getTitle() )->text();
4951 * Check that the user's signature contains no bad XML
4953 * @param string $text
4954 * @return string|bool An expanded string, or false if invalid.
4956 public function validateSig( $text ) {
4957 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4961 * Clean up signature text
4963 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4964 * 2) Substitute all transclusions
4966 * @param string $text
4967 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4968 * @return string Signature text
4970 public function cleanSig( $text, $parsing = false ) {
4973 $magicScopeVariable = $this->lock();
4974 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4977 # Option to disable this feature
4978 if ( !$this->mOptions
->getCleanSignatures() ) {
4982 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4983 # => Move this logic to braceSubstitution()
4984 $substWord = MagicWord
::get( 'subst' );
4985 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4986 $substText = '{{' . $substWord->getSynonym( 0 );
4988 $text = preg_replace( $substRegex, $substText, $text );
4989 $text = self
::cleanSigInSig( $text );
4990 $dom = $this->preprocessToDom( $text );
4991 $frame = $this->getPreprocessor()->newFrame();
4992 $text = $frame->expand( $dom );
4995 $text = $this->mStripState
->unstripBoth( $text );
5002 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5004 * @param string $text
5005 * @return string Signature text with /~{3,5}/ removed
5007 public static function cleanSigInSig( $text ) {
5008 $text = preg_replace( '/~{3,5}/', '', $text );
5013 * Set up some variables which are usually set up in parse()
5014 * so that an external function can call some class members with confidence
5016 * @param Title|null $title
5017 * @param ParserOptions $options
5018 * @param int $outputType
5019 * @param bool $clearState
5021 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5022 $outputType, $clearState = true
5024 $this->startParse( $title, $options, $outputType, $clearState );
5028 * @param Title|null $title
5029 * @param ParserOptions $options
5030 * @param int $outputType
5031 * @param bool $clearState
5033 private function startParse( Title
$title = null, ParserOptions
$options,
5034 $outputType, $clearState = true
5036 $this->setTitle( $title );
5037 $this->mOptions
= $options;
5038 $this->setOutputType( $outputType );
5039 if ( $clearState ) {
5040 $this->clearState();
5045 * Wrapper for preprocess()
5047 * @param string $text The text to preprocess
5048 * @param ParserOptions $options Options
5049 * @param Title|null $title Title object or null to use $wgTitle
5052 public function transformMsg( $text, $options, $title = null ) {
5053 static $executing = false;
5055 # Guard against infinite recursion
5061 wfProfileIn( __METHOD__
);
5067 $text = $this->preprocess( $text, $title, $options );
5070 wfProfileOut( __METHOD__
);
5075 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5076 * The callback should have the following form:
5077 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5079 * Transform and return $text. Use $parser for any required context, e.g. use
5080 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5082 * Hooks may return extended information by returning an array, of which the
5083 * first numbered element (index 0) must be the return string, and all other
5084 * entries are extracted into local variables within an internal function
5085 * in the Parser class.
5087 * This interface (introduced r61913) appears to be undocumented, but
5088 * 'markerName' is used by some core tag hooks to override which strip
5089 * array their results are placed in. **Use great caution if attempting
5090 * this interface, as it is not documented and injudicious use could smash
5091 * private variables.**
5093 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5094 * @param callable $callback The callback function (and object) to use for the tag
5095 * @throws MWException
5096 * @return callable|null The old value of the mTagHooks array associated with the hook
5098 public function setHook( $tag, $callback ) {
5099 $tag = strtolower( $tag );
5100 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5101 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5103 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5104 $this->mTagHooks
[$tag] = $callback;
5105 if ( !in_array( $tag, $this->mStripList
) ) {
5106 $this->mStripList
[] = $tag;
5113 * As setHook(), but letting the contents be parsed.
5115 * Transparent tag hooks are like regular XML-style tag hooks, except they
5116 * operate late in the transformation sequence, on HTML instead of wikitext.
5118 * This is probably obsoleted by things dealing with parser frames?
5119 * The only extension currently using it is geoserver.
5122 * @todo better document or deprecate this
5124 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5125 * @param callable $callback The callback function (and object) to use for the tag
5126 * @throws MWException
5127 * @return callable|null The old value of the mTagHooks array associated with the hook
5129 public function setTransparentTagHook( $tag, $callback ) {
5130 $tag = strtolower( $tag );
5131 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5132 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5134 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5135 $this->mTransparentTagHooks
[$tag] = $callback;
5141 * Remove all tag hooks
5143 public function clearTagHooks() {
5144 $this->mTagHooks
= array();
5145 $this->mFunctionTagHooks
= array();
5146 $this->mStripList
= $this->mDefaultStripList
;
5150 * Create a function, e.g. {{sum:1|2|3}}
5151 * The callback function should have the form:
5152 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5154 * Or with SFH_OBJECT_ARGS:
5155 * function myParserFunction( $parser, $frame, $args ) { ... }
5157 * The callback may either return the text result of the function, or an array with the text
5158 * in element 0, and a number of flags in the other elements. The names of the flags are
5159 * specified in the keys. Valid flags are:
5160 * found The text returned is valid, stop processing the template. This
5162 * nowiki Wiki markup in the return value should be escaped
5163 * isHTML The returned text is HTML, armour it against wikitext transformation
5165 * @param string $id The magic word ID
5166 * @param callable $callback The callback function (and object) to use
5167 * @param int $flags A combination of the following flags:
5168 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5170 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5171 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5172 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5173 * the arguments, and to control the way they are expanded.
5175 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5176 * arguments, for instance:
5177 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5179 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5180 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5181 * working if/when this is changed.
5183 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5186 * Please read the documentation in includes/parser/Preprocessor.php for more information
5187 * about the methods available in PPFrame and PPNode.
5189 * @throws MWException
5190 * @return string|callable The old callback function for this name, if any
5192 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5195 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5196 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5198 # Add to function cache
5199 $mw = MagicWord
::get( $id );
5201 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5204 $synonyms = $mw->getSynonyms();
5205 $sensitive = intval( $mw->isCaseSensitive() );
5207 foreach ( $synonyms as $syn ) {
5209 if ( !$sensitive ) {
5210 $syn = $wgContLang->lc( $syn );
5213 if ( !( $flags & SFH_NO_HASH
) ) {
5216 # Remove trailing colon
5217 if ( substr( $syn, -1, 1 ) === ':' ) {
5218 $syn = substr( $syn, 0, -1 );
5220 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5226 * Get all registered function hook identifiers
5230 public function getFunctionHooks() {
5231 return array_keys( $this->mFunctionHooks
);
5235 * Create a tag function, e.g. "<test>some stuff</test>".
5236 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5237 * Unlike parser functions, their content is not preprocessed.
5238 * @param string $tag
5239 * @param callable $callback
5241 * @throws MWException
5244 public function setFunctionTagHook( $tag, $callback, $flags ) {
5245 $tag = strtolower( $tag );
5246 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5247 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5249 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5250 $this->mFunctionTagHooks
[$tag] : null;
5251 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5253 if ( !in_array( $tag, $this->mStripList
) ) {
5254 $this->mStripList
[] = $tag;
5261 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5262 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5263 * Placeholders created in Skin::makeLinkObj()
5265 * @param string $text
5266 * @param int $options
5268 * @return array Array of link CSS classes, indexed by PDBK.
5270 public function replaceLinkHolders( &$text, $options = 0 ) {
5271 return $this->mLinkHolders
->replace( $text );
5275 * Replace "<!--LINK-->" link placeholders with plain text of links
5276 * (not HTML-formatted).
5278 * @param string $text
5281 public function replaceLinkHoldersText( $text ) {
5282 return $this->mLinkHolders
->replaceText( $text );
5286 * Renders an image gallery from a text with one line per image.
5287 * text labels may be given by using |-style alternative text. E.g.
5288 * Image:one.jpg|The number "1"
5289 * Image:tree.jpg|A tree
5290 * given as text will return the HTML of a gallery with two images,
5291 * labeled 'The number "1"' and
5294 * @param string $text
5295 * @param array $params
5296 * @return string HTML
5298 public function renderImageGallery( $text, $params ) {
5299 wfProfileIn( __METHOD__
);
5302 if ( isset( $params['mode'] ) ) {
5303 $mode = $params['mode'];
5307 $ig = ImageGalleryBase
::factory( $mode );
5308 } catch ( MWException
$e ) {
5309 // If invalid type set, fallback to default.
5310 $ig = ImageGalleryBase
::factory( false );
5313 $ig->setContextTitle( $this->mTitle
);
5314 $ig->setShowBytes( false );
5315 $ig->setShowFilename( false );
5316 $ig->setParser( $this );
5317 $ig->setHideBadImages();
5318 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5320 if ( isset( $params['showfilename'] ) ) {
5321 $ig->setShowFilename( true );
5323 $ig->setShowFilename( false );
5325 if ( isset( $params['caption'] ) ) {
5326 $caption = $params['caption'];
5327 $caption = htmlspecialchars( $caption );
5328 $caption = $this->replaceInternalLinks( $caption );
5329 $ig->setCaptionHtml( $caption );
5331 if ( isset( $params['perrow'] ) ) {
5332 $ig->setPerRow( $params['perrow'] );
5334 if ( isset( $params['widths'] ) ) {
5335 $ig->setWidths( $params['widths'] );
5337 if ( isset( $params['heights'] ) ) {
5338 $ig->setHeights( $params['heights'] );
5340 $ig->setAdditionalOptions( $params );
5342 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5344 $lines = StringUtils
::explode( "\n", $text );
5345 foreach ( $lines as $line ) {
5346 # match lines like these:
5347 # Image:someimage.jpg|This is some image
5349 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5351 if ( count( $matches ) == 0 ) {
5355 if ( strpos( $matches[0], '%' ) !== false ) {
5356 $matches[1] = rawurldecode( $matches[1] );
5358 $title = Title
::newFromText( $matches[1], NS_FILE
);
5359 if ( is_null( $title ) ) {
5360 # Bogus title. Ignore these so we don't bomb out later.
5364 # We need to get what handler the file uses, to figure out parameters.
5365 # Note, a hook can overide the file name, and chose an entirely different
5366 # file (which potentially could be of a different type and have different handler).
5369 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5370 array( $this, $title, &$options, &$descQuery ) );
5371 # Don't register it now, as ImageGallery does that later.
5372 $file = $this->fetchFileNoRegister( $title, $options );
5373 $handler = $file ?
$file->getHandler() : false;
5375 wfProfileIn( __METHOD__
. '-getMagicWord' );
5377 'img_alt' => 'gallery-internal-alt',
5378 'img_link' => 'gallery-internal-link',
5381 $paramMap = $paramMap +
$handler->getParamMap();
5382 // We don't want people to specify per-image widths.
5383 // Additionally the width parameter would need special casing anyhow.
5384 unset( $paramMap['img_width'] );
5387 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5388 wfProfileOut( __METHOD__
. '-getMagicWord' );
5393 $handlerOptions = array();
5394 if ( isset( $matches[3] ) ) {
5395 // look for an |alt= definition while trying not to break existing
5396 // captions with multiple pipes (|) in it, until a more sensible grammar
5397 // is defined for images in galleries
5399 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5400 // splitting on '|' is a bit odd, and different from makeImage.
5401 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5402 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5404 foreach ( $parameterMatches as $parameterMatch ) {
5405 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5407 $paramName = $paramMap[$magicName];
5409 switch ( $paramName ) {
5410 case 'gallery-internal-alt':
5411 $alt = $this->stripAltText( $match, false );
5413 case 'gallery-internal-link':
5414 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5415 $chars = self
::EXT_LINK_URL_CLASS
;
5416 $prots = $this->mUrlProtocols
;
5417 //check to see if link matches an absolute url, if not then it must be a wiki link.
5418 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5421 $localLinkTitle = Title
::newFromText( $linkValue );
5422 if ( $localLinkTitle !== null ) {
5423 $link = $localLinkTitle->getLinkURL();
5428 // Must be a handler specific parameter.
5429 if ( $handler->validateParam( $paramName, $match ) ) {
5430 $handlerOptions[$paramName] = $match;
5432 // Guess not. Append it to the caption.
5433 wfDebug( "$parameterMatch failed parameter validation\n" );
5434 $label .= '|' . $parameterMatch;
5439 // concatenate all other pipes
5440 $label .= '|' . $parameterMatch;
5443 // remove the first pipe
5444 $label = substr( $label, 1 );
5447 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5449 $html = $ig->toHTML();
5450 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5451 wfProfileOut( __METHOD__
);
5456 * @param string $handler
5459 public function getImageParams( $handler ) {
5461 $handlerClass = get_class( $handler );
5465 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5466 # Initialise static lists
5467 static $internalParamNames = array(
5468 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5469 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5470 'bottom', 'text-bottom' ),
5471 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5472 'upright', 'border', 'link', 'alt', 'class' ),
5474 static $internalParamMap;
5475 if ( !$internalParamMap ) {
5476 $internalParamMap = array();
5477 foreach ( $internalParamNames as $type => $names ) {
5478 foreach ( $names as $name ) {
5479 $magicName = str_replace( '-', '_', "img_$name" );
5480 $internalParamMap[$magicName] = array( $type, $name );
5485 # Add handler params
5486 $paramMap = $internalParamMap;
5488 $handlerParamMap = $handler->getParamMap();
5489 foreach ( $handlerParamMap as $magic => $paramName ) {
5490 $paramMap[$magic] = array( 'handler', $paramName );
5493 $this->mImageParams
[$handlerClass] = $paramMap;
5494 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5496 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5500 * Parse image options text and use it to make an image
5502 * @param Title $title
5503 * @param string $options
5504 * @param LinkHolderArray|bool $holders
5505 * @return string HTML
5507 public function makeImage( $title, $options, $holders = false ) {
5508 # Check if the options text is of the form "options|alt text"
5510 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5511 # * left no resizing, just left align. label is used for alt= only
5512 # * right same, but right aligned
5513 # * none same, but not aligned
5514 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5515 # * center center the image
5516 # * frame Keep original image size, no magnify-button.
5517 # * framed Same as "frame"
5518 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5519 # * upright reduce width for upright images, rounded to full __0 px
5520 # * border draw a 1px border around the image
5521 # * alt Text for HTML alt attribute (defaults to empty)
5522 # * class Set a class for img node
5523 # * link Set the target of the image link. Can be external, interwiki, or local
5524 # vertical-align values (no % or length right now):
5534 $parts = StringUtils
::explode( "|", $options );
5536 # Give extensions a chance to select the file revision for us
5539 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5540 array( $this, $title, &$options, &$descQuery ) );
5541 # Fetch and register the file (file title may be different via hooks)
5542 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5545 $handler = $file ?
$file->getHandler() : false;
5547 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5550 $this->addTrackingCategory( 'broken-file-category' );
5553 # Process the input parameters
5555 $params = array( 'frame' => array(), 'handler' => array(),
5556 'horizAlign' => array(), 'vertAlign' => array() );
5557 $seenformat = false;
5558 foreach ( $parts as $part ) {
5559 $part = trim( $part );
5560 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5562 if ( isset( $paramMap[$magicName] ) ) {
5563 list( $type, $paramName ) = $paramMap[$magicName];
5565 # Special case; width and height come in one variable together
5566 if ( $type === 'handler' && $paramName === 'width' ) {
5567 $parsedWidthParam = $this->parseWidthParam( $value );
5568 if ( isset( $parsedWidthParam['width'] ) ) {
5569 $width = $parsedWidthParam['width'];
5570 if ( $handler->validateParam( 'width', $width ) ) {
5571 $params[$type]['width'] = $width;
5575 if ( isset( $parsedWidthParam['height'] ) ) {
5576 $height = $parsedWidthParam['height'];
5577 if ( $handler->validateParam( 'height', $height ) ) {
5578 $params[$type]['height'] = $height;
5582 # else no validation -- bug 13436
5584 if ( $type === 'handler' ) {
5585 # Validate handler parameter
5586 $validated = $handler->validateParam( $paramName, $value );
5588 # Validate internal parameters
5589 switch ( $paramName ) {
5593 # @todo FIXME: Possibly check validity here for
5594 # manualthumb? downstream behavior seems odd with
5595 # missing manual thumbs.
5597 $value = $this->stripAltText( $value, $holders );
5600 $chars = self
::EXT_LINK_URL_CLASS
;
5601 $prots = $this->mUrlProtocols
;
5602 if ( $value === '' ) {
5603 $paramName = 'no-link';
5606 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5607 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5608 $paramName = 'link-url';
5609 $this->mOutput
->addExternalLink( $value );
5610 if ( $this->mOptions
->getExternalLinkTarget() ) {
5611 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5616 $linkTitle = Title
::newFromText( $value );
5618 $paramName = 'link-title';
5619 $value = $linkTitle;
5620 $this->mOutput
->addLink( $linkTitle );
5628 // use first appearing option, discard others.
5629 $validated = ! $seenformat;
5633 # Most other things appear to be empty or numeric...
5634 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5639 $params[$type][$paramName] = $value;
5643 if ( !$validated ) {
5648 # Process alignment parameters
5649 if ( $params['horizAlign'] ) {
5650 $params['frame']['align'] = key( $params['horizAlign'] );
5652 if ( $params['vertAlign'] ) {
5653 $params['frame']['valign'] = key( $params['vertAlign'] );
5656 $params['frame']['caption'] = $caption;
5658 # Will the image be presented in a frame, with the caption below?
5659 $imageIsFramed = isset( $params['frame']['frame'] )
5660 ||
isset( $params['frame']['framed'] )
5661 ||
isset( $params['frame']['thumbnail'] )
5662 ||
isset( $params['frame']['manualthumb'] );
5664 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5665 # came to also set the caption, ordinary text after the image -- which
5666 # makes no sense, because that just repeats the text multiple times in
5667 # screen readers. It *also* came to set the title attribute.
5669 # Now that we have an alt attribute, we should not set the alt text to
5670 # equal the caption: that's worse than useless, it just repeats the
5671 # text. This is the framed/thumbnail case. If there's no caption, we
5672 # use the unnamed parameter for alt text as well, just for the time be-
5673 # ing, if the unnamed param is set and the alt param is not.
5675 # For the future, we need to figure out if we want to tweak this more,
5676 # e.g., introducing a title= parameter for the title; ignoring the un-
5677 # named parameter entirely for images without a caption; adding an ex-
5678 # plicit caption= parameter and preserving the old magic unnamed para-
5680 if ( $imageIsFramed ) { # Framed image
5681 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5682 # No caption or alt text, add the filename as the alt text so
5683 # that screen readers at least get some description of the image
5684 $params['frame']['alt'] = $title->getText();
5686 # Do not set $params['frame']['title'] because tooltips don't make sense
5688 } else { # Inline image
5689 if ( !isset( $params['frame']['alt'] ) ) {
5690 # No alt text, use the "caption" for the alt text
5691 if ( $caption !== '' ) {
5692 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5694 # No caption, fall back to using the filename for the
5696 $params['frame']['alt'] = $title->getText();
5699 # Use the "caption" for the tooltip text
5700 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5703 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5705 # Linker does the rest
5706 $time = isset( $options['time'] ) ?
$options['time'] : false;
5707 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5708 $time, $descQuery, $this->mOptions
->getThumbSize() );
5710 # Give the handler a chance to modify the parser object
5712 $handler->parserTransformHook( $this, $file );
5719 * @param string $caption
5720 * @param LinkHolderArray|bool $holders
5721 * @return mixed|string
5723 protected function stripAltText( $caption, $holders ) {
5724 # Strip bad stuff out of the title (tooltip). We can't just use
5725 # replaceLinkHoldersText() here, because if this function is called
5726 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5728 $tooltip = $holders->replaceText( $caption );
5730 $tooltip = $this->replaceLinkHoldersText( $caption );
5733 # make sure there are no placeholders in thumbnail attributes
5734 # that are later expanded to html- so expand them now and
5736 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5737 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5743 * Set a flag in the output object indicating that the content is dynamic and
5744 * shouldn't be cached.
5746 public function disableCache() {
5747 wfDebug( "Parser output marked as uncacheable.\n" );
5748 if ( !$this->mOutput
) {
5749 throw new MWException( __METHOD__
.
5750 " can only be called when actually parsing something" );
5752 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5753 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5757 * Callback from the Sanitizer for expanding items found in HTML attribute
5758 * values, so they can be safely tested and escaped.
5760 * @param string $text
5761 * @param bool|PPFrame $frame
5764 public function attributeStripCallback( &$text, $frame = false ) {
5765 $text = $this->replaceVariables( $text, $frame );
5766 $text = $this->mStripState
->unstripBoth( $text );
5775 public function getTags() {
5777 array_keys( $this->mTransparentTagHooks
),
5778 array_keys( $this->mTagHooks
),
5779 array_keys( $this->mFunctionTagHooks
)
5784 * Replace transparent tags in $text with the values given by the callbacks.
5786 * Transparent tag hooks are like regular XML-style tag hooks, except they
5787 * operate late in the transformation sequence, on HTML instead of wikitext.
5789 * @param string $text
5793 public function replaceTransparentTags( $text ) {
5795 $elements = array_keys( $this->mTransparentTagHooks
);
5796 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5797 $replacements = array();
5799 foreach ( $matches as $marker => $data ) {
5800 list( $element, $content, $params, $tag ) = $data;
5801 $tagName = strtolower( $element );
5802 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5803 $output = call_user_func_array(
5804 $this->mTransparentTagHooks
[$tagName],
5805 array( $content, $params, $this )
5810 $replacements[$marker] = $output;
5812 return strtr( $text, $replacements );
5816 * Break wikitext input into sections, and either pull or replace
5817 * some particular section's text.
5819 * External callers should use the getSection and replaceSection methods.
5821 * @param string $text Page wikitext
5822 * @param string|number $sectionId A section identifier string of the form:
5823 * "<flag1> - <flag2> - ... - <section number>"
5825 * Currently the only recognised flag is "T", which means the target section number
5826 * was derived during a template inclusion parse, in other words this is a template
5827 * section edit link. If no flags are given, it was an ordinary section edit link.
5828 * This flag is required to avoid a section numbering mismatch when a section is
5829 * enclosed by "<includeonly>" (bug 6563).
5831 * The section number 0 pulls the text before the first heading; other numbers will
5832 * pull the given section along with its lower-level subsections. If the section is
5833 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5835 * Section 0 is always considered to exist, even if it only contains the empty
5836 * string. If $text is the empty string and section 0 is replaced, $newText is
5839 * @param string $mode One of "get" or "replace"
5840 * @param string $newText Replacement text for section data.
5841 * @return string For "get", the extracted section text.
5842 * for "replace", the whole page with the section replaced.
5844 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5845 global $wgTitle; # not generally used but removes an ugly failure mode
5847 $magicScopeVariable = $this->lock();
5848 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5850 $frame = $this->getPreprocessor()->newFrame();
5852 # Process section extraction flags
5854 $sectionParts = explode( '-', $sectionId );
5855 $sectionIndex = array_pop( $sectionParts );
5856 foreach ( $sectionParts as $part ) {
5857 if ( $part === 'T' ) {
5858 $flags |
= self
::PTD_FOR_INCLUSION
;
5862 # Check for empty input
5863 if ( strval( $text ) === '' ) {
5864 # Only sections 0 and T-0 exist in an empty document
5865 if ( $sectionIndex == 0 ) {
5866 if ( $mode === 'get' ) {
5872 if ( $mode === 'get' ) {
5880 # Preprocess the text
5881 $root = $this->preprocessToDom( $text, $flags );
5883 # <h> nodes indicate section breaks
5884 # They can only occur at the top level, so we can find them by iterating the root's children
5885 $node = $root->getFirstChild();
5887 # Find the target section
5888 if ( $sectionIndex == 0 ) {
5889 # Section zero doesn't nest, level=big
5890 $targetLevel = 1000;
5893 if ( $node->getName() === 'h' ) {
5894 $bits = $node->splitHeading();
5895 if ( $bits['i'] == $sectionIndex ) {
5896 $targetLevel = $bits['level'];
5900 if ( $mode === 'replace' ) {
5901 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5903 $node = $node->getNextSibling();
5909 if ( $mode === 'get' ) {
5916 # Find the end of the section, including nested sections
5918 if ( $node->getName() === 'h' ) {
5919 $bits = $node->splitHeading();
5920 $curLevel = $bits['level'];
5921 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5925 if ( $mode === 'get' ) {
5926 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5928 $node = $node->getNextSibling();
5931 # Write out the remainder (in replace mode only)
5932 if ( $mode === 'replace' ) {
5933 # Output the replacement text
5934 # Add two newlines on -- trailing whitespace in $newText is conventionally
5935 # stripped by the editor, so we need both newlines to restore the paragraph gap
5936 # Only add trailing whitespace if there is newText
5937 if ( $newText != "" ) {
5938 $outText .= $newText . "\n\n";
5942 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5943 $node = $node->getNextSibling();
5947 if ( is_string( $outText ) ) {
5948 # Re-insert stripped tags
5949 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5956 * This function returns the text of a section, specified by a number ($section).
5957 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5958 * the first section before any such heading (section 0).
5960 * If a section contains subsections, these are also returned.
5962 * @param string $text Text to look in
5963 * @param string|number $sectionId Section identifier as a number or string
5964 * (e.g. 0, 1 or 'T-1').
5965 * @param string $defaultText Default to return if section is not found
5967 * @return string Text of the requested section
5969 public function getSection( $text, $sectionId, $defaultText = '' ) {
5970 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5974 * This function returns $oldtext after the content of the section
5975 * specified by $section has been replaced with $text. If the target
5976 * section does not exist, $oldtext is returned unchanged.
5978 * @param string $oldText Former text of the article
5979 * @param string|number $sectionId Section identifier as a number or string
5980 * (e.g. 0, 1 or 'T-1').
5981 * @param string $newText Replacing text
5983 * @return string Modified text
5985 public function replaceSection( $oldText, $sectionId, $newText ) {
5986 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5990 * Get the ID of the revision we are parsing
5994 public function getRevisionId() {
5995 return $this->mRevisionId
;
5999 * Get the revision object for $this->mRevisionId
6001 * @return Revision|null Either a Revision object or null
6002 * @since 1.23 (public since 1.23)
6004 public function getRevisionObject() {
6005 if ( !is_null( $this->mRevisionObject
) ) {
6006 return $this->mRevisionObject
;
6008 if ( is_null( $this->mRevisionId
) ) {
6012 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6013 return $this->mRevisionObject
;
6017 * Get the timestamp associated with the current revision, adjusted for
6018 * the default server-local timestamp
6021 public function getRevisionTimestamp() {
6022 if ( is_null( $this->mRevisionTimestamp
) ) {
6023 wfProfileIn( __METHOD__
);
6027 $revObject = $this->getRevisionObject();
6028 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6030 # The cryptic '' timezone parameter tells to use the site-default
6031 # timezone offset instead of the user settings.
6033 # Since this value will be saved into the parser cache, served
6034 # to other users, and potentially even used inside links and such,
6035 # it needs to be consistent for all visitors.
6036 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6038 wfProfileOut( __METHOD__
);
6040 return $this->mRevisionTimestamp
;
6044 * Get the name of the user that edited the last revision
6046 * @return string User name
6048 public function getRevisionUser() {
6049 if ( is_null( $this->mRevisionUser
) ) {
6050 $revObject = $this->getRevisionObject();
6052 # if this template is subst: the revision id will be blank,
6053 # so just use the current user's name
6055 $this->mRevisionUser
= $revObject->getUserText();
6056 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6057 $this->mRevisionUser
= $this->getUser()->getName();
6060 return $this->mRevisionUser
;
6064 * Get the size of the revision
6066 * @return int|null Revision size
6068 public function getRevisionSize() {
6069 if ( is_null( $this->mRevisionSize
) ) {
6070 $revObject = $this->getRevisionObject();
6072 # if this variable is subst: the revision id will be blank,
6073 # so just use the parser input size, because the own substituation
6074 # will change the size.
6076 $this->mRevisionSize
= $revObject->getSize();
6077 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6078 $this->mRevisionSize
= $this->mInputSize
;
6081 return $this->mRevisionSize
;
6085 * Mutator for $mDefaultSort
6087 * @param string $sort New value
6089 public function setDefaultSort( $sort ) {
6090 $this->mDefaultSort
= $sort;
6091 $this->mOutput
->setProperty( 'defaultsort', $sort );
6095 * Accessor for $mDefaultSort
6096 * Will use the empty string if none is set.
6098 * This value is treated as a prefix, so the
6099 * empty string is equivalent to sorting by
6104 public function getDefaultSort() {
6105 if ( $this->mDefaultSort
!== false ) {
6106 return $this->mDefaultSort
;
6113 * Accessor for $mDefaultSort
6114 * Unlike getDefaultSort(), will return false if none is set
6116 * @return string|bool
6118 public function getCustomDefaultSort() {
6119 return $this->mDefaultSort
;
6123 * Try to guess the section anchor name based on a wikitext fragment
6124 * presumably extracted from a heading, for example "Header" from
6127 * @param string $text
6131 public function guessSectionNameFromWikiText( $text ) {
6132 # Strip out wikitext links(they break the anchor)
6133 $text = $this->stripSectionName( $text );
6134 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6135 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6139 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6140 * instead. For use in redirects, since IE6 interprets Redirect: headers
6141 * as something other than UTF-8 (apparently?), resulting in breakage.
6143 * @param string $text The section name
6144 * @return string An anchor
6146 public function guessLegacySectionNameFromWikiText( $text ) {
6147 # Strip out wikitext links(they break the anchor)
6148 $text = $this->stripSectionName( $text );
6149 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6150 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6154 * Strips a text string of wikitext for use in a section anchor
6156 * Accepts a text string and then removes all wikitext from the
6157 * string and leaves only the resultant text (i.e. the result of
6158 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6159 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6160 * to create valid section anchors by mimicing the output of the
6161 * parser when headings are parsed.
6163 * @param string $text Text string to be stripped of wikitext
6164 * for use in a Section anchor
6165 * @return string Filtered text string
6167 public function stripSectionName( $text ) {
6168 # Strip internal link markup
6169 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6170 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6172 # Strip external link markup
6173 # @todo FIXME: Not tolerant to blank link text
6174 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6175 # on how many empty links there are on the page - need to figure that out.
6176 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6178 # Parse wikitext quotes (italics & bold)
6179 $text = $this->doQuotes( $text );
6182 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6187 * strip/replaceVariables/unstrip for preprocessor regression testing
6189 * @param string $text
6190 * @param Title $title
6191 * @param ParserOptions $options
6192 * @param int $outputType
6196 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6197 $magicScopeVariable = $this->lock();
6198 $this->startParse( $title, $options, $outputType, true );
6200 $text = $this->replaceVariables( $text );
6201 $text = $this->mStripState
->unstripBoth( $text );
6202 $text = Sanitizer
::removeHTMLtags( $text );
6207 * @param string $text
6208 * @param Title $title
6209 * @param ParserOptions $options
6212 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6213 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6217 * @param string $text
6218 * @param Title $title
6219 * @param ParserOptions $options
6222 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6223 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6227 * Call a callback function on all regions of the given text that are not
6228 * inside strip markers, and replace those regions with the return value
6229 * of the callback. For example, with input:
6233 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6234 * two strings will be replaced with the value returned by the callback in
6238 * @param callable $callback
6242 public function markerSkipCallback( $s, $callback ) {
6245 while ( $i < strlen( $s ) ) {
6246 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6247 if ( $markerStart === false ) {
6248 $out .= call_user_func( $callback, substr( $s, $i ) );
6251 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6252 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6253 if ( $markerEnd === false ) {
6254 $out .= substr( $s, $markerStart );
6257 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6258 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6267 * Remove any strip markers found in the given text.
6269 * @param string $text Input string
6272 public function killMarkers( $text ) {
6273 return $this->mStripState
->killMarkers( $text );
6277 * Save the parser state required to convert the given half-parsed text to
6278 * HTML. "Half-parsed" in this context means the output of
6279 * recursiveTagParse() or internalParse(). This output has strip markers
6280 * from replaceVariables (extensionSubstitution() etc.), and link
6281 * placeholders from replaceLinkHolders().
6283 * Returns an array which can be serialized and stored persistently. This
6284 * array can later be loaded into another parser instance with
6285 * unserializeHalfParsedText(). The text can then be safely incorporated into
6286 * the return value of a parser hook.
6288 * @param string $text
6292 public function serializeHalfParsedText( $text ) {
6293 wfProfileIn( __METHOD__
);
6296 'version' => self
::HALF_PARSED_VERSION
,
6297 'stripState' => $this->mStripState
->getSubState( $text ),
6298 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6300 wfProfileOut( __METHOD__
);
6305 * Load the parser state given in the $data array, which is assumed to
6306 * have been generated by serializeHalfParsedText(). The text contents is
6307 * extracted from the array, and its markers are transformed into markers
6308 * appropriate for the current Parser instance. This transformed text is
6309 * returned, and can be safely included in the return value of a parser
6312 * If the $data array has been stored persistently, the caller should first
6313 * check whether it is still valid, by calling isValidHalfParsedText().
6315 * @param array $data Serialized data
6316 * @throws MWException
6319 public function unserializeHalfParsedText( $data ) {
6320 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6321 throw new MWException( __METHOD__
. ': invalid version' );
6324 # First, extract the strip state.
6325 $texts = array( $data['text'] );
6326 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6328 # Now renumber links
6329 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6331 # Should be good to go.
6336 * Returns true if the given array, presumed to be generated by
6337 * serializeHalfParsedText(), is compatible with the current version of the
6340 * @param array $data
6344 public function isValidHalfParsedText( $data ) {
6345 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6349 * Parsed a width param of imagelink like 300px or 200x300px
6351 * @param string $value
6356 public function parseWidthParam( $value ) {
6357 $parsedWidthParam = array();
6358 if ( $value === '' ) {
6359 return $parsedWidthParam;
6362 # (bug 13500) In both cases (width/height and width only),
6363 # permit trailing "px" for backward compatibility.
6364 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6365 $width = intval( $m[1] );
6366 $height = intval( $m[2] );
6367 $parsedWidthParam['width'] = $width;
6368 $parsedWidthParam['height'] = $height;
6369 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6370 $width = intval( $value );
6371 $parsedWidthParam['width'] = $width;
6373 return $parsedWidthParam;
6377 * Lock the current instance of the parser.
6379 * This is meant to stop someone from calling the parser
6380 * recursively and messing up all the strip state.
6382 * @throws MWException If parser is in a parse
6383 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6385 protected function lock() {
6386 if ( $this->mInParse
) {
6387 throw new MWException( "Parser state cleared while parsing. "
6388 . "Did you call Parser::parse recursively?" );
6390 $this->mInParse
= true;
6393 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6394 $that->mInParse
= false;
6397 return $recursiveCheck;
6401 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6403 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6404 * or if there is more than one <p/> tag in the input HTML.
6406 * @param string $html
6410 public static function stripOuterParagraph( $html ) {
6412 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6413 if ( strpos( $m[1], '</p>' ) === false ) {
6422 * Return this parser if it is not doing anything, otherwise
6423 * get a fresh parser. You can use this method by doing
6424 * $myParser = $wgParser->getFreshParser(), or more simply
6425 * $wgParser->getFreshParser()->parse( ... );
6426 * if you're unsure if $wgParser is safe to use.
6429 * @return Parser A parser object that is not parsing anything
6431 public function getFreshParser() {
6432 global $wgParserConf;
6433 if ( $this->mInParse
) {
6434 return new $wgParserConf['class']( $wgParserConf );