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 ||
$closematch ) {
2598 $paragraphStack = false;
2599 # @todo bug 5718: paragraph closed
2600 $output .= $this->closeParagraph();
2601 if ( $preOpenMatch && !$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 'currenttimestamp':
3159 $value = wfTimestamp( TS_MW
, $ts );
3161 case 'localtimestamp':
3162 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3164 case 'currentversion':
3165 $value = SpecialVersion
::getVersion();
3168 return $wgArticlePath;
3174 return $wgServerName;
3176 return $wgScriptPath;
3178 return $wgStylePath;
3179 case 'directionmark':
3180 return $pageLang->getDirMark();
3181 case 'contentlanguage':
3182 global $wgLanguageCode;
3183 return $wgLanguageCode;
3184 case 'cascadingsources':
3185 $value = CoreParserFunctions
::cascadingsources( $this );
3190 'ParserGetVariableValueSwitch',
3191 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3198 $this->mVarCache
[$index] = $value;
3205 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3209 public function initialiseVariables() {
3210 wfProfileIn( __METHOD__
);
3211 $variableIDs = MagicWord
::getVariableIDs();
3212 $substIDs = MagicWord
::getSubstIDs();
3214 $this->mVariables
= new MagicWordArray( $variableIDs );
3215 $this->mSubstWords
= new MagicWordArray( $substIDs );
3216 wfProfileOut( __METHOD__
);
3220 * Preprocess some wikitext and return the document tree.
3221 * This is the ghost of replace_variables().
3223 * @param string $text The text to parse
3224 * @param int $flags Bitwise combination of:
3225 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3226 * included. Default is to assume a direct page view.
3228 * The generated DOM tree must depend only on the input text and the flags.
3229 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3231 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3232 * change in the DOM tree for a given text, must be passed through the section identifier
3233 * in the section edit link and thus back to extractSections().
3235 * The output of this function is currently only cached in process memory, but a persistent
3236 * cache may be implemented at a later date which takes further advantage of these strict
3237 * dependency requirements.
3241 public function preprocessToDom( $text, $flags = 0 ) {
3242 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3247 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3253 public static function splitWhitespace( $s ) {
3254 $ltrimmed = ltrim( $s );
3255 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3256 $trimmed = rtrim( $ltrimmed );
3257 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3259 $w2 = substr( $ltrimmed, -$diff );
3263 return array( $w1, $trimmed, $w2 );
3267 * Replace magic variables, templates, and template arguments
3268 * with the appropriate text. Templates are substituted recursively,
3269 * taking care to avoid infinite loops.
3271 * Note that the substitution depends on value of $mOutputType:
3272 * self::OT_WIKI: only {{subst:}} templates
3273 * self::OT_PREPROCESS: templates but not extension tags
3274 * self::OT_HTML: all templates and extension tags
3276 * @param string $text The text to transform
3277 * @param bool|PPFrame $frame Object describing the arguments passed to the
3278 * template. Arguments may also be provided as an associative array, as
3279 * was the usual case before MW1.12. Providing arguments this way may be
3280 * useful for extensions wishing to perform variable replacement
3282 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3283 * double-brace expansion.
3286 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3287 # Is there any text? Also, Prevent too big inclusions!
3288 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3291 wfProfileIn( __METHOD__
);
3293 if ( $frame === false ) {
3294 $frame = $this->getPreprocessor()->newFrame();
3295 } elseif ( !( $frame instanceof PPFrame
) ) {
3296 wfDebug( __METHOD__
. " called using plain parameters instead of "
3297 . "a PPFrame instance. Creating custom frame.\n" );
3298 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3301 $dom = $this->preprocessToDom( $text );
3302 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3303 $text = $frame->expand( $dom, $flags );
3305 wfProfileOut( __METHOD__
);
3310 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3312 * @param array $args
3316 public static function createAssocArgs( $args ) {
3317 $assocArgs = array();
3319 foreach ( $args as $arg ) {
3320 $eqpos = strpos( $arg, '=' );
3321 if ( $eqpos === false ) {
3322 $assocArgs[$index++
] = $arg;
3324 $name = trim( substr( $arg, 0, $eqpos ) );
3325 $value = trim( substr( $arg, $eqpos +
1 ) );
3326 if ( $value === false ) {
3329 if ( $name !== false ) {
3330 $assocArgs[$name] = $value;
3339 * Warn the user when a parser limitation is reached
3340 * Will warn at most once the user per limitation type
3342 * @param string $limitationType Should be one of:
3343 * 'expensive-parserfunction' (corresponding messages:
3344 * 'expensive-parserfunction-warning',
3345 * 'expensive-parserfunction-category')
3346 * 'post-expand-template-argument' (corresponding messages:
3347 * 'post-expand-template-argument-warning',
3348 * 'post-expand-template-argument-category')
3349 * 'post-expand-template-inclusion' (corresponding messages:
3350 * 'post-expand-template-inclusion-warning',
3351 * 'post-expand-template-inclusion-category')
3352 * 'node-count-exceeded' (corresponding messages:
3353 * 'node-count-exceeded-warning',
3354 * 'node-count-exceeded-category')
3355 * 'expansion-depth-exceeded' (corresponding messages:
3356 * 'expansion-depth-exceeded-warning',
3357 * 'expansion-depth-exceeded-category')
3358 * @param string|int|null $current Current value
3359 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3360 * exceeded, provide the values (optional)
3362 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3363 # does no harm if $current and $max are present but are unnecessary for the message
3364 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3365 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3366 $this->mOutput
->addWarning( $warning );
3367 $this->addTrackingCategory( "$limitationType-category" );
3371 * Return the text of a template, after recursively
3372 * replacing any variables or templates within the template.
3374 * @param array $piece The parts of the template
3375 * $piece['title']: the title, i.e. the part before the |
3376 * $piece['parts']: the parameter array
3377 * $piece['lineStart']: whether the brace was at the start of a line
3378 * @param PPFrame $frame The current frame, contains template arguments
3380 * @return string The text of the template
3382 public function braceSubstitution( $piece, $frame ) {
3383 wfProfileIn( __METHOD__
);
3384 wfProfileIn( __METHOD__
. '-setup' );
3388 // $text has been filled
3390 // wiki markup in $text should be escaped
3392 // $text is HTML, armour it against wikitext transformation
3394 // Force interwiki transclusion to be done in raw mode not rendered
3395 $forceRawInterwiki = false;
3396 // $text is a DOM node needing expansion in a child frame
3397 $isChildObj = false;
3398 // $text is a DOM node needing expansion in the current frame
3399 $isLocalObj = false;
3401 # Title object, where $text came from
3404 # $part1 is the bit before the first |, and must contain only title characters.
3405 # Various prefixes will be stripped from it later.
3406 $titleWithSpaces = $frame->expand( $piece['title'] );
3407 $part1 = trim( $titleWithSpaces );
3410 # Original title text preserved for various purposes
3411 $originalTitle = $part1;
3413 # $args is a list of argument nodes, starting from index 0, not including $part1
3414 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3415 # below won't work b/c this $args isn't an object
3416 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3417 wfProfileOut( __METHOD__
. '-setup' );
3419 $titleProfileIn = null; // profile templates
3422 wfProfileIn( __METHOD__
. '-modifiers' );
3425 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3427 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3428 # Decide whether to expand template or keep wikitext as-is.
3429 if ( $this->ot
['wiki'] ) {
3430 if ( $substMatch === false ) {
3431 $literal = true; # literal when in PST with no prefix
3433 $literal = false; # expand when in PST with subst: or safesubst:
3436 if ( $substMatch == 'subst' ) {
3437 $literal = true; # literal when not in PST with plain subst:
3439 $literal = false; # expand when not in PST with safesubst: or no prefix
3443 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3450 if ( !$found && $args->getLength() == 0 ) {
3451 $id = $this->mVariables
->matchStartToEnd( $part1 );
3452 if ( $id !== false ) {
3453 $text = $this->getVariableValue( $id, $frame );
3454 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3455 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3461 # MSG, MSGNW and RAW
3464 $mwMsgnw = MagicWord
::get( 'msgnw' );
3465 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3468 # Remove obsolete MSG:
3469 $mwMsg = MagicWord
::get( 'msg' );
3470 $mwMsg->matchStartAndRemove( $part1 );
3474 $mwRaw = MagicWord
::get( 'raw' );
3475 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3476 $forceRawInterwiki = true;
3479 wfProfileOut( __METHOD__
. '-modifiers' );
3483 wfProfileIn( __METHOD__
. '-pfunc' );
3485 $colonPos = strpos( $part1, ':' );
3486 if ( $colonPos !== false ) {
3487 $func = substr( $part1, 0, $colonPos );
3488 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3489 for ( $i = 0; $i < $args->getLength(); $i++
) {
3490 $funcArgs[] = $args->item( $i );
3493 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3494 } catch ( Exception
$ex ) {
3495 wfProfileOut( __METHOD__
. '-pfunc' );
3496 wfProfileOut( __METHOD__
);
3500 # The interface for parser functions allows for extracting
3501 # flags into the local scope. Extract any forwarded flags
3505 wfProfileOut( __METHOD__
. '-pfunc' );
3508 # Finish mangling title and then check for loops.
3509 # Set $title to a Title object and $titleText to the PDBK
3512 # Split the title into page and subpage
3514 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3515 if ( $part1 !== $relative ) {
3517 $ns = $this->mTitle
->getNamespace();
3519 $title = Title
::newFromText( $part1, $ns );
3521 $titleText = $title->getPrefixedText();
3522 # Check for language variants if the template is not found
3523 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3524 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3526 # Do recursion depth check
3527 $limit = $this->mOptions
->getMaxTemplateDepth();
3528 if ( $frame->depth
>= $limit ) {
3530 $text = '<span class="error">'
3531 . wfMessage( 'parser-template-recursion-depth-warning' )
3532 ->numParams( $limit )->inContentLanguage()->text()
3538 # Load from database
3539 if ( !$found && $title ) {
3540 if ( !Profiler
::instance()->isPersistent() ) {
3541 # Too many unique items can kill profiling DBs/collectors
3542 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3543 wfProfileIn( $titleProfileIn ); // template in
3545 wfProfileIn( __METHOD__
. '-loadtpl' );
3546 if ( !$title->isExternal() ) {
3547 if ( $title->isSpecialPage()
3548 && $this->mOptions
->getAllowSpecialInclusion()
3549 && $this->ot
['html']
3551 // Pass the template arguments as URL parameters.
3552 // "uselang" will have no effect since the Language object
3553 // is forced to the one defined in ParserOptions.
3554 $pageArgs = array();
3555 $argsLength = $args->getLength();
3556 for ( $i = 0; $i < $argsLength; $i++
) {
3557 $bits = $args->item( $i )->splitArg();
3558 if ( strval( $bits['index'] ) === '' ) {
3559 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3560 $value = trim( $frame->expand( $bits['value'] ) );
3561 $pageArgs[$name] = $value;
3565 // Create a new context to execute the special page
3566 $context = new RequestContext
;
3567 $context->setTitle( $title );
3568 $context->setRequest( new FauxRequest( $pageArgs ) );
3569 $context->setUser( $this->getUser() );
3570 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3571 $ret = SpecialPageFactory
::capturePath( $title, $context );
3573 $text = $context->getOutput()->getHTML();
3574 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3577 $this->disableCache();
3579 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3580 $found = false; # access denied
3581 wfDebug( __METHOD__
. ": template inclusion denied for " .
3582 $title->getPrefixedDBkey() . "\n" );
3584 list( $text, $title ) = $this->getTemplateDom( $title );
3585 if ( $text !== false ) {
3591 # If the title is valid but undisplayable, make a link to it
3592 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3593 $text = "[[:$titleText]]";
3596 } elseif ( $title->isTrans() ) {
3597 # Interwiki transclusion
3598 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3599 $text = $this->interwikiTransclude( $title, 'render' );
3602 $text = $this->interwikiTransclude( $title, 'raw' );
3603 # Preprocess it like a template
3604 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3610 # Do infinite loop check
3611 # This has to be done after redirect resolution to avoid infinite loops via redirects
3612 if ( !$frame->loopCheck( $title ) ) {
3614 $text = '<span class="error">'
3615 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3617 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3619 wfProfileOut( __METHOD__
. '-loadtpl' );
3622 # If we haven't found text to substitute by now, we're done
3623 # Recover the source wikitext and return it
3625 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3626 if ( $titleProfileIn ) {
3627 wfProfileOut( $titleProfileIn ); // template out
3629 wfProfileOut( __METHOD__
);
3630 return array( 'object' => $text );
3633 # Expand DOM-style return values in a child frame
3634 if ( $isChildObj ) {
3635 # Clean up argument array
3636 $newFrame = $frame->newChild( $args, $title );
3639 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3640 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3641 # Expansion is eligible for the empty-frame cache
3642 $text = $newFrame->cachedExpand( $titleText, $text );
3644 # Uncached expansion
3645 $text = $newFrame->expand( $text );
3648 if ( $isLocalObj && $nowiki ) {
3649 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3650 $isLocalObj = false;
3653 if ( $titleProfileIn ) {
3654 wfProfileOut( $titleProfileIn ); // template out
3657 # Replace raw HTML by a placeholder
3659 $text = $this->insertStripItem( $text );
3660 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3661 # Escape nowiki-style return values
3662 $text = wfEscapeWikiText( $text );
3663 } elseif ( is_string( $text )
3664 && !$piece['lineStart']
3665 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3667 # Bug 529: if the template begins with a table or block-level
3668 # element, it should be treated as beginning a new line.
3669 # This behavior is somewhat controversial.
3670 $text = "\n" . $text;
3673 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3674 # Error, oversize inclusion
3675 if ( $titleText !== false ) {
3676 # Make a working, properly escaped link if possible (bug 23588)
3677 $text = "[[:$titleText]]";
3679 # This will probably not be a working link, but at least it may
3680 # provide some hint of where the problem is
3681 preg_replace( '/^:/', '', $originalTitle );
3682 $text = "[[:$originalTitle]]";
3684 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3685 . 'post-expand include size too large -->' );
3686 $this->limitationWarn( 'post-expand-template-inclusion' );
3689 if ( $isLocalObj ) {
3690 $ret = array( 'object' => $text );
3692 $ret = array( 'text' => $text );
3695 wfProfileOut( __METHOD__
);
3700 * Call a parser function and return an array with text and flags.
3702 * The returned array will always contain a boolean 'found', indicating
3703 * whether the parser function was found or not. It may also contain the
3705 * text: string|object, resulting wikitext or PP DOM object
3706 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3707 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3708 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3709 * nowiki: bool, wiki markup in $text should be escaped
3712 * @param PPFrame $frame The current frame, contains template arguments
3713 * @param string $function Function name
3714 * @param array $args Arguments to the function
3715 * @throws MWException
3718 public function callParserFunction( $frame, $function, array $args = array() ) {
3721 wfProfileIn( __METHOD__
);
3723 # Case sensitive functions
3724 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3725 $function = $this->mFunctionSynonyms
[1][$function];
3727 # Case insensitive functions
3728 $function = $wgContLang->lc( $function );
3729 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3730 $function = $this->mFunctionSynonyms
[0][$function];
3732 wfProfileOut( __METHOD__
);
3733 return array( 'found' => false );
3737 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3738 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3740 # Workaround for PHP bug 35229 and similar
3741 if ( !is_callable( $callback ) ) {
3742 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3743 wfProfileOut( __METHOD__
);
3744 throw new MWException( "Tag hook for $function is not callable\n" );
3747 $allArgs = array( &$this );
3748 if ( $flags & SFH_OBJECT_ARGS
) {
3749 # Convert arguments to PPNodes and collect for appending to $allArgs
3750 $funcArgs = array();
3751 foreach ( $args as $k => $v ) {
3752 if ( $v instanceof PPNode ||
$k === 0 ) {
3755 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3759 # Add a frame parameter, and pass the arguments as an array
3760 $allArgs[] = $frame;
3761 $allArgs[] = $funcArgs;
3763 # Convert arguments to plain text and append to $allArgs
3764 foreach ( $args as $k => $v ) {
3765 if ( $v instanceof PPNode
) {
3766 $allArgs[] = trim( $frame->expand( $v ) );
3767 } elseif ( is_int( $k ) && $k >= 0 ) {
3768 $allArgs[] = trim( $v );
3770 $allArgs[] = trim( "$k=$v" );
3775 $result = call_user_func_array( $callback, $allArgs );
3777 # The interface for function hooks allows them to return a wikitext
3778 # string or an array containing the string and any flags. This mungs
3779 # things around to match what this method should return.
3780 if ( !is_array( $result ) ) {
3786 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3787 $result['text'] = $result[0];
3789 unset( $result[0] );
3796 $preprocessFlags = 0;
3797 if ( isset( $result['noparse'] ) ) {
3798 $noparse = $result['noparse'];
3800 if ( isset( $result['preprocessFlags'] ) ) {
3801 $preprocessFlags = $result['preprocessFlags'];
3805 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3806 $result['isChildObj'] = true;
3808 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3809 wfProfileOut( __METHOD__
);
3815 * Get the semi-parsed DOM representation of a template with a given title,
3816 * and its redirect destination title. Cached.
3818 * @param Title $title
3822 public function getTemplateDom( $title ) {
3823 $cacheTitle = $title;
3824 $titleText = $title->getPrefixedDBkey();
3826 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3827 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3828 $title = Title
::makeTitle( $ns, $dbk );
3829 $titleText = $title->getPrefixedDBkey();
3831 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3832 return array( $this->mTplDomCache
[$titleText], $title );
3835 # Cache miss, go to the database
3836 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3838 if ( $text === false ) {
3839 $this->mTplDomCache
[$titleText] = false;
3840 return array( false, $title );
3843 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3844 $this->mTplDomCache
[$titleText] = $dom;
3846 if ( !$title->equals( $cacheTitle ) ) {
3847 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3848 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3851 return array( $dom, $title );
3855 * Fetch the current revision of a given title. Note that the revision
3856 * (and even the title) may not exist in the database, so everything
3857 * contributing to the output of the parser should use this method
3858 * where possible, rather than getting the revisions themselves. This
3859 * method also caches its results, so using it benefits performance.
3862 * @param Title $title
3865 public function fetchCurrentRevisionOfTitle( $title ) {
3866 $cacheKey = $title->getPrefixedDBkey();
3867 if ( !$this->currentRevisionCache
) {
3868 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3870 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3871 $this->currentRevisionCache
->set( $cacheKey,
3872 // Defaults to Parser::statelessFetchRevision()
3873 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3876 return $this->currentRevisionCache
->get( $cacheKey );
3880 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3881 * without passing them on to it.
3884 * @param Title $title
3885 * @param Parser|bool $parser
3888 public static function statelessFetchRevision( $title, $parser = false ) {
3889 return Revision
::newFromTitle( $title );
3893 * Fetch the unparsed text of a template and register a reference to it.
3894 * @param Title $title
3895 * @return array ( string or false, Title )
3897 public function fetchTemplateAndTitle( $title ) {
3898 // Defaults to Parser::statelessFetchTemplate()
3899 $templateCb = $this->mOptions
->getTemplateCallback();
3900 $stuff = call_user_func( $templateCb, $title, $this );
3901 $text = $stuff['text'];
3902 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3903 if ( isset( $stuff['deps'] ) ) {
3904 foreach ( $stuff['deps'] as $dep ) {
3905 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3906 if ( $dep['title']->equals( $this->getTitle() ) ) {
3907 // If we transclude ourselves, the final result
3908 // will change based on the new version of the page
3909 $this->mOutput
->setFlag( 'vary-revision' );
3913 return array( $text, $finalTitle );
3917 * Fetch the unparsed text of a template and register a reference to it.
3918 * @param Title $title
3919 * @return string|bool
3921 public function fetchTemplate( $title ) {
3922 $rv = $this->fetchTemplateAndTitle( $title );
3927 * Static function to get a template
3928 * Can be overridden via ParserOptions::setTemplateCallback().
3930 * @param Title $title
3931 * @param bool|Parser $parser
3935 public static function statelessFetchTemplate( $title, $parser = false ) {
3936 $text = $skip = false;
3937 $finalTitle = $title;
3940 # Loop to fetch the article, with up to 1 redirect
3941 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3942 # Give extensions a chance to select the revision instead
3943 $id = false; # Assume current
3944 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3945 array( $parser, $title, &$skip, &$id ) );
3951 'page_id' => $title->getArticleID(),
3958 $rev = Revision
::newFromId( $id );
3959 } elseif ( $parser ) {
3960 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3962 $rev = Revision
::newFromTitle( $title );
3964 $rev_id = $rev ?
$rev->getId() : 0;
3965 # If there is no current revision, there is no page
3966 if ( $id === false && !$rev ) {
3967 $linkCache = LinkCache
::singleton();
3968 $linkCache->addBadLinkObj( $title );
3973 'page_id' => $title->getArticleID(),
3974 'rev_id' => $rev_id );
3975 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3976 # We fetched a rev from a different title; register it too...
3978 'title' => $rev->getTitle(),
3979 'page_id' => $rev->getPage(),
3980 'rev_id' => $rev_id );
3984 $content = $rev->getContent();
3985 $text = $content ?
$content->getWikitextForTransclusion() : null;
3987 if ( $text === false ||
$text === null ) {
3991 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3993 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3994 if ( !$message->exists() ) {
3998 $content = $message->content();
3999 $text = $message->plain();
4007 $finalTitle = $title;
4008 $title = $content->getRedirectTarget();
4012 'finalTitle' => $finalTitle,
4017 * Fetch a file and its title and register a reference to it.
4018 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4019 * @param Title $title
4020 * @param array $options Array of options to RepoGroup::findFile
4023 public function fetchFile( $title, $options = array() ) {
4024 $res = $this->fetchFileAndTitle( $title, $options );
4029 * Fetch a file and its title and register a reference to it.
4030 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4031 * @param Title $title
4032 * @param array $options Array of options to RepoGroup::findFile
4033 * @return array ( File or false, Title of file )
4035 public function fetchFileAndTitle( $title, $options = array() ) {
4036 $file = $this->fetchFileNoRegister( $title, $options );
4038 $time = $file ?
$file->getTimestamp() : false;
4039 $sha1 = $file ?
$file->getSha1() : false;
4040 # Register the file as a dependency...
4041 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4042 if ( $file && !$title->equals( $file->getTitle() ) ) {
4043 # Update fetched file title
4044 $title = $file->getTitle();
4045 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4047 return array( $file, $title );
4051 * Helper function for fetchFileAndTitle.
4053 * Also useful if you need to fetch a file but not use it yet,
4054 * for example to get the file's handler.
4056 * @param Title $title
4057 * @param array $options Array of options to RepoGroup::findFile
4060 protected function fetchFileNoRegister( $title, $options = array() ) {
4061 if ( isset( $options['broken'] ) ) {
4062 $file = false; // broken thumbnail forced by hook
4063 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4064 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4065 } else { // get by (name,timestamp)
4066 $file = wfFindFile( $title, $options );
4072 * Transclude an interwiki link.
4074 * @param Title $title
4075 * @param string $action
4079 public function interwikiTransclude( $title, $action ) {
4080 global $wgEnableScaryTranscluding;
4082 if ( !$wgEnableScaryTranscluding ) {
4083 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4086 $url = $title->getFullURL( array( 'action' => $action ) );
4088 if ( strlen( $url ) > 255 ) {
4089 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4091 return $this->fetchScaryTemplateMaybeFromCache( $url );
4095 * @param string $url
4096 * @return mixed|string
4098 public function fetchScaryTemplateMaybeFromCache( $url ) {
4099 global $wgTranscludeCacheExpiry;
4100 $dbr = wfGetDB( DB_SLAVE
);
4101 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4102 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4103 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4105 return $obj->tc_contents
;
4108 $req = MWHttpRequest
::factory( $url );
4109 $status = $req->execute(); // Status object
4110 if ( $status->isOK() ) {
4111 $text = $req->getContent();
4112 } elseif ( $req->getStatus() != 200 ) {
4113 // Though we failed to fetch the content, this status is useless.
4114 return wfMessage( 'scarytranscludefailed-httpstatus' )
4115 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4117 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4120 $dbw = wfGetDB( DB_MASTER
);
4121 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4123 'tc_time' => $dbw->timestamp( time() ),
4124 'tc_contents' => $text
4130 * Triple brace replacement -- used for template arguments
4133 * @param array $piece
4134 * @param PPFrame $frame
4138 public function argSubstitution( $piece, $frame ) {
4139 wfProfileIn( __METHOD__
);
4142 $parts = $piece['parts'];
4143 $nameWithSpaces = $frame->expand( $piece['title'] );
4144 $argName = trim( $nameWithSpaces );
4146 $text = $frame->getArgument( $argName );
4147 if ( $text === false && $parts->getLength() > 0
4148 && ( $this->ot
['html']
4150 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4153 # No match in frame, use the supplied default
4154 $object = $parts->item( 0 )->getChildren();
4156 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4157 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4158 $this->limitationWarn( 'post-expand-template-argument' );
4161 if ( $text === false && $object === false ) {
4163 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4165 if ( $error !== false ) {
4168 if ( $object !== false ) {
4169 $ret = array( 'object' => $object );
4171 $ret = array( 'text' => $text );
4174 wfProfileOut( __METHOD__
);
4179 * Return the text to be used for a given extension tag.
4180 * This is the ghost of strip().
4182 * @param array $params Associative array of parameters:
4183 * name PPNode for the tag name
4184 * attr PPNode for unparsed text where tag attributes are thought to be
4185 * attributes Optional associative array of parsed attributes
4186 * inner Contents of extension element
4187 * noClose Original text did not have a close tag
4188 * @param PPFrame $frame
4190 * @throws MWException
4193 public function extensionSubstitution( $params, $frame ) {
4194 $name = $frame->expand( $params['name'] );
4195 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4196 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4197 $marker = "{$this->mUniqPrefix}-$name-"
4198 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4200 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4201 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4202 if ( $isFunctionTag ) {
4203 $markerType = 'none';
4205 $markerType = 'general';
4207 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4208 $name = strtolower( $name );
4209 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4210 if ( isset( $params['attributes'] ) ) {
4211 $attributes = $attributes +
$params['attributes'];
4214 if ( isset( $this->mTagHooks
[$name] ) ) {
4215 # Workaround for PHP bug 35229 and similar
4216 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4217 throw new MWException( "Tag hook for $name is not callable\n" );
4219 $output = call_user_func_array( $this->mTagHooks
[$name],
4220 array( $content, $attributes, $this, $frame ) );
4221 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4222 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4223 if ( !is_callable( $callback ) ) {
4224 throw new MWException( "Tag hook for $name is not callable\n" );
4227 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4229 $output = '<span class="error">Invalid tag extension name: ' .
4230 htmlspecialchars( $name ) . '</span>';
4233 if ( is_array( $output ) ) {
4234 # Extract flags to local scope (to override $markerType)
4236 $output = $flags[0];
4241 if ( is_null( $attrText ) ) {
4244 if ( isset( $params['attributes'] ) ) {
4245 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4246 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4247 htmlspecialchars( $attrValue ) . '"';
4250 if ( $content === null ) {
4251 $output = "<$name$attrText/>";
4253 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4254 $output = "<$name$attrText>$content$close";
4258 if ( $markerType === 'none' ) {
4260 } elseif ( $markerType === 'nowiki' ) {
4261 $this->mStripState
->addNoWiki( $marker, $output );
4262 } elseif ( $markerType === 'general' ) {
4263 $this->mStripState
->addGeneral( $marker, $output );
4265 throw new MWException( __METHOD__
. ': invalid marker type' );
4271 * Increment an include size counter
4273 * @param string $type The type of expansion
4274 * @param int $size The size of the text
4275 * @return bool False if this inclusion would take it over the maximum, true otherwise
4277 public function incrementIncludeSize( $type, $size ) {
4278 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4281 $this->mIncludeSizes
[$type] +
= $size;
4287 * Increment the expensive function count
4289 * @return bool False if the limit has been exceeded
4291 public function incrementExpensiveFunctionCount() {
4292 $this->mExpensiveFunctionCount++
;
4293 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4297 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4298 * Fills $this->mDoubleUnderscores, returns the modified text
4300 * @param string $text
4304 public function doDoubleUnderscore( $text ) {
4305 wfProfileIn( __METHOD__
);
4307 # The position of __TOC__ needs to be recorded
4308 $mw = MagicWord
::get( 'toc' );
4309 if ( $mw->match( $text ) ) {
4310 $this->mShowToc
= true;
4311 $this->mForceTocPosition
= true;
4313 # Set a placeholder. At the end we'll fill it in with the TOC.
4314 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4316 # Only keep the first one.
4317 $text = $mw->replace( '', $text );
4320 # Now match and remove the rest of them
4321 $mwa = MagicWord
::getDoubleUnderscoreArray();
4322 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4324 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4325 $this->mOutput
->mNoGallery
= true;
4327 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4328 $this->mShowToc
= false;
4330 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4331 && $this->mTitle
->getNamespace() == NS_CATEGORY
4333 $this->addTrackingCategory( 'hidden-category-category' );
4335 # (bug 8068) Allow control over whether robots index a page.
4337 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4338 # is not desirable, the last one on the page should win.
4339 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4340 $this->mOutput
->setIndexPolicy( 'noindex' );
4341 $this->addTrackingCategory( 'noindex-category' );
4343 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4344 $this->mOutput
->setIndexPolicy( 'index' );
4345 $this->addTrackingCategory( 'index-category' );
4348 # Cache all double underscores in the database
4349 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4350 $this->mOutput
->setProperty( $key, '' );
4353 wfProfileOut( __METHOD__
);
4358 * @see ParserOutput::addTrackingCategory()
4359 * @param string $msg Message key
4360 * @return bool Whether the addition was successful
4362 public function addTrackingCategory( $msg ) {
4363 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4367 * This function accomplishes several tasks:
4368 * 1) Auto-number headings if that option is enabled
4369 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4370 * 3) Add a Table of contents on the top for users who have enabled the option
4371 * 4) Auto-anchor headings
4373 * It loops through all headlines, collects the necessary data, then splits up the
4374 * string and re-inserts the newly formatted headlines.
4376 * @param string $text
4377 * @param string $origText Original, untouched wikitext
4378 * @param bool $isMain
4379 * @return mixed|string
4382 public function formatHeadings( $text, $origText, $isMain = true ) {
4383 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4385 # Inhibit editsection links if requested in the page
4386 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4387 $maybeShowEditLink = $showEditLink = false;
4389 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4390 $showEditLink = $this->mOptions
->getEditSection();
4392 if ( $showEditLink ) {
4393 $this->mOutput
->setEditSectionTokens( true );
4396 # Get all headlines for numbering them and adding funky stuff like [edit]
4397 # links - this is for later, but we need the number of headlines right now
4399 $numMatches = preg_match_all(
4400 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4405 # if there are fewer than 4 headlines in the article, do not show TOC
4406 # unless it's been explicitly enabled.
4407 $enoughToc = $this->mShowToc
&&
4408 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4410 # Allow user to stipulate that a page should have a "new section"
4411 # link added via __NEWSECTIONLINK__
4412 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4413 $this->mOutput
->setNewSection( true );
4416 # Allow user to remove the "new section"
4417 # link via __NONEWSECTIONLINK__
4418 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4419 $this->mOutput
->hideNewSection( true );
4422 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4423 # override above conditions and always show TOC above first header
4424 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4425 $this->mShowToc
= true;
4433 # Ugh .. the TOC should have neat indentation levels which can be
4434 # passed to the skin functions. These are determined here
4438 $sublevelCount = array();
4439 $levelCount = array();
4444 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4445 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4446 $oldType = $this->mOutputType
;
4447 $this->setOutputType( self
::OT_WIKI
);
4448 $frame = $this->getPreprocessor()->newFrame();
4449 $root = $this->preprocessToDom( $origText );
4450 $node = $root->getFirstChild();
4455 foreach ( $matches[3] as $headline ) {
4456 $isTemplate = false;
4458 $sectionIndex = false;
4460 $markerMatches = array();
4461 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4462 $serial = $markerMatches[1];
4463 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4464 $isTemplate = ( $titleText != $baseTitleText );
4465 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4469 $prevlevel = $level;
4471 $level = $matches[1][$headlineCount];
4473 if ( $level > $prevlevel ) {
4474 # Increase TOC level
4476 $sublevelCount[$toclevel] = 0;
4477 if ( $toclevel < $wgMaxTocLevel ) {
4478 $prevtoclevel = $toclevel;
4479 $toc .= Linker
::tocIndent();
4482 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4483 # Decrease TOC level, find level to jump to
4485 for ( $i = $toclevel; $i > 0; $i-- ) {
4486 if ( $levelCount[$i] == $level ) {
4487 # Found last matching level
4490 } elseif ( $levelCount[$i] < $level ) {
4491 # Found first matching level below current level
4499 if ( $toclevel < $wgMaxTocLevel ) {
4500 if ( $prevtoclevel < $wgMaxTocLevel ) {
4501 # Unindent only if the previous toc level was shown :p
4502 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4503 $prevtoclevel = $toclevel;
4505 $toc .= Linker
::tocLineEnd();
4509 # No change in level, end TOC line
4510 if ( $toclevel < $wgMaxTocLevel ) {
4511 $toc .= Linker
::tocLineEnd();
4515 $levelCount[$toclevel] = $level;
4517 # count number of headlines for each level
4518 $sublevelCount[$toclevel]++
;
4520 for ( $i = 1; $i <= $toclevel; $i++
) {
4521 if ( !empty( $sublevelCount[$i] ) ) {
4525 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4530 # The safe header is a version of the header text safe to use for links
4532 # Remove link placeholders by the link text.
4533 # <!--LINK number-->
4535 # link text with suffix
4536 # Do this before unstrip since link text can contain strip markers
4537 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4539 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4540 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4542 # Strip out HTML (first regex removes any tag not allowed)
4544 # * <sup> and <sub> (bug 8393)
4547 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4549 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4550 # to allow setting directionality in toc items.
4551 $tocline = preg_replace(
4553 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4554 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4556 array( '', '<$1>' ),
4559 $tocline = trim( $tocline );
4561 # For the anchor, strip out HTML-y stuff period
4562 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4563 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4565 # Save headline for section edit hint before it's escaped
4566 $headlineHint = $safeHeadline;
4568 if ( $wgExperimentalHtmlIds ) {
4569 # For reverse compatibility, provide an id that's
4570 # HTML4-compatible, like we used to.
4572 # It may be worth noting, academically, that it's possible for
4573 # the legacy anchor to conflict with a non-legacy headline
4574 # anchor on the page. In this case likely the "correct" thing
4575 # would be to either drop the legacy anchors or make sure
4576 # they're numbered first. However, this would require people
4577 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4578 # manually, so let's not bother worrying about it.
4579 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4580 array( 'noninitial', 'legacy' ) );
4581 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4583 if ( $legacyHeadline == $safeHeadline ) {
4584 # No reason to have both (in fact, we can't)
4585 $legacyHeadline = false;
4588 $legacyHeadline = false;
4589 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4593 # HTML names must be case-insensitively unique (bug 10721).
4594 # This does not apply to Unicode characters per
4595 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4596 # @todo FIXME: We may be changing them depending on the current locale.
4597 $arrayKey = strtolower( $safeHeadline );
4598 if ( $legacyHeadline === false ) {
4599 $legacyArrayKey = false;
4601 $legacyArrayKey = strtolower( $legacyHeadline );
4604 # count how many in assoc. array so we can track dupes in anchors
4605 if ( isset( $refers[$arrayKey] ) ) {
4606 $refers[$arrayKey]++
;
4608 $refers[$arrayKey] = 1;
4610 if ( isset( $refers[$legacyArrayKey] ) ) {
4611 $refers[$legacyArrayKey]++
;
4613 $refers[$legacyArrayKey] = 1;
4616 # Don't number the heading if it is the only one (looks silly)
4617 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4618 # the two are different if the line contains a link
4619 $headline = Html
::element(
4621 array( 'class' => 'mw-headline-number' ),
4623 ) . ' ' . $headline;
4626 # Create the anchor for linking from the TOC to the section
4627 $anchor = $safeHeadline;
4628 $legacyAnchor = $legacyHeadline;
4629 if ( $refers[$arrayKey] > 1 ) {
4630 $anchor .= '_' . $refers[$arrayKey];
4632 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4633 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4635 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4636 $toc .= Linker
::tocLine( $anchor, $tocline,
4637 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4640 # Add the section to the section tree
4641 # Find the DOM node for this header
4642 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4643 while ( $node && !$noOffset ) {
4644 if ( $node->getName() === 'h' ) {
4645 $bits = $node->splitHeading();
4646 if ( $bits['i'] == $sectionIndex ) {
4650 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4651 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4652 $node = $node->getNextSibling();
4655 'toclevel' => $toclevel,
4658 'number' => $numbering,
4659 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4660 'fromtitle' => $titleText,
4661 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4662 'anchor' => $anchor,
4665 # give headline the correct <h#> tag
4666 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4667 // Output edit section links as markers with styles that can be customized by skins
4668 if ( $isTemplate ) {
4669 # Put a T flag in the section identifier, to indicate to extractSections()
4670 # that sections inside <includeonly> should be counted.
4671 $editsectionPage = $titleText;
4672 $editsectionSection = "T-$sectionIndex";
4673 $editsectionContent = null;
4675 $editsectionPage = $this->mTitle
->getPrefixedText();
4676 $editsectionSection = $sectionIndex;
4677 $editsectionContent = $headlineHint;
4679 // We use a bit of pesudo-xml for editsection markers. The
4680 // language converter is run later on. Using a UNIQ style marker
4681 // leads to the converter screwing up the tokens when it
4682 // converts stuff. And trying to insert strip tags fails too. At
4683 // this point all real inputted tags have already been escaped,
4684 // so we don't have to worry about a user trying to input one of
4685 // these markers directly. We use a page and section attribute
4686 // to stop the language converter from converting these
4687 // important bits of data, but put the headline hint inside a
4688 // content block because the language converter is supposed to
4689 // be able to convert that piece of data.
4690 // Gets replaced with html in ParserOutput::getText
4691 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4692 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4693 if ( $editsectionContent !== null ) {
4694 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4701 $head[$headlineCount] = Linker
::makeHeadline( $level,
4702 $matches['attrib'][$headlineCount], $anchor, $headline,
4703 $editlink, $legacyAnchor );
4708 $this->setOutputType( $oldType );
4710 # Never ever show TOC if no headers
4711 if ( $numVisible < 1 ) {
4716 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4717 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4719 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4720 $this->mOutput
->setTOCHTML( $toc );
4721 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4722 $this->mOutput
->addModules( 'mediawiki.toc' );
4726 $this->mOutput
->setSections( $tocraw );
4729 # split up and insert constructed headlines
4730 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4733 // build an array of document sections
4734 $sections = array();
4735 foreach ( $blocks as $block ) {
4736 // $head is zero-based, sections aren't.
4737 if ( empty( $head[$i - 1] ) ) {
4738 $sections[$i] = $block;
4740 $sections[$i] = $head[$i - 1] . $block;
4744 * Send a hook, one per section.
4745 * The idea here is to be able to make section-level DIVs, but to do so in a
4746 * lower-impact, more correct way than r50769
4749 * $section : the section number
4750 * &$sectionContent : ref to the content of the section
4751 * $showEditLinks : boolean describing whether this section has an edit link
4753 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4758 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4759 // append the TOC at the beginning
4760 // Top anchor now in skin
4761 $sections[0] = $sections[0] . $toc . "\n";
4764 $full .= join( '', $sections );
4766 if ( $this->mForceTocPosition
) {
4767 return str_replace( '<!--MWTOC-->', $toc, $full );
4774 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4775 * conversion, substitting signatures, {{subst:}} templates, etc.
4777 * @param string $text The text to transform
4778 * @param Title $title The Title object for the current article
4779 * @param User $user The User object describing the current user
4780 * @param ParserOptions $options Parsing options
4781 * @param bool $clearState Whether to clear the parser state first
4782 * @return string The altered wiki markup
4784 public function preSaveTransform( $text, Title
$title, User
$user,
4785 ParserOptions
$options, $clearState = true
4787 if ( $clearState ) {
4788 $magicScopeVariable = $this->lock();
4790 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4791 $this->setUser( $user );
4796 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4797 if ( $options->getPreSaveTransform() ) {
4798 $text = $this->pstPass2( $text, $user );
4800 $text = $this->mStripState
->unstripBoth( $text );
4802 $this->setUser( null ); #Reset
4808 * Pre-save transform helper function
4810 * @param string $text
4815 private function pstPass2( $text, $user ) {
4818 # Note: This is the timestamp saved as hardcoded wikitext to
4819 # the database, we use $wgContLang here in order to give
4820 # everyone the same signature and use the default one rather
4821 # than the one selected in each user's preferences.
4822 # (see also bug 12815)
4823 $ts = $this->mOptions
->getTimestamp();
4824 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4825 $ts = $timestamp->format( 'YmdHis' );
4826 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4828 # Allow translation of timezones through wiki. format() can return
4829 # whatever crap the system uses, localised or not, so we cannot
4830 # ship premade translations.
4831 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4832 $msg = wfMessage( $key )->inContentLanguage();
4833 if ( $msg->exists() ) {
4834 $tzMsg = $msg->text();
4837 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4839 # Variable replacement
4840 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4841 $text = $this->replaceVariables( $text );
4843 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4844 # which may corrupt this parser instance via its wfMessage()->text() call-
4847 $sigText = $this->getUserSig( $user );
4848 $text = strtr( $text, array(
4850 '~~~~' => "$sigText $d",
4854 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4855 $tc = '[' . Title
::legalChars() . ']';
4856 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4858 // [[ns:page (context)|]]
4859 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4860 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4861 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4862 // [[ns:page (context), context|]] (using either single or double-width comma)
4863 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4864 // [[|page]] (reverse pipe trick: add context from page title)
4865 $p2 = "/\[\[\\|($tc+)]]/";
4867 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4868 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4869 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4870 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4872 $t = $this->mTitle
->getText();
4874 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4875 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4876 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4877 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4879 # if there's no context, don't bother duplicating the title
4880 $text = preg_replace( $p2, '[[\\1]]', $text );
4883 # Trim trailing whitespace
4884 $text = rtrim( $text );
4890 * Fetch the user's signature text, if any, and normalize to
4891 * validated, ready-to-insert wikitext.
4892 * If you have pre-fetched the nickname or the fancySig option, you can
4893 * specify them here to save a database query.
4894 * Do not reuse this parser instance after calling getUserSig(),
4895 * as it may have changed if it's the $wgParser.
4898 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4899 * @param bool|null $fancySig whether the nicknname is the complete signature
4900 * or null to use default value
4903 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4904 global $wgMaxSigChars;
4906 $username = $user->getName();
4908 # If not given, retrieve from the user object.
4909 if ( $nickname === false ) {
4910 $nickname = $user->getOption( 'nickname' );
4913 if ( is_null( $fancySig ) ) {
4914 $fancySig = $user->getBoolOption( 'fancysig' );
4917 $nickname = $nickname == null ?
$username : $nickname;
4919 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4920 $nickname = $username;
4921 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4922 } elseif ( $fancySig !== false ) {
4923 # Sig. might contain markup; validate this
4924 if ( $this->validateSig( $nickname ) !== false ) {
4925 # Validated; clean up (if needed) and return it
4926 return $this->cleanSig( $nickname, true );
4928 # Failed to validate; fall back to the default
4929 $nickname = $username;
4930 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4934 # Make sure nickname doesnt get a sig in a sig
4935 $nickname = self
::cleanSigInSig( $nickname );
4937 # If we're still here, make it a link to the user page
4938 $userText = wfEscapeWikiText( $username );
4939 $nickText = wfEscapeWikiText( $nickname );
4940 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4942 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4943 ->title( $this->getTitle() )->text();
4947 * Check that the user's signature contains no bad XML
4949 * @param string $text
4950 * @return string|bool An expanded string, or false if invalid.
4952 public function validateSig( $text ) {
4953 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4957 * Clean up signature text
4959 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4960 * 2) Substitute all transclusions
4962 * @param string $text
4963 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4964 * @return string Signature text
4966 public function cleanSig( $text, $parsing = false ) {
4969 $magicScopeVariable = $this->lock();
4970 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4973 # Option to disable this feature
4974 if ( !$this->mOptions
->getCleanSignatures() ) {
4978 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4979 # => Move this logic to braceSubstitution()
4980 $substWord = MagicWord
::get( 'subst' );
4981 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4982 $substText = '{{' . $substWord->getSynonym( 0 );
4984 $text = preg_replace( $substRegex, $substText, $text );
4985 $text = self
::cleanSigInSig( $text );
4986 $dom = $this->preprocessToDom( $text );
4987 $frame = $this->getPreprocessor()->newFrame();
4988 $text = $frame->expand( $dom );
4991 $text = $this->mStripState
->unstripBoth( $text );
4998 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5000 * @param string $text
5001 * @return string Signature text with /~{3,5}/ removed
5003 public static function cleanSigInSig( $text ) {
5004 $text = preg_replace( '/~{3,5}/', '', $text );
5009 * Set up some variables which are usually set up in parse()
5010 * so that an external function can call some class members with confidence
5012 * @param Title|null $title
5013 * @param ParserOptions $options
5014 * @param int $outputType
5015 * @param bool $clearState
5017 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5018 $outputType, $clearState = true
5020 $this->startParse( $title, $options, $outputType, $clearState );
5024 * @param Title|null $title
5025 * @param ParserOptions $options
5026 * @param int $outputType
5027 * @param bool $clearState
5029 private function startParse( Title
$title = null, ParserOptions
$options,
5030 $outputType, $clearState = true
5032 $this->setTitle( $title );
5033 $this->mOptions
= $options;
5034 $this->setOutputType( $outputType );
5035 if ( $clearState ) {
5036 $this->clearState();
5041 * Wrapper for preprocess()
5043 * @param string $text The text to preprocess
5044 * @param ParserOptions $options Options
5045 * @param Title|null $title Title object or null to use $wgTitle
5048 public function transformMsg( $text, $options, $title = null ) {
5049 static $executing = false;
5051 # Guard against infinite recursion
5057 wfProfileIn( __METHOD__
);
5063 $text = $this->preprocess( $text, $title, $options );
5066 wfProfileOut( __METHOD__
);
5071 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5072 * The callback should have the following form:
5073 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5075 * Transform and return $text. Use $parser for any required context, e.g. use
5076 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5078 * Hooks may return extended information by returning an array, of which the
5079 * first numbered element (index 0) must be the return string, and all other
5080 * entries are extracted into local variables within an internal function
5081 * in the Parser class.
5083 * This interface (introduced r61913) appears to be undocumented, but
5084 * 'markerName' is used by some core tag hooks to override which strip
5085 * array their results are placed in. **Use great caution if attempting
5086 * this interface, as it is not documented and injudicious use could smash
5087 * private variables.**
5089 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5090 * @param callable $callback The callback function (and object) to use for the tag
5091 * @throws MWException
5092 * @return callable|null The old value of the mTagHooks array associated with the hook
5094 public function setHook( $tag, $callback ) {
5095 $tag = strtolower( $tag );
5096 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5097 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5099 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5100 $this->mTagHooks
[$tag] = $callback;
5101 if ( !in_array( $tag, $this->mStripList
) ) {
5102 $this->mStripList
[] = $tag;
5109 * As setHook(), but letting the contents be parsed.
5111 * Transparent tag hooks are like regular XML-style tag hooks, except they
5112 * operate late in the transformation sequence, on HTML instead of wikitext.
5114 * This is probably obsoleted by things dealing with parser frames?
5115 * The only extension currently using it is geoserver.
5118 * @todo better document or deprecate this
5120 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5121 * @param callable $callback The callback function (and object) to use for the tag
5122 * @throws MWException
5123 * @return callable|null The old value of the mTagHooks array associated with the hook
5125 public function setTransparentTagHook( $tag, $callback ) {
5126 $tag = strtolower( $tag );
5127 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5128 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5130 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5131 $this->mTransparentTagHooks
[$tag] = $callback;
5137 * Remove all tag hooks
5139 public function clearTagHooks() {
5140 $this->mTagHooks
= array();
5141 $this->mFunctionTagHooks
= array();
5142 $this->mStripList
= $this->mDefaultStripList
;
5146 * Create a function, e.g. {{sum:1|2|3}}
5147 * The callback function should have the form:
5148 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5150 * Or with SFH_OBJECT_ARGS:
5151 * function myParserFunction( $parser, $frame, $args ) { ... }
5153 * The callback may either return the text result of the function, or an array with the text
5154 * in element 0, and a number of flags in the other elements. The names of the flags are
5155 * specified in the keys. Valid flags are:
5156 * found The text returned is valid, stop processing the template. This
5158 * nowiki Wiki markup in the return value should be escaped
5159 * isHTML The returned text is HTML, armour it against wikitext transformation
5161 * @param string $id The magic word ID
5162 * @param callable $callback The callback function (and object) to use
5163 * @param int $flags A combination of the following flags:
5164 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5166 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5167 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5168 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5169 * the arguments, and to control the way they are expanded.
5171 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5172 * arguments, for instance:
5173 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5175 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5176 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5177 * working if/when this is changed.
5179 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5182 * Please read the documentation in includes/parser/Preprocessor.php for more information
5183 * about the methods available in PPFrame and PPNode.
5185 * @throws MWException
5186 * @return string|callable The old callback function for this name, if any
5188 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5191 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5192 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5194 # Add to function cache
5195 $mw = MagicWord
::get( $id );
5197 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5200 $synonyms = $mw->getSynonyms();
5201 $sensitive = intval( $mw->isCaseSensitive() );
5203 foreach ( $synonyms as $syn ) {
5205 if ( !$sensitive ) {
5206 $syn = $wgContLang->lc( $syn );
5209 if ( !( $flags & SFH_NO_HASH
) ) {
5212 # Remove trailing colon
5213 if ( substr( $syn, -1, 1 ) === ':' ) {
5214 $syn = substr( $syn, 0, -1 );
5216 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5222 * Get all registered function hook identifiers
5226 public function getFunctionHooks() {
5227 return array_keys( $this->mFunctionHooks
);
5231 * Create a tag function, e.g. "<test>some stuff</test>".
5232 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5233 * Unlike parser functions, their content is not preprocessed.
5234 * @param string $tag
5235 * @param callable $callback
5237 * @throws MWException
5240 public function setFunctionTagHook( $tag, $callback, $flags ) {
5241 $tag = strtolower( $tag );
5242 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5243 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5245 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5246 $this->mFunctionTagHooks
[$tag] : null;
5247 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5249 if ( !in_array( $tag, $this->mStripList
) ) {
5250 $this->mStripList
[] = $tag;
5257 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5258 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5259 * Placeholders created in Skin::makeLinkObj()
5261 * @param string $text
5262 * @param int $options
5264 * @return array Array of link CSS classes, indexed by PDBK.
5266 public function replaceLinkHolders( &$text, $options = 0 ) {
5267 return $this->mLinkHolders
->replace( $text );
5271 * Replace "<!--LINK-->" link placeholders with plain text of links
5272 * (not HTML-formatted).
5274 * @param string $text
5277 public function replaceLinkHoldersText( $text ) {
5278 return $this->mLinkHolders
->replaceText( $text );
5282 * Renders an image gallery from a text with one line per image.
5283 * text labels may be given by using |-style alternative text. E.g.
5284 * Image:one.jpg|The number "1"
5285 * Image:tree.jpg|A tree
5286 * given as text will return the HTML of a gallery with two images,
5287 * labeled 'The number "1"' and
5290 * @param string $text
5291 * @param array $params
5292 * @return string HTML
5294 public function renderImageGallery( $text, $params ) {
5295 wfProfileIn( __METHOD__
);
5298 if ( isset( $params['mode'] ) ) {
5299 $mode = $params['mode'];
5303 $ig = ImageGalleryBase
::factory( $mode );
5304 } catch ( MWException
$e ) {
5305 // If invalid type set, fallback to default.
5306 $ig = ImageGalleryBase
::factory( false );
5309 $ig->setContextTitle( $this->mTitle
);
5310 $ig->setShowBytes( false );
5311 $ig->setShowFilename( false );
5312 $ig->setParser( $this );
5313 $ig->setHideBadImages();
5314 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5316 if ( isset( $params['showfilename'] ) ) {
5317 $ig->setShowFilename( true );
5319 $ig->setShowFilename( false );
5321 if ( isset( $params['caption'] ) ) {
5322 $caption = $params['caption'];
5323 $caption = htmlspecialchars( $caption );
5324 $caption = $this->replaceInternalLinks( $caption );
5325 $ig->setCaptionHtml( $caption );
5327 if ( isset( $params['perrow'] ) ) {
5328 $ig->setPerRow( $params['perrow'] );
5330 if ( isset( $params['widths'] ) ) {
5331 $ig->setWidths( $params['widths'] );
5333 if ( isset( $params['heights'] ) ) {
5334 $ig->setHeights( $params['heights'] );
5336 $ig->setAdditionalOptions( $params );
5338 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5340 $lines = StringUtils
::explode( "\n", $text );
5341 foreach ( $lines as $line ) {
5342 # match lines like these:
5343 # Image:someimage.jpg|This is some image
5345 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5347 if ( count( $matches ) == 0 ) {
5351 if ( strpos( $matches[0], '%' ) !== false ) {
5352 $matches[1] = rawurldecode( $matches[1] );
5354 $title = Title
::newFromText( $matches[1], NS_FILE
);
5355 if ( is_null( $title ) ) {
5356 # Bogus title. Ignore these so we don't bomb out later.
5360 # We need to get what handler the file uses, to figure out parameters.
5361 # Note, a hook can overide the file name, and chose an entirely different
5362 # file (which potentially could be of a different type and have different handler).
5365 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5366 array( $this, $title, &$options, &$descQuery ) );
5367 # Don't register it now, as ImageGallery does that later.
5368 $file = $this->fetchFileNoRegister( $title, $options );
5369 $handler = $file ?
$file->getHandler() : false;
5371 wfProfileIn( __METHOD__
. '-getMagicWord' );
5373 'img_alt' => 'gallery-internal-alt',
5374 'img_link' => 'gallery-internal-link',
5377 $paramMap = $paramMap +
$handler->getParamMap();
5378 // We don't want people to specify per-image widths.
5379 // Additionally the width parameter would need special casing anyhow.
5380 unset( $paramMap['img_width'] );
5383 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5384 wfProfileOut( __METHOD__
. '-getMagicWord' );
5389 $handlerOptions = array();
5390 if ( isset( $matches[3] ) ) {
5391 // look for an |alt= definition while trying not to break existing
5392 // captions with multiple pipes (|) in it, until a more sensible grammar
5393 // is defined for images in galleries
5395 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5396 // splitting on '|' is a bit odd, and different from makeImage.
5397 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5398 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5400 foreach ( $parameterMatches as $parameterMatch ) {
5401 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5403 $paramName = $paramMap[$magicName];
5405 switch ( $paramName ) {
5406 case 'gallery-internal-alt':
5407 $alt = $this->stripAltText( $match, false );
5409 case 'gallery-internal-link':
5410 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5411 $chars = self
::EXT_LINK_URL_CLASS
;
5412 $prots = $this->mUrlProtocols
;
5413 //check to see if link matches an absolute url, if not then it must be a wiki link.
5414 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5417 $localLinkTitle = Title
::newFromText( $linkValue );
5418 if ( $localLinkTitle !== null ) {
5419 $link = $localLinkTitle->getLinkURL();
5424 // Must be a handler specific parameter.
5425 if ( $handler->validateParam( $paramName, $match ) ) {
5426 $handlerOptions[$paramName] = $match;
5428 // Guess not. Append it to the caption.
5429 wfDebug( "$parameterMatch failed parameter validation\n" );
5430 $label .= '|' . $parameterMatch;
5435 // concatenate all other pipes
5436 $label .= '|' . $parameterMatch;
5439 // remove the first pipe
5440 $label = substr( $label, 1 );
5443 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5445 $html = $ig->toHTML();
5446 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5447 wfProfileOut( __METHOD__
);
5452 * @param string $handler
5455 public function getImageParams( $handler ) {
5457 $handlerClass = get_class( $handler );
5461 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5462 # Initialise static lists
5463 static $internalParamNames = array(
5464 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5465 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5466 'bottom', 'text-bottom' ),
5467 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5468 'upright', 'border', 'link', 'alt', 'class' ),
5470 static $internalParamMap;
5471 if ( !$internalParamMap ) {
5472 $internalParamMap = array();
5473 foreach ( $internalParamNames as $type => $names ) {
5474 foreach ( $names as $name ) {
5475 $magicName = str_replace( '-', '_', "img_$name" );
5476 $internalParamMap[$magicName] = array( $type, $name );
5481 # Add handler params
5482 $paramMap = $internalParamMap;
5484 $handlerParamMap = $handler->getParamMap();
5485 foreach ( $handlerParamMap as $magic => $paramName ) {
5486 $paramMap[$magic] = array( 'handler', $paramName );
5489 $this->mImageParams
[$handlerClass] = $paramMap;
5490 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5492 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5496 * Parse image options text and use it to make an image
5498 * @param Title $title
5499 * @param string $options
5500 * @param LinkHolderArray|bool $holders
5501 * @return string HTML
5503 public function makeImage( $title, $options, $holders = false ) {
5504 # Check if the options text is of the form "options|alt text"
5506 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5507 # * left no resizing, just left align. label is used for alt= only
5508 # * right same, but right aligned
5509 # * none same, but not aligned
5510 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5511 # * center center the image
5512 # * frame Keep original image size, no magnify-button.
5513 # * framed Same as "frame"
5514 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5515 # * upright reduce width for upright images, rounded to full __0 px
5516 # * border draw a 1px border around the image
5517 # * alt Text for HTML alt attribute (defaults to empty)
5518 # * class Set a class for img node
5519 # * link Set the target of the image link. Can be external, interwiki, or local
5520 # vertical-align values (no % or length right now):
5530 $parts = StringUtils
::explode( "|", $options );
5532 # Give extensions a chance to select the file revision for us
5535 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5536 array( $this, $title, &$options, &$descQuery ) );
5537 # Fetch and register the file (file title may be different via hooks)
5538 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5541 $handler = $file ?
$file->getHandler() : false;
5543 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5546 $this->addTrackingCategory( 'broken-file-category' );
5549 # Process the input parameters
5551 $params = array( 'frame' => array(), 'handler' => array(),
5552 'horizAlign' => array(), 'vertAlign' => array() );
5553 $seenformat = false;
5554 foreach ( $parts as $part ) {
5555 $part = trim( $part );
5556 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5558 if ( isset( $paramMap[$magicName] ) ) {
5559 list( $type, $paramName ) = $paramMap[$magicName];
5561 # Special case; width and height come in one variable together
5562 if ( $type === 'handler' && $paramName === 'width' ) {
5563 $parsedWidthParam = $this->parseWidthParam( $value );
5564 if ( isset( $parsedWidthParam['width'] ) ) {
5565 $width = $parsedWidthParam['width'];
5566 if ( $handler->validateParam( 'width', $width ) ) {
5567 $params[$type]['width'] = $width;
5571 if ( isset( $parsedWidthParam['height'] ) ) {
5572 $height = $parsedWidthParam['height'];
5573 if ( $handler->validateParam( 'height', $height ) ) {
5574 $params[$type]['height'] = $height;
5578 # else no validation -- bug 13436
5580 if ( $type === 'handler' ) {
5581 # Validate handler parameter
5582 $validated = $handler->validateParam( $paramName, $value );
5584 # Validate internal parameters
5585 switch ( $paramName ) {
5589 # @todo FIXME: Possibly check validity here for
5590 # manualthumb? downstream behavior seems odd with
5591 # missing manual thumbs.
5593 $value = $this->stripAltText( $value, $holders );
5596 $chars = self
::EXT_LINK_URL_CLASS
;
5597 $prots = $this->mUrlProtocols
;
5598 if ( $value === '' ) {
5599 $paramName = 'no-link';
5602 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5603 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5604 $paramName = 'link-url';
5605 $this->mOutput
->addExternalLink( $value );
5606 if ( $this->mOptions
->getExternalLinkTarget() ) {
5607 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5612 $linkTitle = Title
::newFromText( $value );
5614 $paramName = 'link-title';
5615 $value = $linkTitle;
5616 $this->mOutput
->addLink( $linkTitle );
5624 // use first appearing option, discard others.
5625 $validated = ! $seenformat;
5629 # Most other things appear to be empty or numeric...
5630 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5635 $params[$type][$paramName] = $value;
5639 if ( !$validated ) {
5644 # Process alignment parameters
5645 if ( $params['horizAlign'] ) {
5646 $params['frame']['align'] = key( $params['horizAlign'] );
5648 if ( $params['vertAlign'] ) {
5649 $params['frame']['valign'] = key( $params['vertAlign'] );
5652 $params['frame']['caption'] = $caption;
5654 # Will the image be presented in a frame, with the caption below?
5655 $imageIsFramed = isset( $params['frame']['frame'] )
5656 ||
isset( $params['frame']['framed'] )
5657 ||
isset( $params['frame']['thumbnail'] )
5658 ||
isset( $params['frame']['manualthumb'] );
5660 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5661 # came to also set the caption, ordinary text after the image -- which
5662 # makes no sense, because that just repeats the text multiple times in
5663 # screen readers. It *also* came to set the title attribute.
5665 # Now that we have an alt attribute, we should not set the alt text to
5666 # equal the caption: that's worse than useless, it just repeats the
5667 # text. This is the framed/thumbnail case. If there's no caption, we
5668 # use the unnamed parameter for alt text as well, just for the time be-
5669 # ing, if the unnamed param is set and the alt param is not.
5671 # For the future, we need to figure out if we want to tweak this more,
5672 # e.g., introducing a title= parameter for the title; ignoring the un-
5673 # named parameter entirely for images without a caption; adding an ex-
5674 # plicit caption= parameter and preserving the old magic unnamed para-
5676 if ( $imageIsFramed ) { # Framed image
5677 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5678 # No caption or alt text, add the filename as the alt text so
5679 # that screen readers at least get some description of the image
5680 $params['frame']['alt'] = $title->getText();
5682 # Do not set $params['frame']['title'] because tooltips don't make sense
5684 } else { # Inline image
5685 if ( !isset( $params['frame']['alt'] ) ) {
5686 # No alt text, use the "caption" for the alt text
5687 if ( $caption !== '' ) {
5688 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5690 # No caption, fall back to using the filename for the
5692 $params['frame']['alt'] = $title->getText();
5695 # Use the "caption" for the tooltip text
5696 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5699 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5701 # Linker does the rest
5702 $time = isset( $options['time'] ) ?
$options['time'] : false;
5703 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5704 $time, $descQuery, $this->mOptions
->getThumbSize() );
5706 # Give the handler a chance to modify the parser object
5708 $handler->parserTransformHook( $this, $file );
5715 * @param string $caption
5716 * @param LinkHolderArray|bool $holders
5717 * @return mixed|string
5719 protected function stripAltText( $caption, $holders ) {
5720 # Strip bad stuff out of the title (tooltip). We can't just use
5721 # replaceLinkHoldersText() here, because if this function is called
5722 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5724 $tooltip = $holders->replaceText( $caption );
5726 $tooltip = $this->replaceLinkHoldersText( $caption );
5729 # make sure there are no placeholders in thumbnail attributes
5730 # that are later expanded to html- so expand them now and
5732 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5733 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5739 * Set a flag in the output object indicating that the content is dynamic and
5740 * shouldn't be cached.
5742 public function disableCache() {
5743 wfDebug( "Parser output marked as uncacheable.\n" );
5744 if ( !$this->mOutput
) {
5745 throw new MWException( __METHOD__
.
5746 " can only be called when actually parsing something" );
5748 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5749 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5753 * Callback from the Sanitizer for expanding items found in HTML attribute
5754 * values, so they can be safely tested and escaped.
5756 * @param string $text
5757 * @param bool|PPFrame $frame
5760 public function attributeStripCallback( &$text, $frame = false ) {
5761 $text = $this->replaceVariables( $text, $frame );
5762 $text = $this->mStripState
->unstripBoth( $text );
5771 public function getTags() {
5773 array_keys( $this->mTransparentTagHooks
),
5774 array_keys( $this->mTagHooks
),
5775 array_keys( $this->mFunctionTagHooks
)
5780 * Replace transparent tags in $text with the values given by the callbacks.
5782 * Transparent tag hooks are like regular XML-style tag hooks, except they
5783 * operate late in the transformation sequence, on HTML instead of wikitext.
5785 * @param string $text
5789 public function replaceTransparentTags( $text ) {
5791 $elements = array_keys( $this->mTransparentTagHooks
);
5792 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5793 $replacements = array();
5795 foreach ( $matches as $marker => $data ) {
5796 list( $element, $content, $params, $tag ) = $data;
5797 $tagName = strtolower( $element );
5798 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5799 $output = call_user_func_array(
5800 $this->mTransparentTagHooks
[$tagName],
5801 array( $content, $params, $this )
5806 $replacements[$marker] = $output;
5808 return strtr( $text, $replacements );
5812 * Break wikitext input into sections, and either pull or replace
5813 * some particular section's text.
5815 * External callers should use the getSection and replaceSection methods.
5817 * @param string $text Page wikitext
5818 * @param string|number $sectionId A section identifier string of the form:
5819 * "<flag1> - <flag2> - ... - <section number>"
5821 * Currently the only recognised flag is "T", which means the target section number
5822 * was derived during a template inclusion parse, in other words this is a template
5823 * section edit link. If no flags are given, it was an ordinary section edit link.
5824 * This flag is required to avoid a section numbering mismatch when a section is
5825 * enclosed by "<includeonly>" (bug 6563).
5827 * The section number 0 pulls the text before the first heading; other numbers will
5828 * pull the given section along with its lower-level subsections. If the section is
5829 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5831 * Section 0 is always considered to exist, even if it only contains the empty
5832 * string. If $text is the empty string and section 0 is replaced, $newText is
5835 * @param string $mode One of "get" or "replace"
5836 * @param string $newText Replacement text for section data.
5837 * @return string For "get", the extracted section text.
5838 * for "replace", the whole page with the section replaced.
5840 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5841 global $wgTitle; # not generally used but removes an ugly failure mode
5843 $magicScopeVariable = $this->lock();
5844 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5846 $frame = $this->getPreprocessor()->newFrame();
5848 # Process section extraction flags
5850 $sectionParts = explode( '-', $sectionId );
5851 $sectionIndex = array_pop( $sectionParts );
5852 foreach ( $sectionParts as $part ) {
5853 if ( $part === 'T' ) {
5854 $flags |
= self
::PTD_FOR_INCLUSION
;
5858 # Check for empty input
5859 if ( strval( $text ) === '' ) {
5860 # Only sections 0 and T-0 exist in an empty document
5861 if ( $sectionIndex == 0 ) {
5862 if ( $mode === 'get' ) {
5868 if ( $mode === 'get' ) {
5876 # Preprocess the text
5877 $root = $this->preprocessToDom( $text, $flags );
5879 # <h> nodes indicate section breaks
5880 # They can only occur at the top level, so we can find them by iterating the root's children
5881 $node = $root->getFirstChild();
5883 # Find the target section
5884 if ( $sectionIndex == 0 ) {
5885 # Section zero doesn't nest, level=big
5886 $targetLevel = 1000;
5889 if ( $node->getName() === 'h' ) {
5890 $bits = $node->splitHeading();
5891 if ( $bits['i'] == $sectionIndex ) {
5892 $targetLevel = $bits['level'];
5896 if ( $mode === 'replace' ) {
5897 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5899 $node = $node->getNextSibling();
5905 if ( $mode === 'get' ) {
5912 # Find the end of the section, including nested sections
5914 if ( $node->getName() === 'h' ) {
5915 $bits = $node->splitHeading();
5916 $curLevel = $bits['level'];
5917 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5921 if ( $mode === 'get' ) {
5922 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5924 $node = $node->getNextSibling();
5927 # Write out the remainder (in replace mode only)
5928 if ( $mode === 'replace' ) {
5929 # Output the replacement text
5930 # Add two newlines on -- trailing whitespace in $newText is conventionally
5931 # stripped by the editor, so we need both newlines to restore the paragraph gap
5932 # Only add trailing whitespace if there is newText
5933 if ( $newText != "" ) {
5934 $outText .= $newText . "\n\n";
5938 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5939 $node = $node->getNextSibling();
5943 if ( is_string( $outText ) ) {
5944 # Re-insert stripped tags
5945 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5952 * This function returns the text of a section, specified by a number ($section).
5953 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5954 * the first section before any such heading (section 0).
5956 * If a section contains subsections, these are also returned.
5958 * @param string $text Text to look in
5959 * @param string|number $sectionId Section identifier as a number or string
5960 * (e.g. 0, 1 or 'T-1').
5961 * @param string $defaultText Default to return if section is not found
5963 * @return string Text of the requested section
5965 public function getSection( $text, $sectionId, $defaultText = '' ) {
5966 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5970 * This function returns $oldtext after the content of the section
5971 * specified by $section has been replaced with $text. If the target
5972 * section does not exist, $oldtext is returned unchanged.
5974 * @param string $oldText Former text of the article
5975 * @param string|number $sectionId Section identifier as a number or string
5976 * (e.g. 0, 1 or 'T-1').
5977 * @param string $newText Replacing text
5979 * @return string Modified text
5981 public function replaceSection( $oldText, $sectionId, $newText ) {
5982 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5986 * Get the ID of the revision we are parsing
5990 public function getRevisionId() {
5991 return $this->mRevisionId
;
5995 * Get the revision object for $this->mRevisionId
5997 * @return Revision|null Either a Revision object or null
5998 * @since 1.23 (public since 1.23)
6000 public function getRevisionObject() {
6001 if ( !is_null( $this->mRevisionObject
) ) {
6002 return $this->mRevisionObject
;
6004 if ( is_null( $this->mRevisionId
) ) {
6008 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6009 return $this->mRevisionObject
;
6013 * Get the timestamp associated with the current revision, adjusted for
6014 * the default server-local timestamp
6017 public function getRevisionTimestamp() {
6018 if ( is_null( $this->mRevisionTimestamp
) ) {
6019 wfProfileIn( __METHOD__
);
6023 $revObject = $this->getRevisionObject();
6024 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6026 # The cryptic '' timezone parameter tells to use the site-default
6027 # timezone offset instead of the user settings.
6029 # Since this value will be saved into the parser cache, served
6030 # to other users, and potentially even used inside links and such,
6031 # it needs to be consistent for all visitors.
6032 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6034 wfProfileOut( __METHOD__
);
6036 return $this->mRevisionTimestamp
;
6040 * Get the name of the user that edited the last revision
6042 * @return string User name
6044 public function getRevisionUser() {
6045 if ( is_null( $this->mRevisionUser
) ) {
6046 $revObject = $this->getRevisionObject();
6048 # if this template is subst: the revision id will be blank,
6049 # so just use the current user's name
6051 $this->mRevisionUser
= $revObject->getUserText();
6052 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6053 $this->mRevisionUser
= $this->getUser()->getName();
6056 return $this->mRevisionUser
;
6060 * Get the size of the revision
6062 * @return int|null Revision size
6064 public function getRevisionSize() {
6065 if ( is_null( $this->mRevisionSize
) ) {
6066 $revObject = $this->getRevisionObject();
6068 # if this variable is subst: the revision id will be blank,
6069 # so just use the parser input size, because the own substituation
6070 # will change the size.
6072 $this->mRevisionSize
= $revObject->getSize();
6073 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6074 $this->mRevisionSize
= $this->mInputSize
;
6077 return $this->mRevisionSize
;
6081 * Mutator for $mDefaultSort
6083 * @param string $sort New value
6085 public function setDefaultSort( $sort ) {
6086 $this->mDefaultSort
= $sort;
6087 $this->mOutput
->setProperty( 'defaultsort', $sort );
6091 * Accessor for $mDefaultSort
6092 * Will use the empty string if none is set.
6094 * This value is treated as a prefix, so the
6095 * empty string is equivalent to sorting by
6100 public function getDefaultSort() {
6101 if ( $this->mDefaultSort
!== false ) {
6102 return $this->mDefaultSort
;
6109 * Accessor for $mDefaultSort
6110 * Unlike getDefaultSort(), will return false if none is set
6112 * @return string|bool
6114 public function getCustomDefaultSort() {
6115 return $this->mDefaultSort
;
6119 * Try to guess the section anchor name based on a wikitext fragment
6120 * presumably extracted from a heading, for example "Header" from
6123 * @param string $text
6127 public function guessSectionNameFromWikiText( $text ) {
6128 # Strip out wikitext links(they break the anchor)
6129 $text = $this->stripSectionName( $text );
6130 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6131 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6135 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6136 * instead. For use in redirects, since IE6 interprets Redirect: headers
6137 * as something other than UTF-8 (apparently?), resulting in breakage.
6139 * @param string $text The section name
6140 * @return string An anchor
6142 public function guessLegacySectionNameFromWikiText( $text ) {
6143 # Strip out wikitext links(they break the anchor)
6144 $text = $this->stripSectionName( $text );
6145 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6146 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6150 * Strips a text string of wikitext for use in a section anchor
6152 * Accepts a text string and then removes all wikitext from the
6153 * string and leaves only the resultant text (i.e. the result of
6154 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6155 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6156 * to create valid section anchors by mimicing the output of the
6157 * parser when headings are parsed.
6159 * @param string $text Text string to be stripped of wikitext
6160 * for use in a Section anchor
6161 * @return string Filtered text string
6163 public function stripSectionName( $text ) {
6164 # Strip internal link markup
6165 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6166 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6168 # Strip external link markup
6169 # @todo FIXME: Not tolerant to blank link text
6170 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6171 # on how many empty links there are on the page - need to figure that out.
6172 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6174 # Parse wikitext quotes (italics & bold)
6175 $text = $this->doQuotes( $text );
6178 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6183 * strip/replaceVariables/unstrip for preprocessor regression testing
6185 * @param string $text
6186 * @param Title $title
6187 * @param ParserOptions $options
6188 * @param int $outputType
6192 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6193 $magicScopeVariable = $this->lock();
6194 $this->startParse( $title, $options, $outputType, true );
6196 $text = $this->replaceVariables( $text );
6197 $text = $this->mStripState
->unstripBoth( $text );
6198 $text = Sanitizer
::removeHTMLtags( $text );
6203 * @param string $text
6204 * @param Title $title
6205 * @param ParserOptions $options
6208 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6209 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6213 * @param string $text
6214 * @param Title $title
6215 * @param ParserOptions $options
6218 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6219 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6223 * Call a callback function on all regions of the given text that are not
6224 * inside strip markers, and replace those regions with the return value
6225 * of the callback. For example, with input:
6229 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6230 * two strings will be replaced with the value returned by the callback in
6234 * @param callable $callback
6238 public function markerSkipCallback( $s, $callback ) {
6241 while ( $i < strlen( $s ) ) {
6242 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6243 if ( $markerStart === false ) {
6244 $out .= call_user_func( $callback, substr( $s, $i ) );
6247 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6248 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6249 if ( $markerEnd === false ) {
6250 $out .= substr( $s, $markerStart );
6253 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6254 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6263 * Remove any strip markers found in the given text.
6265 * @param string $text Input string
6268 public function killMarkers( $text ) {
6269 return $this->mStripState
->killMarkers( $text );
6273 * Save the parser state required to convert the given half-parsed text to
6274 * HTML. "Half-parsed" in this context means the output of
6275 * recursiveTagParse() or internalParse(). This output has strip markers
6276 * from replaceVariables (extensionSubstitution() etc.), and link
6277 * placeholders from replaceLinkHolders().
6279 * Returns an array which can be serialized and stored persistently. This
6280 * array can later be loaded into another parser instance with
6281 * unserializeHalfParsedText(). The text can then be safely incorporated into
6282 * the return value of a parser hook.
6284 * @param string $text
6288 public function serializeHalfParsedText( $text ) {
6289 wfProfileIn( __METHOD__
);
6292 'version' => self
::HALF_PARSED_VERSION
,
6293 'stripState' => $this->mStripState
->getSubState( $text ),
6294 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6296 wfProfileOut( __METHOD__
);
6301 * Load the parser state given in the $data array, which is assumed to
6302 * have been generated by serializeHalfParsedText(). The text contents is
6303 * extracted from the array, and its markers are transformed into markers
6304 * appropriate for the current Parser instance. This transformed text is
6305 * returned, and can be safely included in the return value of a parser
6308 * If the $data array has been stored persistently, the caller should first
6309 * check whether it is still valid, by calling isValidHalfParsedText().
6311 * @param array $data Serialized data
6312 * @throws MWException
6315 public function unserializeHalfParsedText( $data ) {
6316 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6317 throw new MWException( __METHOD__
. ': invalid version' );
6320 # First, extract the strip state.
6321 $texts = array( $data['text'] );
6322 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6324 # Now renumber links
6325 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6327 # Should be good to go.
6332 * Returns true if the given array, presumed to be generated by
6333 * serializeHalfParsedText(), is compatible with the current version of the
6336 * @param array $data
6340 public function isValidHalfParsedText( $data ) {
6341 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6345 * Parsed a width param of imagelink like 300px or 200x300px
6347 * @param string $value
6352 public function parseWidthParam( $value ) {
6353 $parsedWidthParam = array();
6354 if ( $value === '' ) {
6355 return $parsedWidthParam;
6358 # (bug 13500) In both cases (width/height and width only),
6359 # permit trailing "px" for backward compatibility.
6360 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6361 $width = intval( $m[1] );
6362 $height = intval( $m[2] );
6363 $parsedWidthParam['width'] = $width;
6364 $parsedWidthParam['height'] = $height;
6365 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6366 $width = intval( $value );
6367 $parsedWidthParam['width'] = $width;
6369 return $parsedWidthParam;
6373 * Lock the current instance of the parser.
6375 * This is meant to stop someone from calling the parser
6376 * recursively and messing up all the strip state.
6378 * @throws MWException If parser is in a parse
6379 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6381 protected function lock() {
6382 if ( $this->mInParse
) {
6383 throw new MWException( "Parser state cleared while parsing. "
6384 . "Did you call Parser::parse recursively?" );
6386 $this->mInParse
= true;
6389 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6390 $that->mInParse
= false;
6393 return $recursiveCheck;
6397 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6399 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6400 * or if there is more than one <p/> tag in the input HTML.
6402 * @param string $html
6406 public static function stripOuterParagraph( $html ) {
6408 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6409 if ( strpos( $m[1], '</p>' ) === false ) {
6418 * Return this parser if it is not doing anything, otherwise
6419 * get a fresh parser. You can use this method by doing
6420 * $myParser = $wgParser->getFreshParser(), or more simply
6421 * $wgParser->getFreshParser()->parse( ... );
6422 * if you're unsure if $wgParser is safe to use.
6425 * @return Parser A parser object that is not parsing anything
6427 public function getFreshParser() {
6428 global $wgParserConf;
6429 if ( $this->mInParse
) {
6430 return new $wgParserConf['class']( $wgParserConf );