3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
116 * Prefix for temporary replacement strings generated by the preprocessor
117 * ("strip markers"). Using \x7f at the front gives us a little extra
118 * robustness since it shouldn't match when butted up against
119 * identifier-like string constructs.
121 * Must not consist of all title characters, or else it will change
122 * the behavior of <nowiki> in a link.
124 const MARKER_PREFIX
= "\x7fUNIQ";
125 /** Suffix for strip markers */
126 const MARKER_SUFFIX
= "-QINU\x7f";
127 /** Regex which matches the state ID part of strip markers */
128 const MARKER_STATE_ID_REGEX
= '[0-9a-f]{16}';
130 # Markers used for wrapping the table of contents
131 const TOC_START
= '<mw:toc>';
132 const TOC_END
= '</mw:toc>';
135 public $mTagHooks = array();
136 public $mTransparentTagHooks = array();
137 public $mFunctionHooks = array();
138 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
139 public $mFunctionTagHooks = array();
140 public $mStripList = array();
141 public $mDefaultStripList = array();
142 public $mVarCache = array();
143 public $mImageParams = array();
144 public $mImageParamsMagicArray = array();
145 public $mMarkerIndex = 0;
146 public $mFirstCall = true;
148 # Initialised by initialiseVariables()
151 * @var MagicWordArray
156 * @var MagicWordArray
159 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
161 # Cleared with clearState():
166 public $mAutonumber, $mDTopen;
173 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
175 * @var LinkHolderArray
177 public $mLinkHolders;
180 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
181 public $mDefaultSort;
182 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
183 public $mExpensiveFunctionCount; # number of expensive parser function calls
184 public $mShowToc, $mForceTocPosition;
189 public $mUser; # User object; only used when doing pre-save transform
192 # These are variables reset at least once per parse regardless of $clearState
202 public $mTitle; # Title context, used for self-link rendering and similar things
203 public $mOutputType; # Output type, one of the OT_xxx constants
204 public $ot; # Shortcut alias, see setOutputType()
205 public $mRevisionObject; # The revision object of the specified revision ID
206 public $mRevisionId; # ID to display in {{REVISIONID}} tags
207 public $mRevisionTimestamp; # The timestamp of the specified revision ID
208 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
209 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
210 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
211 public $mInputSize = false; # For {{PAGESIZE}} on current page.
219 * @var array Array with the language name of each language link (i.e. the
220 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
221 * duplicate language links to the ParserOutput.
223 public $mLangLinkLanguages;
226 * @var MapCacheLRU|null
229 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
231 public $currentRevisionCache;
234 * @var bool Recursive call protection.
235 * This variable should be treated as if it were private.
237 public $mInParse = false;
242 public function __construct( $conf = array() ) {
243 $this->mConf
= $conf;
244 $this->mUrlProtocols
= wfUrlProtocols();
245 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
246 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
247 if ( isset( $conf['preprocessorClass'] ) ) {
248 $this->mPreprocessorClass
= $conf['preprocessorClass'];
249 } elseif ( defined( 'HPHP_VERSION' ) ) {
250 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
251 $this->mPreprocessorClass
= 'Preprocessor_Hash';
252 } elseif ( extension_loaded( 'domxml' ) ) {
253 # PECL extension that conflicts with the core DOM extension (bug 13770)
254 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
255 $this->mPreprocessorClass
= 'Preprocessor_Hash';
256 } elseif ( extension_loaded( 'dom' ) ) {
257 $this->mPreprocessorClass
= 'Preprocessor_DOM';
259 $this->mPreprocessorClass
= 'Preprocessor_Hash';
261 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
265 * Reduce memory usage to reduce the impact of circular references
267 public function __destruct() {
268 if ( isset( $this->mLinkHolders
) ) {
269 unset( $this->mLinkHolders
);
271 foreach ( $this as $name => $value ) {
272 unset( $this->$name );
277 * Allow extensions to clean up when the parser is cloned
279 public function __clone() {
280 $this->mInParse
= false;
282 // Bug 56226: When you create a reference "to" an object field, that
283 // makes the object field itself be a reference too (until the other
284 // reference goes out of scope). When cloning, any field that's a
285 // reference is copied as a reference in the new object. Both of these
286 // are defined PHP5 behaviors, as inconvenient as it is for us when old
287 // hooks from PHP4 days are passing fields by reference.
288 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
289 // Make a non-reference copy of the field, then rebind the field to
290 // reference the new copy.
296 wfRunHooks( 'ParserCloned', array( $this ) );
300 * Do various kinds of initialisation on the first call of the parser
302 public function firstCallInit() {
303 if ( !$this->mFirstCall
) {
306 $this->mFirstCall
= false;
308 wfProfileIn( __METHOD__
);
310 CoreParserFunctions
::register( $this );
311 CoreTagHooks
::register( $this );
312 $this->initialiseVariables();
314 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
315 wfProfileOut( __METHOD__
);
323 public function clearState() {
324 wfProfileIn( __METHOD__
);
325 if ( $this->mFirstCall
) {
326 $this->firstCallInit();
328 $this->mOutput
= new ParserOutput
;
329 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
330 $this->mAutonumber
= 0;
331 $this->mLastSection
= '';
332 $this->mDTopen
= false;
333 $this->mIncludeCount
= array();
334 $this->mArgStack
= false;
335 $this->mInPre
= false;
336 $this->mLinkHolders
= new LinkHolderArray( $this );
338 $this->mRevisionObject
= $this->mRevisionTimestamp
=
339 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
340 $this->mVarCache
= array();
342 $this->mLangLinkLanguages
= array();
343 $this->currentRevisionCache
= null;
345 $stripId = self
::getRandomString();
346 $this->mUniqPrefix
= self
::MARKER_PREFIX
. $stripId;
347 $this->mStripState
= new StripState( $stripId );
349 # Clear these on every parse, bug 4549
350 $this->mTplRedirCache
= $this->mTplDomCache
= array();
352 $this->mShowToc
= true;
353 $this->mForceTocPosition
= false;
354 $this->mIncludeSizes
= array(
358 $this->mPPNodeCount
= 0;
359 $this->mGeneratedPPNodeCount
= 0;
360 $this->mHighestExpansionDepth
= 0;
361 $this->mDefaultSort
= false;
362 $this->mHeadings
= array();
363 $this->mDoubleUnderscores
= array();
364 $this->mExpensiveFunctionCount
= 0;
367 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
368 $this->mPreprocessor
= null;
371 wfRunHooks( 'ParserClearState', array( &$this ) );
372 wfProfileOut( __METHOD__
);
376 * Convert wikitext to HTML
377 * Do not call this function recursively.
379 * @param string $text Text we want to parse
380 * @param Title $title
381 * @param ParserOptions $options
382 * @param bool $linestart
383 * @param bool $clearState
384 * @param int $revid Number to pass in {{REVISIONID}}
385 * @return ParserOutput A ParserOutput
387 public function parse( $text, Title
$title, ParserOptions
$options,
388 $linestart = true, $clearState = true, $revid = null
391 * First pass--just handle <nowiki> sections, pass the rest off
392 * to internalParse() which does all the real work.
395 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
396 $fname = __METHOD__
. '-' . wfGetCaller();
397 wfProfileIn( __METHOD__
);
398 wfProfileIn( $fname );
401 $magicScopeVariable = $this->lock();
404 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
406 $this->currentRevisionCache
= null;
407 $this->mInputSize
= strlen( $text );
408 if ( $this->mOptions
->getEnableLimitReport() ) {
409 $this->mOutput
->resetParseStartTime();
412 # Remove the strip marker tag prefix from the input, if present.
414 $text = str_replace( $this->mUniqPrefix
, '', $text );
417 $oldRevisionId = $this->mRevisionId
;
418 $oldRevisionObject = $this->mRevisionObject
;
419 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
420 $oldRevisionUser = $this->mRevisionUser
;
421 $oldRevisionSize = $this->mRevisionSize
;
422 if ( $revid !== null ) {
423 $this->mRevisionId
= $revid;
424 $this->mRevisionObject
= null;
425 $this->mRevisionTimestamp
= null;
426 $this->mRevisionUser
= null;
427 $this->mRevisionSize
= null;
430 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
432 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
433 $text = $this->internalParse( $text );
434 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
436 $text = $this->mStripState
->unstripGeneral( $text );
438 # Clean up special characters, only run once, next-to-last before doBlockLevels
440 # french spaces, last one Guillemet-left
441 # only if there is something before the space
442 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
443 # french spaces, Guillemet-right
444 '/(\\302\\253) /' => '\\1 ',
445 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
447 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
449 $text = $this->doBlockLevels( $text, $linestart );
451 $this->replaceLinkHolders( $text );
454 * The input doesn't get language converted if
456 * b) Content isn't converted
457 * c) It's a conversion table
458 * d) it is an interface message (which is in the user language)
460 if ( !( $options->getDisableContentConversion()
461 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
463 if ( !$this->mOptions
->getInterfaceMessage() ) {
464 # The position of the convert() call should not be changed. it
465 # assumes that the links are all replaced and the only thing left
466 # is the <nowiki> mark.
467 $text = $this->getConverterLanguage()->convert( $text );
472 * A converted title will be provided in the output object if title and
473 * content conversion are enabled, the article text does not contain
474 * a conversion-suppressing double-underscore tag, and no
475 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
476 * automatic link conversion.
478 if ( !( $options->getDisableTitleConversion()
479 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
480 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
481 ||
$this->mOutput
->getDisplayTitle() !== false )
483 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
484 if ( $convruletitle ) {
485 $this->mOutput
->setTitleText( $convruletitle );
487 $titleText = $this->getConverterLanguage()->convertTitle( $title );
488 $this->mOutput
->setTitleText( $titleText );
492 $text = $this->mStripState
->unstripNoWiki( $text );
494 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
496 $text = $this->replaceTransparentTags( $text );
497 $text = $this->mStripState
->unstripGeneral( $text );
499 $text = Sanitizer
::normalizeCharReferences( $text );
501 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
502 $text = MWTidy
::tidy( $text );
504 # attempt to sanitize at least some nesting problems
505 # (bug #2702 and quite a few others)
507 # ''Something [http://www.cool.com cool''] -->
508 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
509 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
510 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
511 # fix up an anchor inside another anchor, only
512 # at least for a single single nested link (bug 3695)
513 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
514 '\\1\\2</a>\\3</a>\\1\\4</a>',
515 # fix div inside inline elements- doBlockLevels won't wrap a line which
516 # contains a div, so fix it up here; replace
517 # div with escaped text
518 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
519 '\\1\\3<div\\5>\\6</div>\\8\\9',
520 # remove empty italic or bold tag pairs, some
521 # introduced by rules above
522 '/<([bi])><\/\\1>/' => '',
525 $text = preg_replace(
526 array_keys( $tidyregs ),
527 array_values( $tidyregs ),
531 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
532 $this->limitationWarn( 'expensive-parserfunction',
533 $this->mExpensiveFunctionCount
,
534 $this->mOptions
->getExpensiveParserFunctionLimit()
538 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
540 # Information on include size limits, for the benefit of users who try to skirt them
541 if ( $this->mOptions
->getEnableLimitReport() ) {
542 $max = $this->mOptions
->getMaxIncludeSize();
544 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
545 if ( $cpuTime !== null ) {
546 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
547 sprintf( "%.3f", $cpuTime )
551 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
552 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
553 sprintf( "%.3f", $wallTime )
556 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
557 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
559 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
560 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
562 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
563 array( $this->mIncludeSizes
['post-expand'], $max )
565 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
566 array( $this->mIncludeSizes
['arg'], $max )
568 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
569 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
571 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
572 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
574 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
576 $limitReport = "NewPP limit report\n";
577 if ( $wgShowHostnames ) {
578 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
580 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
581 if ( wfRunHooks( 'ParserLimitReportFormat',
582 array( $key, &$value, &$limitReport, false, false )
584 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
585 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
586 ->inLanguage( 'en' )->useDatabase( false );
587 if ( !$valueMsg->exists() ) {
588 $valueMsg = new RawMessage( '$1' );
590 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
591 $valueMsg->params( $value );
592 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
596 // Since we're not really outputting HTML, decode the entities and
597 // then re-encode the things that need hiding inside HTML comments.
598 $limitReport = htmlspecialchars_decode( $limitReport );
599 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
601 // Sanitize for comment. Note '‐' in the replacement is U+2010,
602 // which looks much like the problematic '-'.
603 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
604 $text .= "\n<!-- \n$limitReport-->\n";
606 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
607 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
608 $this->mTitle
->getPrefixedDBkey() );
611 $this->mOutput
->setText( $text );
613 $this->mRevisionId
= $oldRevisionId;
614 $this->mRevisionObject
= $oldRevisionObject;
615 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
616 $this->mRevisionUser
= $oldRevisionUser;
617 $this->mRevisionSize
= $oldRevisionSize;
618 $this->mInputSize
= false;
619 $this->currentRevisionCache
= null;
620 wfProfileOut( $fname );
621 wfProfileOut( __METHOD__
);
623 return $this->mOutput
;
627 * Recursive parser entry point that can be called from an extension tag
630 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
632 * @param string $text Text extension wants to have parsed
633 * @param bool|PPFrame $frame The frame to use for expanding any template variables
637 public function recursiveTagParse( $text, $frame = false ) {
638 wfProfileIn( __METHOD__
);
639 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
640 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
641 $text = $this->internalParse( $text, false, $frame );
642 wfProfileOut( __METHOD__
);
647 * Expand templates and variables in the text, producing valid, static wikitext.
648 * Also removes comments.
649 * Do not call this function recursively.
650 * @param string $text
651 * @param Title $title
652 * @param ParserOptions $options
653 * @param int|null $revid
654 * @param bool|PPFrame $frame
655 * @return mixed|string
657 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
658 wfProfileIn( __METHOD__
);
659 $magicScopeVariable = $this->lock();
660 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
661 if ( $revid !== null ) {
662 $this->mRevisionId
= $revid;
664 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
665 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
666 $text = $this->replaceVariables( $text, $frame );
667 $text = $this->mStripState
->unstripBoth( $text );
668 wfProfileOut( __METHOD__
);
673 * Recursive parser entry point that can be called from an extension tag
676 * @param string $text Text to be expanded
677 * @param bool|PPFrame $frame The frame to use for expanding any template variables
681 public function recursivePreprocess( $text, $frame = false ) {
682 wfProfileIn( __METHOD__
);
683 $text = $this->replaceVariables( $text, $frame );
684 $text = $this->mStripState
->unstripBoth( $text );
685 wfProfileOut( __METHOD__
);
690 * Process the wikitext for the "?preload=" feature. (bug 5210)
692 * "<noinclude>", "<includeonly>" etc. are parsed as for template
693 * transclusion, comments, templates, arguments, tags hooks and parser
694 * functions are untouched.
696 * @param string $text
697 * @param Title $title
698 * @param ParserOptions $options
699 * @param array $params
702 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
703 $msg = new RawMessage( $text );
704 $text = $msg->params( $params )->plain();
706 # Parser (re)initialisation
707 $magicScopeVariable = $this->lock();
708 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
710 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
711 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
712 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
713 $text = $this->mStripState
->unstripBoth( $text );
718 * Get a random string
722 public static function getRandomString() {
723 return wfRandomString( 16 );
727 * Set the current user.
728 * Should only be used when doing pre-save transform.
730 * @param User|null $user User object or null (to reset)
732 public function setUser( $user ) {
733 $this->mUser
= $user;
737 * Accessor for mUniqPrefix.
741 public function uniqPrefix() {
742 if ( !isset( $this->mUniqPrefix
) ) {
743 # @todo FIXME: This is probably *horribly wrong*
744 # LanguageConverter seems to want $wgParser's uniqPrefix, however
745 # if this is called for a parser cache hit, the parser may not
746 # have ever been initialized in the first place.
747 # Not really sure what the heck is supposed to be going on here.
749 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
751 return $this->mUniqPrefix
;
755 * Set the context title
759 public function setTitle( $t ) {
761 $t = Title
::newFromText( 'NO TITLE' );
764 if ( $t->hasFragment() ) {
765 # Strip the fragment to avoid various odd effects
766 $this->mTitle
= clone $t;
767 $this->mTitle
->setFragment( '' );
774 * Accessor for the Title object
778 public function getTitle() {
779 return $this->mTitle
;
783 * Accessor/mutator for the Title object
785 * @param Title $x Title object or null to just get the current one
788 public function Title( $x = null ) {
789 return wfSetVar( $this->mTitle
, $x );
793 * Set the output type
795 * @param int $ot New value
797 public function setOutputType( $ot ) {
798 $this->mOutputType
= $ot;
801 'html' => $ot == self
::OT_HTML
,
802 'wiki' => $ot == self
::OT_WIKI
,
803 'pre' => $ot == self
::OT_PREPROCESS
,
804 'plain' => $ot == self
::OT_PLAIN
,
809 * Accessor/mutator for the output type
811 * @param int|null $x New value or null to just get the current one
814 public function OutputType( $x = null ) {
815 return wfSetVar( $this->mOutputType
, $x );
819 * Get the ParserOutput object
821 * @return ParserOutput
823 public function getOutput() {
824 return $this->mOutput
;
828 * Get the ParserOptions object
830 * @return ParserOptions
832 public function getOptions() {
833 return $this->mOptions
;
837 * Accessor/mutator for the ParserOptions object
839 * @param ParserOptions $x New value or null to just get the current one
840 * @return ParserOptions Current ParserOptions object
842 public function Options( $x = null ) {
843 return wfSetVar( $this->mOptions
, $x );
849 public function nextLinkID() {
850 return $this->mLinkID++
;
856 public function setLinkID( $id ) {
857 $this->mLinkID
= $id;
861 * Get a language object for use in parser functions such as {{FORMATNUM:}}
864 public function getFunctionLang() {
865 return $this->getTargetLanguage();
869 * Get the target language for the content being parsed. This is usually the
870 * language that the content is in.
874 * @throws MWException
877 public function getTargetLanguage() {
878 $target = $this->mOptions
->getTargetLanguage();
880 if ( $target !== null ) {
882 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
883 return $this->mOptions
->getUserLangObj();
884 } elseif ( is_null( $this->mTitle
) ) {
885 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
888 return $this->mTitle
->getPageLanguage();
892 * Get the language object for language conversion
893 * @return Language|null
895 public function getConverterLanguage() {
896 return $this->getTargetLanguage();
900 * Get a User object either from $this->mUser, if set, or from the
901 * ParserOptions object otherwise
905 public function getUser() {
906 if ( !is_null( $this->mUser
) ) {
909 return $this->mOptions
->getUser();
913 * Get a preprocessor object
915 * @return Preprocessor
917 public function getPreprocessor() {
918 if ( !isset( $this->mPreprocessor
) ) {
919 $class = $this->mPreprocessorClass
;
920 $this->mPreprocessor
= new $class( $this );
922 return $this->mPreprocessor
;
926 * Replaces all occurrences of HTML-style comments and the given tags
927 * in the text with a random marker and returns the next text. The output
928 * parameter $matches will be an associative array filled with data in
932 * 'UNIQ-xxxxx' => array(
935 * array( 'param' => 'x' ),
936 * '<element param="x">tag content</element>' ) )
939 * @param array $elements List of element names. Comments are always extracted.
940 * @param string $text Source text string.
941 * @param array $matches Out parameter, Array: extracted tags
942 * @param string $uniq_prefix
943 * @return string Stripped text
945 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
950 $taglist = implode( '|', $elements );
951 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
953 while ( $text != '' ) {
954 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
956 if ( count( $p ) < 5 ) {
959 if ( count( $p ) > 5 ) {
973 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
974 $stripped .= $marker;
976 if ( $close === '/>' ) {
977 # Empty element tag, <tag />
982 if ( $element === '!--' ) {
985 $end = "/(<\\/$element\\s*>)/i";
987 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
989 if ( count( $q ) < 3 ) {
990 # No end tag -- let it run out to the end of the text.
999 $matches[$marker] = array( $element,
1001 Sanitizer
::decodeTagAttributes( $attributes ),
1002 "<$element$attributes$close$content$tail" );
1008 * Get a list of strippable XML-like elements
1012 public function getStripList() {
1013 return $this->mStripList
;
1017 * Add an item to the strip state
1018 * Returns the unique tag which must be inserted into the stripped text
1019 * The tag will be replaced with the original text in unstrip()
1021 * @param string $text
1025 public function insertStripItem( $text ) {
1026 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1027 $this->mMarkerIndex++
;
1028 $this->mStripState
->addGeneral( $rnd, $text );
1033 * parse the wiki syntax used to render tables
1036 * @param string $text
1039 public function doTableStuff( $text ) {
1040 wfProfileIn( __METHOD__
);
1042 $lines = StringUtils
::explode( "\n", $text );
1044 $td_history = array(); # Is currently a td tag open?
1045 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1046 $tr_history = array(); # Is currently a tr tag open?
1047 $tr_attributes = array(); # history of tr attributes
1048 $has_opened_tr = array(); # Did this table open a <tr> element?
1049 $indent_level = 0; # indent level of the table
1051 foreach ( $lines as $outLine ) {
1052 $line = trim( $outLine );
1054 if ( $line === '' ) { # empty line, go to next line
1055 $out .= $outLine . "\n";
1059 $first_character = $line[0];
1062 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1063 # First check if we are starting a new table
1064 $indent_level = strlen( $matches[1] );
1066 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1067 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1069 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1070 array_push( $td_history, false );
1071 array_push( $last_tag_history, '' );
1072 array_push( $tr_history, false );
1073 array_push( $tr_attributes, '' );
1074 array_push( $has_opened_tr, false );
1075 } elseif ( count( $td_history ) == 0 ) {
1076 # Don't do any of the following
1077 $out .= $outLine . "\n";
1079 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1080 # We are ending a table
1081 $line = '</table>' . substr( $line, 2 );
1082 $last_tag = array_pop( $last_tag_history );
1084 if ( !array_pop( $has_opened_tr ) ) {
1085 $line = "<tr><td></td></tr>{$line}";
1088 if ( array_pop( $tr_history ) ) {
1089 $line = "</tr>{$line}";
1092 if ( array_pop( $td_history ) ) {
1093 $line = "</{$last_tag}>{$line}";
1095 array_pop( $tr_attributes );
1096 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1097 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1098 # Now we have a table row
1099 $line = preg_replace( '#^\|-+#', '', $line );
1101 # Whats after the tag is now only attributes
1102 $attributes = $this->mStripState
->unstripBoth( $line );
1103 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1104 array_pop( $tr_attributes );
1105 array_push( $tr_attributes, $attributes );
1108 $last_tag = array_pop( $last_tag_history );
1109 array_pop( $has_opened_tr );
1110 array_push( $has_opened_tr, true );
1112 if ( array_pop( $tr_history ) ) {
1116 if ( array_pop( $td_history ) ) {
1117 $line = "</{$last_tag}>{$line}";
1121 array_push( $tr_history, false );
1122 array_push( $td_history, false );
1123 array_push( $last_tag_history, '' );
1124 } elseif ( $first_character === '|'
1125 ||
$first_character === '!'
1126 ||
substr( $line, 0, 2 ) === '|+'
1128 # This might be cell elements, td, th or captions
1129 if ( substr( $line, 0, 2 ) === '|+' ) {
1130 $first_character = '+';
1131 $line = substr( $line, 1 );
1134 $line = substr( $line, 1 );
1136 if ( $first_character === '!' ) {
1137 $line = str_replace( '!!', '||', $line );
1140 # Split up multiple cells on the same line.
1141 # FIXME : This can result in improper nesting of tags processed
1142 # by earlier parser steps, but should avoid splitting up eg
1143 # attribute values containing literal "||".
1144 $cells = StringUtils
::explodeMarkup( '||', $line );
1148 # Loop through each table cell
1149 foreach ( $cells as $cell ) {
1151 if ( $first_character !== '+' ) {
1152 $tr_after = array_pop( $tr_attributes );
1153 if ( !array_pop( $tr_history ) ) {
1154 $previous = "<tr{$tr_after}>\n";
1156 array_push( $tr_history, true );
1157 array_push( $tr_attributes, '' );
1158 array_pop( $has_opened_tr );
1159 array_push( $has_opened_tr, true );
1162 $last_tag = array_pop( $last_tag_history );
1164 if ( array_pop( $td_history ) ) {
1165 $previous = "</{$last_tag}>\n{$previous}";
1168 if ( $first_character === '|' ) {
1170 } elseif ( $first_character === '!' ) {
1172 } elseif ( $first_character === '+' ) {
1173 $last_tag = 'caption';
1178 array_push( $last_tag_history, $last_tag );
1180 # A cell could contain both parameters and data
1181 $cell_data = explode( '|', $cell, 2 );
1183 # Bug 553: Note that a '|' inside an invalid link should not
1184 # be mistaken as delimiting cell parameters
1185 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1186 $cell = "{$previous}<{$last_tag}>{$cell}";
1187 } elseif ( count( $cell_data ) == 1 ) {
1188 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1190 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1191 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1192 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1196 array_push( $td_history, true );
1199 $out .= $outLine . "\n";
1202 # Closing open td, tr && table
1203 while ( count( $td_history ) > 0 ) {
1204 if ( array_pop( $td_history ) ) {
1207 if ( array_pop( $tr_history ) ) {
1210 if ( !array_pop( $has_opened_tr ) ) {
1211 $out .= "<tr><td></td></tr>\n";
1214 $out .= "</table>\n";
1217 # Remove trailing line-ending (b/c)
1218 if ( substr( $out, -1 ) === "\n" ) {
1219 $out = substr( $out, 0, -1 );
1222 # special case: don't return empty table
1223 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1227 wfProfileOut( __METHOD__
);
1233 * Helper function for parse() that transforms wiki markup into
1234 * HTML. Only called for $mOutputType == self::OT_HTML.
1238 * @param string $text
1239 * @param bool $isMain
1240 * @param bool $frame
1244 public function internalParse( $text, $isMain = true, $frame = false ) {
1245 wfProfileIn( __METHOD__
);
1249 # Hook to suspend the parser in this state
1250 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1251 wfProfileOut( __METHOD__
);
1255 # if $frame is provided, then use $frame for replacing any variables
1257 # use frame depth to infer how include/noinclude tags should be handled
1258 # depth=0 means this is the top-level document; otherwise it's an included document
1259 if ( !$frame->depth
) {
1262 $flag = Parser
::PTD_FOR_INCLUSION
;
1264 $dom = $this->preprocessToDom( $text, $flag );
1265 $text = $frame->expand( $dom );
1267 # if $frame is not provided, then use old-style replaceVariables
1268 $text = $this->replaceVariables( $text );
1271 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1272 $text = Sanitizer
::removeHTMLtags(
1274 array( &$this, 'attributeStripCallback' ),
1276 array_keys( $this->mTransparentTagHooks
)
1278 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1280 # Tables need to come after variable replacement for things to work
1281 # properly; putting them before other transformations should keep
1282 # exciting things like link expansions from showing up in surprising
1284 $text = $this->doTableStuff( $text );
1286 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1288 $text = $this->doDoubleUnderscore( $text );
1290 $text = $this->doHeadings( $text );
1291 $text = $this->replaceInternalLinks( $text );
1292 $text = $this->doAllQuotes( $text );
1293 $text = $this->replaceExternalLinks( $text );
1295 # replaceInternalLinks may sometimes leave behind
1296 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1297 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1299 $text = $this->doMagicLinks( $text );
1300 $text = $this->formatHeadings( $text, $origText, $isMain );
1302 wfProfileOut( __METHOD__
);
1307 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1308 * magic external links.
1313 * @param string $text
1317 public function doMagicLinks( $text ) {
1318 wfProfileIn( __METHOD__
);
1319 $prots = wfUrlProtocolsWithoutProtRel();
1320 $urlChar = self
::EXT_LINK_URL_CLASS
;
1321 $text = preg_replace_callback(
1323 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1324 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1325 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1326 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1327 ISBN\s+(\b # m[5]: ISBN, capture number
1328 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1329 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1330 [0-9Xx] # check digit
1332 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1333 wfProfileOut( __METHOD__
);
1338 * @throws MWException
1340 * @return HTML|string
1342 public function magicLinkCallback( $m ) {
1343 if ( isset( $m[1] ) && $m[1] !== '' ) {
1346 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1349 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1350 # Free external link
1351 return $this->makeFreeExternalLink( $m[0] );
1352 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1354 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1357 $cssClass = 'mw-magiclink-rfc';
1359 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1361 $urlmsg = 'pubmedurl';
1362 $cssClass = 'mw-magiclink-pmid';
1365 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1366 substr( $m[0], 0, 20 ) . '"' );
1368 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1369 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1370 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1373 $num = strtr( $isbn, array(
1378 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1379 return '<a href="' .
1380 htmlspecialchars( $titleObj->getLocalURL() ) .
1381 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1388 * Make a free external link, given a user-supplied URL
1390 * @param string $url
1392 * @return string HTML
1395 public function makeFreeExternalLink( $url ) {
1396 wfProfileIn( __METHOD__
);
1400 # The characters '<' and '>' (which were escaped by
1401 # removeHTMLtags()) should not be included in
1402 # URLs, per RFC 2396.
1404 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1405 $trail = substr( $url, $m2[0][1] ) . $trail;
1406 $url = substr( $url, 0, $m2[0][1] );
1409 # Move trailing punctuation to $trail
1411 # If there is no left bracket, then consider right brackets fair game too
1412 if ( strpos( $url, '(' ) === false ) {
1416 $numSepChars = strspn( strrev( $url ), $sep );
1417 if ( $numSepChars ) {
1418 $trail = substr( $url, -$numSepChars ) . $trail;
1419 $url = substr( $url, 0, -$numSepChars );
1422 $url = Sanitizer
::cleanUrl( $url );
1424 # Is this an external image?
1425 $text = $this->maybeMakeExternalImage( $url );
1426 if ( $text === false ) {
1427 # Not an image, make a link
1428 $text = Linker
::makeExternalLink( $url,
1429 $this->getConverterLanguage()->markNoConversion( $url, true ),
1431 $this->getExternalLinkAttribs( $url ) );
1432 # Register it in the output object...
1433 # Replace unnecessary URL escape codes with their equivalent characters
1434 $pasteurized = self
::normalizeLinkUrl( $url );
1435 $this->mOutput
->addExternalLink( $pasteurized );
1437 wfProfileOut( __METHOD__
);
1438 return $text . $trail;
1442 * Parse headers and return html
1446 * @param string $text
1450 public function doHeadings( $text ) {
1451 wfProfileIn( __METHOD__
);
1452 for ( $i = 6; $i >= 1; --$i ) {
1453 $h = str_repeat( '=', $i );
1454 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1456 wfProfileOut( __METHOD__
);
1461 * Replace single quotes with HTML markup
1464 * @param string $text
1466 * @return string The altered text
1468 public function doAllQuotes( $text ) {
1469 wfProfileIn( __METHOD__
);
1471 $lines = StringUtils
::explode( "\n", $text );
1472 foreach ( $lines as $line ) {
1473 $outtext .= $this->doQuotes( $line ) . "\n";
1475 $outtext = substr( $outtext, 0, -1 );
1476 wfProfileOut( __METHOD__
);
1481 * Helper function for doAllQuotes()
1483 * @param string $text
1487 public function doQuotes( $text ) {
1488 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1489 $countarr = count( $arr );
1490 if ( $countarr == 1 ) {
1494 // First, do some preliminary work. This may shift some apostrophes from
1495 // being mark-up to being text. It also counts the number of occurrences
1496 // of bold and italics mark-ups.
1499 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1500 $thislen = strlen( $arr[$i] );
1501 // If there are ever four apostrophes, assume the first is supposed to
1502 // be text, and the remaining three constitute mark-up for bold text.
1503 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1504 if ( $thislen == 4 ) {
1505 $arr[$i - 1] .= "'";
1508 } elseif ( $thislen > 5 ) {
1509 // If there are more than 5 apostrophes in a row, assume they're all
1510 // text except for the last 5.
1511 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1512 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1516 // Count the number of occurrences of bold and italics mark-ups.
1517 if ( $thislen == 2 ) {
1519 } elseif ( $thislen == 3 ) {
1521 } elseif ( $thislen == 5 ) {
1527 // If there is an odd number of both bold and italics, it is likely
1528 // that one of the bold ones was meant to be an apostrophe followed
1529 // by italics. Which one we cannot know for certain, but it is more
1530 // likely to be one that has a single-letter word before it.
1531 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1532 $firstsingleletterword = -1;
1533 $firstmultiletterword = -1;
1535 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1536 if ( strlen( $arr[$i] ) == 3 ) {
1537 $x1 = substr( $arr[$i - 1], -1 );
1538 $x2 = substr( $arr[$i - 1], -2, 1 );
1539 if ( $x1 === ' ' ) {
1540 if ( $firstspace == -1 ) {
1543 } elseif ( $x2 === ' ' ) {
1544 if ( $firstsingleletterword == -1 ) {
1545 $firstsingleletterword = $i;
1546 // if $firstsingleletterword is set, we don't
1547 // look at the other options, so we can bail early.
1551 if ( $firstmultiletterword == -1 ) {
1552 $firstmultiletterword = $i;
1558 // If there is a single-letter word, use it!
1559 if ( $firstsingleletterword > -1 ) {
1560 $arr[$firstsingleletterword] = "''";
1561 $arr[$firstsingleletterword - 1] .= "'";
1562 } elseif ( $firstmultiletterword > -1 ) {
1563 // If not, but there's a multi-letter word, use that one.
1564 $arr[$firstmultiletterword] = "''";
1565 $arr[$firstmultiletterword - 1] .= "'";
1566 } elseif ( $firstspace > -1 ) {
1567 // ... otherwise use the first one that has neither.
1568 // (notice that it is possible for all three to be -1 if, for example,
1569 // there is only one pentuple-apostrophe in the line)
1570 $arr[$firstspace] = "''";
1571 $arr[$firstspace - 1] .= "'";
1575 // Now let's actually convert our apostrophic mush to HTML!
1580 foreach ( $arr as $r ) {
1581 if ( ( $i %
2 ) == 0 ) {
1582 if ( $state === 'both' ) {
1588 $thislen = strlen( $r );
1589 if ( $thislen == 2 ) {
1590 if ( $state === 'i' ) {
1593 } elseif ( $state === 'bi' ) {
1596 } elseif ( $state === 'ib' ) {
1597 $output .= '</b></i><b>';
1599 } elseif ( $state === 'both' ) {
1600 $output .= '<b><i>' . $buffer . '</i>';
1602 } else { // $state can be 'b' or ''
1606 } elseif ( $thislen == 3 ) {
1607 if ( $state === 'b' ) {
1610 } elseif ( $state === 'bi' ) {
1611 $output .= '</i></b><i>';
1613 } elseif ( $state === 'ib' ) {
1616 } elseif ( $state === 'both' ) {
1617 $output .= '<i><b>' . $buffer . '</b>';
1619 } else { // $state can be 'i' or ''
1623 } elseif ( $thislen == 5 ) {
1624 if ( $state === 'b' ) {
1625 $output .= '</b><i>';
1627 } elseif ( $state === 'i' ) {
1628 $output .= '</i><b>';
1630 } elseif ( $state === 'bi' ) {
1631 $output .= '</i></b>';
1633 } elseif ( $state === 'ib' ) {
1634 $output .= '</b></i>';
1636 } elseif ( $state === 'both' ) {
1637 $output .= '<i><b>' . $buffer . '</b></i>';
1639 } else { // ($state == '')
1647 // Now close all remaining tags. Notice that the order is important.
1648 if ( $state === 'b' ||
$state === 'ib' ) {
1651 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1654 if ( $state === 'bi' ) {
1657 // There might be lonely ''''', so make sure we have a buffer
1658 if ( $state === 'both' && $buffer ) {
1659 $output .= '<b><i>' . $buffer . '</i></b>';
1665 * Replace external links (REL)
1667 * Note: this is all very hackish and the order of execution matters a lot.
1668 * Make sure to run tests/parserTests.php if you change this code.
1672 * @param string $text
1674 * @throws MWException
1677 public function replaceExternalLinks( $text ) {
1678 wfProfileIn( __METHOD__
);
1680 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1681 if ( $bits === false ) {
1682 wfProfileOut( __METHOD__
);
1683 throw new MWException( "PCRE needs to be compiled with "
1684 . "--enable-unicode-properties in order for MediaWiki to function" );
1686 $s = array_shift( $bits );
1689 while ( $i < count( $bits ) ) {
1692 $text = $bits[$i++
];
1693 $trail = $bits[$i++
];
1695 # The characters '<' and '>' (which were escaped by
1696 # removeHTMLtags()) should not be included in
1697 # URLs, per RFC 2396.
1699 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1700 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1701 $url = substr( $url, 0, $m2[0][1] );
1704 # If the link text is an image URL, replace it with an <img> tag
1705 # This happened by accident in the original parser, but some people used it extensively
1706 $img = $this->maybeMakeExternalImage( $text );
1707 if ( $img !== false ) {
1713 # Set linktype for CSS - if URL==text, link is essentially free
1714 $linktype = ( $text === $url ) ?
'free' : 'text';
1716 # No link text, e.g. [http://domain.tld/some.link]
1717 if ( $text == '' ) {
1719 $langObj = $this->getTargetLanguage();
1720 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1721 $linktype = 'autonumber';
1723 # Have link text, e.g. [http://domain.tld/some.link text]s
1725 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1728 $text = $this->getConverterLanguage()->markNoConversion( $text );
1730 $url = Sanitizer
::cleanUrl( $url );
1732 # Use the encoded URL
1733 # This means that users can paste URLs directly into the text
1734 # Funny characters like ö aren't valid in URLs anyway
1735 # This was changed in August 2004
1736 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1737 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1739 # Register link in the output object.
1740 # Replace unnecessary URL escape codes with the referenced character
1741 # This prevents spammers from hiding links from the filters
1742 $pasteurized = self
::normalizeLinkUrl( $url );
1743 $this->mOutput
->addExternalLink( $pasteurized );
1746 wfProfileOut( __METHOD__
);
1751 * Get the rel attribute for a particular external link.
1754 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1755 * nofollow if appropriate
1756 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1757 * @return string|null Rel attribute for $url
1759 public static function getExternalLinkRel( $url = false, $title = null ) {
1760 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1761 $ns = $title ?
$title->getNamespace() : false;
1762 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1763 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1771 * Get an associative array of additional HTML attributes appropriate for a
1772 * particular external link. This currently may include rel => nofollow
1773 * (depending on configuration, namespace, and the URL's domain) and/or a
1774 * target attribute (depending on configuration).
1776 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1777 * nofollow if appropriate
1778 * @return array Associative array of HTML attributes
1780 public function getExternalLinkAttribs( $url = false ) {
1782 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1784 if ( $this->mOptions
->getExternalLinkTarget() ) {
1785 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1791 * Replace unusual escape codes in a URL with their equivalent characters
1793 * @deprecated since 1.24, use normalizeLinkUrl
1794 * @param string $url
1797 public static function replaceUnusualEscapes( $url ) {
1798 wfDeprecated( __METHOD__
, '1.24' );
1799 return self
::normalizeLinkUrl( $url );
1803 * Replace unusual escape codes in a URL with their equivalent characters
1805 * This generally follows the syntax defined in RFC 3986, with special
1806 * consideration for HTTP query strings.
1808 * @param string $url
1811 public static function normalizeLinkUrl( $url ) {
1812 # First, make sure unsafe characters are encoded
1813 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1815 return rawurlencode( $m[0] );
1821 $end = strlen( $url );
1823 # Fragment part - 'fragment'
1824 $start = strpos( $url, '#' );
1825 if ( $start !== false && $start < $end ) {
1826 $ret = self
::normalizeUrlComponent(
1827 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1831 # Query part - 'query' minus &=+;
1832 $start = strpos( $url, '?' );
1833 if ( $start !== false && $start < $end ) {
1834 $ret = self
::normalizeUrlComponent(
1835 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1839 # Scheme and path part - 'pchar'
1840 # (we assume no userinfo or encoded colons in the host)
1841 $ret = self
::normalizeUrlComponent(
1842 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1847 private static function normalizeUrlComponent( $component, $unsafe ) {
1848 $callback = function ( $matches ) use ( $unsafe ) {
1849 $char = urldecode( $matches[0] );
1850 $ord = ord( $char );
1851 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1855 # Leave it escaped, but use uppercase for a-f
1856 return strtoupper( $matches[0] );
1859 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1863 * make an image if it's allowed, either through the global
1864 * option, through the exception, or through the on-wiki whitelist
1866 * @param string $url
1870 private function maybeMakeExternalImage( $url ) {
1871 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1872 $imagesexception = !empty( $imagesfrom );
1874 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1875 if ( $imagesexception && is_array( $imagesfrom ) ) {
1876 $imagematch = false;
1877 foreach ( $imagesfrom as $match ) {
1878 if ( strpos( $url, $match ) === 0 ) {
1883 } elseif ( $imagesexception ) {
1884 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1886 $imagematch = false;
1889 if ( $this->mOptions
->getAllowExternalImages()
1890 ||
( $imagesexception && $imagematch )
1892 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1894 $text = Linker
::makeExternalImage( $url );
1897 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1898 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1900 $whitelist = explode(
1902 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1905 foreach ( $whitelist as $entry ) {
1906 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1907 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1910 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1911 # Image matches a whitelist entry
1912 $text = Linker
::makeExternalImage( $url );
1921 * Process [[ ]] wikilinks
1925 * @return string Processed text
1929 public function replaceInternalLinks( $s ) {
1930 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1935 * Process [[ ]] wikilinks (RIL)
1937 * @throws MWException
1938 * @return LinkHolderArray
1942 public function replaceInternalLinks2( &$s ) {
1943 global $wgExtraInterlanguageLinkPrefixes;
1944 wfProfileIn( __METHOD__
);
1946 wfProfileIn( __METHOD__
. '-setup' );
1947 static $tc = false, $e1, $e1_img;
1948 # the % is needed to support urlencoded titles as well
1950 $tc = Title
::legalChars() . '#%';
1951 # Match a link having the form [[namespace:link|alternate]]trail
1952 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1953 # Match cases where there is no "]]", which might still be images
1954 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1957 $holders = new LinkHolderArray( $this );
1959 # split the entire text string on occurrences of [[
1960 $a = StringUtils
::explode( '[[', ' ' . $s );
1961 # get the first element (all text up to first [[), and remove the space we added
1964 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1965 $s = substr( $s, 1 );
1967 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1969 if ( $useLinkPrefixExtension ) {
1970 # Match the end of a line for a word that's not followed by whitespace,
1971 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1973 $charset = $wgContLang->linkPrefixCharset();
1974 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1977 if ( is_null( $this->mTitle
) ) {
1978 wfProfileOut( __METHOD__
. '-setup' );
1979 wfProfileOut( __METHOD__
);
1980 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1982 $nottalk = !$this->mTitle
->isTalkPage();
1984 if ( $useLinkPrefixExtension ) {
1986 if ( preg_match( $e2, $s, $m ) ) {
1987 $first_prefix = $m[2];
1989 $first_prefix = false;
1995 $useSubpages = $this->areSubpagesAllowed();
1996 wfProfileOut( __METHOD__
. '-setup' );
1998 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1999 # Loop for each link
2000 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2001 // @codingStandardsIgnoreStart
2003 # Check for excessive memory usage
2004 if ( $holders->isBig() ) {
2006 # Do the existence check, replace the link holders and clear the array
2007 $holders->replace( $s );
2011 if ( $useLinkPrefixExtension ) {
2012 wfProfileIn( __METHOD__
. '-prefixhandling' );
2013 if ( preg_match( $e2, $s, $m ) ) {
2020 if ( $first_prefix ) {
2021 $prefix = $first_prefix;
2022 $first_prefix = false;
2024 wfProfileOut( __METHOD__
. '-prefixhandling' );
2027 $might_be_img = false;
2029 wfProfileIn( __METHOD__
. "-e1" );
2030 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2032 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2033 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2034 # the real problem is with the $e1 regex
2037 # Still some problems for cases where the ] is meant to be outside punctuation,
2038 # and no image is in sight. See bug 2095.
2041 && substr( $m[3], 0, 1 ) === ']'
2042 && strpos( $text, '[' ) !== false
2044 $text .= ']'; # so that replaceExternalLinks($text) works later
2045 $m[3] = substr( $m[3], 1 );
2047 # fix up urlencoded title texts
2048 if ( strpos( $m[1], '%' ) !== false ) {
2049 # Should anchors '#' also be rejected?
2050 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2053 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2054 # Invalid, but might be an image with a link in its caption
2055 $might_be_img = true;
2057 if ( strpos( $m[1], '%' ) !== false ) {
2058 $m[1] = rawurldecode( $m[1] );
2061 } else { # Invalid form; output directly
2062 $s .= $prefix . '[[' . $line;
2063 wfProfileOut( __METHOD__
. "-e1" );
2066 wfProfileOut( __METHOD__
. "-e1" );
2067 wfProfileIn( __METHOD__
. "-misc" );
2071 # Don't allow internal links to pages containing
2072 # PROTO: where PROTO is a valid URL protocol; these
2073 # should be external links.
2074 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2075 $s .= $prefix . '[[' . $line;
2076 wfProfileOut( __METHOD__
. "-misc" );
2080 # Make subpage if necessary
2081 if ( $useSubpages ) {
2082 $link = $this->maybeDoSubpageLink( $origLink, $text );
2087 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2089 # Strip off leading ':'
2090 $link = substr( $link, 1 );
2093 wfProfileOut( __METHOD__
. "-misc" );
2094 wfProfileIn( __METHOD__
. "-title" );
2095 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2096 if ( $nt === null ) {
2097 $s .= $prefix . '[[' . $line;
2098 wfProfileOut( __METHOD__
. "-title" );
2102 $ns = $nt->getNamespace();
2103 $iw = $nt->getInterwiki();
2104 wfProfileOut( __METHOD__
. "-title" );
2106 if ( $might_be_img ) { # if this is actually an invalid link
2107 wfProfileIn( __METHOD__
. "-might_be_img" );
2108 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2111 # look at the next 'line' to see if we can close it there
2113 $next_line = $a->current();
2114 if ( $next_line === false ||
$next_line === null ) {
2117 $m = explode( ']]', $next_line, 3 );
2118 if ( count( $m ) == 3 ) {
2119 # the first ]] closes the inner link, the second the image
2121 $text .= "[[{$m[0]}]]{$m[1]}";
2124 } elseif ( count( $m ) == 2 ) {
2125 # if there's exactly one ]] that's fine, we'll keep looking
2126 $text .= "[[{$m[0]}]]{$m[1]}";
2128 # if $next_line is invalid too, we need look no further
2129 $text .= '[[' . $next_line;
2134 # we couldn't find the end of this imageLink, so output it raw
2135 # but don't ignore what might be perfectly normal links in the text we've examined
2136 $holders->merge( $this->replaceInternalLinks2( $text ) );
2137 $s .= "{$prefix}[[$link|$text";
2138 # note: no $trail, because without an end, there *is* no trail
2139 wfProfileOut( __METHOD__
. "-might_be_img" );
2142 } else { # it's not an image, so output it raw
2143 $s .= "{$prefix}[[$link|$text";
2144 # note: no $trail, because without an end, there *is* no trail
2145 wfProfileOut( __METHOD__
. "-might_be_img" );
2148 wfProfileOut( __METHOD__
. "-might_be_img" );
2151 $wasblank = ( $text == '' );
2155 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2156 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2157 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2158 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2159 $text = $this->doQuotes( $text );
2162 # Link not escaped by : , create the various objects
2163 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2165 wfProfileIn( __METHOD__
. "-interwiki" );
2167 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2168 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2169 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2172 # Bug 24502: filter duplicates
2173 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2174 $this->mLangLinkLanguages
[$iw] = true;
2175 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2178 $s = rtrim( $s . $prefix );
2179 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2180 wfProfileOut( __METHOD__
. "-interwiki" );
2183 wfProfileOut( __METHOD__
. "-interwiki" );
2185 if ( $ns == NS_FILE
) {
2186 wfProfileIn( __METHOD__
. "-image" );
2187 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2189 # if no parameters were passed, $text
2190 # becomes something like "File:Foo.png",
2191 # which we don't want to pass on to the
2195 # recursively parse links inside the image caption
2196 # actually, this will parse them in any other parameters, too,
2197 # but it might be hard to fix that, and it doesn't matter ATM
2198 $text = $this->replaceExternalLinks( $text );
2199 $holders->merge( $this->replaceInternalLinks2( $text ) );
2201 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2202 $s .= $prefix . $this->armorLinks(
2203 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2205 $s .= $prefix . $trail;
2207 wfProfileOut( __METHOD__
. "-image" );
2211 if ( $ns == NS_CATEGORY
) {
2212 wfProfileIn( __METHOD__
. "-category" );
2213 $s = rtrim( $s . "\n" ); # bug 87
2216 $sortkey = $this->getDefaultSort();
2220 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2221 $sortkey = str_replace( "\n", '', $sortkey );
2222 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2223 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2226 * Strip the whitespace Category links produce, see bug 87
2228 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2230 wfProfileOut( __METHOD__
. "-category" );
2235 # Self-link checking. For some languages, variants of the title are checked in
2236 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2237 # for linking to a different variant.
2238 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2239 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2243 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2244 # @todo FIXME: Should do batch file existence checks, see comment below
2245 if ( $ns == NS_MEDIA
) {
2246 wfProfileIn( __METHOD__
. "-media" );
2247 # Give extensions a chance to select the file revision for us
2250 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2251 array( $this, $nt, &$options, &$descQuery ) );
2252 # Fetch and register the file (file title may be different via hooks)
2253 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2254 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2255 $s .= $prefix . $this->armorLinks(
2256 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2257 wfProfileOut( __METHOD__
. "-media" );
2261 wfProfileIn( __METHOD__
. "-always_known" );
2262 # Some titles, such as valid special pages or files in foreign repos, should
2263 # be shown as bluelinks even though they're not included in the page table
2265 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2266 # batch file existence checks for NS_FILE and NS_MEDIA
2267 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2268 $this->mOutput
->addLink( $nt );
2269 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2271 # Links will be added to the output link list after checking
2272 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2274 wfProfileOut( __METHOD__
. "-always_known" );
2276 wfProfileOut( __METHOD__
);
2281 * Render a forced-blue link inline; protect against double expansion of
2282 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2283 * Since this little disaster has to split off the trail text to avoid
2284 * breaking URLs in the following text without breaking trails on the
2285 * wiki links, it's been made into a horrible function.
2288 * @param string $text
2289 * @param array|string $query
2290 * @param string $trail
2291 * @param string $prefix
2292 * @return string HTML-wikitext mix oh yuck
2294 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2295 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2297 if ( is_string( $query ) ) {
2298 $query = wfCgiToArray( $query );
2300 if ( $text == '' ) {
2301 $text = htmlspecialchars( $nt->getPrefixedText() );
2304 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2306 return $this->armorLinks( $link ) . $trail;
2310 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2311 * going to go through further parsing steps before inline URL expansion.
2313 * Not needed quite as much as it used to be since free links are a bit
2314 * more sensible these days. But bracketed links are still an issue.
2316 * @param string $text More-or-less HTML
2317 * @return string Less-or-more HTML with NOPARSE bits
2319 public function armorLinks( $text ) {
2320 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2321 "{$this->mUniqPrefix}NOPARSE$1", $text );
2325 * Return true if subpage links should be expanded on this page.
2328 public function areSubpagesAllowed() {
2329 # Some namespaces don't allow subpages
2330 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2334 * Handle link to subpage if necessary
2336 * @param string $target The source of the link
2337 * @param string &$text The link text, modified as necessary
2338 * @return string The full name of the link
2341 public function maybeDoSubpageLink( $target, &$text ) {
2342 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2346 * Used by doBlockLevels()
2351 public function closeParagraph() {
2353 if ( $this->mLastSection
!= '' ) {
2354 $result = '</' . $this->mLastSection
. ">\n";
2356 $this->mInPre
= false;
2357 $this->mLastSection
= '';
2362 * getCommon() returns the length of the longest common substring
2363 * of both arguments, starting at the beginning of both.
2366 * @param string $st1
2367 * @param string $st2
2371 public function getCommon( $st1, $st2 ) {
2372 $fl = strlen( $st1 );
2373 $shorter = strlen( $st2 );
2374 if ( $fl < $shorter ) {
2378 for ( $i = 0; $i < $shorter; ++
$i ) {
2379 if ( $st1[$i] != $st2[$i] ) {
2387 * These next three functions open, continue, and close the list
2388 * element appropriate to the prefix character passed into them.
2391 * @param string $char
2395 public function openList( $char ) {
2396 $result = $this->closeParagraph();
2398 if ( '*' === $char ) {
2399 $result .= "<ul><li>";
2400 } elseif ( '#' === $char ) {
2401 $result .= "<ol><li>";
2402 } elseif ( ':' === $char ) {
2403 $result .= "<dl><dd>";
2404 } elseif ( ';' === $char ) {
2405 $result .= "<dl><dt>";
2406 $this->mDTopen
= true;
2408 $result = '<!-- ERR 1 -->';
2416 * @param string $char
2421 public function nextItem( $char ) {
2422 if ( '*' === $char ||
'#' === $char ) {
2423 return "</li>\n<li>";
2424 } elseif ( ':' === $char ||
';' === $char ) {
2426 if ( $this->mDTopen
) {
2429 if ( ';' === $char ) {
2430 $this->mDTopen
= true;
2431 return $close . '<dt>';
2433 $this->mDTopen
= false;
2434 return $close . '<dd>';
2437 return '<!-- ERR 2 -->';
2442 * @param string $char
2447 public function closeList( $char ) {
2448 if ( '*' === $char ) {
2449 $text = "</li></ul>";
2450 } elseif ( '#' === $char ) {
2451 $text = "</li></ol>";
2452 } elseif ( ':' === $char ) {
2453 if ( $this->mDTopen
) {
2454 $this->mDTopen
= false;
2455 $text = "</dt></dl>";
2457 $text = "</dd></dl>";
2460 return '<!-- ERR 3 -->';
2467 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2469 * @param string $text
2470 * @param bool $linestart Whether or not this is at the start of a line.
2472 * @return string The lists rendered as HTML
2474 public function doBlockLevels( $text, $linestart ) {
2475 wfProfileIn( __METHOD__
);
2477 # Parsing through the text line by line. The main thing
2478 # happening here is handling of block-level elements p, pre,
2479 # and making lists from lines starting with * # : etc.
2481 $textLines = StringUtils
::explode( "\n", $text );
2483 $lastPrefix = $output = '';
2484 $this->mDTopen
= $inBlockElem = false;
2486 $paragraphStack = false;
2487 $inBlockquote = false;
2489 foreach ( $textLines as $oLine ) {
2491 if ( !$linestart ) {
2501 $lastPrefixLength = strlen( $lastPrefix );
2502 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2503 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2504 # If not in a <pre> element, scan for and figure out what prefixes are there.
2505 if ( !$this->mInPre
) {
2506 # Multiple prefixes may abut each other for nested lists.
2507 $prefixLength = strspn( $oLine, '*#:;' );
2508 $prefix = substr( $oLine, 0, $prefixLength );
2511 # ; and : are both from definition-lists, so they're equivalent
2512 # for the purposes of determining whether or not we need to open/close
2514 $prefix2 = str_replace( ';', ':', $prefix );
2515 $t = substr( $oLine, $prefixLength );
2516 $this->mInPre
= (bool)$preOpenMatch;
2518 # Don't interpret any other prefixes in preformatted text
2520 $prefix = $prefix2 = '';
2525 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2526 # Same as the last item, so no need to deal with nesting or opening stuff
2527 $output .= $this->nextItem( substr( $prefix, -1 ) );
2528 $paragraphStack = false;
2530 if ( substr( $prefix, -1 ) === ';' ) {
2531 # The one nasty exception: definition lists work like this:
2532 # ; title : definition text
2533 # So we check for : in the remainder text to split up the
2534 # title and definition, without b0rking links.
2536 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2538 $output .= $term . $this->nextItem( ':' );
2541 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2542 # We need to open or close prefixes, or both.
2544 # Either open or close a level...
2545 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2546 $paragraphStack = false;
2548 # Close all the prefixes which aren't shared.
2549 while ( $commonPrefixLength < $lastPrefixLength ) {
2550 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2551 --$lastPrefixLength;
2554 # Continue the current prefix if appropriate.
2555 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2556 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2559 # Open prefixes where appropriate.
2560 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2563 while ( $prefixLength > $commonPrefixLength ) {
2564 $char = substr( $prefix, $commonPrefixLength, 1 );
2565 $output .= $this->openList( $char );
2567 if ( ';' === $char ) {
2568 # @todo FIXME: This is dupe of code above
2569 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2571 $output .= $term . $this->nextItem( ':' );
2574 ++
$commonPrefixLength;
2576 if ( !$prefixLength && $lastPrefix ) {
2579 $lastPrefix = $prefix2;
2582 # If we have no prefixes, go to paragraph mode.
2583 if ( 0 == $prefixLength ) {
2584 wfProfileIn( __METHOD__
. "-paragraph" );
2585 # No prefix (not in list)--go to paragraph mode
2586 # XXX: use a stack for nestable elements like span, table and div
2587 $openmatch = preg_match(
2588 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2589 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2592 $closematch = preg_match(
2593 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2594 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2595 . $this->mUniqPrefix
2596 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2600 if ( $openmatch or $closematch ) {
2601 $paragraphStack = false;
2602 # @todo bug 5718: paragraph closed
2603 $output .= $this->closeParagraph();
2604 if ( $preOpenMatch and !$preCloseMatch ) {
2605 $this->mInPre
= true;
2608 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2609 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2610 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2612 $inBlockElem = !$closematch;
2613 } elseif ( !$inBlockElem && !$this->mInPre
) {
2614 if ( ' ' == substr( $t, 0, 1 )
2615 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2619 if ( $this->mLastSection
!== 'pre' ) {
2620 $paragraphStack = false;
2621 $output .= $this->closeParagraph() . '<pre>';
2622 $this->mLastSection
= 'pre';
2624 $t = substr( $t, 1 );
2627 if ( trim( $t ) === '' ) {
2628 if ( $paragraphStack ) {
2629 $output .= $paragraphStack . '<br />';
2630 $paragraphStack = false;
2631 $this->mLastSection
= 'p';
2633 if ( $this->mLastSection
!== 'p' ) {
2634 $output .= $this->closeParagraph();
2635 $this->mLastSection
= '';
2636 $paragraphStack = '<p>';
2638 $paragraphStack = '</p><p>';
2642 if ( $paragraphStack ) {
2643 $output .= $paragraphStack;
2644 $paragraphStack = false;
2645 $this->mLastSection
= 'p';
2646 } elseif ( $this->mLastSection
!== 'p' ) {
2647 $output .= $this->closeParagraph() . '<p>';
2648 $this->mLastSection
= 'p';
2653 wfProfileOut( __METHOD__
. "-paragraph" );
2655 # somewhere above we forget to get out of pre block (bug 785)
2656 if ( $preCloseMatch && $this->mInPre
) {
2657 $this->mInPre
= false;
2659 if ( $paragraphStack === false ) {
2661 if ( $prefixLength === 0 ) {
2666 while ( $prefixLength ) {
2667 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2669 if ( !$prefixLength ) {
2673 if ( $this->mLastSection
!= '' ) {
2674 $output .= '</' . $this->mLastSection
. '>';
2675 $this->mLastSection
= '';
2678 wfProfileOut( __METHOD__
);
2683 * Split up a string on ':', ignoring any occurrences inside tags
2684 * to prevent illegal overlapping.
2686 * @param string $str The string to split
2687 * @param string &$before Set to everything before the ':'
2688 * @param string &$after Set to everything after the ':'
2689 * @throws MWException
2690 * @return string The position of the ':', or false if none found
2692 public function findColonNoLinks( $str, &$before, &$after ) {
2693 wfProfileIn( __METHOD__
);
2695 $pos = strpos( $str, ':' );
2696 if ( $pos === false ) {
2698 wfProfileOut( __METHOD__
);
2702 $lt = strpos( $str, '<' );
2703 if ( $lt === false ||
$lt > $pos ) {
2704 # Easy; no tag nesting to worry about
2705 $before = substr( $str, 0, $pos );
2706 $after = substr( $str, $pos +
1 );
2707 wfProfileOut( __METHOD__
);
2711 # Ugly state machine to walk through avoiding tags.
2712 $state = self
::COLON_STATE_TEXT
;
2714 $len = strlen( $str );
2715 for ( $i = 0; $i < $len; $i++
) {
2719 # (Using the number is a performance hack for common cases)
2720 case 0: # self::COLON_STATE_TEXT:
2723 # Could be either a <start> tag or an </end> tag
2724 $state = self
::COLON_STATE_TAGSTART
;
2727 if ( $stack == 0 ) {
2729 $before = substr( $str, 0, $i );
2730 $after = substr( $str, $i +
1 );
2731 wfProfileOut( __METHOD__
);
2734 # Embedded in a tag; don't break it.
2737 # Skip ahead looking for something interesting
2738 $colon = strpos( $str, ':', $i );
2739 if ( $colon === false ) {
2740 # Nothing else interesting
2741 wfProfileOut( __METHOD__
);
2744 $lt = strpos( $str, '<', $i );
2745 if ( $stack === 0 ) {
2746 if ( $lt === false ||
$colon < $lt ) {
2748 $before = substr( $str, 0, $colon );
2749 $after = substr( $str, $colon +
1 );
2750 wfProfileOut( __METHOD__
);
2754 if ( $lt === false ) {
2755 # Nothing else interesting to find; abort!
2756 # We're nested, but there's no close tags left. Abort!
2759 # Skip ahead to next tag start
2761 $state = self
::COLON_STATE_TAGSTART
;
2764 case 1: # self::COLON_STATE_TAG:
2769 $state = self
::COLON_STATE_TEXT
;
2772 # Slash may be followed by >?
2773 $state = self
::COLON_STATE_TAGSLASH
;
2779 case 2: # self::COLON_STATE_TAGSTART:
2782 $state = self
::COLON_STATE_CLOSETAG
;
2785 $state = self
::COLON_STATE_COMMENT
;
2788 # Illegal early close? This shouldn't happen D:
2789 $state = self
::COLON_STATE_TEXT
;
2792 $state = self
::COLON_STATE_TAG
;
2795 case 3: # self::COLON_STATE_CLOSETAG:
2800 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2801 wfProfileOut( __METHOD__
);
2804 $state = self
::COLON_STATE_TEXT
;
2807 case self
::COLON_STATE_TAGSLASH
:
2809 # Yes, a self-closed tag <blah/>
2810 $state = self
::COLON_STATE_TEXT
;
2812 # Probably we're jumping the gun, and this is an attribute
2813 $state = self
::COLON_STATE_TAG
;
2816 case 5: # self::COLON_STATE_COMMENT:
2818 $state = self
::COLON_STATE_COMMENTDASH
;
2821 case self
::COLON_STATE_COMMENTDASH
:
2823 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2825 $state = self
::COLON_STATE_COMMENT
;
2828 case self
::COLON_STATE_COMMENTDASHDASH
:
2830 $state = self
::COLON_STATE_TEXT
;
2832 $state = self
::COLON_STATE_COMMENT
;
2836 wfProfileOut( __METHOD__
);
2837 throw new MWException( "State machine error in " . __METHOD__
);
2841 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2842 wfProfileOut( __METHOD__
);
2845 wfProfileOut( __METHOD__
);
2850 * Return value of a magic variable (like PAGENAME)
2855 * @param bool|PPFrame $frame
2857 * @throws MWException
2860 public function getVariableValue( $index, $frame = false ) {
2861 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2862 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2864 if ( is_null( $this->mTitle
) ) {
2865 // If no title set, bad things are going to happen
2866 // later. Title should always be set since this
2867 // should only be called in the middle of a parse
2868 // operation (but the unit-tests do funky stuff)
2869 throw new MWException( __METHOD__
. ' Should only be '
2870 . ' called while parsing (no title set)' );
2874 * Some of these require message or data lookups and can be
2875 * expensive to check many times.
2877 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2878 if ( isset( $this->mVarCache
[$index] ) ) {
2879 return $this->mVarCache
[$index];
2883 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2884 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2886 $pageLang = $this->getFunctionLang();
2892 case 'currentmonth':
2893 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2895 case 'currentmonth1':
2896 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2898 case 'currentmonthname':
2899 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2901 case 'currentmonthnamegen':
2902 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2904 case 'currentmonthabbrev':
2905 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2908 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2911 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2914 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2917 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2919 case 'localmonthname':
2920 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2922 case 'localmonthnamegen':
2923 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2925 case 'localmonthabbrev':
2926 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2929 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2932 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2935 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2938 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2940 case 'fullpagename':
2941 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2943 case 'fullpagenamee':
2944 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2947 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2949 case 'subpagenamee':
2950 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2952 case 'rootpagename':
2953 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2955 case 'rootpagenamee':
2956 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2959 $this->mTitle
->getRootText()
2962 case 'basepagename':
2963 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2965 case 'basepagenamee':
2966 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2969 $this->mTitle
->getBaseText()
2972 case 'talkpagename':
2973 if ( $this->mTitle
->canTalk() ) {
2974 $talkPage = $this->mTitle
->getTalkPage();
2975 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2980 case 'talkpagenamee':
2981 if ( $this->mTitle
->canTalk() ) {
2982 $talkPage = $this->mTitle
->getTalkPage();
2983 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2988 case 'subjectpagename':
2989 $subjPage = $this->mTitle
->getSubjectPage();
2990 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2992 case 'subjectpagenamee':
2993 $subjPage = $this->mTitle
->getSubjectPage();
2994 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2996 case 'pageid': // requested in bug 23427
2997 $pageid = $this->getTitle()->getArticleID();
2998 if ( $pageid == 0 ) {
2999 # 0 means the page doesn't exist in the database,
3000 # which means the user is previewing a new page.
3001 # The vary-revision flag must be set, because the magic word
3002 # will have a different value once the page is saved.
3003 $this->mOutput
->setFlag( 'vary-revision' );
3004 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3006 $value = $pageid ?
$pageid : null;
3009 # Let the edit saving system know we should parse the page
3010 # *after* a revision ID has been assigned.
3011 $this->mOutput
->setFlag( 'vary-revision' );
3012 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3013 $value = $this->mRevisionId
;
3016 # Let the edit saving system know we should parse the page
3017 # *after* a revision ID has been assigned. This is for null edits.
3018 $this->mOutput
->setFlag( 'vary-revision' );
3019 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3020 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3022 case 'revisionday2':
3023 # Let the edit saving system know we should parse the page
3024 # *after* a revision ID has been assigned. This is for null edits.
3025 $this->mOutput
->setFlag( 'vary-revision' );
3026 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3027 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3029 case 'revisionmonth':
3030 # Let the edit saving system know we should parse the page
3031 # *after* a revision ID has been assigned. This is for null edits.
3032 $this->mOutput
->setFlag( 'vary-revision' );
3033 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3034 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3036 case 'revisionmonth1':
3037 # Let the edit saving system know we should parse the page
3038 # *after* a revision ID has been assigned. This is for null edits.
3039 $this->mOutput
->setFlag( 'vary-revision' );
3040 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3041 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3043 case 'revisionyear':
3044 # Let the edit saving system know we should parse the page
3045 # *after* a revision ID has been assigned. This is for null edits.
3046 $this->mOutput
->setFlag( 'vary-revision' );
3047 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3048 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3050 case 'revisiontimestamp':
3051 # Let the edit saving system know we should parse the page
3052 # *after* a revision ID has been assigned. This is for null edits.
3053 $this->mOutput
->setFlag( 'vary-revision' );
3054 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3055 $value = $this->getRevisionTimestamp();
3057 case 'revisionuser':
3058 # Let the edit saving system know we should parse the page
3059 # *after* a revision ID has been assigned. This is for null edits.
3060 $this->mOutput
->setFlag( 'vary-revision' );
3061 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3062 $value = $this->getRevisionUser();
3064 case 'revisionsize':
3065 # Let the edit saving system know we should parse the page
3066 # *after* a revision ID has been assigned. This is for null edits.
3067 $this->mOutput
->setFlag( 'vary-revision' );
3068 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3069 $value = $this->getRevisionSize();
3072 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3075 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3077 case 'namespacenumber':
3078 $value = $this->mTitle
->getNamespace();
3081 $value = $this->mTitle
->canTalk()
3082 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3086 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3088 case 'subjectspace':
3089 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3091 case 'subjectspacee':
3092 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3094 case 'currentdayname':
3095 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3098 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3101 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3104 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3107 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3108 # int to remove the padding
3109 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3112 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3114 case 'localdayname':
3115 $value = $pageLang->getWeekdayName(
3116 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3120 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3123 $value = $pageLang->time(
3124 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3130 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3133 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3134 # int to remove the padding
3135 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3138 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3140 case 'numberofarticles':
3141 $value = $pageLang->formatNum( SiteStats
::articles() );
3143 case 'numberoffiles':
3144 $value = $pageLang->formatNum( SiteStats
::images() );
3146 case 'numberofusers':
3147 $value = $pageLang->formatNum( SiteStats
::users() );
3149 case 'numberofactiveusers':
3150 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3152 case 'numberofpages':
3153 $value = $pageLang->formatNum( SiteStats
::pages() );
3155 case 'numberofadmins':
3156 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3158 case 'numberofedits':
3159 $value = $pageLang->formatNum( SiteStats
::edits() );
3161 case 'currenttimestamp':
3162 $value = wfTimestamp( TS_MW
, $ts );
3164 case 'localtimestamp':
3165 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3167 case 'currentversion':
3168 $value = SpecialVersion
::getVersion();
3171 return $wgArticlePath;
3177 return $wgServerName;
3179 return $wgScriptPath;
3181 return $wgStylePath;
3182 case 'directionmark':
3183 return $pageLang->getDirMark();
3184 case 'contentlanguage':
3185 global $wgLanguageCode;
3186 return $wgLanguageCode;
3187 case 'cascadingsources':
3188 $value = CoreParserFunctions
::cascadingsources( $this );
3193 'ParserGetVariableValueSwitch',
3194 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3201 $this->mVarCache
[$index] = $value;
3208 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3212 public function initialiseVariables() {
3213 wfProfileIn( __METHOD__
);
3214 $variableIDs = MagicWord
::getVariableIDs();
3215 $substIDs = MagicWord
::getSubstIDs();
3217 $this->mVariables
= new MagicWordArray( $variableIDs );
3218 $this->mSubstWords
= new MagicWordArray( $substIDs );
3219 wfProfileOut( __METHOD__
);
3223 * Preprocess some wikitext and return the document tree.
3224 * This is the ghost of replace_variables().
3226 * @param string $text The text to parse
3227 * @param int $flags Bitwise combination of:
3228 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3229 * included. Default is to assume a direct page view.
3231 * The generated DOM tree must depend only on the input text and the flags.
3232 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3234 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3235 * change in the DOM tree for a given text, must be passed through the section identifier
3236 * in the section edit link and thus back to extractSections().
3238 * The output of this function is currently only cached in process memory, but a persistent
3239 * cache may be implemented at a later date which takes further advantage of these strict
3240 * dependency requirements.
3244 public function preprocessToDom( $text, $flags = 0 ) {
3245 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3250 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3256 public static function splitWhitespace( $s ) {
3257 $ltrimmed = ltrim( $s );
3258 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3259 $trimmed = rtrim( $ltrimmed );
3260 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3262 $w2 = substr( $ltrimmed, -$diff );
3266 return array( $w1, $trimmed, $w2 );
3270 * Replace magic variables, templates, and template arguments
3271 * with the appropriate text. Templates are substituted recursively,
3272 * taking care to avoid infinite loops.
3274 * Note that the substitution depends on value of $mOutputType:
3275 * self::OT_WIKI: only {{subst:}} templates
3276 * self::OT_PREPROCESS: templates but not extension tags
3277 * self::OT_HTML: all templates and extension tags
3279 * @param string $text The text to transform
3280 * @param bool|PPFrame $frame Object describing the arguments passed to the
3281 * template. Arguments may also be provided as an associative array, as
3282 * was the usual case before MW1.12. Providing arguments this way may be
3283 * useful for extensions wishing to perform variable replacement
3285 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3286 * double-brace expansion.
3289 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3290 # Is there any text? Also, Prevent too big inclusions!
3291 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3294 wfProfileIn( __METHOD__
);
3296 if ( $frame === false ) {
3297 $frame = $this->getPreprocessor()->newFrame();
3298 } elseif ( !( $frame instanceof PPFrame
) ) {
3299 wfDebug( __METHOD__
. " called using plain parameters instead of "
3300 . "a PPFrame instance. Creating custom frame.\n" );
3301 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3304 $dom = $this->preprocessToDom( $text );
3305 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3306 $text = $frame->expand( $dom, $flags );
3308 wfProfileOut( __METHOD__
);
3313 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3315 * @param array $args
3319 public static function createAssocArgs( $args ) {
3320 $assocArgs = array();
3322 foreach ( $args as $arg ) {
3323 $eqpos = strpos( $arg, '=' );
3324 if ( $eqpos === false ) {
3325 $assocArgs[$index++
] = $arg;
3327 $name = trim( substr( $arg, 0, $eqpos ) );
3328 $value = trim( substr( $arg, $eqpos +
1 ) );
3329 if ( $value === false ) {
3332 if ( $name !== false ) {
3333 $assocArgs[$name] = $value;
3342 * Warn the user when a parser limitation is reached
3343 * Will warn at most once the user per limitation type
3345 * @param string $limitationType Should be one of:
3346 * 'expensive-parserfunction' (corresponding messages:
3347 * 'expensive-parserfunction-warning',
3348 * 'expensive-parserfunction-category')
3349 * 'post-expand-template-argument' (corresponding messages:
3350 * 'post-expand-template-argument-warning',
3351 * 'post-expand-template-argument-category')
3352 * 'post-expand-template-inclusion' (corresponding messages:
3353 * 'post-expand-template-inclusion-warning',
3354 * 'post-expand-template-inclusion-category')
3355 * 'node-count-exceeded' (corresponding messages:
3356 * 'node-count-exceeded-warning',
3357 * 'node-count-exceeded-category')
3358 * 'expansion-depth-exceeded' (corresponding messages:
3359 * 'expansion-depth-exceeded-warning',
3360 * 'expansion-depth-exceeded-category')
3361 * @param string|int|null $current Current value
3362 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3363 * exceeded, provide the values (optional)
3365 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3366 # does no harm if $current and $max are present but are unnecessary for the message
3367 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3368 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3369 $this->mOutput
->addWarning( $warning );
3370 $this->addTrackingCategory( "$limitationType-category" );
3374 * Return the text of a template, after recursively
3375 * replacing any variables or templates within the template.
3377 * @param array $piece The parts of the template
3378 * $piece['title']: the title, i.e. the part before the |
3379 * $piece['parts']: the parameter array
3380 * $piece['lineStart']: whether the brace was at the start of a line
3381 * @param PPFrame $frame The current frame, contains template arguments
3383 * @return string The text of the template
3385 public function braceSubstitution( $piece, $frame ) {
3386 wfProfileIn( __METHOD__
);
3387 wfProfileIn( __METHOD__
. '-setup' );
3391 // $text has been filled
3393 // wiki markup in $text should be escaped
3395 // $text is HTML, armour it against wikitext transformation
3397 // Force interwiki transclusion to be done in raw mode not rendered
3398 $forceRawInterwiki = false;
3399 // $text is a DOM node needing expansion in a child frame
3400 $isChildObj = false;
3401 // $text is a DOM node needing expansion in the current frame
3402 $isLocalObj = false;
3404 # Title object, where $text came from
3407 # $part1 is the bit before the first |, and must contain only title characters.
3408 # Various prefixes will be stripped from it later.
3409 $titleWithSpaces = $frame->expand( $piece['title'] );
3410 $part1 = trim( $titleWithSpaces );
3413 # Original title text preserved for various purposes
3414 $originalTitle = $part1;
3416 # $args is a list of argument nodes, starting from index 0, not including $part1
3417 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3418 # below won't work b/c this $args isn't an object
3419 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3420 wfProfileOut( __METHOD__
. '-setup' );
3422 $titleProfileIn = null; // profile templates
3425 wfProfileIn( __METHOD__
. '-modifiers' );
3428 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3430 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3431 # Decide whether to expand template or keep wikitext as-is.
3432 if ( $this->ot
['wiki'] ) {
3433 if ( $substMatch === false ) {
3434 $literal = true; # literal when in PST with no prefix
3436 $literal = false; # expand when in PST with subst: or safesubst:
3439 if ( $substMatch == 'subst' ) {
3440 $literal = true; # literal when not in PST with plain subst:
3442 $literal = false; # expand when not in PST with safesubst: or no prefix
3446 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3453 if ( !$found && $args->getLength() == 0 ) {
3454 $id = $this->mVariables
->matchStartToEnd( $part1 );
3455 if ( $id !== false ) {
3456 $text = $this->getVariableValue( $id, $frame );
3457 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3458 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3464 # MSG, MSGNW and RAW
3467 $mwMsgnw = MagicWord
::get( 'msgnw' );
3468 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3471 # Remove obsolete MSG:
3472 $mwMsg = MagicWord
::get( 'msg' );
3473 $mwMsg->matchStartAndRemove( $part1 );
3477 $mwRaw = MagicWord
::get( 'raw' );
3478 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3479 $forceRawInterwiki = true;
3482 wfProfileOut( __METHOD__
. '-modifiers' );
3486 wfProfileIn( __METHOD__
. '-pfunc' );
3488 $colonPos = strpos( $part1, ':' );
3489 if ( $colonPos !== false ) {
3490 $func = substr( $part1, 0, $colonPos );
3491 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3492 for ( $i = 0; $i < $args->getLength(); $i++
) {
3493 $funcArgs[] = $args->item( $i );
3496 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3497 } catch ( Exception
$ex ) {
3498 wfProfileOut( __METHOD__
. '-pfunc' );
3499 wfProfileOut( __METHOD__
);
3503 # The interface for parser functions allows for extracting
3504 # flags into the local scope. Extract any forwarded flags
3508 wfProfileOut( __METHOD__
. '-pfunc' );
3511 # Finish mangling title and then check for loops.
3512 # Set $title to a Title object and $titleText to the PDBK
3515 # Split the title into page and subpage
3517 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3518 if ( $part1 !== $relative ) {
3520 $ns = $this->mTitle
->getNamespace();
3522 $title = Title
::newFromText( $part1, $ns );
3524 $titleText = $title->getPrefixedText();
3525 # Check for language variants if the template is not found
3526 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3527 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3529 # Do recursion depth check
3530 $limit = $this->mOptions
->getMaxTemplateDepth();
3531 if ( $frame->depth
>= $limit ) {
3533 $text = '<span class="error">'
3534 . wfMessage( 'parser-template-recursion-depth-warning' )
3535 ->numParams( $limit )->inContentLanguage()->text()
3541 # Load from database
3542 if ( !$found && $title ) {
3543 if ( !Profiler
::instance()->isPersistent() ) {
3544 # Too many unique items can kill profiling DBs/collectors
3545 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3546 wfProfileIn( $titleProfileIn ); // template in
3548 wfProfileIn( __METHOD__
. '-loadtpl' );
3549 if ( !$title->isExternal() ) {
3550 if ( $title->isSpecialPage()
3551 && $this->mOptions
->getAllowSpecialInclusion()
3552 && $this->ot
['html']
3554 // Pass the template arguments as URL parameters.
3555 // "uselang" will have no effect since the Language object
3556 // is forced to the one defined in ParserOptions.
3557 $pageArgs = array();
3558 $argsLength = $args->getLength();
3559 for ( $i = 0; $i < $argsLength; $i++
) {
3560 $bits = $args->item( $i )->splitArg();
3561 if ( strval( $bits['index'] ) === '' ) {
3562 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3563 $value = trim( $frame->expand( $bits['value'] ) );
3564 $pageArgs[$name] = $value;
3568 // Create a new context to execute the special page
3569 $context = new RequestContext
;
3570 $context->setTitle( $title );
3571 $context->setRequest( new FauxRequest( $pageArgs ) );
3572 $context->setUser( $this->getUser() );
3573 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3574 $ret = SpecialPageFactory
::capturePath( $title, $context );
3576 $text = $context->getOutput()->getHTML();
3577 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3580 $this->disableCache();
3582 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3583 $found = false; # access denied
3584 wfDebug( __METHOD__
. ": template inclusion denied for " .
3585 $title->getPrefixedDBkey() . "\n" );
3587 list( $text, $title ) = $this->getTemplateDom( $title );
3588 if ( $text !== false ) {
3594 # If the title is valid but undisplayable, make a link to it
3595 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3596 $text = "[[:$titleText]]";
3599 } elseif ( $title->isTrans() ) {
3600 # Interwiki transclusion
3601 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3602 $text = $this->interwikiTransclude( $title, 'render' );
3605 $text = $this->interwikiTransclude( $title, 'raw' );
3606 # Preprocess it like a template
3607 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3613 # Do infinite loop check
3614 # This has to be done after redirect resolution to avoid infinite loops via redirects
3615 if ( !$frame->loopCheck( $title ) ) {
3617 $text = '<span class="error">'
3618 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3620 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3622 wfProfileOut( __METHOD__
. '-loadtpl' );
3625 # If we haven't found text to substitute by now, we're done
3626 # Recover the source wikitext and return it
3628 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3629 if ( $titleProfileIn ) {
3630 wfProfileOut( $titleProfileIn ); // template out
3632 wfProfileOut( __METHOD__
);
3633 return array( 'object' => $text );
3636 # Expand DOM-style return values in a child frame
3637 if ( $isChildObj ) {
3638 # Clean up argument array
3639 $newFrame = $frame->newChild( $args, $title );
3642 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3643 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3644 # Expansion is eligible for the empty-frame cache
3645 $text = $newFrame->cachedExpand( $titleText, $text );
3647 # Uncached expansion
3648 $text = $newFrame->expand( $text );
3651 if ( $isLocalObj && $nowiki ) {
3652 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3653 $isLocalObj = false;
3656 if ( $titleProfileIn ) {
3657 wfProfileOut( $titleProfileIn ); // template out
3660 # Replace raw HTML by a placeholder
3662 $text = $this->insertStripItem( $text );
3663 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3664 # Escape nowiki-style return values
3665 $text = wfEscapeWikiText( $text );
3666 } elseif ( is_string( $text )
3667 && !$piece['lineStart']
3668 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3670 # Bug 529: if the template begins with a table or block-level
3671 # element, it should be treated as beginning a new line.
3672 # This behavior is somewhat controversial.
3673 $text = "\n" . $text;
3676 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3677 # Error, oversize inclusion
3678 if ( $titleText !== false ) {
3679 # Make a working, properly escaped link if possible (bug 23588)
3680 $text = "[[:$titleText]]";
3682 # This will probably not be a working link, but at least it may
3683 # provide some hint of where the problem is
3684 preg_replace( '/^:/', '', $originalTitle );
3685 $text = "[[:$originalTitle]]";
3687 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3688 . 'post-expand include size too large -->' );
3689 $this->limitationWarn( 'post-expand-template-inclusion' );
3692 if ( $isLocalObj ) {
3693 $ret = array( 'object' => $text );
3695 $ret = array( 'text' => $text );
3698 wfProfileOut( __METHOD__
);
3703 * Call a parser function and return an array with text and flags.
3705 * The returned array will always contain a boolean 'found', indicating
3706 * whether the parser function was found or not. It may also contain the
3708 * text: string|object, resulting wikitext or PP DOM object
3709 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3710 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3711 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3712 * nowiki: bool, wiki markup in $text should be escaped
3715 * @param PPFrame $frame The current frame, contains template arguments
3716 * @param string $function Function name
3717 * @param array $args Arguments to the function
3718 * @throws MWException
3721 public function callParserFunction( $frame, $function, array $args = array() ) {
3724 wfProfileIn( __METHOD__
);
3726 # Case sensitive functions
3727 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3728 $function = $this->mFunctionSynonyms
[1][$function];
3730 # Case insensitive functions
3731 $function = $wgContLang->lc( $function );
3732 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3733 $function = $this->mFunctionSynonyms
[0][$function];
3735 wfProfileOut( __METHOD__
);
3736 return array( 'found' => false );
3740 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3741 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3743 # Workaround for PHP bug 35229 and similar
3744 if ( !is_callable( $callback ) ) {
3745 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3746 wfProfileOut( __METHOD__
);
3747 throw new MWException( "Tag hook for $function is not callable\n" );
3750 $allArgs = array( &$this );
3751 if ( $flags & SFH_OBJECT_ARGS
) {
3752 # Convert arguments to PPNodes and collect for appending to $allArgs
3753 $funcArgs = array();
3754 foreach ( $args as $k => $v ) {
3755 if ( $v instanceof PPNode ||
$k === 0 ) {
3758 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3762 # Add a frame parameter, and pass the arguments as an array
3763 $allArgs[] = $frame;
3764 $allArgs[] = $funcArgs;
3766 # Convert arguments to plain text and append to $allArgs
3767 foreach ( $args as $k => $v ) {
3768 if ( $v instanceof PPNode
) {
3769 $allArgs[] = trim( $frame->expand( $v ) );
3770 } elseif ( is_int( $k ) && $k >= 0 ) {
3771 $allArgs[] = trim( $v );
3773 $allArgs[] = trim( "$k=$v" );
3778 $result = call_user_func_array( $callback, $allArgs );
3780 # The interface for function hooks allows them to return a wikitext
3781 # string or an array containing the string and any flags. This mungs
3782 # things around to match what this method should return.
3783 if ( !is_array( $result ) ) {
3789 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3790 $result['text'] = $result[0];
3792 unset( $result[0] );
3799 $preprocessFlags = 0;
3800 if ( isset( $result['noparse'] ) ) {
3801 $noparse = $result['noparse'];
3803 if ( isset( $result['preprocessFlags'] ) ) {
3804 $preprocessFlags = $result['preprocessFlags'];
3808 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3809 $result['isChildObj'] = true;
3811 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3812 wfProfileOut( __METHOD__
);
3818 * Get the semi-parsed DOM representation of a template with a given title,
3819 * and its redirect destination title. Cached.
3821 * @param Title $title
3825 public function getTemplateDom( $title ) {
3826 $cacheTitle = $title;
3827 $titleText = $title->getPrefixedDBkey();
3829 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3830 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3831 $title = Title
::makeTitle( $ns, $dbk );
3832 $titleText = $title->getPrefixedDBkey();
3834 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3835 return array( $this->mTplDomCache
[$titleText], $title );
3838 # Cache miss, go to the database
3839 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3841 if ( $text === false ) {
3842 $this->mTplDomCache
[$titleText] = false;
3843 return array( false, $title );
3846 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3847 $this->mTplDomCache
[$titleText] = $dom;
3849 if ( !$title->equals( $cacheTitle ) ) {
3850 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3851 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3854 return array( $dom, $title );
3858 * Fetch the current revision of a given title. Note that the revision
3859 * (and even the title) may not exist in the database, so everything
3860 * contributing to the output of the parser should use this method
3861 * where possible, rather than getting the revisions themselves. This
3862 * method also caches its results, so using it benefits performance.
3865 * @param Title $title
3868 public function fetchCurrentRevisionOfTitle( $title ) {
3869 $cacheKey = $title->getPrefixedDBkey();
3870 if ( !$this->currentRevisionCache
) {
3871 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3873 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3874 $this->currentRevisionCache
->set( $cacheKey,
3875 // Defaults to Parser::statelessFetchRevision()
3876 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3879 return $this->currentRevisionCache
->get( $cacheKey );
3883 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3884 * without passing them on to it.
3887 * @param Title $title
3888 * @param Parser|bool $parser
3891 public static function statelessFetchRevision( $title, $parser = false ) {
3892 return Revision
::newFromTitle( $title );
3896 * Fetch the unparsed text of a template and register a reference to it.
3897 * @param Title $title
3898 * @return array ( string or false, Title )
3900 public function fetchTemplateAndTitle( $title ) {
3901 // Defaults to Parser::statelessFetchTemplate()
3902 $templateCb = $this->mOptions
->getTemplateCallback();
3903 $stuff = call_user_func( $templateCb, $title, $this );
3904 $text = $stuff['text'];
3905 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3906 if ( isset( $stuff['deps'] ) ) {
3907 foreach ( $stuff['deps'] as $dep ) {
3908 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3909 if ( $dep['title']->equals( $this->getTitle() ) ) {
3910 // If we transclude ourselves, the final result
3911 // will change based on the new version of the page
3912 $this->mOutput
->setFlag( 'vary-revision' );
3916 return array( $text, $finalTitle );
3920 * Fetch the unparsed text of a template and register a reference to it.
3921 * @param Title $title
3922 * @return string|bool
3924 public function fetchTemplate( $title ) {
3925 $rv = $this->fetchTemplateAndTitle( $title );
3930 * Static function to get a template
3931 * Can be overridden via ParserOptions::setTemplateCallback().
3933 * @param Title $title
3934 * @param bool|Parser $parser
3938 public static function statelessFetchTemplate( $title, $parser = false ) {
3939 $text = $skip = false;
3940 $finalTitle = $title;
3943 # Loop to fetch the article, with up to 1 redirect
3944 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3945 # Give extensions a chance to select the revision instead
3946 $id = false; # Assume current
3947 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3948 array( $parser, $title, &$skip, &$id ) );
3954 'page_id' => $title->getArticleID(),
3961 $rev = Revision
::newFromId( $id );
3962 } elseif ( $parser ) {
3963 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3965 $rev = Revision
::newFromTitle( $title );
3967 $rev_id = $rev ?
$rev->getId() : 0;
3968 # If there is no current revision, there is no page
3969 if ( $id === false && !$rev ) {
3970 $linkCache = LinkCache
::singleton();
3971 $linkCache->addBadLinkObj( $title );
3976 'page_id' => $title->getArticleID(),
3977 'rev_id' => $rev_id );
3978 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3979 # We fetched a rev from a different title; register it too...
3981 'title' => $rev->getTitle(),
3982 'page_id' => $rev->getPage(),
3983 'rev_id' => $rev_id );
3987 $content = $rev->getContent();
3988 $text = $content ?
$content->getWikitextForTransclusion() : null;
3990 if ( $text === false ||
$text === null ) {
3994 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3996 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3997 if ( !$message->exists() ) {
4001 $content = $message->content();
4002 $text = $message->plain();
4010 $finalTitle = $title;
4011 $title = $content->getRedirectTarget();
4015 'finalTitle' => $finalTitle,
4020 * Fetch a file and its title and register a reference to it.
4021 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4022 * @param Title $title
4023 * @param array $options Array of options to RepoGroup::findFile
4026 public function fetchFile( $title, $options = array() ) {
4027 $res = $this->fetchFileAndTitle( $title, $options );
4032 * Fetch a file and its title and register a reference to it.
4033 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4034 * @param Title $title
4035 * @param array $options Array of options to RepoGroup::findFile
4036 * @return array ( File or false, Title of file )
4038 public function fetchFileAndTitle( $title, $options = array() ) {
4039 $file = $this->fetchFileNoRegister( $title, $options );
4041 $time = $file ?
$file->getTimestamp() : false;
4042 $sha1 = $file ?
$file->getSha1() : false;
4043 # Register the file as a dependency...
4044 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4045 if ( $file && !$title->equals( $file->getTitle() ) ) {
4046 # Update fetched file title
4047 $title = $file->getTitle();
4048 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4050 return array( $file, $title );
4054 * Helper function for fetchFileAndTitle.
4056 * Also useful if you need to fetch a file but not use it yet,
4057 * for example to get the file's handler.
4059 * @param Title $title
4060 * @param array $options Array of options to RepoGroup::findFile
4063 protected function fetchFileNoRegister( $title, $options = array() ) {
4064 if ( isset( $options['broken'] ) ) {
4065 $file = false; // broken thumbnail forced by hook
4066 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4067 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4068 } else { // get by (name,timestamp)
4069 $file = wfFindFile( $title, $options );
4075 * Transclude an interwiki link.
4077 * @param Title $title
4078 * @param string $action
4082 public function interwikiTransclude( $title, $action ) {
4083 global $wgEnableScaryTranscluding;
4085 if ( !$wgEnableScaryTranscluding ) {
4086 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4089 $url = $title->getFullURL( array( 'action' => $action ) );
4091 if ( strlen( $url ) > 255 ) {
4092 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4094 return $this->fetchScaryTemplateMaybeFromCache( $url );
4098 * @param string $url
4099 * @return mixed|string
4101 public function fetchScaryTemplateMaybeFromCache( $url ) {
4102 global $wgTranscludeCacheExpiry;
4103 $dbr = wfGetDB( DB_SLAVE
);
4104 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4105 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4106 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4108 return $obj->tc_contents
;
4111 $req = MWHttpRequest
::factory( $url );
4112 $status = $req->execute(); // Status object
4113 if ( $status->isOK() ) {
4114 $text = $req->getContent();
4115 } elseif ( $req->getStatus() != 200 ) {
4116 // Though we failed to fetch the content, this status is useless.
4117 return wfMessage( 'scarytranscludefailed-httpstatus' )
4118 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4120 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4123 $dbw = wfGetDB( DB_MASTER
);
4124 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4126 'tc_time' => $dbw->timestamp( time() ),
4127 'tc_contents' => $text
4133 * Triple brace replacement -- used for template arguments
4136 * @param array $piece
4137 * @param PPFrame $frame
4141 public function argSubstitution( $piece, $frame ) {
4142 wfProfileIn( __METHOD__
);
4145 $parts = $piece['parts'];
4146 $nameWithSpaces = $frame->expand( $piece['title'] );
4147 $argName = trim( $nameWithSpaces );
4149 $text = $frame->getArgument( $argName );
4150 if ( $text === false && $parts->getLength() > 0
4151 && ( $this->ot
['html']
4153 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4156 # No match in frame, use the supplied default
4157 $object = $parts->item( 0 )->getChildren();
4159 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4160 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4161 $this->limitationWarn( 'post-expand-template-argument' );
4164 if ( $text === false && $object === false ) {
4166 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4168 if ( $error !== false ) {
4171 if ( $object !== false ) {
4172 $ret = array( 'object' => $object );
4174 $ret = array( 'text' => $text );
4177 wfProfileOut( __METHOD__
);
4182 * Return the text to be used for a given extension tag.
4183 * This is the ghost of strip().
4185 * @param array $params Associative array of parameters:
4186 * name PPNode for the tag name
4187 * attr PPNode for unparsed text where tag attributes are thought to be
4188 * attributes Optional associative array of parsed attributes
4189 * inner Contents of extension element
4190 * noClose Original text did not have a close tag
4191 * @param PPFrame $frame
4193 * @throws MWException
4196 public function extensionSubstitution( $params, $frame ) {
4197 $name = $frame->expand( $params['name'] );
4198 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4199 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4200 $marker = "{$this->mUniqPrefix}-$name-"
4201 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4203 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4204 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4205 if ( $isFunctionTag ) {
4206 $markerType = 'none';
4208 $markerType = 'general';
4210 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4211 $name = strtolower( $name );
4212 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4213 if ( isset( $params['attributes'] ) ) {
4214 $attributes = $attributes +
$params['attributes'];
4217 if ( isset( $this->mTagHooks
[$name] ) ) {
4218 # Workaround for PHP bug 35229 and similar
4219 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4220 throw new MWException( "Tag hook for $name is not callable\n" );
4222 $output = call_user_func_array( $this->mTagHooks
[$name],
4223 array( $content, $attributes, $this, $frame ) );
4224 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4225 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4226 if ( !is_callable( $callback ) ) {
4227 throw new MWException( "Tag hook for $name is not callable\n" );
4230 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4232 $output = '<span class="error">Invalid tag extension name: ' .
4233 htmlspecialchars( $name ) . '</span>';
4236 if ( is_array( $output ) ) {
4237 # Extract flags to local scope (to override $markerType)
4239 $output = $flags[0];
4244 if ( is_null( $attrText ) ) {
4247 if ( isset( $params['attributes'] ) ) {
4248 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4249 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4250 htmlspecialchars( $attrValue ) . '"';
4253 if ( $content === null ) {
4254 $output = "<$name$attrText/>";
4256 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4257 $output = "<$name$attrText>$content$close";
4261 if ( $markerType === 'none' ) {
4263 } elseif ( $markerType === 'nowiki' ) {
4264 $this->mStripState
->addNoWiki( $marker, $output );
4265 } elseif ( $markerType === 'general' ) {
4266 $this->mStripState
->addGeneral( $marker, $output );
4268 throw new MWException( __METHOD__
. ': invalid marker type' );
4274 * Increment an include size counter
4276 * @param string $type The type of expansion
4277 * @param int $size The size of the text
4278 * @return bool False if this inclusion would take it over the maximum, true otherwise
4280 public function incrementIncludeSize( $type, $size ) {
4281 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4284 $this->mIncludeSizes
[$type] +
= $size;
4290 * Increment the expensive function count
4292 * @return bool False if the limit has been exceeded
4294 public function incrementExpensiveFunctionCount() {
4295 $this->mExpensiveFunctionCount++
;
4296 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4300 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4301 * Fills $this->mDoubleUnderscores, returns the modified text
4303 * @param string $text
4307 public function doDoubleUnderscore( $text ) {
4308 wfProfileIn( __METHOD__
);
4310 # The position of __TOC__ needs to be recorded
4311 $mw = MagicWord
::get( 'toc' );
4312 if ( $mw->match( $text ) ) {
4313 $this->mShowToc
= true;
4314 $this->mForceTocPosition
= true;
4316 # Set a placeholder. At the end we'll fill it in with the TOC.
4317 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4319 # Only keep the first one.
4320 $text = $mw->replace( '', $text );
4323 # Now match and remove the rest of them
4324 $mwa = MagicWord
::getDoubleUnderscoreArray();
4325 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4327 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4328 $this->mOutput
->mNoGallery
= true;
4330 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4331 $this->mShowToc
= false;
4333 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4334 && $this->mTitle
->getNamespace() == NS_CATEGORY
4336 $this->addTrackingCategory( 'hidden-category-category' );
4338 # (bug 8068) Allow control over whether robots index a page.
4340 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4341 # is not desirable, the last one on the page should win.
4342 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4343 $this->mOutput
->setIndexPolicy( 'noindex' );
4344 $this->addTrackingCategory( 'noindex-category' );
4346 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4347 $this->mOutput
->setIndexPolicy( 'index' );
4348 $this->addTrackingCategory( 'index-category' );
4351 # Cache all double underscores in the database
4352 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4353 $this->mOutput
->setProperty( $key, '' );
4356 wfProfileOut( __METHOD__
);
4361 * @see ParserOutput::addTrackingCategory()
4362 * @param string $msg Message key
4363 * @return bool Whether the addition was successful
4365 public function addTrackingCategory( $msg ) {
4366 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4370 * This function accomplishes several tasks:
4371 * 1) Auto-number headings if that option is enabled
4372 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4373 * 3) Add a Table of contents on the top for users who have enabled the option
4374 * 4) Auto-anchor headings
4376 * It loops through all headlines, collects the necessary data, then splits up the
4377 * string and re-inserts the newly formatted headlines.
4379 * @param string $text
4380 * @param string $origText Original, untouched wikitext
4381 * @param bool $isMain
4382 * @return mixed|string
4385 public function formatHeadings( $text, $origText, $isMain = true ) {
4386 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4388 # Inhibit editsection links if requested in the page
4389 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4390 $maybeShowEditLink = $showEditLink = false;
4392 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4393 $showEditLink = $this->mOptions
->getEditSection();
4395 if ( $showEditLink ) {
4396 $this->mOutput
->setEditSectionTokens( true );
4399 # Get all headlines for numbering them and adding funky stuff like [edit]
4400 # links - this is for later, but we need the number of headlines right now
4402 $numMatches = preg_match_all(
4403 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4408 # if there are fewer than 4 headlines in the article, do not show TOC
4409 # unless it's been explicitly enabled.
4410 $enoughToc = $this->mShowToc
&&
4411 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4413 # Allow user to stipulate that a page should have a "new section"
4414 # link added via __NEWSECTIONLINK__
4415 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4416 $this->mOutput
->setNewSection( true );
4419 # Allow user to remove the "new section"
4420 # link via __NONEWSECTIONLINK__
4421 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4422 $this->mOutput
->hideNewSection( true );
4425 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4426 # override above conditions and always show TOC above first header
4427 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4428 $this->mShowToc
= true;
4436 # Ugh .. the TOC should have neat indentation levels which can be
4437 # passed to the skin functions. These are determined here
4441 $sublevelCount = array();
4442 $levelCount = array();
4447 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4448 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4449 $oldType = $this->mOutputType
;
4450 $this->setOutputType( self
::OT_WIKI
);
4451 $frame = $this->getPreprocessor()->newFrame();
4452 $root = $this->preprocessToDom( $origText );
4453 $node = $root->getFirstChild();
4458 foreach ( $matches[3] as $headline ) {
4459 $isTemplate = false;
4461 $sectionIndex = false;
4463 $markerMatches = array();
4464 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4465 $serial = $markerMatches[1];
4466 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4467 $isTemplate = ( $titleText != $baseTitleText );
4468 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4472 $prevlevel = $level;
4474 $level = $matches[1][$headlineCount];
4476 if ( $level > $prevlevel ) {
4477 # Increase TOC level
4479 $sublevelCount[$toclevel] = 0;
4480 if ( $toclevel < $wgMaxTocLevel ) {
4481 $prevtoclevel = $toclevel;
4482 $toc .= Linker
::tocIndent();
4485 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4486 # Decrease TOC level, find level to jump to
4488 for ( $i = $toclevel; $i > 0; $i-- ) {
4489 if ( $levelCount[$i] == $level ) {
4490 # Found last matching level
4493 } elseif ( $levelCount[$i] < $level ) {
4494 # Found first matching level below current level
4502 if ( $toclevel < $wgMaxTocLevel ) {
4503 if ( $prevtoclevel < $wgMaxTocLevel ) {
4504 # Unindent only if the previous toc level was shown :p
4505 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4506 $prevtoclevel = $toclevel;
4508 $toc .= Linker
::tocLineEnd();
4512 # No change in level, end TOC line
4513 if ( $toclevel < $wgMaxTocLevel ) {
4514 $toc .= Linker
::tocLineEnd();
4518 $levelCount[$toclevel] = $level;
4520 # count number of headlines for each level
4521 $sublevelCount[$toclevel]++
;
4523 for ( $i = 1; $i <= $toclevel; $i++
) {
4524 if ( !empty( $sublevelCount[$i] ) ) {
4528 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4533 # The safe header is a version of the header text safe to use for links
4535 # Remove link placeholders by the link text.
4536 # <!--LINK number-->
4538 # link text with suffix
4539 # Do this before unstrip since link text can contain strip markers
4540 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4542 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4543 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4545 # Strip out HTML (first regex removes any tag not allowed)
4547 # * <sup> and <sub> (bug 8393)
4550 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4552 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4553 # to allow setting directionality in toc items.
4554 $tocline = preg_replace(
4556 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4557 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4559 array( '', '<$1>' ),
4562 $tocline = trim( $tocline );
4564 # For the anchor, strip out HTML-y stuff period
4565 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4566 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4568 # Save headline for section edit hint before it's escaped
4569 $headlineHint = $safeHeadline;
4571 if ( $wgExperimentalHtmlIds ) {
4572 # For reverse compatibility, provide an id that's
4573 # HTML4-compatible, like we used to.
4575 # It may be worth noting, academically, that it's possible for
4576 # the legacy anchor to conflict with a non-legacy headline
4577 # anchor on the page. In this case likely the "correct" thing
4578 # would be to either drop the legacy anchors or make sure
4579 # they're numbered first. However, this would require people
4580 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4581 # manually, so let's not bother worrying about it.
4582 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4583 array( 'noninitial', 'legacy' ) );
4584 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4586 if ( $legacyHeadline == $safeHeadline ) {
4587 # No reason to have both (in fact, we can't)
4588 $legacyHeadline = false;
4591 $legacyHeadline = false;
4592 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4596 # HTML names must be case-insensitively unique (bug 10721).
4597 # This does not apply to Unicode characters per
4598 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4599 # @todo FIXME: We may be changing them depending on the current locale.
4600 $arrayKey = strtolower( $safeHeadline );
4601 if ( $legacyHeadline === false ) {
4602 $legacyArrayKey = false;
4604 $legacyArrayKey = strtolower( $legacyHeadline );
4607 # count how many in assoc. array so we can track dupes in anchors
4608 if ( isset( $refers[$arrayKey] ) ) {
4609 $refers[$arrayKey]++
;
4611 $refers[$arrayKey] = 1;
4613 if ( isset( $refers[$legacyArrayKey] ) ) {
4614 $refers[$legacyArrayKey]++
;
4616 $refers[$legacyArrayKey] = 1;
4619 # Don't number the heading if it is the only one (looks silly)
4620 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4621 # the two are different if the line contains a link
4622 $headline = Html
::element(
4624 array( 'class' => 'mw-headline-number' ),
4626 ) . ' ' . $headline;
4629 # Create the anchor for linking from the TOC to the section
4630 $anchor = $safeHeadline;
4631 $legacyAnchor = $legacyHeadline;
4632 if ( $refers[$arrayKey] > 1 ) {
4633 $anchor .= '_' . $refers[$arrayKey];
4635 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4636 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4638 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4639 $toc .= Linker
::tocLine( $anchor, $tocline,
4640 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4643 # Add the section to the section tree
4644 # Find the DOM node for this header
4645 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4646 while ( $node && !$noOffset ) {
4647 if ( $node->getName() === 'h' ) {
4648 $bits = $node->splitHeading();
4649 if ( $bits['i'] == $sectionIndex ) {
4653 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4654 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4655 $node = $node->getNextSibling();
4658 'toclevel' => $toclevel,
4661 'number' => $numbering,
4662 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4663 'fromtitle' => $titleText,
4664 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4665 'anchor' => $anchor,
4668 # give headline the correct <h#> tag
4669 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4670 // Output edit section links as markers with styles that can be customized by skins
4671 if ( $isTemplate ) {
4672 # Put a T flag in the section identifier, to indicate to extractSections()
4673 # that sections inside <includeonly> should be counted.
4674 $editsectionPage = $titleText;
4675 $editsectionSection = "T-$sectionIndex";
4676 $editsectionContent = null;
4678 $editsectionPage = $this->mTitle
->getPrefixedText();
4679 $editsectionSection = $sectionIndex;
4680 $editsectionContent = $headlineHint;
4682 // We use a bit of pesudo-xml for editsection markers. The
4683 // language converter is run later on. Using a UNIQ style marker
4684 // leads to the converter screwing up the tokens when it
4685 // converts stuff. And trying to insert strip tags fails too. At
4686 // this point all real inputted tags have already been escaped,
4687 // so we don't have to worry about a user trying to input one of
4688 // these markers directly. We use a page and section attribute
4689 // to stop the language converter from converting these
4690 // important bits of data, but put the headline hint inside a
4691 // content block because the language converter is supposed to
4692 // be able to convert that piece of data.
4693 // Gets replaced with html in ParserOutput::getText
4694 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4695 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4696 if ( $editsectionContent !== null ) {
4697 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4704 $head[$headlineCount] = Linker
::makeHeadline( $level,
4705 $matches['attrib'][$headlineCount], $anchor, $headline,
4706 $editlink, $legacyAnchor );
4711 $this->setOutputType( $oldType );
4713 # Never ever show TOC if no headers
4714 if ( $numVisible < 1 ) {
4719 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4720 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4722 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4723 $this->mOutput
->setTOCHTML( $toc );
4724 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4725 $this->mOutput
->addModules( 'mediawiki.toc' );
4729 $this->mOutput
->setSections( $tocraw );
4732 # split up and insert constructed headlines
4733 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4736 // build an array of document sections
4737 $sections = array();
4738 foreach ( $blocks as $block ) {
4739 // $head is zero-based, sections aren't.
4740 if ( empty( $head[$i - 1] ) ) {
4741 $sections[$i] = $block;
4743 $sections[$i] = $head[$i - 1] . $block;
4747 * Send a hook, one per section.
4748 * The idea here is to be able to make section-level DIVs, but to do so in a
4749 * lower-impact, more correct way than r50769
4752 * $section : the section number
4753 * &$sectionContent : ref to the content of the section
4754 * $showEditLinks : boolean describing whether this section has an edit link
4756 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4761 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4762 // append the TOC at the beginning
4763 // Top anchor now in skin
4764 $sections[0] = $sections[0] . $toc . "\n";
4767 $full .= join( '', $sections );
4769 if ( $this->mForceTocPosition
) {
4770 return str_replace( '<!--MWTOC-->', $toc, $full );
4777 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4778 * conversion, substitting signatures, {{subst:}} templates, etc.
4780 * @param string $text The text to transform
4781 * @param Title $title The Title object for the current article
4782 * @param User $user The User object describing the current user
4783 * @param ParserOptions $options Parsing options
4784 * @param bool $clearState Whether to clear the parser state first
4785 * @return string The altered wiki markup
4787 public function preSaveTransform( $text, Title
$title, User
$user,
4788 ParserOptions
$options, $clearState = true
4790 if ( $clearState ) {
4791 $magicScopeVariable = $this->lock();
4793 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4794 $this->setUser( $user );
4799 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4800 if ( $options->getPreSaveTransform() ) {
4801 $text = $this->pstPass2( $text, $user );
4803 $text = $this->mStripState
->unstripBoth( $text );
4805 $this->setUser( null ); #Reset
4811 * Pre-save transform helper function
4813 * @param string $text
4818 private function pstPass2( $text, $user ) {
4821 # Note: This is the timestamp saved as hardcoded wikitext to
4822 # the database, we use $wgContLang here in order to give
4823 # everyone the same signature and use the default one rather
4824 # than the one selected in each user's preferences.
4825 # (see also bug 12815)
4826 $ts = $this->mOptions
->getTimestamp();
4827 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4828 $ts = $timestamp->format( 'YmdHis' );
4829 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4831 # Allow translation of timezones through wiki. format() can return
4832 # whatever crap the system uses, localised or not, so we cannot
4833 # ship premade translations.
4834 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4835 $msg = wfMessage( $key )->inContentLanguage();
4836 if ( $msg->exists() ) {
4837 $tzMsg = $msg->text();
4840 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4842 # Variable replacement
4843 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4844 $text = $this->replaceVariables( $text );
4846 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4847 # which may corrupt this parser instance via its wfMessage()->text() call-
4850 $sigText = $this->getUserSig( $user );
4851 $text = strtr( $text, array(
4853 '~~~~' => "$sigText $d",
4857 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4858 $tc = '[' . Title
::legalChars() . ']';
4859 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4861 // [[ns:page (context)|]]
4862 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4863 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4864 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4865 // [[ns:page (context), context|]] (using either single or double-width comma)
4866 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4867 // [[|page]] (reverse pipe trick: add context from page title)
4868 $p2 = "/\[\[\\|($tc+)]]/";
4870 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4871 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4872 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4873 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4875 $t = $this->mTitle
->getText();
4877 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4878 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4879 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4880 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4882 # if there's no context, don't bother duplicating the title
4883 $text = preg_replace( $p2, '[[\\1]]', $text );
4886 # Trim trailing whitespace
4887 $text = rtrim( $text );
4893 * Fetch the user's signature text, if any, and normalize to
4894 * validated, ready-to-insert wikitext.
4895 * If you have pre-fetched the nickname or the fancySig option, you can
4896 * specify them here to save a database query.
4897 * Do not reuse this parser instance after calling getUserSig(),
4898 * as it may have changed if it's the $wgParser.
4901 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4902 * @param bool|null $fancySig whether the nicknname is the complete signature
4903 * or null to use default value
4906 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4907 global $wgMaxSigChars;
4909 $username = $user->getName();
4911 # If not given, retrieve from the user object.
4912 if ( $nickname === false ) {
4913 $nickname = $user->getOption( 'nickname' );
4916 if ( is_null( $fancySig ) ) {
4917 $fancySig = $user->getBoolOption( 'fancysig' );
4920 $nickname = $nickname == null ?
$username : $nickname;
4922 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4923 $nickname = $username;
4924 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4925 } elseif ( $fancySig !== false ) {
4926 # Sig. might contain markup; validate this
4927 if ( $this->validateSig( $nickname ) !== false ) {
4928 # Validated; clean up (if needed) and return it
4929 return $this->cleanSig( $nickname, true );
4931 # Failed to validate; fall back to the default
4932 $nickname = $username;
4933 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4937 # Make sure nickname doesnt get a sig in a sig
4938 $nickname = self
::cleanSigInSig( $nickname );
4940 # If we're still here, make it a link to the user page
4941 $userText = wfEscapeWikiText( $username );
4942 $nickText = wfEscapeWikiText( $nickname );
4943 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4945 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4946 ->title( $this->getTitle() )->text();
4950 * Check that the user's signature contains no bad XML
4952 * @param string $text
4953 * @return string|bool An expanded string, or false if invalid.
4955 public function validateSig( $text ) {
4956 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4960 * Clean up signature text
4962 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4963 * 2) Substitute all transclusions
4965 * @param string $text
4966 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4967 * @return string Signature text
4969 public function cleanSig( $text, $parsing = false ) {
4972 $magicScopeVariable = $this->lock();
4973 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4976 # Option to disable this feature
4977 if ( !$this->mOptions
->getCleanSignatures() ) {
4981 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4982 # => Move this logic to braceSubstitution()
4983 $substWord = MagicWord
::get( 'subst' );
4984 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4985 $substText = '{{' . $substWord->getSynonym( 0 );
4987 $text = preg_replace( $substRegex, $substText, $text );
4988 $text = self
::cleanSigInSig( $text );
4989 $dom = $this->preprocessToDom( $text );
4990 $frame = $this->getPreprocessor()->newFrame();
4991 $text = $frame->expand( $dom );
4994 $text = $this->mStripState
->unstripBoth( $text );
5001 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5003 * @param string $text
5004 * @return string Signature text with /~{3,5}/ removed
5006 public static function cleanSigInSig( $text ) {
5007 $text = preg_replace( '/~{3,5}/', '', $text );
5012 * Set up some variables which are usually set up in parse()
5013 * so that an external function can call some class members with confidence
5015 * @param Title|null $title
5016 * @param ParserOptions $options
5017 * @param int $outputType
5018 * @param bool $clearState
5020 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5021 $outputType, $clearState = true
5023 $this->startParse( $title, $options, $outputType, $clearState );
5027 * @param Title|null $title
5028 * @param ParserOptions $options
5029 * @param int $outputType
5030 * @param bool $clearState
5032 private function startParse( Title
$title = null, ParserOptions
$options,
5033 $outputType, $clearState = true
5035 $this->setTitle( $title );
5036 $this->mOptions
= $options;
5037 $this->setOutputType( $outputType );
5038 if ( $clearState ) {
5039 $this->clearState();
5044 * Wrapper for preprocess()
5046 * @param string $text The text to preprocess
5047 * @param ParserOptions $options Options
5048 * @param Title|null $title Title object or null to use $wgTitle
5051 public function transformMsg( $text, $options, $title = null ) {
5052 static $executing = false;
5054 # Guard against infinite recursion
5060 wfProfileIn( __METHOD__
);
5066 $text = $this->preprocess( $text, $title, $options );
5069 wfProfileOut( __METHOD__
);
5074 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5075 * The callback should have the following form:
5076 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5078 * Transform and return $text. Use $parser for any required context, e.g. use
5079 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5081 * Hooks may return extended information by returning an array, of which the
5082 * first numbered element (index 0) must be the return string, and all other
5083 * entries are extracted into local variables within an internal function
5084 * in the Parser class.
5086 * This interface (introduced r61913) appears to be undocumented, but
5087 * 'markerName' is used by some core tag hooks to override which strip
5088 * array their results are placed in. **Use great caution if attempting
5089 * this interface, as it is not documented and injudicious use could smash
5090 * private variables.**
5092 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5093 * @param callable $callback The callback function (and object) to use for the tag
5094 * @throws MWException
5095 * @return callable|null The old value of the mTagHooks array associated with the hook
5097 public function setHook( $tag, $callback ) {
5098 $tag = strtolower( $tag );
5099 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5100 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5102 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5103 $this->mTagHooks
[$tag] = $callback;
5104 if ( !in_array( $tag, $this->mStripList
) ) {
5105 $this->mStripList
[] = $tag;
5112 * As setHook(), but letting the contents be parsed.
5114 * Transparent tag hooks are like regular XML-style tag hooks, except they
5115 * operate late in the transformation sequence, on HTML instead of wikitext.
5117 * This is probably obsoleted by things dealing with parser frames?
5118 * The only extension currently using it is geoserver.
5121 * @todo better document or deprecate this
5123 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5124 * @param callable $callback The callback function (and object) to use for the tag
5125 * @throws MWException
5126 * @return callable|null The old value of the mTagHooks array associated with the hook
5128 public function setTransparentTagHook( $tag, $callback ) {
5129 $tag = strtolower( $tag );
5130 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5131 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5133 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5134 $this->mTransparentTagHooks
[$tag] = $callback;
5140 * Remove all tag hooks
5142 public function clearTagHooks() {
5143 $this->mTagHooks
= array();
5144 $this->mFunctionTagHooks
= array();
5145 $this->mStripList
= $this->mDefaultStripList
;
5149 * Create a function, e.g. {{sum:1|2|3}}
5150 * The callback function should have the form:
5151 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5153 * Or with SFH_OBJECT_ARGS:
5154 * function myParserFunction( $parser, $frame, $args ) { ... }
5156 * The callback may either return the text result of the function, or an array with the text
5157 * in element 0, and a number of flags in the other elements. The names of the flags are
5158 * specified in the keys. Valid flags are:
5159 * found The text returned is valid, stop processing the template. This
5161 * nowiki Wiki markup in the return value should be escaped
5162 * isHTML The returned text is HTML, armour it against wikitext transformation
5164 * @param string $id The magic word ID
5165 * @param callable $callback The callback function (and object) to use
5166 * @param int $flags A combination of the following flags:
5167 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5169 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5170 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5171 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5172 * the arguments, and to control the way they are expanded.
5174 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5175 * arguments, for instance:
5176 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5178 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5179 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5180 * working if/when this is changed.
5182 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5185 * Please read the documentation in includes/parser/Preprocessor.php for more information
5186 * about the methods available in PPFrame and PPNode.
5188 * @throws MWException
5189 * @return string|callable The old callback function for this name, if any
5191 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5194 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5195 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5197 # Add to function cache
5198 $mw = MagicWord
::get( $id );
5200 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5203 $synonyms = $mw->getSynonyms();
5204 $sensitive = intval( $mw->isCaseSensitive() );
5206 foreach ( $synonyms as $syn ) {
5208 if ( !$sensitive ) {
5209 $syn = $wgContLang->lc( $syn );
5212 if ( !( $flags & SFH_NO_HASH
) ) {
5215 # Remove trailing colon
5216 if ( substr( $syn, -1, 1 ) === ':' ) {
5217 $syn = substr( $syn, 0, -1 );
5219 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5225 * Get all registered function hook identifiers
5229 public function getFunctionHooks() {
5230 return array_keys( $this->mFunctionHooks
);
5234 * Create a tag function, e.g. "<test>some stuff</test>".
5235 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5236 * Unlike parser functions, their content is not preprocessed.
5237 * @param string $tag
5238 * @param callable $callback
5240 * @throws MWException
5243 public function setFunctionTagHook( $tag, $callback, $flags ) {
5244 $tag = strtolower( $tag );
5245 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5246 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5248 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5249 $this->mFunctionTagHooks
[$tag] : null;
5250 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5252 if ( !in_array( $tag, $this->mStripList
) ) {
5253 $this->mStripList
[] = $tag;
5260 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5261 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5262 * Placeholders created in Skin::makeLinkObj()
5264 * @param string $text
5265 * @param int $options
5267 * @return array Array of link CSS classes, indexed by PDBK.
5269 public function replaceLinkHolders( &$text, $options = 0 ) {
5270 return $this->mLinkHolders
->replace( $text );
5274 * Replace "<!--LINK-->" link placeholders with plain text of links
5275 * (not HTML-formatted).
5277 * @param string $text
5280 public function replaceLinkHoldersText( $text ) {
5281 return $this->mLinkHolders
->replaceText( $text );
5285 * Renders an image gallery from a text with one line per image.
5286 * text labels may be given by using |-style alternative text. E.g.
5287 * Image:one.jpg|The number "1"
5288 * Image:tree.jpg|A tree
5289 * given as text will return the HTML of a gallery with two images,
5290 * labeled 'The number "1"' and
5293 * @param string $text
5294 * @param array $params
5295 * @return string HTML
5297 public function renderImageGallery( $text, $params ) {
5298 wfProfileIn( __METHOD__
);
5301 if ( isset( $params['mode'] ) ) {
5302 $mode = $params['mode'];
5306 $ig = ImageGalleryBase
::factory( $mode );
5307 } catch ( MWException
$e ) {
5308 // If invalid type set, fallback to default.
5309 $ig = ImageGalleryBase
::factory( false );
5312 $ig->setContextTitle( $this->mTitle
);
5313 $ig->setShowBytes( false );
5314 $ig->setShowFilename( false );
5315 $ig->setParser( $this );
5316 $ig->setHideBadImages();
5317 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5319 if ( isset( $params['showfilename'] ) ) {
5320 $ig->setShowFilename( true );
5322 $ig->setShowFilename( false );
5324 if ( isset( $params['caption'] ) ) {
5325 $caption = $params['caption'];
5326 $caption = htmlspecialchars( $caption );
5327 $caption = $this->replaceInternalLinks( $caption );
5328 $ig->setCaptionHtml( $caption );
5330 if ( isset( $params['perrow'] ) ) {
5331 $ig->setPerRow( $params['perrow'] );
5333 if ( isset( $params['widths'] ) ) {
5334 $ig->setWidths( $params['widths'] );
5336 if ( isset( $params['heights'] ) ) {
5337 $ig->setHeights( $params['heights'] );
5339 $ig->setAdditionalOptions( $params );
5341 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5343 $lines = StringUtils
::explode( "\n", $text );
5344 foreach ( $lines as $line ) {
5345 # match lines like these:
5346 # Image:someimage.jpg|This is some image
5348 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5350 if ( count( $matches ) == 0 ) {
5354 if ( strpos( $matches[0], '%' ) !== false ) {
5355 $matches[1] = rawurldecode( $matches[1] );
5357 $title = Title
::newFromText( $matches[1], NS_FILE
);
5358 if ( is_null( $title ) ) {
5359 # Bogus title. Ignore these so we don't bomb out later.
5363 # We need to get what handler the file uses, to figure out parameters.
5364 # Note, a hook can overide the file name, and chose an entirely different
5365 # file (which potentially could be of a different type and have different handler).
5368 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5369 array( $this, $title, &$options, &$descQuery ) );
5370 # Don't register it now, as ImageGallery does that later.
5371 $file = $this->fetchFileNoRegister( $title, $options );
5372 $handler = $file ?
$file->getHandler() : false;
5374 wfProfileIn( __METHOD__
. '-getMagicWord' );
5376 'img_alt' => 'gallery-internal-alt',
5377 'img_link' => 'gallery-internal-link',
5380 $paramMap = $paramMap +
$handler->getParamMap();
5381 // We don't want people to specify per-image widths.
5382 // Additionally the width parameter would need special casing anyhow.
5383 unset( $paramMap['img_width'] );
5386 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5387 wfProfileOut( __METHOD__
. '-getMagicWord' );
5392 $handlerOptions = array();
5393 if ( isset( $matches[3] ) ) {
5394 // look for an |alt= definition while trying not to break existing
5395 // captions with multiple pipes (|) in it, until a more sensible grammar
5396 // is defined for images in galleries
5398 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5399 // splitting on '|' is a bit odd, and different from makeImage.
5400 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5401 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5403 foreach ( $parameterMatches as $parameterMatch ) {
5404 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5406 $paramName = $paramMap[$magicName];
5408 switch ( $paramName ) {
5409 case 'gallery-internal-alt':
5410 $alt = $this->stripAltText( $match, false );
5412 case 'gallery-internal-link':
5413 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5414 $chars = self
::EXT_LINK_URL_CLASS
;
5415 $prots = $this->mUrlProtocols
;
5416 //check to see if link matches an absolute url, if not then it must be a wiki link.
5417 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5420 $localLinkTitle = Title
::newFromText( $linkValue );
5421 if ( $localLinkTitle !== null ) {
5422 $link = $localLinkTitle->getLinkURL();
5427 // Must be a handler specific parameter.
5428 if ( $handler->validateParam( $paramName, $match ) ) {
5429 $handlerOptions[$paramName] = $match;
5431 // Guess not. Append it to the caption.
5432 wfDebug( "$parameterMatch failed parameter validation\n" );
5433 $label .= '|' . $parameterMatch;
5438 // concatenate all other pipes
5439 $label .= '|' . $parameterMatch;
5442 // remove the first pipe
5443 $label = substr( $label, 1 );
5446 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5448 $html = $ig->toHTML();
5449 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5450 wfProfileOut( __METHOD__
);
5455 * @param string $handler
5458 public function getImageParams( $handler ) {
5460 $handlerClass = get_class( $handler );
5464 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5465 # Initialise static lists
5466 static $internalParamNames = array(
5467 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5468 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5469 'bottom', 'text-bottom' ),
5470 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5471 'upright', 'border', 'link', 'alt', 'class' ),
5473 static $internalParamMap;
5474 if ( !$internalParamMap ) {
5475 $internalParamMap = array();
5476 foreach ( $internalParamNames as $type => $names ) {
5477 foreach ( $names as $name ) {
5478 $magicName = str_replace( '-', '_', "img_$name" );
5479 $internalParamMap[$magicName] = array( $type, $name );
5484 # Add handler params
5485 $paramMap = $internalParamMap;
5487 $handlerParamMap = $handler->getParamMap();
5488 foreach ( $handlerParamMap as $magic => $paramName ) {
5489 $paramMap[$magic] = array( 'handler', $paramName );
5492 $this->mImageParams
[$handlerClass] = $paramMap;
5493 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5495 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5499 * Parse image options text and use it to make an image
5501 * @param Title $title
5502 * @param string $options
5503 * @param LinkHolderArray|bool $holders
5504 * @return string HTML
5506 public function makeImage( $title, $options, $holders = false ) {
5507 # Check if the options text is of the form "options|alt text"
5509 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5510 # * left no resizing, just left align. label is used for alt= only
5511 # * right same, but right aligned
5512 # * none same, but not aligned
5513 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5514 # * center center the image
5515 # * frame Keep original image size, no magnify-button.
5516 # * framed Same as "frame"
5517 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5518 # * upright reduce width for upright images, rounded to full __0 px
5519 # * border draw a 1px border around the image
5520 # * alt Text for HTML alt attribute (defaults to empty)
5521 # * class Set a class for img node
5522 # * link Set the target of the image link. Can be external, interwiki, or local
5523 # vertical-align values (no % or length right now):
5533 $parts = StringUtils
::explode( "|", $options );
5535 # Give extensions a chance to select the file revision for us
5538 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5539 array( $this, $title, &$options, &$descQuery ) );
5540 # Fetch and register the file (file title may be different via hooks)
5541 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5544 $handler = $file ?
$file->getHandler() : false;
5546 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5549 $this->addTrackingCategory( 'broken-file-category' );
5552 # Process the input parameters
5554 $params = array( 'frame' => array(), 'handler' => array(),
5555 'horizAlign' => array(), 'vertAlign' => array() );
5556 $seenformat = false;
5557 foreach ( $parts as $part ) {
5558 $part = trim( $part );
5559 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5561 if ( isset( $paramMap[$magicName] ) ) {
5562 list( $type, $paramName ) = $paramMap[$magicName];
5564 # Special case; width and height come in one variable together
5565 if ( $type === 'handler' && $paramName === 'width' ) {
5566 $parsedWidthParam = $this->parseWidthParam( $value );
5567 if ( isset( $parsedWidthParam['width'] ) ) {
5568 $width = $parsedWidthParam['width'];
5569 if ( $handler->validateParam( 'width', $width ) ) {
5570 $params[$type]['width'] = $width;
5574 if ( isset( $parsedWidthParam['height'] ) ) {
5575 $height = $parsedWidthParam['height'];
5576 if ( $handler->validateParam( 'height', $height ) ) {
5577 $params[$type]['height'] = $height;
5581 # else no validation -- bug 13436
5583 if ( $type === 'handler' ) {
5584 # Validate handler parameter
5585 $validated = $handler->validateParam( $paramName, $value );
5587 # Validate internal parameters
5588 switch ( $paramName ) {
5592 # @todo FIXME: Possibly check validity here for
5593 # manualthumb? downstream behavior seems odd with
5594 # missing manual thumbs.
5596 $value = $this->stripAltText( $value, $holders );
5599 $chars = self
::EXT_LINK_URL_CLASS
;
5600 $prots = $this->mUrlProtocols
;
5601 if ( $value === '' ) {
5602 $paramName = 'no-link';
5605 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5606 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5607 $paramName = 'link-url';
5608 $this->mOutput
->addExternalLink( $value );
5609 if ( $this->mOptions
->getExternalLinkTarget() ) {
5610 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5615 $linkTitle = Title
::newFromText( $value );
5617 $paramName = 'link-title';
5618 $value = $linkTitle;
5619 $this->mOutput
->addLink( $linkTitle );
5627 // use first appearing option, discard others.
5628 $validated = ! $seenformat;
5632 # Most other things appear to be empty or numeric...
5633 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5638 $params[$type][$paramName] = $value;
5642 if ( !$validated ) {
5647 # Process alignment parameters
5648 if ( $params['horizAlign'] ) {
5649 $params['frame']['align'] = key( $params['horizAlign'] );
5651 if ( $params['vertAlign'] ) {
5652 $params['frame']['valign'] = key( $params['vertAlign'] );
5655 $params['frame']['caption'] = $caption;
5657 # Will the image be presented in a frame, with the caption below?
5658 $imageIsFramed = isset( $params['frame']['frame'] )
5659 ||
isset( $params['frame']['framed'] )
5660 ||
isset( $params['frame']['thumbnail'] )
5661 ||
isset( $params['frame']['manualthumb'] );
5663 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5664 # came to also set the caption, ordinary text after the image -- which
5665 # makes no sense, because that just repeats the text multiple times in
5666 # screen readers. It *also* came to set the title attribute.
5668 # Now that we have an alt attribute, we should not set the alt text to
5669 # equal the caption: that's worse than useless, it just repeats the
5670 # text. This is the framed/thumbnail case. If there's no caption, we
5671 # use the unnamed parameter for alt text as well, just for the time be-
5672 # ing, if the unnamed param is set and the alt param is not.
5674 # For the future, we need to figure out if we want to tweak this more,
5675 # e.g., introducing a title= parameter for the title; ignoring the un-
5676 # named parameter entirely for images without a caption; adding an ex-
5677 # plicit caption= parameter and preserving the old magic unnamed para-
5679 if ( $imageIsFramed ) { # Framed image
5680 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5681 # No caption or alt text, add the filename as the alt text so
5682 # that screen readers at least get some description of the image
5683 $params['frame']['alt'] = $title->getText();
5685 # Do not set $params['frame']['title'] because tooltips don't make sense
5687 } else { # Inline image
5688 if ( !isset( $params['frame']['alt'] ) ) {
5689 # No alt text, use the "caption" for the alt text
5690 if ( $caption !== '' ) {
5691 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5693 # No caption, fall back to using the filename for the
5695 $params['frame']['alt'] = $title->getText();
5698 # Use the "caption" for the tooltip text
5699 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5702 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5704 # Linker does the rest
5705 $time = isset( $options['time'] ) ?
$options['time'] : false;
5706 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5707 $time, $descQuery, $this->mOptions
->getThumbSize() );
5709 # Give the handler a chance to modify the parser object
5711 $handler->parserTransformHook( $this, $file );
5718 * @param string $caption
5719 * @param LinkHolderArray|bool $holders
5720 * @return mixed|string
5722 protected function stripAltText( $caption, $holders ) {
5723 # Strip bad stuff out of the title (tooltip). We can't just use
5724 # replaceLinkHoldersText() here, because if this function is called
5725 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5727 $tooltip = $holders->replaceText( $caption );
5729 $tooltip = $this->replaceLinkHoldersText( $caption );
5732 # make sure there are no placeholders in thumbnail attributes
5733 # that are later expanded to html- so expand them now and
5735 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5736 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5742 * Set a flag in the output object indicating that the content is dynamic and
5743 * shouldn't be cached.
5745 public function disableCache() {
5746 wfDebug( "Parser output marked as uncacheable.\n" );
5747 if ( !$this->mOutput
) {
5748 throw new MWException( __METHOD__
.
5749 " can only be called when actually parsing something" );
5751 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5752 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5756 * Callback from the Sanitizer for expanding items found in HTML attribute
5757 * values, so they can be safely tested and escaped.
5759 * @param string $text
5760 * @param bool|PPFrame $frame
5763 public function attributeStripCallback( &$text, $frame = false ) {
5764 $text = $this->replaceVariables( $text, $frame );
5765 $text = $this->mStripState
->unstripBoth( $text );
5774 public function getTags() {
5776 array_keys( $this->mTransparentTagHooks
),
5777 array_keys( $this->mTagHooks
),
5778 array_keys( $this->mFunctionTagHooks
)
5783 * Replace transparent tags in $text with the values given by the callbacks.
5785 * Transparent tag hooks are like regular XML-style tag hooks, except they
5786 * operate late in the transformation sequence, on HTML instead of wikitext.
5788 * @param string $text
5792 public function replaceTransparentTags( $text ) {
5794 $elements = array_keys( $this->mTransparentTagHooks
);
5795 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5796 $replacements = array();
5798 foreach ( $matches as $marker => $data ) {
5799 list( $element, $content, $params, $tag ) = $data;
5800 $tagName = strtolower( $element );
5801 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5802 $output = call_user_func_array(
5803 $this->mTransparentTagHooks
[$tagName],
5804 array( $content, $params, $this )
5809 $replacements[$marker] = $output;
5811 return strtr( $text, $replacements );
5815 * Break wikitext input into sections, and either pull or replace
5816 * some particular section's text.
5818 * External callers should use the getSection and replaceSection methods.
5820 * @param string $text Page wikitext
5821 * @param string|number $sectionId A section identifier string of the form:
5822 * "<flag1> - <flag2> - ... - <section number>"
5824 * Currently the only recognised flag is "T", which means the target section number
5825 * was derived during a template inclusion parse, in other words this is a template
5826 * section edit link. If no flags are given, it was an ordinary section edit link.
5827 * This flag is required to avoid a section numbering mismatch when a section is
5828 * enclosed by "<includeonly>" (bug 6563).
5830 * The section number 0 pulls the text before the first heading; other numbers will
5831 * pull the given section along with its lower-level subsections. If the section is
5832 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5834 * Section 0 is always considered to exist, even if it only contains the empty
5835 * string. If $text is the empty string and section 0 is replaced, $newText is
5838 * @param string $mode One of "get" or "replace"
5839 * @param string $newText Replacement text for section data.
5840 * @return string For "get", the extracted section text.
5841 * for "replace", the whole page with the section replaced.
5843 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5844 global $wgTitle; # not generally used but removes an ugly failure mode
5846 $magicScopeVariable = $this->lock();
5847 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5849 $frame = $this->getPreprocessor()->newFrame();
5851 # Process section extraction flags
5853 $sectionParts = explode( '-', $sectionId );
5854 $sectionIndex = array_pop( $sectionParts );
5855 foreach ( $sectionParts as $part ) {
5856 if ( $part === 'T' ) {
5857 $flags |
= self
::PTD_FOR_INCLUSION
;
5861 # Check for empty input
5862 if ( strval( $text ) === '' ) {
5863 # Only sections 0 and T-0 exist in an empty document
5864 if ( $sectionIndex == 0 ) {
5865 if ( $mode === 'get' ) {
5871 if ( $mode === 'get' ) {
5879 # Preprocess the text
5880 $root = $this->preprocessToDom( $text, $flags );
5882 # <h> nodes indicate section breaks
5883 # They can only occur at the top level, so we can find them by iterating the root's children
5884 $node = $root->getFirstChild();
5886 # Find the target section
5887 if ( $sectionIndex == 0 ) {
5888 # Section zero doesn't nest, level=big
5889 $targetLevel = 1000;
5892 if ( $node->getName() === 'h' ) {
5893 $bits = $node->splitHeading();
5894 if ( $bits['i'] == $sectionIndex ) {
5895 $targetLevel = $bits['level'];
5899 if ( $mode === 'replace' ) {
5900 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5902 $node = $node->getNextSibling();
5908 if ( $mode === 'get' ) {
5915 # Find the end of the section, including nested sections
5917 if ( $node->getName() === 'h' ) {
5918 $bits = $node->splitHeading();
5919 $curLevel = $bits['level'];
5920 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5924 if ( $mode === 'get' ) {
5925 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5927 $node = $node->getNextSibling();
5930 # Write out the remainder (in replace mode only)
5931 if ( $mode === 'replace' ) {
5932 # Output the replacement text
5933 # Add two newlines on -- trailing whitespace in $newText is conventionally
5934 # stripped by the editor, so we need both newlines to restore the paragraph gap
5935 # Only add trailing whitespace if there is newText
5936 if ( $newText != "" ) {
5937 $outText .= $newText . "\n\n";
5941 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5942 $node = $node->getNextSibling();
5946 if ( is_string( $outText ) ) {
5947 # Re-insert stripped tags
5948 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5955 * This function returns the text of a section, specified by a number ($section).
5956 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5957 * the first section before any such heading (section 0).
5959 * If a section contains subsections, these are also returned.
5961 * @param string $text Text to look in
5962 * @param string|number $sectionId Section identifier as a number or string
5963 * (e.g. 0, 1 or 'T-1').
5964 * @param string $defaultText Default to return if section is not found
5966 * @return string Text of the requested section
5968 public function getSection( $text, $sectionId, $defaultText = '' ) {
5969 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5973 * This function returns $oldtext after the content of the section
5974 * specified by $section has been replaced with $text. If the target
5975 * section does not exist, $oldtext is returned unchanged.
5977 * @param string $oldText Former text of the article
5978 * @param string|number $sectionId Section identifier as a number or string
5979 * (e.g. 0, 1 or 'T-1').
5980 * @param string $newText Replacing text
5982 * @return string Modified text
5984 public function replaceSection( $oldText, $sectionId, $newText ) {
5985 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5989 * Get the ID of the revision we are parsing
5993 public function getRevisionId() {
5994 return $this->mRevisionId
;
5998 * Get the revision object for $this->mRevisionId
6000 * @return Revision|null Either a Revision object or null
6001 * @since 1.23 (public since 1.23)
6003 public function getRevisionObject() {
6004 if ( !is_null( $this->mRevisionObject
) ) {
6005 return $this->mRevisionObject
;
6007 if ( is_null( $this->mRevisionId
) ) {
6011 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6012 return $this->mRevisionObject
;
6016 * Get the timestamp associated with the current revision, adjusted for
6017 * the default server-local timestamp
6020 public function getRevisionTimestamp() {
6021 if ( is_null( $this->mRevisionTimestamp
) ) {
6022 wfProfileIn( __METHOD__
);
6026 $revObject = $this->getRevisionObject();
6027 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6029 # The cryptic '' timezone parameter tells to use the site-default
6030 # timezone offset instead of the user settings.
6032 # Since this value will be saved into the parser cache, served
6033 # to other users, and potentially even used inside links and such,
6034 # it needs to be consistent for all visitors.
6035 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6037 wfProfileOut( __METHOD__
);
6039 return $this->mRevisionTimestamp
;
6043 * Get the name of the user that edited the last revision
6045 * @return string User name
6047 public function getRevisionUser() {
6048 if ( is_null( $this->mRevisionUser
) ) {
6049 $revObject = $this->getRevisionObject();
6051 # if this template is subst: the revision id will be blank,
6052 # so just use the current user's name
6054 $this->mRevisionUser
= $revObject->getUserText();
6055 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6056 $this->mRevisionUser
= $this->getUser()->getName();
6059 return $this->mRevisionUser
;
6063 * Get the size of the revision
6065 * @return int|null Revision size
6067 public function getRevisionSize() {
6068 if ( is_null( $this->mRevisionSize
) ) {
6069 $revObject = $this->getRevisionObject();
6071 # if this variable is subst: the revision id will be blank,
6072 # so just use the parser input size, because the own substituation
6073 # will change the size.
6075 $this->mRevisionSize
= $revObject->getSize();
6076 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6077 $this->mRevisionSize
= $this->mInputSize
;
6080 return $this->mRevisionSize
;
6084 * Mutator for $mDefaultSort
6086 * @param string $sort New value
6088 public function setDefaultSort( $sort ) {
6089 $this->mDefaultSort
= $sort;
6090 $this->mOutput
->setProperty( 'defaultsort', $sort );
6094 * Accessor for $mDefaultSort
6095 * Will use the empty string if none is set.
6097 * This value is treated as a prefix, so the
6098 * empty string is equivalent to sorting by
6103 public function getDefaultSort() {
6104 if ( $this->mDefaultSort
!== false ) {
6105 return $this->mDefaultSort
;
6112 * Accessor for $mDefaultSort
6113 * Unlike getDefaultSort(), will return false if none is set
6115 * @return string|bool
6117 public function getCustomDefaultSort() {
6118 return $this->mDefaultSort
;
6122 * Try to guess the section anchor name based on a wikitext fragment
6123 * presumably extracted from a heading, for example "Header" from
6126 * @param string $text
6130 public function guessSectionNameFromWikiText( $text ) {
6131 # Strip out wikitext links(they break the anchor)
6132 $text = $this->stripSectionName( $text );
6133 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6134 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6138 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6139 * instead. For use in redirects, since IE6 interprets Redirect: headers
6140 * as something other than UTF-8 (apparently?), resulting in breakage.
6142 * @param string $text The section name
6143 * @return string An anchor
6145 public function guessLegacySectionNameFromWikiText( $text ) {
6146 # Strip out wikitext links(they break the anchor)
6147 $text = $this->stripSectionName( $text );
6148 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6149 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6153 * Strips a text string of wikitext for use in a section anchor
6155 * Accepts a text string and then removes all wikitext from the
6156 * string and leaves only the resultant text (i.e. the result of
6157 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6158 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6159 * to create valid section anchors by mimicing the output of the
6160 * parser when headings are parsed.
6162 * @param string $text Text string to be stripped of wikitext
6163 * for use in a Section anchor
6164 * @return string Filtered text string
6166 public function stripSectionName( $text ) {
6167 # Strip internal link markup
6168 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6169 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6171 # Strip external link markup
6172 # @todo FIXME: Not tolerant to blank link text
6173 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6174 # on how many empty links there are on the page - need to figure that out.
6175 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6177 # Parse wikitext quotes (italics & bold)
6178 $text = $this->doQuotes( $text );
6181 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6186 * strip/replaceVariables/unstrip for preprocessor regression testing
6188 * @param string $text
6189 * @param Title $title
6190 * @param ParserOptions $options
6191 * @param int $outputType
6195 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6196 $magicScopeVariable = $this->lock();
6197 $this->startParse( $title, $options, $outputType, true );
6199 $text = $this->replaceVariables( $text );
6200 $text = $this->mStripState
->unstripBoth( $text );
6201 $text = Sanitizer
::removeHTMLtags( $text );
6206 * @param string $text
6207 * @param Title $title
6208 * @param ParserOptions $options
6211 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6212 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6216 * @param string $text
6217 * @param Title $title
6218 * @param ParserOptions $options
6221 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6222 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6226 * Call a callback function on all regions of the given text that are not
6227 * inside strip markers, and replace those regions with the return value
6228 * of the callback. For example, with input:
6232 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6233 * two strings will be replaced with the value returned by the callback in
6237 * @param callable $callback
6241 public function markerSkipCallback( $s, $callback ) {
6244 while ( $i < strlen( $s ) ) {
6245 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6246 if ( $markerStart === false ) {
6247 $out .= call_user_func( $callback, substr( $s, $i ) );
6250 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6251 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6252 if ( $markerEnd === false ) {
6253 $out .= substr( $s, $markerStart );
6256 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6257 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6266 * Remove any strip markers found in the given text.
6268 * @param string $text Input string
6271 public function killMarkers( $text ) {
6272 return $this->mStripState
->killMarkers( $text );
6276 * Save the parser state required to convert the given half-parsed text to
6277 * HTML. "Half-parsed" in this context means the output of
6278 * recursiveTagParse() or internalParse(). This output has strip markers
6279 * from replaceVariables (extensionSubstitution() etc.), and link
6280 * placeholders from replaceLinkHolders().
6282 * Returns an array which can be serialized and stored persistently. This
6283 * array can later be loaded into another parser instance with
6284 * unserializeHalfParsedText(). The text can then be safely incorporated into
6285 * the return value of a parser hook.
6287 * @param string $text
6291 public function serializeHalfParsedText( $text ) {
6292 wfProfileIn( __METHOD__
);
6295 'version' => self
::HALF_PARSED_VERSION
,
6296 'stripState' => $this->mStripState
->getSubState( $text ),
6297 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6299 wfProfileOut( __METHOD__
);
6304 * Load the parser state given in the $data array, which is assumed to
6305 * have been generated by serializeHalfParsedText(). The text contents is
6306 * extracted from the array, and its markers are transformed into markers
6307 * appropriate for the current Parser instance. This transformed text is
6308 * returned, and can be safely included in the return value of a parser
6311 * If the $data array has been stored persistently, the caller should first
6312 * check whether it is still valid, by calling isValidHalfParsedText().
6314 * @param array $data Serialized data
6315 * @throws MWException
6318 public function unserializeHalfParsedText( $data ) {
6319 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6320 throw new MWException( __METHOD__
. ': invalid version' );
6323 # First, extract the strip state.
6324 $texts = array( $data['text'] );
6325 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6327 # Now renumber links
6328 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6330 # Should be good to go.
6335 * Returns true if the given array, presumed to be generated by
6336 * serializeHalfParsedText(), is compatible with the current version of the
6339 * @param array $data
6343 public function isValidHalfParsedText( $data ) {
6344 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6348 * Parsed a width param of imagelink like 300px or 200x300px
6350 * @param string $value
6355 public function parseWidthParam( $value ) {
6356 $parsedWidthParam = array();
6357 if ( $value === '' ) {
6358 return $parsedWidthParam;
6361 # (bug 13500) In both cases (width/height and width only),
6362 # permit trailing "px" for backward compatibility.
6363 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6364 $width = intval( $m[1] );
6365 $height = intval( $m[2] );
6366 $parsedWidthParam['width'] = $width;
6367 $parsedWidthParam['height'] = $height;
6368 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6369 $width = intval( $value );
6370 $parsedWidthParam['width'] = $width;
6372 return $parsedWidthParam;
6376 * Lock the current instance of the parser.
6378 * This is meant to stop someone from calling the parser
6379 * recursively and messing up all the strip state.
6381 * @throws MWException If parser is in a parse
6382 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6384 protected function lock() {
6385 if ( $this->mInParse
) {
6386 throw new MWException( "Parser state cleared while parsing. "
6387 . "Did you call Parser::parse recursively?" );
6389 $this->mInParse
= true;
6392 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6393 $that->mInParse
= false;
6396 return $recursiveCheck;
6400 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6402 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6403 * or if there is more than one <p/> tag in the input HTML.
6405 * @param string $html
6409 public static function stripOuterParagraph( $html ) {
6411 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6412 if ( strpos( $m[1], '</p>' ) === false ) {
6421 * Return this parser if it is not doing anything, otherwise
6422 * get a fresh parser. You can use this method by doing
6423 * $myParser = $wgParser->getFreshParser(), or more simply
6424 * $wgParser->getFreshParser()->parse( ... );
6425 * if you're unsure if $wgParser is safe to use.
6428 * @return Parser A parser object that is not parsing anything
6430 public function getFreshParser() {
6431 global $wgParserConf;
6432 if ( $this->mInParse
) {
6433 return new $wgParserConf['class']( $wgParserConf );